1: from Products.ExternalFile.FileUtils import copy_file
2: from Products.ExternalFile.ExternalFile import ExternalFile
3: from OFS.Folder import Folder
4: from OFS.Image import File
5: from OFS.Image import cookId
6: from Globals import DTMLFile, InitializeClass,package_home
7: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
8: from AccessControl import getSecurityManager
9: from Products.PageTemplates.PageTemplate import PageTemplate
10: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
11: from AccessControl import ClassSecurityInfo
12: import os.path
13: import time
14:
15: def sortv(x,y):
16: return cmp(x[0],y[0])
17:
18: class externalVersionedFileFolder(Folder):
19: """Folder with externalVersioned files"""
20:
21:
22: meta_type = "externalVersionedFileFolder"
23:
24: security= ClassSecurityInfo()
25: security.declareProtected('AUTHENTICATED_USER','addFileForm')
26:
27: manage_options = Folder.manage_options+(
28: {'label':'Generate Index.html','action':'generateIndexHTML'},
29: {'label':'Generate history_template.html','action':'generateHistoryHTML'},
30: {'label':'Change Path to Folder','action':'changePathForm'},
31: )
32:
33: def changePathForm(self):
34: """change the path form"""
35: pt=PageTemplateFile('Products/externalVersionedFile/zpt/changePath').__of__(self)
36: return pt()
37:
38: def changePath(self,baseFolderPath,RESPONSE=None):
39: """change the path"""
40: self.baseFolderPath=baseFolderPath
41: if RESPONSE is not None:
42: return self.manage_main(self, RESPONSE)
43:
44:
45:
46: def helpDownload(self):
47: """download help"""
48:
49: pt=PageTemplateFile('Products/externalVersionedFile/zpt/helpDownload').__of__(self)
50: return pt()
51:
52:
53: def generateIndexHTML(self,RESPONSE=None):
54: """lege standard index.html an"""
55:
56:
57:
58:
59: if not hasattr(self,'index.html'):
60: zt=ZopePageTemplate('index.html')
61: self._setObject('index.html',zt)
62: default_content_fn = os.path.join(package_home(globals()),
63: 'zpt/versionFileFolderMain.zpt')
64: text = open(default_content_fn).read()
65: zt.pt_edit(text, 'text/html')
66:
67: else:
68: return "already exists!"
69:
70: if RESPONSE is not None:
71: RESPONSE.redirect('manage_main')
72:
73:
74: def generateHistoryHTML(self,RESPONSE=None):
75: """lege standard index.html an"""
76:
77:
78:
79:
80: if not hasattr(self,'history_template.html'):
81: zt=ZopePageTemplate('history_template.html')
82: self._setObject('history_template.html',zt)
83: default_content_fn = os.path.join(package_home(globals()),
84: 'zpt/versionHistory.zpt')
85: text = open(default_content_fn).read()
86: zt.pt_edit(text, 'text/html')
87:
88: else:
89: return "already exists!"
90:
91: if RESPONSE is not None:
92: RESPONSE.redirect('manage_main')
93:
94: def getVersionedFiles(self,sortField='title'):
95: """get all versioned files"""
96:
97: def sortName(x,y):
98: return cmp(x[1].title.lower(),y[1].title.lower())
99:
100: def sortDate(x,y):
101: return cmp(y[1].getLastVersion().getTime(),x[1].getLastVersion().getTime())
102:
103:
104: def sortAuthor(x,y):
105:
106: return cmp(x[1].getLastVersion().lastEditor(),y[1].getLastVersion().lastEditor())
107:
108: externalVersionedFiles=self.ZopeFind(self,obj_metatypes=['externalVersionedFile'])
109:
110: if sortField=='title':
111: externalVersionedFiles.sort(sortName)
112: elif sortField=='date':
113: externalVersionedFiles.sort(sortDate)
114: elif sortField=='author':
115: externalVersionedFiles.sort(sortAuthor)
116:
117: return externalVersionedFiles
118:
119:
120: def header_html(self):
121: """zusätzlicher header"""
122: ext=self.ZopeFind(self,obj_ids=["header.html"])
123: if ext:
124: return ext[0][1]()
125: else:
126: return ""
127:
128: # security.declareProtected('index_html')
129: def index_html(self):
130: """main"""
131: ext=self.ZopeFind(self,obj_ids=["index.html"])
132: if ext:
133: return ext[0][1]()
134:
135: pt=PageTemplateFile('Products/externalVersionedFile/zpt/versionFileFolderMain').__of__(self)
136: return pt()
137:
138:
139: def addFileForm(self):
140: """add a file"""
141: out=DTMLFile('dtml/newFileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject',version='1').__of__(self)
142: return out()
143:
144:
145: def addFile(self,vC,file,author,newName='',content_type='',RESPONSE=None):
146: """ add a new file"""
147: if newName=='':
148: id=file.filename
149: else:
150: id=newName
151:
152: vC=self.REQUEST.form['vC']
153: manage_addExternalVersionedFile(self,id,'','')
154: ob=self._getOb(id)
155: ob.title=id
156: file2=file
157: ob.manage_addExternalVersionedFileObject(id,vC,author,file2,content_type=content_type)
158:
159: RESPONSE.redirect(self.REQUEST['URL1'])
160:
161:
162: manage_addExternalVersionedFileFolderForm=DTMLFile('dtml/folderAdd', globals())
163:
164:
165: def manage_addExternalVersionedFileFolder(self, id, baseFolderPath,title='',
166: createPublic=0,
167: createUserF=0,
168: REQUEST=None):
169: """Add a new Folder object with id *id*.
170:
171: If the 'createPublic' and 'createUserF' parameters are set to any true
172: value, an 'index_html' and a 'UserFolder' objects are created respectively
173: in the new folder.
174: """
175: ob=externalVersionedFileFolder()
176: ob.id=str(id)
177: ob.title=title
178: self._setObject(id, ob)
179: ob=self._getOb(id)
180: setattr(ob,'baseFolderPath',baseFolderPath)
181: checkPermission=getSecurityManager().checkPermission
182:
183: if createUserF:
184: if not checkPermission('Add User Folders', ob):
185: raise Unauthorized, (
186: 'You are not authorized to add User Folders.'
187: )
188: ob.manage_addUserFolder()
189:
190:
191: if REQUEST is not None:
192: return self.manage_main(self, REQUEST, update_menu=1)
193:
194:
195:
196: class externalVersionedFileObject(ExternalFile):
197: """File Object im Folder"""
198:
199: meta_type = "externalVersionedFileObject"
200:
201: manage_editForm =DTMLFile('dtml/fileEdit',globals(),
202: Kind='File',kind='file')
203: manage_editForm._setName('manage_editForm')
204:
205: def getTime(self):
206: """getTime"""
207: #return self.bobobase_modification_time().ISO()
208: if hasattr(self,'time'):
209: return time.strftime("%Y-%m-%d %H:%M:%S",self.time)
210: else:
211: return self.bobobase_modification_time().ISO()
212:
213: def download(self):
214: """download and lock"""
215:
216:
217: self.content_type="application/octet-stream"
218: self.REQUEST.RESPONSE.redirect(self.absolute_url())
219:
220: def downloadLocked(self):
221: """download and lock"""
222:
223:
224: if self.REQUEST['AUTHENTICATED_USER']=='Anonymous User':
225: return "please login first"
226: if not self.aq_parent.lockedBy=="":
227: return "cannot be locked because is already locked by %s"%self.lockedBy
228: self.aq_parent.lockedBy=self.REQUEST['AUTHENTICATED_USER']
229:
230: self.content_type="application/octet-stream"
231: self.REQUEST.RESPONSE.redirect(self.absolute_url())
232:
233: def setVersionNumber(self,versionNumber):
234: """set version"""
235: self.versionNumber=versionNumber
236:
237: def getVersionNumber(self):
238: """get version"""
239: return self.versionNumber
240:
241: def lastEditor(self):
242: """last Editor"""
243: if hasattr(self,'author'):
244: return self.author
245: else:
246: jar=self._p_jar
247: oid=self._p_oid
248:
249: if jar is None or oid is None: return None
250:
251: return jar.db().history(oid)[0]['user_name']
252:
253:
254:
255:
256: manage_addExternalVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject', version='1')
257:
258: def manage_addExternalVersionedFileObject(self,id,vC='',author='', file='',title='',precondition='', content_type='',
259: REQUEST=None):
260: """
261:
262: Factory method to actually create an instance of ExternalFile.
263: ExternalFile. This method assumes all parameters are correct (it
264: does no error checking). It is called from CreationDialog.py once
265: all of the confirmation and error checking steps have been taken.
266:
267: You should call this method directly if you are creating an
268: instance of ExternalFile programmatically and have 'vetted' all of
269: your parameters for correctness.
270:
271: """
272: target_filepath=os.path.join(self.baseFolderPath,id)
273: basedir=''
274: if not id:
275: raise Exception('Required fields must not be blank')
276:
277: fully_resolved_target_filepath = os.path.join(basedir,target_filepath)
278: if file:
279: copy_file(file, fully_resolved_target_filepath)
280:
281: self._setObject(id, externalVersionedFileObject(id, title, str(vC),
282: fully_resolved_target_filepath))
283: self._getOb(id).reindex_object()
284:
285: self._getOb(id).versionComment=str(vC)
286: setattr(self._getOb(id),'author',author)
287:
288: if REQUEST is not None:
289: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
290:
291: def manage_addExternalVersionedFileObject_old(self,id,vC='',author='', file='',title='',precondition='', content_type='',
292: REQUEST=None):
293: """Add a new File object.
294:
295: Creates a new File object 'id' with the contents of 'file'"""
296:
297: id=str(id)
298: title=str(title)
299: content_type=str(content_type)
300: precondition=str(precondition)
301:
302: id, title = cookId(id, title, file)
303:
304: self=self.this()
305:
306: # First, we create the file without data:
307: self._setObject(id, externalVersionedFileObject(id,title,'',content_type, precondition))
308: self._getOb(id).versionComment=str(vC)
309: self._getOb(id).time=time.localtime()
310: setattr(self._getOb(id),'author',author)
311:
312: # Now we "upload" the data. By doing this in two steps, we
313: # can use a database trick to make the upload more efficient.
314: if file:
315: self._getOb(id).manage_upload(file)
316: if content_type:
317: self._getOb(id).content_type=content_type
318:
319: if REQUEST is not None:
320: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
321:
322:
323:
324:
325: class externalVersionedFile(Folder):
326: """Versioniertes File"""
327:
328:
329:
330: def showDiffsForm(self):
331: """showdiffs"""
332: pt=PageTemplateFile('Products/externalVersionedFile/zpt/selectDiff').__of__(self)
333: return pt()
334:
335: def showDiffs(self,fileList):
336: """show"""
337: self.REQUEST.SESSION['fileList']=fileList
338: pt=PageTemplateFile('Products/externalVersionedFile/zpt/showDiffs').__of__(self)
339: return pt()
340:
341: def formatDiffs(self,fileList):
342: """generate diffs"""
343: from difflib import context_diff
344: import re
345:
346: v1=getattr(self,fileList[0])()
347: v1=re.sub("\r","\n",v1)
348: v1s=v1.split("\n")
349:
350: v2=getattr(self,fileList[1])()
351: #print v2
352: v2=re.sub("\r","\n",v2)
353: v2s=v2.split("\n")
354:
355: #print v1s
356: xx=context_diff(v1s,v2s)
357: #for x in xx:
358: # print x
359:
360: list=[]
361: counter=-1
362: toggle=0
363:
364: for x in xx:
365:
366: if x[0:2]=="**":
367: counter+=1
368: toggle=0
369: list.append(['',''])
370: elif x[0:2]=="--":
371: toggle=1
372: else:
373: try:
374: x=re.sub(">",">",x)
375: x=re.sub("<","<",x)
376: if x[0]=="!":
377: x="""<span style="color:brown;">%s</span>"""%x[1:]
378: if x[0]=="+":
379: x="""<span style="color:red;">%s</span>"""%x[1:]
380: if x[0]=="-":
381: x="""<span style="color:green;">%s</span>"""%x[1:]
382: list[counter][toggle]+=x+"<br>"
383: except:
384: """none"""
385: return list
386:
387: def __init__(self, id, title, lockedBy,author):
388: """init"""
389: self.id=id
390: self.title=title
391: self.lockedBy=lockedBy
392: self.author=author
393:
394: security= ClassSecurityInfo()
395: meta_type="externalVersionedFile"
396:
397: def getLastVersion(self):
398: """Last Version"""
399: tmp=0
400: lastVersion=None
401:
402: for version in self.ZopeFind(self):
403:
404: if hasattr(version[1],'versionNumber'):
405:
406: if int(version[1].versionNumber) > tmp:
407: tmp=int(version[1].versionNumber,)
408: lastVersion=version[1]
409: return lastVersion
410:
411: def index_html(self):
412: """main view"""
413: lastVersion=self.getLastVersion()
414: #return "File:"+self.title+" Version:%i"%lastVersion.versionNumber," modified:",lastVersion.bobobase_modification_time()," size:",lastVersion.getSize(),"modified by:",lastVersion.lastEditor()
415: return "File: %s Version:%i modified:%s size:%s modified by:%s"%(self.title,lastVersion.versionNumber,lastVersion.bobobase_modification_time(),lastVersion.getSize(),lastVersion.lastEditor())
416:
417: def getVersion(self):
418: tmp=0
419: for version in self.ZopeFind(self):
420:
421: if hasattr(version[1],'versionNumber'):
422:
423: if int(version[1].versionNumber) > tmp:
424: tmp=int(version[1].versionNumber,)
425: return tmp+1
426:
427:
428: security.declareProtected('AUTHENTICATED_USER','unlock')
429:
430: def history(self):
431: """history"""
432:
433: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
434: if ext:
435: return getattr(self,ext[0][1].getId())()
436:
437: pt=PageTemplateFile('Products/externalVersionedFile/zpt/versionHistory').__of__(self)
438: return pt()
439:
440: def getVersions(self):
441: """get all versions"""
442: ret=[]
443: for version in self.ZopeFind(self):
444: if hasattr(version[1],'versionNumber'):
445: ret.append((version[1].versionNumber,version[1]))
446: ret.sort(sortv)
447: return ret
448:
449: security.declareProtected('AUTHENTICATED_USER','unlock')
450: def unlock(self,RESPONSE):
451: """unlock"""
452: if str(self.lockedBy) in [str(self.REQUEST['AUTHENTICATED_USER'])]:
453: self.lockedBy=''
454: RESPONSE.redirect(self.REQUEST['URL2'])
455: else:
456: return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER'])
457:
458:
459: security.declareProtected('AUTHENTICATED_USER','addExternalVersionedFileObjectForm')
460:
461: def addExternalVersionedFileObjectForm(self):
462: """add a new version"""
463:
464: if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
465: return "please login first"
466: if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
467: out=DTMLFile('dtml/fileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject',version=self.getVersion()).__of__(self)
468: return out()
469: else:
470: return "Sorry file is locked by somebody else"
471:
472: def manage_addExternalVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', RESPONSE=None):
473: """add"""
474:
475: vC=self.REQUEST['vC']
476: author=self.REQUEST['author']
477:
478: if changeName=="yes":
479: self.title=file.filename[0:]
480:
481: if not newName=='':
482: self.title=newName[0:]
483:
484: id="V%i"%self.getVersion()+"_"+self.title
485: manage_addExternalVersionedFileObject(self,id,vC,author,file,"V%i"%self.getVersion()+"_"+self.title,precondition, content_type)
486: print self.ZopeFind(self,obj_ids=[id])[0]
487: objs=self.ZopeFind(self,obj_ids=[id])[0][1].setVersionNumber(int(self.getVersion()))
488:
489: if RESPONSE:
490: RESPONSE.redirect(self.REQUEST['URL2'])
491:
492: security.declareProtected('AUTHENTICATED_USER','downloadLocked')
493:
494: def download(self):
495: """download and lock"""
496: self.getLastVersion().content_type="application/octet-stream"
497: self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId())
498:
499: def downloadLocked(self):
500: """download and lock"""
501: if self.REQUEST['AUTHENTICATED_USER']=='Anonymous User':
502: return "please login first"
503: if not self.lockedBy=="":
504: return "cannot be locked because is already locked by %s"%self.lockedBy
505: self.lockedBy=self.REQUEST['AUTHENTICATED_USER']
506: self.getLastVersion().content_type="application/octet-stream"
507: self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId())
508:
509: def manage_addExternalVersionedFileForm(self):
510: """interface for adding the OSAS_root"""
511: pt=PageTemplateFile('Products/externalVersionedFile/zpt/addExternalVersionedFile.zpt').__of__(self)
512: return pt()
513:
514: def manage_addExternalVersionedFile(self,id,title,lockedBy, author=None, RESPONSE=None):
515: """add the OSAS_root"""
516: newObj=externalVersionedFile(id,title,lockedBy,author)
517: self._setObject(id,newObj)
518:
519: if RESPONSE is not None:
520: RESPONSE.redirect('manage_main')
521:
522:
523: InitializeClass(externalVersionedFile)
524: InitializeClass(externalVersionedFileFolder)
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>