File: Utility.py

package info (click to toggle)
squishdot 1.3.0-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 896 kB
  • ctags: 349
  • sloc: python: 2,313; makefile: 56; sh: 54
file content (237 lines) | stat: -rw-r--r-- 7,381 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
##############################################################################  
#   
# This software is released under the Zope Public License (ZPL) Version 1.0
#
# Copyright (c) Digital Creations.  All rights reserved.  
# Portions Copyright (c) 1999 by Butch Landingin.
# Portions Copyright (c) 2000-2001 by Chris Withers.
#   
##############################################################################  
     
import re    
from Globals import HTMLFile, MessageDialog
import Globals
from time import time, localtime, strftime, gmtime
from string import strip,split,atoi
from types import IntType
from urllib import quote
from DocumentTemplate.DT_Util import html_quote
from Squishfile import Squishfile
from StringIO import StringIO
from Products.PythonScripts.PythonScript import manage_addPythonScript

# Some handy regular expression
CRLF=re.compile('\r\n|\n\r')    
tagRegex = re.compile("<.*?>")

# where we exist on the file system
file_path = Globals.package_home(globals())
    
class Stack:     
    def __init__(self):     
        self.mlist = []     
    def pop(self):     
        data = self.mlist[-1]     
        del self.mlist[-1]     
        return data     
    def push(self,data):     
        self.mlist.append(data)     
    def isEmpty(self):     
        return (len(self.mlist) == 0)     
     
def sameday(n, m):     
    n = localtime(n)     
    m = localtime(m)     
    if m[0] == n[0] and m[1] == n[1] and m[2] == n[2]:     
        return 1     
    else:     
        return 0     
     
def addPythonScript(obj,id,file):
    f=open(file_path+'/'+file+'.py')     
    file=f.read()     
    f.close()     
    manage_addPythonScript(obj,id)
    obj._getOb(id).write(file)
    return getattr(obj,id)     

def addDTML(obj,id,title,file):     
    f=open(file_path+'/'+file+'.dtml')     
    file=f.read()     
    f.close()     
    obj.manage_addDTMLMethod(id,title,file)     
    return getattr(obj,id)     
     
def addImage(obj,id,file):     
    f=open(file_path+'/'+file,'rb')     
       
    contents=f.read()     
    f.close()     
    title=''     
    tlen = len(contents)     
    new_id = obj.manage_addImage(id,contents,title=title)   
    img_obj = obj.__getitem__(new_id)  
    img_obj.content_type = 'image/gif'  
    
     
def addTable(obj,addmethod,id,fname):     
    file=open(file_path+'/'+fname+'.tbl')     
    cols=file.readline()     
    cols=cols[:-1] # takeout newline     
    fcontent=file.read()     
    file.close()     
    title=''
    getattr(obj,addmethod)(id,title,cols)
    tbl=getattr(obj,id)     
    tbl.manage_editData(fcontent)     
     
def addArt(obj,file):
    f=open(file_path+'/'+file)     
    file=''
    REQUEST=obj.REQUEST
    REQUEST['title'] = f.readline()[:-1] # removes newline char     
    REQUEST['subject'] = f.readline()[:-1]     
    REQUEST['author'] = f.readline()[:-1]     
    REQUEST['email'] = f.readline()[:-1]     
    REQUEST['notify']= f.readline()[:-1]     
    REQUEST['dept']=f.readline()[:-1]
    
    summary=''     
    currline=f.readline()     
    while strip(currline) <> '%%' and currline <> '':     
        summary = summary + currline     
        currline=f.readline()
    REQUEST['summary']=summary
    
    body=''     
    currline=f.readline()     
    while strip(currline) <> '%%' and currline <> '':     
        body = body + currline     
        currline=f.readline()
    REQUEST['body']=body
    
    f.close()
    id =  obj.addPosting(file,REQUEST)     
    msg = obj.data[id]     
    msg.reviewed = 1
    return id     
     
PATH_SEP=re.compile('[\\/]')      
    
def createUploadable(filepath):
    f=open(filepath,'rb')
    # extra step 'cos we can't set attributes on files
    s=StringIO(f.read())
    s.filename=filepath
    return s
    
def addFile(posting,file):
    f  = createUploadable(file_path+'/'+file)
    sf = Squishfile(f)
    posting.file = sf
    setattr(posting,sf.file_name(),sf)
    
htmlhead =  '''<html><head><title>%s</title>  
<body><pre>    
'''    
    
htmlend = '''   
</pre></body></html>    
'''    
    
def addText(file,title):    
    global htmlhead, htmlend     
    try:     
        f=open(file_path+'/'+file,'rb')     
    except:     
        return htmlhead + htmlend         
    s = f.read()     
    f.close()     
    return (htmlhead % title) + html_quote(s) + htmlend

def doAddPosting(self, file, REQUEST,RESPONSE,moderated,message,klass):     
        """ add a posting """
        moderated = getattr(self,moderated)
        comment = klass.meta_type=='Comment'
        # This sets reviewed if comments aren't moderated and leaves it at 0 if they are.
        reviewed = not moderated
        
        id=self.createId()     
        thread=[]     
        map(thread.append, self.thread)
        if comment:
            thread.append(atoi(self.id))     
        for t in thread:     
            obj=self.data[t]     
            obj.modified=id     
            if not reviewed:     
                obj.revsub=obj.revsub+1     
            else:     
                obj.reply_cnt = obj.reply_cnt+1     
     
        msg=klass(id, thread, self.level+1, reviewed).__of__(self)     

        message = msg.edit(REQUEST,None,'delete attachment',file,reviewed)
        if message:
            return message

        if comment:
            msg.subject = self.subject
        
        self.setItem(id, msg)     
        self.expire_items()     
          
        if RESPONSE:
            if hasattr(self,'doNotify'):
                self.doNotify(msg,REQUEST)
            
            if comment and self.mail_replies or klass.meta_type=='Article' and self.mail_articles:
                self.sendEmail(msg,self.admin_address,REQUEST,manage_notify=1)

            gtime = gmtime(id)     
            glist = list(gtime)     
            glist[0] = glist[0] + 1 # add 1 year to expiry date     
            glist[1] = 12     
            glist[2] = 31     
            glist[3] = 23     
            glist[4] = 59     
            glist[5] = 59     
            glist[6] = 0     
            glist[7] = 365     
            glist[8] = 0     
            gtime = tuple(glist)     
            e = strftime('%A, %d-%b-%y %H:%M:%S GMT',gtime)     
            author = quote(msg.author)    
            RESPONSE.setCookie('_suggest_author',author,expires=e,path='/')     
            email = quote(msg.email)    
            RESPONSE.setCookie('_suggest_email',email,expires=e,path='/')     
            RESPONSE.setCookie('suggest_notify',msg.notify,expires=e,path='/')
            
            path = self.absolute_url()            
            if not moderated:
                path = path + '/%s' % id

            return self.showMessage(self, REQUEST=REQUEST, title='%s Posted' % klass.meta_type,     
                                 message=message,     
                                 action=path     
                                )

        return id


def getitem(self,id):
    """ Get a posting from the SquishSite data store """

    # make sure id is an integer
    try:
        if not isinstance(id,IntType):
            id=atoi(id)
    except ValueError:
        raise KeyError, id

    # make sure it's in our list of children
    if not self.ids.has_key(id):
        raise KeyError, id
        
    # return the posting
    return self.data[id].__of__(self)