Annotation of versionedFile/versionedFile.py, revision 1.52
1.1 dwinter 1: from OFS.Folder import Folder
2: from OFS.Image import File
3: from OFS.Image import cookId
1.5 dwinter 4: from Globals import DTMLFile, InitializeClass,package_home
1.1 dwinter 5: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
6: from AccessControl import getSecurityManager
7: from Products.PageTemplates.PageTemplate import PageTemplate
1.5 dwinter 8: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
1.1 dwinter 9: from AccessControl import ClassSecurityInfo
1.51 dwinter 10:
11:
1.50 dwinter 12: from Products.ZCatalog.CatalogPathAwareness import CatalogAware
1.51 dwinter 13:
1.43 dwinter 14: try:
15: from Products.ImageArchive.ImageArchive import manage_AddImageZogiLib
16: except:
17: print "no images"
1.51 dwinter 18:
1.35 dwinter 19:
20: from threading import Thread
21: import shutil
22: import tempfile
1.5 dwinter 23: import os.path
1.44 dwinter 24: import urllib
1.39 dwinter 25:
1.15 dwinter 26: import time
1.19 dwinter 27: try:
28: from Products.ECHO_content.ECHO_collection import ECHO_basis
29: except:
30: print "ECHO Elements not imported"
1.20 dwinter 31: class ECHO_basis:
1.31 dwinter 32: """leer"""
33: manage_options=()
1.1 dwinter 34:
1.19 dwinter 35:
1.1 dwinter 36: def sortv(x,y):
37: return cmp(x[0],y[0])
1.37 dwinter 38: tdir = "/tmp/downloadVersionedFiles"
1.35 dwinter 39:
40: class generateDownloadZip:
41: """generateDownloadSet"""
42:
43: def __init__(self,folderObject,url):
44: """init downloadzip"""
45: self.folder=folderObject
46: self.done=None
47: self.response=""
48: self.url=url
49:
50: def __call__(self):
51: """call generate download zip"""
52: storeTempDir=tempfile.tempdir
53: tempfile.tempdir=tdir
54:
55: tmpPath=tempfile.mktemp()
56: tmpZip=tempfile.mktemp()+".gtz"
57: tmpFn=os.path.split(tmpZip)[1]
58:
59: if not os.path.exists(tempfile.tempdir):
60: os.mkdir(tempfile.tempdir)
61:
62: if not os.path.exists(tmpPath):
63: os.mkdir(tmpPath)
64:
1.37 dwinter 65: self.response="<h3>1. step: getting the files</h3>"
1.35 dwinter 66:
67: for files in self.folder.ZopeFind(self.folder,obj_metatypes=['versionedFile']):
68: lastV=files[1].getLastVersion()
69: self.response+=str("<p>Get File: %s<br>\n"%lastV.title)
70:
71: savePath=os.path.join(tmpPath,lastV.title)
72: fh=file(savePath,"w")
73: fh.write(lastV.data)
74: fh.close()
75:
76: self.response+="<h3>2. step: creating the downloadable file</h3>"
77: self.response+="<p>Create gtar<br>"
78: self.response+="<p>This can take a while....<br>\n"
79:
80: fh=os.popen2("tar zcvf %s %s/*"%(tmpZip,tmpPath),1)[1]
81: self.response+="<br>"
82: for c in fh.read():
83: self.response+=c
84: if c==")":
85: self.response+="<br>\n"
86:
87:
88:
89:
90: shutil.rmtree(tmpPath)
91:
92: self.response+="<p>finished<br>\n"
93:
94: len=os.stat(tmpZip)[6]
95: downloadUrl=self.url+"/downloadSet"
96: self.response+="""<h1><a href="downloadSet?fn=%s">Click here for download ( %i Byte)</a></h1>\n"""%(tmpFn,len)
1.36 dwinter 97: 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>"""
1.35 dwinter 98: self.response+="""<p>The file will be stored for a while, you can download it later, the URL is:</p>
99: <p><a href="downloadSet?fn=%s">%s?fn=%s</a></h1>\n"""%(tmpFn,downloadUrl,tmpFn)
100:
101: self.done=True
102:
1.1 dwinter 103:
1.35 dwinter 104: def getResult(self):
105: """get result"""
106: return self.response
107:
108: def isDone(self):
109: if self.done:
110: return True
111: else:
112: return False
113:
114:
1.19 dwinter 115: class versionedFileFolder(Folder,ECHO_basis):
1.1 dwinter 116: """Folder with versioned files"""
117:
1.14 dwinter 118:
1.1 dwinter 119: meta_type = "versionedFileFolder"
120:
121: security= ClassSecurityInfo()
122: security.declareProtected('AUTHENTICATED_USER','addFileForm')
1.50 dwinter 123: filesMetaType=['versionedFile']
1.19 dwinter 124: if ECHO_basis:
125: optTMP= Folder.manage_options+ECHO_basis.manage_options
126: else:
127: optTMP= Folder.manage_options
128:
129: manage_options =optTMP+(
1.5 dwinter 130: {'label':'Generate Index.html','action':'generateIndexHTML'},
1.39 dwinter 131: {'label':'Generate Image Index.html','action':'generateIndexHTML_image'},
1.6 dwinter 132: {'label':'Generate history_template.html','action':'generateHistoryHTML'},
1.35 dwinter 133: {'label':'Import Folder','action':'importFolderForm'},
1.36 dwinter 134: {'label':'Export Folder','action':'exportFolder'},
1.51 dwinter 135: {'label':'Position of version number','action':'changeHistoryFileNamesForm'},
1.19 dwinter 136: )
1.5 dwinter 137:
1.51 dwinter 138: def changeHistoryFileNamesForm(self):
139: """change position of version num"""
140: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeHistoryFileNamesForm.zpt')).__of__(self)
141: return pt()
142:
143:
144: def changeHistoryFileNames(self,positionVersionNum="front",RESPONSE=None):
145: """change position of version num"""
146:
147:
148:
149: versions=self.ZopeFind(self,obj_metatypes=['versionedFileObject'],search_sub=1)
150:
151: if not (getattr(self,'positionVersionNum','front')==positionVersionNum):
152:
153: for version in versions:
154:
155: if positionVersionNum=="front":
156:
157: titleTmp=os.path.splitext(version[1].title)
158: titleTmp2="_".join(titleTmp[0].split("_")[0:-1])
159: if len(titleTmp)>1:
160: id=titleTmp[0].split("_")[-1]+"_"+titleTmp2+"."+titleTmp[1]
161: else:
162: id=titleTmp[0].split("_")[-1]+"_"+titleTmp2
163:
164: else:
165: titleTmp="_".join(version[1].getId().split("_")[1:])
166: tmp=os.path.splitext(titleTmp)
167: if len(tmp)>1:
168: id=tmp[0]+"_"+version[1].getId().split("_")[0]+tmp[1]
169: else:
170: id=tmp[0]+"_"+version[1].getId().split("_")[0]
171:
172: print version[0],id
173:
174: version[1].aq_parent.manage_renameObjects(ids=[version[1].getId()],new_ids=[id])
175: version[1].title=id
176:
177:
178: self.positionVersionNum=positionVersionNum
179: if RESPONSE:
180: RESPONSE.redirect("manage_main")
181:
182:
183:
1.35 dwinter 184: def importFolderForm(self):
185: """form fuer folder import"""
186: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','importFolderForm.zpt')).__of__(self)
187: return pt()
188:
189: def importFolder(self,path,comment="",author=None,lockedBy=None,RESPONSE=None):
190: """importiere inhalt eines folders"""
191:
192: for fileName in os.listdir(path):
193: if os.path.isfile(os.path.join(path,fileName)):
194: manage_addVersionedFile(self,fileName,'','')
195: id=fileName
196: ob=self._getOb(fileName)
197: ob.title=id
198: file2=file(os.path.join(path,fileName))
199:
200: obj=ob.manage_addVersionedFileObject(id,comment,author,file2,content_type='')
201:
202: if RESPONSE:
203: RESPONSE.redirect(self.REQUEST['URL1'])
204:
205: zipThreads={}
206: zipThreads2={}
207:
208: def refreshTxt(self):
209: """txt fuer refresh"""
210: tn=self.REQUEST.SESSION['threadName']
211: return """ 2;url=%s?repeat=%s """%(self.absolute_url()+"/exportFolder",tn)
212:
213: def exportFolder(self,repeat=None):
214: """exportiert alle akutellen files des folders"""
215: threadName=repeat
216:
1.37 dwinter 217: downloadZip=generateDownloadZip(self,self.absolute_url())
218: downloadZip()
219: return downloadZip.getResult()
220: ## if not threadName or threadName=="":
221: ## threadStart=generateDownloadZip(self,self.absolute_url())
222: ## thread=Thread(target=threadStart)
1.35 dwinter 223:
1.37 dwinter 224: ## thread.start()
1.35 dwinter 225:
226:
1.37 dwinter 227: ## self.zipThreads[thread.getName()[0:]]=threadStart
228: ## self.zipThreads2[thread.getName()[0:]]=thread
229: ## self.REQUEST.SESSION['threadName']=thread.getName()[0:]
230: ## wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['zip_wait_template'])
231: ## if wait_template:
232: ## return wait_template[0][1]()
233: ## pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait.zpt')).__of__(self)
234: ## return pt()
1.35 dwinter 235:
1.37 dwinter 236: ## else:
237: ## self.REQUEST.SESSION['threadName']=threadName
1.35 dwinter 238:
1.37 dwinter 239: ## if (self.zipThreads[threadName].getResult()==None):
1.35 dwinter 240:
1.37 dwinter 241: ## wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
242: ## if wait_template:
243: ## return wait_template[0][1]()
244:
245: ## pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait.zpt')).__of__(self)
246: ## return pt()
247: ## else:
248: ## if self.zipThreads[threadName].isDone():
249: ## self.REQUEST.SESSION['result']=self.zipThreads[threadName].getResult()
250: ## self.zipThreads2[threadName].join()
251: ## del(self.zipThreads2[threadName])
252: ## del(self.zipThreads[threadName])
253: ## pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_result.zpt')).__of__(self)
254: ## return pt()
255:
256: ## else:
257: ## self.REQUEST.SESSION['result']=self.zipThreads[threadName].getResult()
258: ## self.REQUEST.SESSION['threadName']=threadName
259: ## pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait_result.zpt')).__of__(self)
260: ## return pt()
1.35 dwinter 261:
262: def downloadSet(self,fn):
263: """download prepared set"""
264: filename=os.path.join(tdir,fn)
265:
266:
1.38 dwinter 267: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename="%s" """%"downloadFileFolder.tgz")
1.35 dwinter 268: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
269: len=os.stat(filename)[6]
270: self.REQUEST.RESPONSE.setHeader("Content-Length",len)
271: images=file(filename).read()
272: self.REQUEST.RESPONSE.write(images)
273: self.REQUEST.RESPONSE.close()
274:
275:
276:
1.14 dwinter 277: def helpDownload(self):
278: """download help"""
279:
1.19 dwinter 280: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','helpDownload')).__of__(self)
1.14 dwinter 281: return pt()
282:
1.39 dwinter 283: def generateIndexHTML_image(self,RESPONSE=None):
284: """lege standard index.html an"""
285:
286:
287: if not self.ZopeFind(self,obj_ids=['index.html']):
288: zt=ZopePageTemplate('index.html')
289: self._setObject('index.html',zt)
290: default_content_fn = os.path.join(package_home(globals()),
291: 'zpt/versionFileFolderMain_image.zpt')
292: text = open(default_content_fn).read()
293: zt.pt_edit(text, 'text/html')
294:
295: else:
296: return "already exists!"
297:
298: if RESPONSE is not None:
299: RESPONSE.redirect('manage_main')
300:
1.5 dwinter 301: def generateIndexHTML(self,RESPONSE=None):
302: """lege standard index.html an"""
303:
304:
1.22 dwinter 305: if not self.ZopeFind(self,obj_ids=['index.html']):
1.5 dwinter 306: zt=ZopePageTemplate('index.html')
307: self._setObject('index.html',zt)
308: default_content_fn = os.path.join(package_home(globals()),
309: 'zpt/versionFileFolderMain.zpt')
310: text = open(default_content_fn).read()
311: zt.pt_edit(text, 'text/html')
312:
313: else:
314: return "already exists!"
315:
316: if RESPONSE is not None:
317: RESPONSE.redirect('manage_main')
318:
1.6 dwinter 319:
320: def generateHistoryHTML(self,RESPONSE=None):
321: """lege standard index.html an"""
322:
1.5 dwinter 323:
1.6 dwinter 324:
1.22 dwinter 325: if not self.ZopeFind(self,obj_ids=['history_template.html']):
1.6 dwinter 326: zt=ZopePageTemplate('history_template.html')
327: self._setObject('history_template.html',zt)
328: default_content_fn = os.path.join(package_home(globals()),
329: 'zpt/versionHistory.zpt')
330: text = open(default_content_fn).read()
331: zt.pt_edit(text, 'text/html')
332:
333: else:
334: return "already exists!"
335:
336: if RESPONSE is not None:
337: RESPONSE.redirect('manage_main')
338:
1.32 dwinter 339:
340:
341:
1.12 dwinter 342: def getVersionedFiles(self,sortField='title'):
1.1 dwinter 343: """get all versioned files"""
1.12 dwinter 344:
345: def sortName(x,y):
1.18 dwinter 346: return cmp(x[1].title.lower(),y[1].title.lower())
1.12 dwinter 347:
348: def sortDate(x,y):
1.17 dwinter 349: return cmp(y[1].getLastVersion().getTime(),x[1].getLastVersion().getTime())
1.12 dwinter 350:
1.32 dwinter 351:
1.30 dwinter 352: def sortComment(x,y):
1.34 dwinter 353:
354:
355:
1.31 dwinter 356: try:
1.34 dwinter 357: xc=getattr(x[1],'comment','ZZZZZZZZZZZZZ').lower()
1.31 dwinter 358: except:
1.34 dwinter 359: xc='ZZZZZZZZZZZZZ'.lower()
1.31 dwinter 360: try:
1.34 dwinter 361: yc=getattr(y[1],'comment','ZZZZZZZZZZZZZ').lower()
1.31 dwinter 362: except:
1.34 dwinter 363: yc='ZZZZZZZZZZZZZ'.lower()
364:
365:
366: if (xc=='') or (xc=='ZZZZZZZZZZZZZ'.lower()):
367:
368: try:
369: xc=x[1].getLastVersion().getVComment().lower()
370: except:
371: xc='ZZZZZZZZZZZZZ'.lower()
372:
373: if (yc=='') or (yc=='ZZZZZZZZZZZZZ'.lower()):
374: try:
375: yc=y[1].getLastVersion().getVComment().lower()
376: except:
377: yc='ZZZZZZZZZZZZZ'.lower()
378:
379:
380: return cmp(xc,yc)
1.31 dwinter 381:
1.12 dwinter 382: def sortAuthor(x,y):
1.13 dwinter 383:
1.30 dwinter 384: return cmp(x[1].getLastVersion().lastEditor().lower(),y[1].getLastVersion().lastEditor().lower())
1.3 dwinter 385:
1.50 dwinter 386: versionedFiles=self.ZopeFind(self,obj_metatypes=self.filesMetaType)
387:
388:
1.12 dwinter 389: if sortField=='title':
390: versionedFiles.sort(sortName)
391: elif sortField=='date':
392: versionedFiles.sort(sortDate)
393: elif sortField=='author':
394: versionedFiles.sort(sortAuthor)
1.30 dwinter 395: elif sortField=='comment':
396: versionedFiles.sort(sortComment)
1.12 dwinter 397:
1.1 dwinter 398: return versionedFiles
399:
1.4 dwinter 400:
401: def header_html(self):
402: """zusätzlicher header"""
403: ext=self.ZopeFind(self,obj_ids=["header.html"])
404: if ext:
405: return ext[0][1]()
406: else:
407: return ""
1.41 dwinter 408:
409:
410: security.declareProtected('View','index_html')
1.1 dwinter 411: def index_html(self):
412: """main"""
1.4 dwinter 413: ext=self.ZopeFind(self,obj_ids=["index.html"])
414: if ext:
1.5 dwinter 415: return ext[0][1]()
1.4 dwinter 416:
1.19 dwinter 417: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionFileFolderMain')).__of__(self)
1.1 dwinter 418: return pt()
419:
420:
421: def addFileForm(self):
422: """add a file"""
1.21 dwinter 423: ext=self.ZopeFind(self,obj_ids=["addFileForm.dtml"])
424: if ext:
425: return ext[0][1]('',globals(),version='1',AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)
426:
1.1 dwinter 427: out=DTMLFile('dtml/newFileAdd', globals(),Kind='VersionedFileObject',kind='versionedFileObject',version='1').__of__(self)
428: return out()
429:
430:
1.11 dwinter 431: def addFile(self,vC,file,author,newName='',content_type='',RESPONSE=None):
1.1 dwinter 432: """ add a new file"""
1.11 dwinter 433: if newName=='':
1.24 dwinter 434: filename=file.filename
435: id=filename[max(filename.rfind('/'),
436: filename.rfind('\\'),
437: filename.rfind(':'),
438: )+1:]
1.25 dwinter 439:
1.11 dwinter 440: else:
441: id=newName
1.1 dwinter 442:
443: vC=self.REQUEST.form['vC']
444: manage_addVersionedFile(self,id,'','')
1.21 dwinter 445: #if (getattr(self,'commentNonEmpty',0)==1) and vC.strip()=="":
446:
447:
1.1 dwinter 448: ob=self._getOb(id)
449: ob.title=id
1.3 dwinter 450: file2=file
1.23 dwinter 451:
452: obj=ob.manage_addVersionedFileObject(id,vC,author,file2,content_type=content_type)
1.27 dwinter 453: self.REQUEST.SESSION['objID']=ob.getId()
454: self.REQUEST.SESSION['objID_parent']=None
1.1 dwinter 455:
1.23 dwinter 456: if obj.getSize()==0:
457: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
458: return pt()
459:
1.1 dwinter 460: RESPONSE.redirect(self.REQUEST['URL1'])
461:
1.27 dwinter 462:
463: def deleteEmptyObject(self,submit,RESPONSE=None):
464: """deleteemptyobject"""
465: if submit=="delete it":
466: if self.REQUEST.SESSION['objID_parent']:
467: obj=getattr(self,self.REQUEST.SESSION['objID_parent'])
468:
469: else:
470: obj=self
471: obj.manage_delObjects([self.REQUEST.SESSION['objID']])
472:
473: RESPONSE.redirect(self.REQUEST['URL1'])
474:
1.1 dwinter 475:
476: manage_addVersionedFileFolderForm=DTMLFile('dtml/folderAdd', globals())
477:
478:
479: def manage_addVersionedFileFolder(self, id, title='',
480: createPublic=0,
481: createUserF=0,
482: REQUEST=None):
483: """Add a new Folder object with id *id*.
484:
485: If the 'createPublic' and 'createUserF' parameters are set to any true
486: value, an 'index_html' and a 'UserFolder' objects are created respectively
487: in the new folder.
488: """
489: ob=versionedFileFolder()
490: ob.id=str(id)
491: ob.title=title
492: self._setObject(id, ob)
493: ob=self._getOb(id)
494:
495: checkPermission=getSecurityManager().checkPermission
496:
497: if createUserF:
498: if not checkPermission('Add User Folders', ob):
499: raise Unauthorized, (
500: 'You are not authorized to add User Folders.'
501: )
502: ob.manage_addUserFolder()
503:
504:
505: if REQUEST is not None:
506: return self.manage_main(self, REQUEST, update_menu=1)
507:
508:
509:
510: class versionedFileObject(File):
511: """File Object im Folder"""
1.50 dwinter 512: security= ClassSecurityInfo()
1.1 dwinter 513: meta_type = "versionedFileObject"
514:
515: manage_editForm =DTMLFile('dtml/fileEdit',globals(),
516: Kind='File',kind='file')
517: manage_editForm._setName('manage_editForm')
1.51 dwinter 518:
1.50 dwinter 519:
520: security.declarePublic('getVComment')
1.39 dwinter 521:
1.32 dwinter 522: def getVComment(self):
523: """get the comment of this file"""
524: if not hasattr(self,'vComment') or (not self.vComment) or (self.vComment.lstrip()==""):
525: return "Add comment"
526:
527: else:
528: return self.vComment
529:
530: def manageVCommentForm(self):
531: """add a comment"""
1.34 dwinter 532:
533: self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
534:
535:
536:
1.32 dwinter 537: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addVComment')).__of__(self)
538: return pt()
539:
540: def manageVComment(self,text,comment_author,submit,REQUEST=None):
541: """manage comments"""
542: if submit =='change':
543: if text=='':
544: self.vComment=None
545: else:
546: self.vComment=text
547: self.vComment_author=comment_author
548:
549: self.vComment_date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
550:
1.34 dwinter 551: if self.REQUEST.SESSION.has_key('refer'):
552:
553: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
1.32 dwinter 554: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url()+"/history")
555:
1.51 dwinter 556:
1.50 dwinter 557: security.declarePublic('getVersionComment')
558: def getVersionComment(self):
559: """getversioncomment"""
560: return self.versionComment
561:
562: security.declarePublic('getTime')
1.51 dwinter 563:
1.15 dwinter 564: def getTime(self):
565: """getTime"""
566: #return self.bobobase_modification_time().ISO()
567: if hasattr(self,'time'):
568: return time.strftime("%Y-%m-%d %H:%M:%S",self.time)
1.16 dwinter 569: elif hasattr(self,'timefixed'):
570: return self.timefixed
1.15 dwinter 571: else:
1.16 dwinter 572: setattr(self,'timefixed',self.bobobase_modification_time().ISO())
1.15 dwinter 573: return self.bobobase_modification_time().ISO()
574:
575:
576:
1.14 dwinter 577:
1.1 dwinter 578:
1.48 dwinter 579: def download(self,REQUEST=None,RESPONSE=None):
1.7 dwinter 580: """download and lock"""
581:
1.33 dwinter 582: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getId())
1.47 dwinter 583: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
1.49 dwinter 584: #try:
585: # txt=self.index_html()
586: #except:
587: # txt=self.index_html(REQUEST,RESPONSE)
588: #
589: #self.REQUEST.RESPONSE.setHeader("Content-Length","str(len(txt)+1000)")
590:
1.10 dwinter 591: self.content_type="application/octet-stream"
1.49 dwinter 592: self.REQUEST.RESPONSE.redirect(self.absolute_url())
1.45 dwinter 593: #txt=urllib.urlopen(self.absolute_url()).read()
1.47 dwinter 594: #self.REQUEST.RESPONSE.write(txt)
1.49 dwinter 595:
1.47 dwinter 596:
1.49 dwinter 597: #self.REQUEST.close()
1.7 dwinter 598:
599: def downloadLocked(self):
600: """download and lock"""
601:
602:
603: if self.REQUEST['AUTHENTICATED_USER']=='Anonymous User':
604: return "please login first"
605: if not self.aq_parent.lockedBy=="":
606: return "cannot be locked because is already locked by %s"%self.lockedBy
607: self.aq_parent.lockedBy=self.REQUEST['AUTHENTICATED_USER']
1.1 dwinter 608:
1.10 dwinter 609: self.content_type="application/octet-stream"
1.7 dwinter 610: self.REQUEST.RESPONSE.redirect(self.absolute_url())
611:
1.1 dwinter 612: def setVersionNumber(self,versionNumber):
613: """set version"""
614: self.versionNumber=versionNumber
615:
1.50 dwinter 616:
1.42 dwinter 617: security.declarePublic('getVersionNumber')
1.51 dwinter 618:
1.1 dwinter 619: def getVersionNumber(self):
620: """get version"""
621: return self.versionNumber
622:
1.42 dwinter 623: security.declarePublic('getVersionComment')
624: def getVersionComment(self):
625: """get version"""
626: return self.versionComment
627:
1.32 dwinter 628:
1.51 dwinter 629:
1.42 dwinter 630: security.declarePublic('lastEditor')
1.51 dwinter 631:
1.1 dwinter 632: def lastEditor(self):
633: """last Editor"""
1.5 dwinter 634: if hasattr(self,'author'):
1.32 dwinter 635: ret=self.author.replace("-","\n")
636: ret=ret.replace("\r","\n")
637: return ret
638:
1.5 dwinter 639: else:
640: jar=self._p_jar
641: oid=self._p_oid
642:
643: if jar is None or oid is None: return None
644:
645: return jar.db().history(oid)[0]['user_name']
1.1 dwinter 646:
647:
648:
649:
650: manage_addVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='VersionedFileObject',kind='versionedFileObject', version='1')
651:
1.5 dwinter 652: def manage_addVersionedFileObject(self,id,vC='',author='', file='',title='',precondition='', content_type='',
1.1 dwinter 653: REQUEST=None):
654: """Add a new File object.
655:
656: Creates a new File object 'id' with the contents of 'file'"""
1.5 dwinter 657:
1.1 dwinter 658: id=str(id)
659: title=str(title)
660: content_type=str(content_type)
661: precondition=str(precondition)
1.3 dwinter 662:
1.1 dwinter 663: id, title = cookId(id, title, file)
664:
665: self=self.this()
666:
667: # First, we create the file without data:
668: self._setObject(id, versionedFileObject(id,title,'',content_type, precondition))
669: self._getOb(id).versionComment=str(vC)
1.15 dwinter 670: self._getOb(id).time=time.localtime()
671:
1.5 dwinter 672: setattr(self._getOb(id),'author',author)
1.1 dwinter 673:
674: # Now we "upload" the data. By doing this in two steps, we
675: # can use a database trick to make the upload more efficient.
676: if file:
677: self._getOb(id).manage_upload(file)
678: if content_type:
679: self._getOb(id).content_type=content_type
680:
681: if REQUEST is not None:
682: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
683:
684:
685:
686:
1.50 dwinter 687: class versionedFile(CatalogAware,Folder):
1.1 dwinter 688: """Versioniertes File"""
689:
1.50 dwinter 690: default_catalog='fileCatalog'
691:
692: def PrincipiaSearchSource(self):
693: """Return cataloguable key for ourselves."""
694: return str(self)
695:
1.5 dwinter 696: def __init__(self, id, title, lockedBy,author):
1.1 dwinter 697: """init"""
698: self.id=id
699: self.title=title
700: self.lockedBy=lockedBy
1.5 dwinter 701: self.author=author
1.32 dwinter 702:
1.39 dwinter 703: def manageImagesForm(self):
704: """manage Images attached to the file"""
1.40 dwinter 705:
706: self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
707:
1.39 dwinter 708: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','manageImage')).__of__(self)
709: return pt()
710:
1.40 dwinter 711: def manageImages(self,imageUrl=None,caption=None,REQUEST=None):
1.39 dwinter 712: """manage URL"""
713: if imageUrl and (not imageUrl==""):
714: manage_AddImageZogiLib(self,libPath=imageUrl,caption=caption)
715:
1.40 dwinter 716: if self.REQUEST.SESSION.has_key('refer'):
717:
718: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
719: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
720:
721:
722:
723: def changeImages(self,caption=None,submit=None,id=None,REQUEST=None):
1.39 dwinter 724: """manage URL"""
725: if submit=="change caption":
726: image=self.ZopeFind(self,obj_ids=[id])
727: if image:
728: image[0][1].caption=caption[0:]
729:
730: elif submit=="delete":
731: image=self.ZopeFind(self,obj_ids=[id])
732: if image:
733: self.manage_delObjects([image[0][1].getId()])
1.40 dwinter 734:
735:
736: if self.REQUEST.SESSION.has_key('refer'):
737:
738: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
739: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
740:
741:
1.39 dwinter 742:
743:
744: def getImages(self):
745: """get Images"""
746: images=self.ZopeFind(self,obj_metatypes=["ImageZogiLib"])
747: if not images:
748: return None
749: else:
750: return images
751:
752:
1.32 dwinter 753: def getComment(self):
754: """get the comment of this file"""
755: if not hasattr(self,'comment') or (not self.comment) or (self.comment.lstrip()==""):
756: return "Add comment"
757:
758: else:
759: return self.comment
760:
1.1 dwinter 761:
762: meta_type="versionedFile"
763:
1.26 dwinter 764: def manageCommentForm(self):
765: """add a comment"""
766: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addComment')).__of__(self)
767: return pt()
768:
769: def manageComment(self,text,comment_author,submit,REQUEST=None):
770: """manage comments"""
771: if submit =='change':
772: if text=='':
773: self.comment=None
774: else:
775: self.comment=text
776: self.comment_author=comment_author
777:
778: self.comment_date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
779:
780: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
781:
1.1 dwinter 782: def getLastVersion(self):
783: """Last Version"""
784: tmp=0
785: lastVersion=None
1.2 dwinter 786:
1.50 dwinter 787:
1.1 dwinter 788: for version in self.ZopeFind(self):
1.2 dwinter 789:
1.1 dwinter 790: if hasattr(version[1],'versionNumber'):
1.2 dwinter 791:
1.1 dwinter 792: if int(version[1].versionNumber) > tmp:
793: tmp=int(version[1].versionNumber,)
794: lastVersion=version[1]
1.50 dwinter 795: if lastVersion==None:
796: lastVersion=version[1]
797: lastVersion.versionNumber=1
1.1 dwinter 798: return lastVersion
799:
800: def index_html(self):
801: """main view"""
802: lastVersion=self.getLastVersion()
803: #return "File:"+self.title+" Version:%i"%lastVersion.versionNumber," modified:",lastVersion.bobobase_modification_time()," size:",lastVersion.getSize(),"modified by:",lastVersion.lastEditor()
1.15 dwinter 804: return "File: %s Version:%i modified:%s size:%s modified by:%s"%(self.title,lastVersion.versionNumber,lastVersion.getTime(),lastVersion.getSize(),lastVersion.lastEditor())
1.42 dwinter 805: security= ClassSecurityInfo()
806: security.declarePublic('getVersion')
1.1 dwinter 807: def getVersion(self):
808: tmp=0
809: for version in self.ZopeFind(self):
1.2 dwinter 810:
1.1 dwinter 811: if hasattr(version[1],'versionNumber'):
1.2 dwinter 812:
1.1 dwinter 813: if int(version[1].versionNumber) > tmp:
814: tmp=int(version[1].versionNumber,)
815: return tmp+1
816:
1.42 dwinter 817:
1.1 dwinter 818: security.declareProtected('AUTHENTICATED_USER','unlock')
819:
820: def history(self):
1.6 dwinter 821: """history"""
822:
823: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
824: if ext:
825: return getattr(self,ext[0][1].getId())()
826:
1.19 dwinter 827: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionHistory')).__of__(self)
1.1 dwinter 828: return pt()
829:
830: def getVersions(self):
831: """get all versions"""
832: ret=[]
833: for version in self.ZopeFind(self):
834: if hasattr(version[1],'versionNumber'):
835: ret.append((version[1].versionNumber,version[1]))
836: ret.sort(sortv)
837: return ret
838:
1.28 dwinter 839: security.declareProtected('AUTHENTICATED_USER','forceunlock')
840: def forceunlock(self,RESPONSE):
1.1 dwinter 841: """unlock"""
1.28 dwinter 842: self.lockedBy=''
1.29 dwinter 843:
844: security.declareProtected('AUTHENTICATED_USER','unlock')
845: def unlock(self,RESPONSE):
846: """unlock"""
847: if str(self.lockedBy) in [str(self.REQUEST['AUTHENTICATED_USER'])]:
848: self.lockedBy=''
849: RESPONSE.redirect(self.REQUEST['URL2'])
850: else:
851: return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER'])
852:
853:
1.8 dwinter 854:
1.1 dwinter 855: security.declareProtected('AUTHENTICATED_USER','addVersionedFileObjectForm')
856:
857: def addVersionedFileObjectForm(self):
858: """add a new version"""
1.2 dwinter 859:
860: if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
1.1 dwinter 861: return "please login first"
862: if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
863: out=DTMLFile('dtml/fileAdd', globals(),Kind='VersionedFileObject',kind='versionedFileObject',version=self.getVersion()).__of__(self)
864: return out()
865: else:
866: return "Sorry file is locked by somebody else"
867:
1.11 dwinter 868: def manage_addVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', RESPONSE=None):
1.1 dwinter 869: """add"""
1.35 dwinter 870: try: #der ganze vC unsinn muss ueberarbeitet werden
871: vC=self.REQUEST['vC']
872: except:
873: pass
1.1 dwinter 874:
1.5 dwinter 875: author=self.REQUEST['author']
1.6 dwinter 876:
877: if changeName=="yes":
1.24 dwinter 878: filename=file.filename
879: self.title=filename[max(filename.rfind('/'),
880: filename.rfind('\\'),
881: filename.rfind(':'),
882: )+1:]
883:
1.6 dwinter 884:
1.11 dwinter 885: if not newName=='':
886: self.title=newName[0:]
1.35 dwinter 887:
1.23 dwinter 888:
1.51 dwinter 889:
890:
891:
892: positionVersionNum=getattr(self,'positionVersionNum','front')
893:
894: if positionVersionNum=='front':
895: id="V%i"%self.getVersion()+"_"+self.title
896: else:
897: tmp=os.path.splitext(self.title)
898: if len(tmp)>1:
899: id=tmp[0]+"_V%i"%self.getVersion()+tmp[1]
900: else:
901: id=tmp[0]+"_V%i"%self.getVersion()
902:
903:
904: manage_addVersionedFileObject(self,id,vC,author,file,id,precondition, content_type)
1.1 dwinter 905: objs=self.ZopeFind(self,obj_ids=[id])[0][1].setVersionNumber(int(self.getVersion()))
1.27 dwinter 906: self.REQUEST.SESSION['objID_parent']=self.getId()
1.23 dwinter 907:
1.1 dwinter 908: if RESPONSE:
1.27 dwinter 909: obj=self.ZopeFind(self,obj_ids=[id])[0][1]
910: if obj.getSize()==0:
911: self.REQUEST.SESSION['objID']=obj.getId()
1.23 dwinter 912: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
913: return pt()
914:
915: else:
916: RESPONSE.redirect(self.REQUEST['URL2'])
1.1 dwinter 917:
1.23 dwinter 918: else:
919: return self.ZopeFind(self,obj_ids=[id])[0][1]
920:
1.1 dwinter 921: security.declareProtected('AUTHENTICATED_USER','downloadLocked')
922:
1.7 dwinter 923: def download(self):
924: """download and lock"""
1.33 dwinter 925:
926: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getLastVersion().getId())
1.47 dwinter 927: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
1.33 dwinter 928:
1.49 dwinter 929: #try:
930: # txt=self.getLastVersion.index_html()
931: #except:
932: # txt=self.getLastVersion.index_html(REQUEST,RESPONSE)
933:
934: #self.REQUEST.RESPONSE.setHeader("Content-Length","str(len(txt)+1000)")
935:
1.33 dwinter 936: self.content_type="application/octet-stream"
937: #self.REQUEST.RESPONSE.write("bl")
1.49 dwinter 938: #self.REQUEST.RESPONSE.write(txt)
939: #self.REQUEST.close()
1.33 dwinter 940:
941: #self.getLastVersion().content_type="application/octet-stream"
1.49 dwinter 942: self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId())
1.7 dwinter 943:
1.1 dwinter 944: def downloadLocked(self):
945: """download and lock"""
946: if self.REQUEST['AUTHENTICATED_USER']=='Anonymous User':
947: return "please login first"
948: if not self.lockedBy=="":
949: return "cannot be locked because is already locked by %s"%self.lockedBy
950: self.lockedBy=self.REQUEST['AUTHENTICATED_USER']
1.9 dwinter 951: self.getLastVersion().content_type="application/octet-stream"
1.1 dwinter 952: self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId())
953:
954: def manage_addVersionedFileForm(self):
955: """interface for adding the OSAS_root"""
1.19 dwinter 956: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addVersionedFile.zpt')).__of__(self)
1.1 dwinter 957: return pt()
958:
1.5 dwinter 959: def manage_addVersionedFile(self,id,title,lockedBy, author=None, RESPONSE=None):
1.1 dwinter 960: """add the OSAS_root"""
1.5 dwinter 961: newObj=versionedFile(id,title,lockedBy,author)
1.1 dwinter 962: self._setObject(id,newObj)
1.5 dwinter 963:
1.1 dwinter 964: if RESPONSE is not None:
965: RESPONSE.redirect('manage_main')
966:
967:
968: InitializeClass(versionedFile)
969: InitializeClass(versionedFileFolder)
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>