1: """actual version of the versioned file folder with external filestorage,
2: using the ExtFile Product, this version replaces externaVersionedFile.py
3: DW 11.10.2006
4: """
5:
6: import email
7: from OFS.Folder import Folder
8: from OFS.Image import File
9: from OFS.Image import cookId
10: from Globals import DTMLFile, InitializeClass,package_home
11: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
12: from AccessControl import getSecurityManager
13: from Products.PageTemplates.PageTemplate import PageTemplate
14: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
15: from AccessControl import ClassSecurityInfo
16: from difflib import Differ
17: from pprint import pprint
18: from Products.ExtFile.ExtFile import *
19: from Products.ZCatalog.CatalogPathAwareness import CatalogAware
20:
21: try:
22: from Products.ImageArchive.ImageArchive import manage_AddImageZogiLib
23: except:
24: print "no images"
25:
26: from threading import Thread
27: import shutil
28: import tempfile
29: import os.path
30: import urllib
31: import time
32: import logging
33: import types
34:
35: try:
36: from Products.ECHO_content.ECHO_collection import ECHO_basis
37: except:
38: print "ECHO Elements not imported"
39: class ECHO_basis:
40: """leer"""
41: manage_options=()
42:
43:
44: def sortv(x,y):
45: return cmp(x[0],y[0])
46:
47: tdir = "/tmp/downloadVersionedFiles"
48:
49: class generateDownloadZip:
50: """generateDownloadSet"""
51:
52: def __init__(self,folderObject,url):
53: """init downloadzip"""
54: self.folder=folderObject
55: self.done=None
56: self.response=""
57: self.url=url
58:
59: def __call__(self):
60: """call generate download zip"""
61: storeTempDir=tempfile.tempdir
62: tempfile.tempdir=tdir
63:
64: tmpPath=tempfile.mktemp()
65: tmpZip=tempfile.mktemp()+".tgz"
66: tmpFn=os.path.split(tmpZip)[1]
67:
68: if not os.path.exists(tempfile.tempdir):
69: os.mkdir(tempfile.tempdir)
70:
71: if not os.path.exists(tmpPath):
72: os.mkdir(tmpPath)
73:
74: self.response="<h3>1. step: getting the files</h3>"
75:
76: for files in self.folder.ZopeFind(self.folder,obj_metatypes=['extVersionedFile']):
77: lastV=files[1].getContentObject()
78: self.response+=str("<p>Get File: %s<br>\n"%lastV.title)
79:
80: savePath=os.path.join(tmpPath,lastV.title)
81: fh=file(savePath,"w")
82: fh.write(lastV.getData())
83: fh.close()
84:
85: self.response+="<h3>2. step: creating the downloadable file</h3>"
86: self.response+="<p>Create gtar<br>"
87: self.response+="<p>This can take a while....<br>\n"
88:
89: fh=os.popen2("tar zcvf %s %s/*"%(tmpZip,tmpPath),1)[1]
90: self.response+="<br>"
91: for c in fh.read():
92: self.response+=c
93: if c==")":
94: self.response+="<br>\n"
95:
96: shutil.rmtree(tmpPath)
97:
98: self.response+="<p>finished<br>\n"
99:
100: len=os.stat(tmpZip)[6]
101: downloadUrl=self.url+"/downloadSet"
102: self.response+="""<h1><a href="downloadSet?fn=%s">Click here for download ( %i Byte)</a></h1>\n"""%(tmpFn,len)
103: self.response+="""<p>The file you receive is a tar (gnutar) compressed file, after unpacking you will find a new folder <emph>tmp</emph> where the files are stored in.</p>"""
104: self.response+="""<p>The file will be stored for a while, you can download it later, the URL is:</p>
105: <p><a href="downloadSet?fn=%s">%s?fn=%s</a></h1>\n"""%(tmpFn,downloadUrl,tmpFn)
106:
107: self.done=True
108:
109:
110: def getResult(self):
111: """get result"""
112: return self.response
113:
114: def isDone(self):
115: if self.done:
116: return True
117: else:
118: return False
119:
120:
121: class extVersionedFileFolder(Folder,ECHO_basis):
122: """Folder with versioned files"""
123: meta_type = "extVersionedFileFolder"
124:
125: security= ClassSecurityInfo()
126: security.declareProtected('AUTHENTICATED_USER','addFileForm')
127:
128: file_meta_type=['extVersionedFile']
129:
130: if ECHO_basis:
131: optTMP= Folder.manage_options+ECHO_basis.manage_options
132: else:
133: optTMP= Folder.manage_options
134:
135: manage_options =optTMP+(
136: {'label':'Generate Index.html','action':'generateIndexHTML'},
137: {'label':'Generate Image Index.html','action':'generateIndexHTML_image'},
138: {'label':'Generate history_template.html','action':'generateHistoryHTML'},
139: {'label':'Import directory','action':'importFolderForm'},
140: {'label':'Export as file','action':'exportFolder'},
141: {'label':'Import versionedFileFolder','action':'importVersionedFileFolderForm'},
142: {'label':'Position of version number','action':'changeHistoryFileNamesForm'},
143: )
144:
145:
146: def redirect(self,RESPONSE,url):
147: """mache ein redirect mit einem angehaengten time stamp um ein reload zu erzwingen"""
148:
149: timeStamp=time.time()
150:
151: if url.find("?")>-1: #giebt es schon parameter
152: addStr="&time=%s"
153: else:
154: addStr="?time=%s"
155:
156: RESPONSE.setHeader('Last-Modified',email.Utils.formatdate().split("-")[0]+'GMT')
157: logging.error(email.Utils.formatdate()+' GMT')
158: RESPONSE.redirect(url+addStr%timeStamp)
159:
160: def changeHistoryFileNamesForm(self):
161: """change position of version num"""
162: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeHistoryFileNamesForm.zpt')).__of__(self)
163: return pt()
164:
165:
166: def changeHistoryFileNames(self,positionVersionNum="front",RESPONSE=None):
167: """change position of version num"""
168: versions=self.ZopeFind(self,obj_metatypes=['extVersionedFileObject'],search_sub=1)
169:
170: if not (getattr(self,'positionVersionNum','front')==positionVersionNum):
171:
172: for version in versions:
173:
174: if positionVersionNum=="front":
175:
176: titleTmp=os.path.splitext(version[1].title)
177: titleTmp2="_".join(titleTmp[0].split("_")[0:-1])
178: if len(titleTmp)>1:
179: id=titleTmp[0].split("_")[-1]+"_"+titleTmp2+"."+titleTmp[1]
180: else:
181: id=titleTmp[0].split("_")[-1]+"_"+titleTmp2
182:
183: else:
184: titleTmp="_".join(version[1].getId().split("_")[1:])
185: tmp=os.path.splitext(titleTmp)
186: if len(tmp)>1:
187: id=tmp[0]+"_"+version[1].getId().split("_")[0]+tmp[1]
188: else:
189: id=tmp[0]+"_"+version[1].getId().split("_")[0]
190:
191: version[1].aq_parent.manage_renameObjects(ids=[version[1].getId()],new_ids=[id])
192: version[1].title=id
193:
194: self.positionVersionNum=positionVersionNum
195: if RESPONSE:
196: RESPONSE.redirect("manage_main")
197:
198:
199:
200: def importFolderForm(self):
201: """form fuer folder import"""
202: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','importFolderForm.zpt')).__of__(self)
203: return pt()
204:
205: def importFolder(self,path,comment="",author=None,lockedBy=None,RESPONSE=None):
206: """import contents of a folder on the server"""
207: for fileName in os.listdir(path):
208: fn = os.path.join(path,fileName)
209: if os.path.isfile(fn):
210: f = file(fn)
211: self.addFile(vC=comment, file=f, author=author)
212:
213: if RESPONSE:
214: RESPONSE.redirect(self.REQUEST['URL1'])
215:
216: def importVersionedFileFolderForm(self):
217: """form fuer versionedFileFolder import"""
218: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','importVersionedFileFolderForm.zpt')).__of__(self)
219: return pt()
220:
221: def importVersionedFileFolder(self,path,RESPONSE=None):
222: """import contents of a versionedFileFolder on the server"""
223: vff = getattr(self.aq_parent, path, None)
224: if vff is None:
225: return "SORRY, unable to import %s"%path
226:
227: tmpPath=tempfile.mktemp()
228: if not os.path.exists(tempfile.tempdir):
229: os.mkdir(tempfile.tempdir)
230:
231: if not os.path.exists(tmpPath):
232: os.mkdir(tmpPath)
233:
234: for (vfn, vf) in vff.getVersionedFiles():
235: if vf.meta_type == 'versionedFile':
236: logging.error("importvff: importing %s of type %s!"%(vfn,vf.meta_type))
237: title = vf.title
238: fob = vf.getLastVersion()
239: author = fob.getLastEditor()
240: vc = fob.getVersionComment()
241: # save file to filesystem
242: savePath=os.path.join(tmpPath,title)
243: fh=file(savePath,"w")
244: data = vf.getLastVersion().data
245: if isinstance(data, str):
246: # simple data object
247: fh.write(data)
248: else:
249: # chained data objects
250: while data is not None:
251: fh.write(data.data)
252: data = data.next
253: fh.close()
254: # and read in again
255: fh = file(savePath)
256: logging.error("importvff: comment=%s author=%s!"%(vc,author))
257: self.addFile(vC=vc, file=fh, author=author)
258: # copy more fields
259: newfob = getattr(self, vfn).getContentObject()
260: newfob.vComment = fob.vComment
261: newfob.time = fob.time
262: logging.error("importvff: vc=%s time=%s of %s!"%(fob.vComment,fob.time,fob.getId()))
263:
264: else:
265: logging.error("importvff: unable to import %s of type %s!"%(vfn,vf.meta_type))
266:
267: shutil.rmtree(tmpPath)
268:
269: if RESPONSE:
270: RESPONSE.redirect(self.REQUEST['URL1'])
271:
272: zipThreads={}
273: zipThreads2={}
274:
275: def refreshTxt(self):
276: """txt fuer refresh"""
277: tn=self.REQUEST.SESSION['threadName']
278: return """ 2;url=%s?repeat=%s """%(self.absolute_url()+"/exportFolder",tn)
279:
280: def exportFolder(self,repeat=None):
281: """exportiert alle akutellen files des folders"""
282: threadName=repeat
283:
284: downloadZip=generateDownloadZip(self,self.absolute_url())
285: downloadZip()
286: return downloadZip.getResult()
287:
288: ## if not threadName or threadName=="":
289: ## threadStart=generateDownloadZip(self,self.absolute_url())
290: ## thread=Thread(target=threadStart)
291:
292: ## thread.start()
293:
294:
295: ## self.zipThreads[thread.getName()[0:]]=threadStart
296: ## self.zipThreads2[thread.getName()[0:]]=thread
297: ## self.REQUEST.SESSION['threadName']=thread.getName()[0:]
298: ## wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['zip_wait_template'])
299: ## if wait_template:
300: ## return wait_template[0][1]()
301: ## pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait.zpt')).__of__(self)
302: ## return pt()
303:
304: ## else:
305: ## self.REQUEST.SESSION['threadName']=threadName
306:
307: ## if (self.zipThreads[threadName].getResult()==None):
308:
309: ## wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
310: ## if wait_template:
311: ## return wait_template[0][1]()
312:
313: ## pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait.zpt')).__of__(self)
314: ## return pt()
315: ## else:
316: ## if self.zipThreads[threadName].isDone():
317: ## self.REQUEST.SESSION['result']=self.zipThreads[threadName].getResult()
318: ## self.zipThreads2[threadName].join()
319: ## del(self.zipThreads2[threadName])
320: ## del(self.zipThreads[threadName])
321: ## pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_result.zpt')).__of__(self)
322: ## return pt()
323:
324: ## else:
325: ## self.REQUEST.SESSION['result']=self.zipThreads[threadName].getResult()
326: ## self.REQUEST.SESSION['threadName']=threadName
327: ## pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait_result.zpt')).__of__(self)
328: ## return pt()
329:
330: def downloadSet(self,fn):
331: """download prepared set"""
332: filename=os.path.join(tdir,fn)
333:
334:
335: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename="%s" """%"downloadFileFolder.tgz")
336: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
337: len=os.stat(filename)[6]
338: self.REQUEST.RESPONSE.setHeader("Content-Length",len)
339: images=file(filename).read()
340: self.REQUEST.RESPONSE.write(images)
341: self.REQUEST.RESPONSE.close()
342:
343:
344:
345: def helpDownload(self):
346: """download help"""
347:
348: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','helpDownload')).__of__(self)
349: return pt()
350:
351: def generateIndexHTML_image(self,RESPONSE=None):
352: """lege standard index.html an"""
353:
354:
355: if not self.ZopeFind(self,obj_ids=['index.html']):
356: zt=ZopePageTemplate('index.html')
357: self._setObject('index.html',zt)
358: default_content_fn = os.path.join(package_home(globals()),
359: 'zpt/versionFileFolderMain_image.zpt')
360: text = open(default_content_fn).read()
361: zt.pt_edit(text, 'text/html')
362:
363: else:
364: return "already exists!"
365:
366: if RESPONSE is not None:
367: RESPONSE.redirect('manage_main')
368:
369:
370: def generateAddFileForm(self,RESPONSE=None):
371: """lege standard addfileform an"""
372: #TODO: write generateaddfileform only a dummy at them moment
373:
374: if not self.ZopeFind(self,obj_ids=['addFileForm.dtml']):
375: zt=ZopePageTemplate('index.html')
376: self._setObject('index.html',zt)
377: default_content_fn = os.path.join(package_home(globals()),
378: 'zpt/versionFileFolderMain.zpt')
379: text = open(default_content_fn).read()
380: zt.pt_edit(text, 'text/html')
381:
382: else:
383: return "already exists!"
384:
385: if RESPONSE is not None:
386: RESPONSE.redirect('manage_main')
387:
388:
389: def generateIndexHTML(self,RESPONSE=None):
390: """lege standard index.html an"""
391: if not self.ZopeFind(self,obj_ids=['index.html']):
392: zt=ZopePageTemplate('index.html')
393: self._setObject('index.html',zt)
394: default_content_fn = os.path.join(package_home(globals()),
395: 'zpt/versionFileFolderMain.zpt')
396: text = open(default_content_fn).read()
397: zt.pt_edit(text, 'text/html')
398:
399: else:
400: return "already exists!"
401:
402: if RESPONSE is not None:
403: RESPONSE.redirect('manage_main')
404:
405:
406: def generateHistoryHTML(self,RESPONSE=None):
407: """lege standard index.html an"""
408: if not self.ZopeFind(self,obj_ids=['history_template.html']):
409: zt=ZopePageTemplate('history_template.html')
410: self._setObject('history_template.html',zt)
411: default_content_fn = os.path.join(package_home(globals()),
412: 'zpt/versionHistory.zpt')
413: text = open(default_content_fn).read()
414: zt.pt_edit(text, 'text/html')
415:
416: else:
417: return "already exists!"
418:
419: if RESPONSE is not None:
420: RESPONSE.redirect('manage_main')
421:
422:
423: def getVersionedFiles(self,sortField='title'):
424: """get all versioned files"""
425:
426: def sortName(x,y):
427: return cmp(x[1].title.lower(),y[1].title.lower())
428:
429: def sortDate(x,y):
430:
431: return cmp(y[1].getContentObject().getTime(),x[1].getContentObject().getTime())
432:
433: def sortComment(x,y):
434: try:
435: xc=getattr(x[1],'comment','ZZZZZZZZZZZZZ').lower()
436: except:
437: xc='ZZZZZZZZZZZZZ'.lower()
438:
439: try:
440: yc=getattr(y[1],'comment','ZZZZZZZZZZZZZ').lower()
441: except:
442: yc='ZZZZZZZZZZZZZ'.lower()
443:
444: if (xc=='') or (xc=='ZZZZZZZZZZZZZ'.lower()):
445: try:
446: xc=x[1].getContentObject().getVComment().lower()
447: except:
448: xc='ZZZZZZZZZZZZZ'.lower()
449:
450:
451: if (yc=='') or (yc=='ZZZZZZZZZZZZZ'.lower()):
452: try:
453: yc=y[1].getContentObject().getVComment().lower()
454: except:
455: yc='ZZZZZZZZZZZZZ'.lower()
456:
457:
458: return cmp(xc,yc)
459:
460: def sortAuthor(x,y):
461:
462: return cmp(x[1].getContentObject().lastEditor().lower(),y[1].getContentObject().lastEditor().lower())
463:
464:
465: def sortVersionComment(x,y):
466:
467: return cmp(x[1].getContentObject().getVersionComment().lower(),y[1].getContentObject().getVersionComment().lower())
468:
469: versionedFiles=self.objectItems(self.file_meta_type)
470: logging.debug("versionedfiles: %s of type %s"%(repr(versionedFiles),repr(self.file_meta_type)))
471:
472: if sortField=='title':
473: versionedFiles.sort(sortName)
474: elif sortField=='date':
475: versionedFiles.sort(sortDate)
476: elif sortField=='author':
477: versionedFiles.sort(sortAuthor)
478: elif sortField=='versioncomment':
479: versionedFiles.sort(sortVersionComment)
480: elif sortField=='comment':
481: versionedFiles.sort(sortComment)
482:
483:
484: return versionedFiles
485:
486:
487: def header_html(self):
488: """zusaetzlicher header"""
489: ext=self.ZopeFind(self,obj_ids=["header.html"])
490: if ext:
491: return ext[0][1]()
492: else:
493: return ""
494:
495:
496: security.declareProtected('View','index_html')
497: def index_html(self):
498: """main"""
499: ext=self.ZopeFind(self,obj_ids=["index.html"])
500: if ext:
501: return ext[0][1]()
502:
503: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionFileFolderMain')).__of__(self)
504: return pt()
505:
506:
507:
508: def addFileForm(self):
509: """add a file"""
510: ext=self.ZopeFind(self,obj_ids=["addFileForm.dtml"])
511: if ext:
512: return ext[0][1]('',globals(),version='1',AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)
513:
514: out=DTMLFile('dtml/newFileAdd', globals(),Kind='versionedFileObject',kind='versionedFileObject',version='1').__of__(self)
515: return out()
516:
517:
518: def addFile(self,vC,file,author='',newName='',content_type='',RESPONSE=None):
519: """ add a new file"""
520: # is file is a real file or a zope download object?
521: isRealFile = type(file) is types.FileType
522:
523: if newName=='':
524: logging.debug("fileobject: %s real:%s"%(repr(file),repr(isRealFile)))
525: if isRealFile:
526: filename = file.name
527: else:
528: filename=file.filename
529:
530: id=filename[max(filename.rfind('/'),
531: filename.rfind('\\'),
532: filename.rfind(':'),
533: )+1:]
534:
535: else:
536: id=newName
537:
538: if vC is None:
539: vC=self.REQUEST.form['vC']
540:
541: # get new extVersionedFile
542: vf = self._newVersionedFile(id,title=id)
543: logging.error("addFile id=%s vf=%s of %s"%(repr(id),repr(vf),repr(self)))
544: # add its content (and don't index)
545: self._setObject(id,vf)
546: vf=getattr(self,id)
547:
548: obj=vf.addContentObject(id,vC,author=author,file=file,content_type=content_type,from_tmp=isRealFile,index=False)
549: # add file to this folder (this should do the indexing)
550: #self._setObject(id,vf)
551:
552: try:
553: self.REQUEST.SESSION['objID']=vf.getId()
554: self.REQUEST.SESSION['objID_parent']=None
555: except:
556: pass
557:
558: if obj.getSize()==0:
559: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
560: return pt()
561:
562: if RESPONSE is not None:
563: RESPONSE.redirect(self.REQUEST['URL1'])
564:
565:
566: def _newVersionedFile(self, id, title='', lockedBy=None, author=None):
567: """factory for versioned files. to be overridden in derived classes."""
568: return extVersionedFile(id, title, lockedBy=lockedBy, author=author)
569:
570:
571: def deleteEmptyObject(self,submit,RESPONSE=None):
572: """deleteemptyobject"""
573: if submit=="delete it":
574: if self.REQUEST.SESSION['objID_parent']:
575: obj=getattr(self,self.REQUEST.SESSION['objID_parent'])
576:
577: else:
578: obj=self
579: obj.manage_delObjects([self.REQUEST.SESSION['objID']])
580:
581: RESPONSE.redirect(self.REQUEST['URL1'])
582:
583:
584: security.declareProtected('AUTHENTICATED_USER','fixVersionNumbers')
585: def fixVersionNumbers(self):
586: """fix last version number of all files"""
587: for (id,vf) in self.getVersionedFiles():
588: vf.fixVersionNumbers()
589: # recursively
590: for (id,vf) in self.objectItems(self.meta_type):
591: vf.fixVersionNumbers()
592:
593:
594: manage_addextVersionedFileFolderForm=DTMLFile('dtml/extfolderAdd', globals())
595:
596:
597: def manage_addextVersionedFileFolder(self, id, title='',
598: createPublic=0,
599: createUserF=0,
600: REQUEST=None):
601: """Add a new Folder object with id *id*.
602:
603: If the 'createPublic' and 'createUserF' parameters are set to any true
604: value, an 'index_html' and a 'UserFolder' objects are created respectively
605: in the new folder.
606: """
607: ob=extVersionedFileFolder()
608: ob.id=str(id)
609: ob.title=title
610: self._setObject(id, ob)
611: ob=self._getOb(id)
612:
613: checkPermission=getSecurityManager().checkPermission
614:
615: if createUserF:
616: if not checkPermission('Add User Folders', ob):
617: raise Unauthorized, (
618: 'You are not authorized to add User Folders.'
619: )
620: ob.manage_addUserFolder()
621:
622:
623: if REQUEST is not None:
624: return self.manage_main(self, REQUEST, update_menu=1)
625:
626:
627:
628: class extVersionedFileObject(ExtFile):
629: """File Object im Folder"""
630: security= ClassSecurityInfo()
631: meta_type = "extVersionedFileObject"
632:
633: manage_editForm=DTMLFile('dtml/fileEdit',globals(),
634: Kind='File',kind='file')
635: manage_editForm._setName('manage_editForm')
636:
637: def __init__(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
638: """Initialize a new instance of extVersionedFileObject (taken from ExtFile)"""
639: ExtFile.__init__(self,id,title)
640: self.versionNumber = versionNumber
641: self.versionComment= versionComment
642: self.time = time
643: self.author = author
644:
645: security.declareProtected('manage','changeObject')
646: def changeObject(self,**args):
647: """modify any of the objects attributes"""
648: for arg in args:
649: if hasattr(self, arg):
650: logging.debug("changeObject %s: %s=%s"%(repr(self),arg,args[arg]))
651: setattr(self, arg, args[arg])
652:
653: security.declarePublic('getTitle')
654: def getTitle(self):
655: """get title"""
656: return self.title
657:
658: def getData(self):
659: """returns object content (calls ExtFile.index_html)"""
660: #logging.debug("+++++++getData1:"+repr(self.get_filename()))
661: filename = self.get_filename()
662: #return ExtFile.index_html(self)
663: try:
664: logging.info("readfile:"+filename)
665: return file(filename).read()
666: except:
667: logging.info("cannot readfile:"+filename)
668: return ExtFile.index_html(self)
669:
670:
671: def getFileName(self):
672: """return filename"""
673: return self.get_filename()
674:
675: def addToFile(self,filehandle):
676: filehandle.write(self.getData())
677:
678: def addToFile2(self,filename):
679: str="cat %s > %s"%(self.get_filename(),filename)
680: os.popen(str)
681:
682: security.declarePublic('getVComment')
683: def getVComment(self):
684: """get the comment of this file"""
685: if not hasattr(self,'vComment') or (not self.vComment) or (self.vComment.lstrip()==""):
686: return "Add comment"
687:
688: else:
689: return self.vComment
690:
691: def manageVCommentForm(self):
692: """add a comment"""
693: self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
694: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addVComment')).__of__(self)
695: return pt()
696:
697: def manageVComment(self,text,comment_author,submit,REQUEST=None):
698: """manage comments"""
699: if submit =='change':
700: if text=='':
701: self.vComment=None
702: else:
703: self.vComment=text
704: self.vComment_author=comment_author
705:
706: self.vComment_date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
707:
708: if self.REQUEST.SESSION.has_key('refer'):
709:
710: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
711: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url()+"/history")
712:
713:
714: security.declarePublic('getVersionComment')
715: def getVersionComment(self):
716: """getversioncomment"""
717: return self.versionComment
718:
719: security.declarePublic('getTime')
720: def getTime(self):
721: """getTime"""
722: #return self.bobobase_modification_time().ISO()
723: if hasattr(self,'time'):
724: return time.strftime("%Y-%m-%d %H:%M:%S",self.time)
725: elif hasattr(self,'timefixed'):
726: return self.timefixed
727: else:
728: setattr(self,'timefixed',self.bobobase_modification_time().ISO())
729: return self.bobobase_modification_time().ISO()
730:
731: def download(self,REQUEST=None,RESPONSE=None):
732: """download and lock"""
733:
734: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getId())
735: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
736: #try:
737: # txt=self.index_html()
738: #except:
739: # txt=self.index_html(REQUEST,RESPONSE)
740: #
741: #self.REQUEST.RESPONSE.setHeader("Content-Length","str(len(txt)+1000)")
742:
743: self.content_type="application/octet-stream"
744: return self.getData()
745: #self.REQUEST.RESPONSE.redirect(self.absolute_url())
746: #txt=urllib.urlopen(self.absolute_url()).read()
747: #self.REQUEST.RESPONSE.write(txt)
748:
749:
750: #self.REQUEST.close()
751:
752: view = download
753:
754: security.declareProtected('AUTHENTICATED_USER','downloadLocked')
755: def downloadLocked(self):
756: """download and lock"""
757: if repr(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
758: return "please login first"
759: if (not ((self.aq_parent.lockedBy=="") or (self.aq_parent.lockedBy==None))):
760: return "cannot be locked because is already locked by %s"%self.lockedBy
761: self.aq_parent.lockedBy=self.REQUEST['AUTHENTICATED_USER']
762:
763: self.content_type="application/octet-stream"
764: self.REQUEST.RESPONSE.redirect(self.absolute_url())
765:
766: security.declarePublic('getVersionNumber')
767: def getVersionNumber(self):
768: """get version"""
769: return self.versionNumber
770:
771: security.declarePublic('getVersionComment')
772:
773:
774: security.declarePublic('lastEditor')
775: def lastEditor(self):
776: """last Editor"""
777: if hasattr(self,'author'):
778: try:
779: ret=self.author.replace("-","\n")
780: except:#old version of versionded file sometimes stored the user object and not only the name the following corrects this
781: ret=str(self.author).replace("-","\n")
782: ret=ret.replace("\r","\n")
783: return ret.lstrip().rstrip()
784:
785: else:
786: jar=self._p_jar
787: oid=self._p_oid
788:
789: if jar is None or oid is None: return None
790:
791: return jar.db().history(oid)[0]['user_name']
792:
793:
794: manage_addextVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='extVersionedFileObject',kind='extVersionedFileObject', version='1')
795:
796: def manage_addextVersionedFileObject(self,id,vC='',author='', file='',title='',versionNumber=0,
797: precondition='', content_type='', REQUEST=None):
798: """Add a new File object.
799:
800: Creates a new File object 'id' with the contents of 'file'"""
801:
802: id=str(id)
803: title=str(title)
804: content_type=str(content_type)
805: precondition=str(precondition)
806:
807: id, title = cookId(id, title, file)
808:
809: self=self.this()
810:
811: # First, we create the file without data:
812: self._setObject(id, extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=str(vC),author=author))
813: fob = self._getOb(id)
814:
815: # Now we "upload" the data. By doing this in two steps, we
816: # can use a database trick to make the upload more efficient.
817: if file:
818: fob.manage_upload(file)
819: if content_type:
820: fob.content_type=content_type
821:
822: if REQUEST is not None:
823: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
824:
825:
826:
827: class extVersionedFile(CatalogAware,Folder):
828: """Versioniertes File"""
829:
830: meta_type = 'extVersionedFile'
831: # meta_type of contained objects
832: content_meta_type = ['extVersionedFileObject']
833: # default catalog for extVersionedFile objects
834: default_catalog = 'fileCatalog'
835:
836: manage_options = Folder.manage_options+({'label':'Main Config','action':'changeVersionedFileForm'},)
837:
838:
839: security=ClassSecurityInfo()
840:
841: def __init__(self, id, title, lockedBy,author,defaultAction='history'):
842: """init"""
843: self.id=id
844: self.title=title
845: self.lockedBy=lockedBy
846: if self.lockedBy is None:
847: self.lockedBy = ''
848: self.author=author
849: self.lastVersionNumber=0
850: self.lastVersionId=None
851: self.defaultAction = defaultAction
852:
853: security.declarePublic('getTitle')
854: def getTitle(self):
855: """get title"""
856: return self.title
857:
858: def PrincipiaSearchSource(self):
859: """Return cataloguable key for ourselves."""
860: return str(self)
861:
862: def manageImagesForm(self):
863: """manage Images attached to the file"""
864:
865: self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
866:
867: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','manageImage')).__of__(self)
868: return pt()
869:
870: def manageImages(self,imageUrl=None,caption=None,REQUEST=None):
871: """manage URL"""
872: if imageUrl and (not imageUrl==""):
873: manage_AddImageZogiLib(self,libPath=imageUrl,caption=caption)
874:
875: if self.REQUEST.SESSION.has_key('refer'):
876:
877: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
878: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
879:
880: def changeImages(self,caption=None,submit=None,id=None,REQUEST=None):
881: """manage URL"""
882: if submit=="change caption":
883: image=self.ZopeFind(self,obj_ids=[id])
884: if image:
885: image[0][1].caption=caption[0:]
886:
887: elif submit=="delete":
888: image=self.ZopeFind(self,obj_ids=[id])
889: if image:
890: self.manage_delObjects([image[0][1].getId()])
891:
892: if self.REQUEST.SESSION.has_key('refer'):
893: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
894:
895: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
896:
897: def getImages(self):
898: """get Images"""
899: images=self.ZopeFind(self,obj_metatypes=["ImageZogiLib"])
900: if not images:
901: return None
902: else:
903: return images
904:
905: security.declarePublic('getComment')
906: def getComment(self):
907: """get the comment of this file"""
908: if not hasattr(self,'comment') or (not self.comment) or (self.comment.lstrip()==""):
909: return "Add comment"
910: else:
911: return self.comment
912:
913: def manageCommentForm(self):
914: """add a comment"""
915: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addComment')).__of__(self)
916: return pt()
917:
918: def manageComment(self,text,comment_author,submit,REQUEST=None):
919: """manage comments"""
920: if submit =='change':
921: if text=='':
922: self.comment=None
923: else:
924: self.comment=text
925: self.comment_author=comment_author
926:
927: self.comment_date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
928:
929: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
930:
931: security.declarePublic('getLastChangeDate')
932: def getLastChangeDate(self):
933: """get last change date"""
934: lv=self.getContentObject()
935: if lv:
936: time=lv.getTime()
937: return time
938: return None
939:
940: def getLastEditor(self):
941: """get last change date"""
942: lv=self.getContentObject()
943: le=lv.lastEditor()
944: return le
945:
946: def getLockedBy(self):
947: """get locked by"""
948: if self.lockedBy is None:
949: self.lockedBy = ''
950: return str(self.lockedBy)
951:
952: def getLastVersionNumber(self):
953: """returns the highest version number of all included objects"""
954: lv = self.findLastVersion()
955: if lv:
956: return lv.getVersionNumber()
957: else:
958: return 0
959:
960: def findLastVersion(self):
961: """finds and returns the object with the highest version number"""
962: lvn=0
963: lv=None
964:
965: for v in self.objectValues(self.content_meta_type):
966: logging.debug("findlastversion: check %s"%v.getId())
967: if v.getVersionNumber() > lvn:
968: lvn=v.getVersionNumber()
969: lv=v
970:
971: if lv:
972: logging.debug("findlastversion: got %s"%lv.getId())
973: return lv
974:
975: security.declarePublic('getLastVersion')
976: def getLastVersion(self):
977: """Last Version (old)"""
978: # tmp=0
979: # lv=None
980: #
981: # for v in self.objectValues(self.content_meta_type):
982: # #logging.debug("getlastversion: check %s"%v.getId())
983: # if v.getVersionNumber() > tmp:
984: # tmp=v.getVersionNumber()
985: # lv=v
986: #
987: # #ogging.debug("getlastversion: got %s"%lv.getId())
988: # return lv
989: return self.getContentObject();
990:
991: def getContentObject(self):
992: """returns the last version object"""
993: if (not getattr(self, 'lastVersionId', None)) or (not getattr(self, self.lastVersionId, None)):
994: # find last version and save it
995: lv = self.findLastVersion()
996: if lv is None:
997: return None
998: self.lastVersionNumber = lv.getVersionNumber()
999: self.lastVersionId = lv.getId()
1000: return getattr(self, self.lastVersionId, None)
1001:
1002: security.declarePublic('getData')
1003: def getData(self):
1004: """Returns the content of the last version"""
1005: logging.debug("+++++++getData2")
1006: ob = self.getContentObject()
1007: if ob is not None:
1008: return ob.getData()
1009: else:
1010: return None
1011:
1012: security.declarePublic('view')
1013: def view(self,REQUEST=None,RESPONSE=None):
1014: """Returns the last version's view"""
1015: ob = self.getContentObject()
1016: if ob is not None:
1017: return ob.view(REQUEST=REQUEST,RESPONSE=RESPONSE)
1018: else:
1019: return None
1020:
1021: def diff(self,data):
1022: """differenz between lastversion and data"""
1023: d=Differ()
1024: tmp=self.getData()
1025: #print "XX",data,tmp
1026: try:
1027: l=list(d.compare(data.splitlines(1),tmp.splitlines(1)))
1028: except:
1029: return 0,""
1030: plus=0
1031: minus=0
1032: for a in l:
1033: if a[0]=='+':
1034: plus+=1
1035: if a[0]=='-':
1036: minus+=1
1037:
1038: return max([plus,minus]),l
1039:
1040:
1041: security.declarePublic('index_html')
1042: def index_html(self,REQUEST=None, RESPONSE=None):
1043: """main view"""
1044: #lastVersion=self.getContentObject()
1045: #return "File:"+self.title+" Version:%i"%lastVersion.versionNumber," modified:",lastVersion.bobobase_modification_time()," size:",lastVersion.getSize(),"modified by:",lastVersion.lastEditor()
1046: #return "File: %s Version:%i modified:%s size:%s modified by:%s"%(self.title,lastVersion.versionNumber,lastVersion.getTime(),lastVersion.getSize(),lastVersion.lastEditor())
1047: act = getattr(self, 'defaultAction', 'history')
1048: if act == 'download':
1049: return self.getContentObject().download()
1050: elif act == 'view':
1051: #return self.getContentObject().download()
1052: return self.getContentObject().index_html(REQUEST=REQUEST, RESPONSE=RESPONSE)
1053: else:
1054: return self.history()
1055:
1056: def getVersionNr(self,nr):
1057: """get version with number nr"""
1058: tmp=0
1059: lastVersion=None
1060: for version in self.ZopeFind(self):
1061: if hasattr(version[1],'versionNumber'):
1062: if int(version[1].versionNumber) ==nr :
1063: return version[1]
1064:
1065: return None
1066:
1067: security.declarePublic('getVersion')
1068: def getVersion(self):
1069: # TODO: this is ugly and it returns the next version number
1070: tmp=0
1071: for version in self.ZopeFind(self):
1072:
1073: if hasattr(version[1],'versionNumber'):
1074:
1075: if int(version[1].versionNumber) > tmp:
1076: tmp=int(version[1].versionNumber,)
1077: return tmp+1
1078:
1079: def history(self):
1080: """history"""
1081: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
1082: if ext:
1083: return getattr(self,ext[0][1].getId())()
1084:
1085: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionHistory')).__of__(self)
1086: return pt()
1087:
1088: def getVersions(self):
1089: """get all versions"""
1090: ret=[]
1091: for version in self.ZopeFind(self):
1092: if hasattr(version[1],'versionNumber'):
1093: ret.append((version[1].versionNumber,version[1]))
1094: ret.sort(sortv)
1095: return ret
1096:
1097: def getVersionList(self):
1098: """get a list of dicts with author, comment, filename, etc, of all versions"""
1099: vl = []
1100: for v in self.objectValues(self.content_meta_type):
1101: vl.append({'versionNumber':getattr(v,'versionNumber',0),
1102: 'title':v.getTitle(),
1103: 'id':v.getId(),
1104: 'date':v.getTime(),
1105: 'author':getattr(v,'author',''),
1106: 'comment':getattr(v,'versionComment','')
1107: })
1108: return vl
1109:
1110: security.declareProtected('AUTHENTICATED_USER','forceunlock')
1111: def forceunlock(self,RESPONSE=None,user=None):
1112: """unlock"""
1113: #safe who had the lock
1114: logging.debug("extVersionFile: (forceunlock)"+str(user))
1115: if self.lockedBy:
1116: if user is not None:
1117: if str(self.lockedBy)==user:
1118: self.brokenLock=str(self.lockedBy)
1119: self.lockedBy=''
1120: else:
1121: self.brokenLock=""
1122: else:
1123: self.brokenLock=str(self.lockedBy)
1124: self.lockedBy=''
1125: else:
1126: self.brokenLock=""
1127:
1128: return self.brokenLock
1129:
1130: security.declareProtected('AUTHENTICATED_USER','unlock')
1131: def unlock(self,RESPONSE):
1132: """unlock"""
1133: if str(self.lockedBy) in [str(self.REQUEST['AUTHENTICATED_USER'])]:
1134: self.lockedBy=''
1135: RESPONSE.redirect(self.REQUEST['HTTP_REFERER'])
1136: else:
1137: return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER'])
1138:
1139:
1140:
1141: def _newContentObject(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
1142: """factory for content objects. to be overridden in derived classes."""
1143: return extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=versionComment,time=time,author=author)
1144:
1145:
1146: def addContentObject(self,id,vC,author=None,file=None,title='',changeName='no',newName='',from_tmp=False,index=True,
1147: precondition='', content_type=''):
1148: """add"""
1149:
1150: if changeName=="yes":
1151: filename=file.filename
1152: self.title=filename[max(filename.rfind('/'),
1153: filename.rfind('\\'),
1154: filename.rfind(':'),
1155: )+1:]
1156:
1157: if not newName=='':
1158: self.title=newName[0:]
1159:
1160: posVersNum=getattr(self,'positionVersionNum','front')
1161:
1162: versNum = self.getLastVersionNumber() + 1
1163:
1164: if posVersNum=='front':
1165: id="V%i_%s"%(versNum,self.title)
1166: else:
1167: fn=os.path.splitext(self.title)
1168: if len(fn)>1:
1169: id=fn[0]+"_V%i%s"%(versNum,fn[1])
1170: else:
1171: id=fn[0]+"_V%i"%versNum
1172:
1173: # what does this do?
1174: id, title = cookId(id, title, file)
1175: self=self.this()
1176:
1177: # First, we create the file without data:
1178: self._setObject(id, self._newContentObject(id,title,versionNumber=versNum,versionComment=str(vC),
1179: time=time.localtime(),author=author))
1180: fob = self._getOb(id)
1181:
1182: # Now we "upload" the data. By doing this in two steps, we
1183: # can use a database trick to make the upload more efficient.
1184: if file and not from_tmp:
1185: fob.manage_upload(file)
1186: elif file and from_tmp:
1187: fob.manage_file_upload(file) # manage_upload_from_tmp doesn't exist in ExtFile2
1188: # fob.manage_upload_from_tmp(file) # manage_upload_from_tmp doesn't exist in ExtFile2
1189: fob.content_type=content_type
1190:
1191: self.lastVersionNumber = versNum
1192: self.lastVersionId = id
1193:
1194: #logging.debug("addcontentobject: lastversion=%s"%self.getData())
1195: #logging.debug("addcontentobject: fob_data=%s"%fob.getData())
1196: if index and self.default_catalog:
1197: logging.debug("reindex1: %s in %s"%(repr(self),repr(self.default_catalog)))
1198: self.reindex_object()
1199:
1200: return fob
1201:
1202:
1203: security.declareProtected('AUTHENTICATED_USER','addVersionedFileObjectForm')
1204: def addVersionedFileObjectForm(self):
1205: """add a new version"""
1206:
1207: if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
1208: return "please login first"
1209: if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy=='') or (self.lockedBy==None):
1210: ext=self.ZopeFind(self.aq_parent,obj_ids=["addNewVersion.dtml"])
1211: if ext:
1212: return ext[0][1]('',globals(),version=self.getVersion(),lastComment=self.getContentObject().getVersionComment(),AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)
1213: else:
1214: out=DTMLFile('dtml/fileAdd', globals(),Kind='VersionedFileObject',kind='versionedFileObject',version=self.getVersion()).__of__(self)
1215: return out()
1216: else:
1217: return "Sorry file is locked by somebody else"
1218:
1219:
1220: def manage_addVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', from_tmp=False, RESPONSE=None):
1221: """add"""
1222: try: #der ganze vC unsinn muss ueberarbeitet werden
1223: vC=self.REQUEST['vC']
1224: except:
1225: pass
1226:
1227: author=self.REQUEST['author']
1228:
1229: ob = self.addContentObject(id, vC, author, file, title, changeName=changeName, newName=newName, from_tmp=from_tmp,
1230: precondition=precondition, content_type=content_type)
1231:
1232: self.REQUEST.SESSION['objID_parent']=self.getId()
1233:
1234: if RESPONSE:
1235: if ob.getSize()==0:
1236: self.REQUEST.SESSION['objID']=ob.getId()
1237: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
1238: return pt()
1239:
1240: else:
1241: RESPONSE.redirect(self.absolute_url()+'/history')
1242: else:
1243: return ob
1244:
1245:
1246: changeVersionedFileForm = PageTemplateFile('zpt/changeVersionedFile', globals())
1247:
1248: def manage_changeVersionedFile(self,title,vC,author,comment,defaultAction='history',RESPONSE=None):
1249: """Change VersionedFile metadata"""
1250: self.title = title
1251: self.author = author
1252: self.defaultAction = defaultAction
1253: cob = self.getContentObject()
1254: if cob:
1255: if vC:
1256: cob.vComment=vC
1257:
1258: if comment=='':
1259: cob.versionComment=None
1260: else:
1261: cob.versionComment=comment
1262:
1263: if RESPONSE:
1264: RESPONSE.redirect('manage_main')
1265:
1266:
1267: def download(self):
1268: """download"""
1269:
1270: txt=self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId()+'/download'
1271:
1272: self.REQUEST.RESPONSE.redirect(txt)
1273:
1274:
1275: security.declareProtected('AUTHENTICATED_USER','downloadLocked')
1276: def downloadLocked(self):
1277: """download and lock"""
1278:
1279: if repr(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
1280: return "please login first"
1281: if not ((self.lockedBy=="") or (self.lockedBy==None)):
1282: return "cannot be locked because is already locked by %s"%self.lockedBy
1283: self.lockedBy=self.REQUEST['AUTHENTICATED_USER']
1284: self.getContentObject().content_type="application/octet-stream"
1285: self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId())
1286:
1287:
1288: security.declareProtected('AUTHENTICATED_USER','fixVersionNumbers')
1289: def fixVersionNumbers(self):
1290: """check last version number and id"""
1291: if not hasattr(self, 'lastVersionId'):
1292: self.lastVersionNumber = 0
1293: self.lastVersionId = None
1294:
1295: lv = self.getContentObject()
1296: if lv is not None:
1297: lvn = lv.getVersionNumber()
1298: if lvn == 0:
1299: lvn = 1
1300: lv.versionNumber = 1
1301: self.lastVersionNumber = lvn
1302: self.lastVersionId = lv.getId()
1303: else:
1304: self.lastVersionNumber = 0
1305: self.lastVersionId = None
1306: logging.debug("fixing last version number of %s to %s (%s)"%(self.getId(),self.lastVersionNumber,self.lastVersionId))
1307:
1308:
1309: def manage_addextVersionedFileForm(self):
1310: """interface for adding the OSAS_root"""
1311: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addextVersionedFile.zpt')).__of__(self)
1312: return pt()
1313:
1314: def manage_addextVersionedFile(self,id,title,lockedBy, author=None, defaultAction='history', RESPONSE=None):
1315: """add the OSAS_root"""
1316: newObj=extVersionedFile(id,title,lockedBy,author,defaultAction=defaultAction)
1317: self._setObject(id,newObj)
1318:
1319: if RESPONSE is not None:
1320: RESPONSE.redirect('manage_main')
1321:
1322:
1323: InitializeClass(extVersionedFile)
1324: InitializeClass(extVersionedFileFolder)
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>