Annotation of versionedFile/extVersionedFile.py, revision 1.35
1.3 dwinter 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:
1.32 dwinter 6: import email
1.1 dwinter 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:
1.6 casties 22: from Products.ImageArchive.ImageArchive import manage_AddImageZogiLib
1.1 dwinter 23: except:
1.6 casties 24: print "no images"
1.1 dwinter 25:
26: from threading import Thread
27: import shutil
28: import tempfile
29: import os.path
30: import urllib
1.5 casties 31: import time
32: import logging
1.9 casties 33: import types
1.1 dwinter 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:
1.6 casties 40: """leer"""
41: manage_options=()
1.1 dwinter 42:
43:
44: def sortv(x,y):
45: return cmp(x[0],y[0])
1.7 casties 46:
1.1 dwinter 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
1.6 casties 62: tempfile.tempdir=tdir
1.1 dwinter 63:
64: tmpPath=tempfile.mktemp()
1.6 casties 65: tmpZip=tempfile.mktemp()+".tgz"
1.1 dwinter 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):
1.6 casties 72: os.mkdir(tmpPath)
1.1 dwinter 73:
1.6 casties 74: self.response="<h3>1. step: getting the files</h3>"
1.1 dwinter 75:
76: for files in self.folder.ZopeFind(self.folder,obj_metatypes=['extVersionedFile']):
1.7 casties 77: lastV=files[1].getContentObject()
1.1 dwinter 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")
1.2 dwinter 82: fh.write(lastV.getData())
1.1 dwinter 83: fh.close()
84:
85: self.response+="<h3>2. step: creating the downloadable file</h3>"
1.6 casties 86: self.response+="<p>Create gtar<br>"
1.1 dwinter 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:
1.6 casties 109:
1.1 dwinter 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')
1.6 casties 127:
1.7 casties 128: file_meta_type=['extVersionedFile']
1.6 casties 129:
1.1 dwinter 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+(
1.6 casties 136: {'label':'Generate Index.html','action':'generateIndexHTML'},
137: {'label':'Generate Image Index.html','action':'generateIndexHTML_image'},
138: {'label':'Generate history_template.html','action':'generateHistoryHTML'},
1.12 casties 139: {'label':'Import directory','action':'importFolderForm'},
140: {'label':'Export as file','action':'exportFolder'},
141: {'label':'Import versionedFileFolder','action':'importVersionedFileFolderForm'},
1.6 casties 142: {'label':'Position of version number','action':'changeHistoryFileNamesForm'},
143: )
1.1 dwinter 144:
1.6 casties 145:
1.32 dwinter 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)
1.35 ! casties 159:
1.1 dwinter 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:
1.6 casties 173:
1.1 dwinter 174: if positionVersionNum=="front":
1.6 casties 175:
1.1 dwinter 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()
1.6 casties 204:
1.1 dwinter 205: def importFolder(self,path,comment="",author=None,lockedBy=None,RESPONSE=None):
1.8 casties 206: """import contents of a folder on the server"""
1.1 dwinter 207: for fileName in os.listdir(path):
1.8 casties 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)
1.1 dwinter 212:
213: if RESPONSE:
214: RESPONSE.redirect(self.REQUEST['URL1'])
215:
1.10 casties 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':
1.11 casties 236: logging.error("importvff: importing %s of type %s!"%(vfn,vf.meta_type))
1.10 casties 237: title = vf.title
1.11 casties 238: fob = vf.getLastVersion()
239: author = fob.getLastEditor()
240: vc = fob.getVersionComment()
1.10 casties 241: # save file to filesystem
242: savePath=os.path.join(tmpPath,title)
243: fh=file(savePath,"w")
1.11 casties 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
1.10 casties 253: fh.close()
254: # and read in again
255: fh = file(savePath)
1.11 casties 256: logging.error("importvff: comment=%s author=%s!"%(vc,author))
1.10 casties 257: self.addFile(vC=vc, file=fh, author=author)
1.11 casties 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()))
1.10 casties 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:
1.1 dwinter 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()
1.8 casties 287:
1.1 dwinter 288: ## if not threadName or threadName=="":
289: ## threadStart=generateDownloadZip(self,self.absolute_url())
290: ## thread=Thread(target=threadStart)
1.6 casties 291:
1.1 dwinter 292: ## thread.start()
293:
1.6 casties 294:
1.1 dwinter 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()
1.6 casties 303:
1.1 dwinter 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):
1.6 casties 331: """download prepared set"""
332: filename=os.path.join(tdir,fn)
1.1 dwinter 333:
1.6 casties 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()
1.1 dwinter 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()),
1.6 casties 359: 'zpt/versionFileFolderMain_image.zpt')
1.1 dwinter 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()),
1.6 casties 378: 'zpt/versionFileFolderMain.zpt')
1.1 dwinter 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()),
1.6 casties 395: 'zpt/versionFileFolderMain.zpt')
1.1 dwinter 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()),
1.6 casties 412: 'zpt/versionHistory.zpt')
1.1 dwinter 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')
1.6 casties 421:
1.1 dwinter 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):
1.7 casties 430: return cmp(y[1].getContentObject().getTime(),x[1].getContentObject().getTime())
1.1 dwinter 431:
432: def sortComment(x,y):
1.6 casties 433: try:
434: xc=getattr(x[1],'comment','ZZZZZZZZZZZZZ').lower()
435: except:
436: xc='ZZZZZZZZZZZZZ'.lower()
437:
438: try:
439: yc=getattr(y[1],'comment','ZZZZZZZZZZZZZ').lower()
440: except:
441: yc='ZZZZZZZZZZZZZ'.lower()
442:
443: if (xc=='') or (xc=='ZZZZZZZZZZZZZ'.lower()):
444: try:
1.7 casties 445: xc=x[1].getContentObject().getVComment().lower()
1.6 casties 446: except:
447: xc='ZZZZZZZZZZZZZ'.lower()
448:
449: if (yc=='') or (yc=='ZZZZZZZZZZZZZ'.lower()):
450: try:
1.7 casties 451: yc=y[1].getContentObject().getVComment().lower()
1.6 casties 452: except:
453: yc='ZZZZZZZZZZZZZ'.lower()
454:
455: return cmp(xc,yc)
1.1 dwinter 456:
457: def sortAuthor(x,y):
458:
1.7 casties 459: return cmp(x[1].getContentObject().lastEditor().lower(),y[1].getContentObject().lastEditor().lower())
1.1 dwinter 460:
1.7 casties 461: versionedFiles=self.objectItems(self.file_meta_type)
462: logging.debug("versionedfiles: %s of type %s"%(repr(versionedFiles),repr(self.file_meta_type)))
1.1 dwinter 463:
464: if sortField=='title':
465: versionedFiles.sort(sortName)
466: elif sortField=='date':
467: versionedFiles.sort(sortDate)
468: elif sortField=='author':
469: versionedFiles.sort(sortAuthor)
470: elif sortField=='comment':
471: versionedFiles.sort(sortComment)
472:
473: return versionedFiles
474:
475:
476: def header_html(self):
1.5 casties 477: """zusaetzlicher header"""
1.1 dwinter 478: ext=self.ZopeFind(self,obj_ids=["header.html"])
479: if ext:
480: return ext[0][1]()
481: else:
482: return ""
483:
484:
485: security.declareProtected('View','index_html')
486: def index_html(self):
487: """main"""
488: ext=self.ZopeFind(self,obj_ids=["index.html"])
489: if ext:
490: return ext[0][1]()
491:
492: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionFileFolderMain')).__of__(self)
493: return pt()
494:
495:
496:
497: def addFileForm(self):
498: """add a file"""
499: ext=self.ZopeFind(self,obj_ids=["addFileForm.dtml"])
500: if ext:
501: return ext[0][1]('',globals(),version='1',AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)
502:
503: out=DTMLFile('dtml/newFileAdd', globals(),Kind='versionedFileObject',kind='versionedFileObject',version='1').__of__(self)
504: return out()
505:
506:
1.8 casties 507: def addFile(self,vC,file,author='',newName='',content_type='',RESPONSE=None):
1.1 dwinter 508: """ add a new file"""
1.9 casties 509: # is file is a real file or a zope download object?
510: isRealFile = type(file) is types.FileType
511:
1.1 dwinter 512: if newName=='':
1.9 casties 513: logging.debug("fileobject: %s real:%s"%(repr(file),repr(isRealFile)))
514: if isRealFile:
515: filename = file.name
516: else:
517: filename=file.filename
518:
1.1 dwinter 519: id=filename[max(filename.rfind('/'),
1.6 casties 520: filename.rfind('\\'),
521: filename.rfind(':'),
522: )+1:]
1.1 dwinter 523:
524: else:
525: id=newName
526:
1.11 casties 527: if vC is None:
1.9 casties 528: vC=self.REQUEST.form['vC']
1.8 casties 529:
530: # get new extVersionedFile
531: vf = self._newVersionedFile(id,title=id)
1.26 dwinter 532: logging.error("addFile id=%s vf=%s of %s"%(repr(id),repr(vf),repr(self)))
1.18 casties 533: # add its content (and don't index)
1.34 dwinter 534: self._setObject(id,vf)
535: vf=getattr(self,id)
536:
1.18 casties 537: obj=vf.addContentObject(id,vC,author=author,file=file,content_type=content_type,from_tmp=isRealFile,index=False)
538: # add file to this folder (this should do the indexing)
1.34 dwinter 539: #self._setObject(id,vf)
1.1 dwinter 540:
1.18 casties 541: try:
542: self.REQUEST.SESSION['objID']=vf.getId()
543: self.REQUEST.SESSION['objID_parent']=None
544: except:
545: pass
1.1 dwinter 546:
547: if obj.getSize()==0:
548: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
549: return pt()
550:
1.9 casties 551: if RESPONSE is not None:
552: RESPONSE.redirect(self.REQUEST['URL1'])
1.1 dwinter 553:
554:
1.8 casties 555: def _newVersionedFile(self, id, title='', lockedBy=None, author=None):
556: """factory for versioned files. to be overridden in derived classes."""
557: return extVersionedFile(id, title, lockedBy=lockedBy, author=author)
558:
559:
1.1 dwinter 560: def deleteEmptyObject(self,submit,RESPONSE=None):
561: """deleteemptyobject"""
562: if submit=="delete it":
563: if self.REQUEST.SESSION['objID_parent']:
564: obj=getattr(self,self.REQUEST.SESSION['objID_parent'])
565:
566: else:
567: obj=self
568: obj.manage_delObjects([self.REQUEST.SESSION['objID']])
569:
570: RESPONSE.redirect(self.REQUEST['URL1'])
571:
1.7 casties 572:
573: security.declareProtected('AUTHENTICATED_USER','fixVersionNumbers')
574: def fixVersionNumbers(self):
575: """fix last version number of all files"""
576: for (id,vf) in self.getVersionedFiles():
577: vf.fixVersionNumbers()
1.13 casties 578: # recursively
579: for (id,vf) in self.objectItems(self.meta_type):
580: vf.fixVersionNumbers()
1.1 dwinter 581:
1.8 casties 582:
1.1 dwinter 583: manage_addextVersionedFileFolderForm=DTMLFile('dtml/extfolderAdd', globals())
584:
585:
586: def manage_addextVersionedFileFolder(self, id, title='',
1.6 casties 587: createPublic=0,
588: createUserF=0,
589: REQUEST=None):
1.1 dwinter 590: """Add a new Folder object with id *id*.
591:
592: If the 'createPublic' and 'createUserF' parameters are set to any true
593: value, an 'index_html' and a 'UserFolder' objects are created respectively
594: in the new folder.
595: """
596: ob=extVersionedFileFolder()
597: ob.id=str(id)
598: ob.title=title
599: self._setObject(id, ob)
600: ob=self._getOb(id)
601:
602: checkPermission=getSecurityManager().checkPermission
603:
604: if createUserF:
605: if not checkPermission('Add User Folders', ob):
606: raise Unauthorized, (
1.6 casties 607: 'You are not authorized to add User Folders.'
608: )
1.1 dwinter 609: ob.manage_addUserFolder()
610:
1.6 casties 611:
1.1 dwinter 612: if REQUEST is not None:
613: return self.manage_main(self, REQUEST, update_menu=1)
614:
615:
616:
617: class extVersionedFileObject(ExtFile):
618: """File Object im Folder"""
619: security= ClassSecurityInfo()
620: meta_type = "extVersionedFileObject"
621:
1.7 casties 622: manage_editForm=DTMLFile('dtml/fileEdit',globals(),
1.1 dwinter 623: Kind='File',kind='file')
624: manage_editForm._setName('manage_editForm')
625:
1.7 casties 626: def __init__(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
627: """Initialize a new instance of extVersionedFileObject (taken from ExtFile)"""
628: ExtFile.__init__(self,id,title)
629: self.versionNumber = versionNumber
630: self.versionComment= versionComment
631: self.time = time
632: self.author = author
633:
1.22 casties 634: security.declareProtected('manage','changeObject')
635: def changeObject(self,**args):
1.23 casties 636: """modify any of the objects attributes"""
1.22 casties 637: for arg in args:
638: if hasattr(self, arg):
1.24 casties 639: logging.debug("changeObject %s: %s=%s"%(repr(self),arg,args[arg]))
1.22 casties 640: setattr(self, arg, args[arg])
1.7 casties 641:
1.1 dwinter 642: security.declarePublic('getTitle')
643: def getTitle(self):
644: """get title"""
645: return self.title
1.6 casties 646:
647: def getData(self):
648: """returns object content (calls ExtFile.index_html)"""
1.27 dwinter 649: #logging.debug("+++++++getData1:"+repr(self.get_filename()))
650: filename = self.get_filename()
651: #return ExtFile.index_html(self)
1.29 dwinter 652: try:
1.32 dwinter 653: logging.info("readfile:"+filename)
1.29 dwinter 654: return file(filename).read()
655: except:
1.32 dwinter 656: logging.info("cannot readfile:"+filename)
1.29 dwinter 657: return ExtFile.index_html(self)
658:
1.27 dwinter 659:
660: def getFileName(self):
661: """return filename"""
662: return self.get_filename()
663:
664: def addToFile(self,filehandle):
665: filehandle.write(self.getData())
666:
667: def addToFile2(self,filename):
668: str="cat %s > %s"%(self.get_filename(),filename)
669: os.popen(str)
670:
1.1 dwinter 671: security.declarePublic('getVComment')
672: def getVComment(self):
673: """get the comment of this file"""
674: if not hasattr(self,'vComment') or (not self.vComment) or (self.vComment.lstrip()==""):
675: return "Add comment"
676:
677: else:
678: return self.vComment
1.6 casties 679:
1.1 dwinter 680: def manageVCommentForm(self):
681: """add a comment"""
682: self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
683: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addVComment')).__of__(self)
684: return pt()
685:
686: def manageVComment(self,text,comment_author,submit,REQUEST=None):
687: """manage comments"""
688: if submit =='change':
689: if text=='':
690: self.vComment=None
691: else:
692: self.vComment=text
693: self.vComment_author=comment_author
694:
695: self.vComment_date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
696:
697: if self.REQUEST.SESSION.has_key('refer'):
698:
699: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
700: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url()+"/history")
701:
702:
703: security.declarePublic('getVersionComment')
704: def getVersionComment(self):
705: """getversioncomment"""
706: return self.versionComment
707:
708: security.declarePublic('getTime')
709: def getTime(self):
710: """getTime"""
711: #return self.bobobase_modification_time().ISO()
712: if hasattr(self,'time'):
713: return time.strftime("%Y-%m-%d %H:%M:%S",self.time)
714: elif hasattr(self,'timefixed'):
1.6 casties 715: return self.timefixed
1.1 dwinter 716: else:
717: setattr(self,'timefixed',self.bobobase_modification_time().ISO())
718: return self.bobobase_modification_time().ISO()
719:
720: def download(self,REQUEST=None,RESPONSE=None):
721: """download and lock"""
722:
723: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getId())
724: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
725: #try:
726: # txt=self.index_html()
727: #except:
728: # txt=self.index_html(REQUEST,RESPONSE)
729: #
730: #self.REQUEST.RESPONSE.setHeader("Content-Length","str(len(txt)+1000)")
731:
732: self.content_type="application/octet-stream"
1.26 dwinter 733: return self.getData()
734: #self.REQUEST.RESPONSE.redirect(self.absolute_url())
1.1 dwinter 735: #txt=urllib.urlopen(self.absolute_url()).read()
736: #self.REQUEST.RESPONSE.write(txt)
737:
738:
739: #self.REQUEST.close()
740:
1.19 casties 741: view = download
742:
1.1 dwinter 743: security.declareProtected('AUTHENTICATED_USER','downloadLocked')
744: def downloadLocked(self):
745: """download and lock"""
746: if repr(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
747: return "please login first"
748: if not self.aq_parent.lockedBy=="":
749: return "cannot be locked because is already locked by %s"%self.lockedBy
750: self.aq_parent.lockedBy=self.REQUEST['AUTHENTICATED_USER']
751:
752: self.content_type="application/octet-stream"
753: self.REQUEST.RESPONSE.redirect(self.absolute_url())
754:
755: security.declarePublic('getVersionNumber')
756: def getVersionNumber(self):
757: """get version"""
758: return self.versionNumber
759:
760: security.declarePublic('getVersionComment')
761: def getVersionComment(self):
762: """get version"""
763: return self.versionComment
764:
765: security.declarePublic('lastEditor')
766: def lastEditor(self):
767: """last Editor"""
768: if hasattr(self,'author'):
769: try:
770: ret=self.author.replace("-","\n")
771: except:#old version of versionded file sometimes stored the user object and not only the name the following corrects this
772: ret=str(self.author).replace("-","\n")
773: ret=ret.replace("\r","\n")
774: return ret.lstrip().rstrip()
775:
776: else:
777: jar=self._p_jar
778: oid=self._p_oid
779:
780: if jar is None or oid is None: return None
781:
782: return jar.db().history(oid)[0]['user_name']
783:
784:
785: manage_addextVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='extVersionedFileObject',kind='extVersionedFileObject', version='1')
786:
1.7 casties 787: def manage_addextVersionedFileObject(self,id,vC='',author='', file='',title='',versionNumber=0,
788: precondition='', content_type='', REQUEST=None):
1.1 dwinter 789: """Add a new File object.
790:
791: Creates a new File object 'id' with the contents of 'file'"""
792:
793: id=str(id)
794: title=str(title)
795: content_type=str(content_type)
796: precondition=str(precondition)
797:
798: id, title = cookId(id, title, file)
799:
800: self=self.this()
801:
802: # First, we create the file without data:
1.7 casties 803: self._setObject(id, extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=str(vC),author=author))
804: fob = self._getOb(id)
1.1 dwinter 805:
806: # Now we "upload" the data. By doing this in two steps, we
807: # can use a database trick to make the upload more efficient.
808: if file:
1.7 casties 809: fob.manage_upload(file)
1.1 dwinter 810: if content_type:
1.7 casties 811: fob.content_type=content_type
1.1 dwinter 812:
813: if REQUEST is not None:
814: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
815:
816:
817:
818: class extVersionedFile(CatalogAware,Folder):
819: """Versioniertes File"""
820:
1.7 casties 821: meta_type = 'extVersionedFile'
822: # meta_type of contained objects
823: content_meta_type = ['extVersionedFileObject']
1.15 casties 824: # default catalog for extVersionedFile objects
1.7 casties 825: default_catalog = 'fileCatalog'
1.1 dwinter 826:
1.15 casties 827: manage_options = Folder.manage_options+({'label':'Main Config','action':'changeVersionedFileForm'},)
828:
829:
1.7 casties 830: security=ClassSecurityInfo()
1.1 dwinter 831:
1.35 ! casties 832: def __init__(self, id, title, lockedBy,author,defaultAction='history'):
1.7 casties 833: """init"""
834: self.id=id
835: self.title=title
836: self.lockedBy=lockedBy
1.25 casties 837: if self.lockedBy is None:
838: self.lockedBy = ''
1.7 casties 839: self.author=author
840: self.lastVersionNumber=0
841: self.lastVersionId=None
1.35 ! casties 842: self.defaultAction = defaultAction
1.7 casties 843:
1.1 dwinter 844: security.declarePublic('getTitle')
845: def getTitle(self):
846: """get title"""
847: return self.title
848:
849: def PrincipiaSearchSource(self):
1.6 casties 850: """Return cataloguable key for ourselves."""
851: return str(self)
1.1 dwinter 852:
853: def manageImagesForm(self):
854: """manage Images attached to the file"""
855:
856: self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
857:
858: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','manageImage')).__of__(self)
859: return pt()
860:
861: def manageImages(self,imageUrl=None,caption=None,REQUEST=None):
862: """manage URL"""
863: if imageUrl and (not imageUrl==""):
864: manage_AddImageZogiLib(self,libPath=imageUrl,caption=caption)
865:
866: if self.REQUEST.SESSION.has_key('refer'):
867:
868: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
869: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
870:
871: def changeImages(self,caption=None,submit=None,id=None,REQUEST=None):
872: """manage URL"""
873: if submit=="change caption":
874: image=self.ZopeFind(self,obj_ids=[id])
875: if image:
876: image[0][1].caption=caption[0:]
877:
878: elif submit=="delete":
879: image=self.ZopeFind(self,obj_ids=[id])
880: if image:
881: self.manage_delObjects([image[0][1].getId()])
882:
883: if self.REQUEST.SESSION.has_key('refer'):
1.7 casties 884: return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
1.1 dwinter 885:
886: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
887:
888: def getImages(self):
889: """get Images"""
890: images=self.ZopeFind(self,obj_metatypes=["ImageZogiLib"])
891: if not images:
892: return None
893: else:
894: return images
1.6 casties 895:
1.1 dwinter 896: security.declarePublic('getComment')
897: def getComment(self):
898: """get the comment of this file"""
899: if not hasattr(self,'comment') or (not self.comment) or (self.comment.lstrip()==""):
900: return "Add comment"
901: else:
902: return self.comment
903:
904: def manageCommentForm(self):
905: """add a comment"""
906: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addComment')).__of__(self)
907: return pt()
908:
909: def manageComment(self,text,comment_author,submit,REQUEST=None):
910: """manage comments"""
911: if submit =='change':
912: if text=='':
913: self.comment=None
914: else:
915: self.comment=text
916: self.comment_author=comment_author
917:
918: self.comment_date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
919:
920: return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
1.6 casties 921:
1.1 dwinter 922: security.declarePublic('getLastChangeDate')
923: def getLastChangeDate(self):
924: """get last change date"""
1.7 casties 925: lv=self.getContentObject()
1.18 casties 926: if lv:
927: time=lv.getTime()
928: return time
929: return None
1.1 dwinter 930:
931: def getLastEditor(self):
932: """get last change date"""
1.7 casties 933: lv=self.getContentObject()
1.1 dwinter 934: le=lv.lastEditor()
935: return le
936:
937: def getLockedBy(self):
938: """get locked by"""
1.25 casties 939: if self.lockedBy is None:
940: self.lockedBy = ''
1.1 dwinter 941: return str(self.lockedBy)
1.6 casties 942:
1.7 casties 943: def getLastVersionNumber(self):
944: """returns the highest version number of all included objects"""
945: lv = self.findLastVersion()
946: if lv:
947: return lv.getVersionNumber()
948: else:
949: return 0
950:
951: def findLastVersion(self):
952: """finds and returns the object with the highest version number"""
953: lvn=0
954: lv=None
955:
956: for v in self.objectValues(self.content_meta_type):
957: logging.debug("findlastversion: check %s"%v.getId())
958: if v.getVersionNumber() > lvn:
959: lvn=v.getVersionNumber()
960: lv=v
961:
962: if lv:
963: logging.debug("findlastversion: got %s"%lv.getId())
964: return lv
965:
1.1 dwinter 966: security.declarePublic('getLastVersion')
967: def getLastVersion(self):
1.7 casties 968: """Last Version (old)"""
1.1 dwinter 969: tmp=0
1.7 casties 970: lv=None
1.1 dwinter 971:
1.7 casties 972: for v in self.objectValues(self.content_meta_type):
1.28 dwinter 973: #logging.debug("getlastversion: check %s"%v.getId())
1.7 casties 974: if v.getVersionNumber() > tmp:
975: tmp=v.getVersionNumber()
976: lv=v
977:
1.28 dwinter 978: #ogging.debug("getlastversion: got %s"%lv.getId())
1.7 casties 979: return lv
980:
981: def getContentObject(self):
982: """returns the last version object"""
1.18 casties 983: if not getattr(self, 'lastVersionId', None):
1.14 casties 984: # find last version and save it
1.7 casties 985: lv = self.findLastVersion()
986: if lv is None:
987: return None
988: self.lastVersionNumber = lv.getVersionNumber()
989: self.lastVersionId = lv.getId()
1.1 dwinter 990:
1.18 casties 991: return getattr(self, self.lastVersionId, None)
1.7 casties 992:
993: security.declarePublic('getData')
994: def getData(self):
995: """Returns the content of the last version"""
1.27 dwinter 996: logging.debug("+++++++getData2")
1.7 casties 997: ob = self.getContentObject()
998: if ob is not None:
999: return ob.getData()
1000: else:
1001: return None
1.1 dwinter 1002:
1.19 casties 1003: security.declarePublic('view')
1004: def view(self,REQUEST=None,RESPONSE=None):
1005: """Returns the last version's view"""
1006: ob = self.getContentObject()
1007: if ob is not None:
1008: return ob.view(REQUEST=REQUEST,RESPONSE=RESPONSE)
1009: else:
1010: return None
1011:
1.1 dwinter 1012: def diff(self,data):
1013: """differenz between lastversion and data"""
1014: d=Differ()
1.7 casties 1015: tmp=self.getData()
1.1 dwinter 1016: #print "XX",data,tmp
1017: try:
1.6 casties 1018: l=list(d.compare(data.splitlines(1),tmp.splitlines(1)))
1.1 dwinter 1019: except:
1020: return 0,""
1021: plus=0
1022: minus=0
1023: for a in l:
1024: if a[0]=='+':
1025: plus+=1
1026: if a[0]=='-':
1027: minus+=1
1028:
1029: return max([plus,minus]),l
1.6 casties 1030:
1031:
1.1 dwinter 1032: security.declarePublic('index_html')
1.35 ! casties 1033: def index_html(self,REQUEST=None, RESPONSE=None):
1.1 dwinter 1034: """main view"""
1.7 casties 1035: #lastVersion=self.getContentObject()
1.1 dwinter 1036: #return "File:"+self.title+" Version:%i"%lastVersion.versionNumber," modified:",lastVersion.bobobase_modification_time()," size:",lastVersion.getSize(),"modified by:",lastVersion.lastEditor()
1.4 dwinter 1037: #return "File: %s Version:%i modified:%s size:%s modified by:%s"%(self.title,lastVersion.versionNumber,lastVersion.getTime(),lastVersion.getSize(),lastVersion.lastEditor())
1.35 ! casties 1038: act = getattr(self, 'defaultAction', 'history')
! 1039: if act == 'download':
! 1040: return self.getContentObject().download()
! 1041: elif act == 'view':
! 1042: #return self.getContentObject().download()
! 1043: return self.getContentObject().index_html(REQUEST=REQUEST, RESPONSE=RESPONSE)
! 1044: else:
! 1045: return self.history()
1.1 dwinter 1046:
1.30 dwinter 1047: def getVersionNr(self,nr):
1048: """get version with number nr"""
1049: tmp=0
1050: lastVersion=None
1051: for version in self.ZopeFind(self):
1052: if hasattr(version[1],'versionNumber'):
1053: if int(version[1].versionNumber) ==nr :
1054: return version[1]
1055:
1056: return None
1.35 ! casties 1057:
1.1 dwinter 1058: security.declarePublic('getVersion')
1059: def getVersion(self):
1.7 casties 1060: # TODO: this is ugly and it returns the next version number
1.1 dwinter 1061: tmp=0
1062: for version in self.ZopeFind(self):
1063:
1064: if hasattr(version[1],'versionNumber'):
1065:
1066: if int(version[1].versionNumber) > tmp:
1067: tmp=int(version[1].versionNumber,)
1.7 casties 1068: return tmp+1
1.1 dwinter 1069:
1070: def history(self):
1071: """history"""
1072: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
1073: if ext:
1074: return getattr(self,ext[0][1].getId())()
1075:
1076: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionHistory')).__of__(self)
1077: return pt()
1078:
1079: def getVersions(self):
1080: """get all versions"""
1081: ret=[]
1082: for version in self.ZopeFind(self):
1083: if hasattr(version[1],'versionNumber'):
1084: ret.append((version[1].versionNumber,version[1]))
1085: ret.sort(sortv)
1086: return ret
1087:
1.20 casties 1088: def getVersionList(self):
1089: """get a list of dicts with author, comment, filename, etc, of all versions"""
1090: vl = []
1091: for v in self.objectValues(self.content_meta_type):
1.21 casties 1092: vl.append({'versionNumber':getattr(v,'versionNumber',0),
1.20 casties 1093: 'title':v.getTitle(),
1.21 casties 1094: 'id':v.getId(),
1.20 casties 1095: 'date':v.getTime(),
1.21 casties 1096: 'author':getattr(v,'author',''),
1097: 'comment':getattr(v,'versionComment','')
1.20 casties 1098: })
1.21 casties 1099: return vl
1.20 casties 1100:
1.1 dwinter 1101: security.declareProtected('AUTHENTICATED_USER','forceunlock')
1.31 dwinter 1102: def forceunlock(self,RESPONSE=None,user=None):
1.1 dwinter 1103: """unlock"""
1104: #safe who had the lock
1.31 dwinter 1105: logging.debug("extVersionFile: (forceunlock)"+str(user))
1.1 dwinter 1106: if self.lockedBy:
1.31 dwinter 1107: if user is not None:
1108: if str(self.lockedBy)==user:
1109: self.brokenLock=str(self.lockedBy)
1110: self.lockedBy=''
1111: else:
1112: self.brokenLock=""
1113: else:
1114: self.brokenLock=str(self.lockedBy)
1115: self.lockedBy=''
1.1 dwinter 1116: else:
1117: self.brokenLock=""
1.31 dwinter 1118:
1.1 dwinter 1119: return self.brokenLock
1120:
1121: security.declareProtected('AUTHENTICATED_USER','unlock')
1122: def unlock(self,RESPONSE):
1123: """unlock"""
1124: if str(self.lockedBy) in [str(self.REQUEST['AUTHENTICATED_USER'])]:
1125: self.lockedBy=''
1.33 dwinter 1126: RESPONSE.redirect(self.REQUEST['HTTP_REFERER'])
1.1 dwinter 1127: else:
1128: return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER'])
1129:
1.7 casties 1130:
1.33 dwinter 1131:
1.7 casties 1132: def _newContentObject(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
1133: """factory for content objects. to be overridden in derived classes."""
1134: return extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=versionComment,time=time,author=author)
1135:
1136:
1.18 casties 1137: def addContentObject(self,id,vC,author=None,file=None,title='',changeName='no',newName='',from_tmp=False,index=True,
1.7 casties 1138: precondition='', content_type=''):
1139: """add"""
1140:
1141: if changeName=="yes":
1142: filename=file.filename
1143: self.title=filename[max(filename.rfind('/'),
1144: filename.rfind('\\'),
1145: filename.rfind(':'),
1146: )+1:]
1147:
1148: if not newName=='':
1149: self.title=newName[0:]
1150:
1151: posVersNum=getattr(self,'positionVersionNum','front')
1152:
1153: versNum = self.getLastVersionNumber() + 1
1154:
1155: if posVersNum=='front':
1156: id="V%i_%s"%(versNum,self.title)
1157: else:
1158: fn=os.path.splitext(self.title)
1159: if len(fn)>1:
1160: id=fn[0]+"_V%i%s"%(versNum,fn[1])
1161: else:
1162: id=fn[0]+"_V%i"%versNum
1.1 dwinter 1163:
1.7 casties 1164: # what does this do?
1165: id, title = cookId(id, title, file)
1166: self=self.this()
1167:
1168: # First, we create the file without data:
1169: self._setObject(id, self._newContentObject(id,title,versionNumber=versNum,versionComment=str(vC),
1170: time=time.localtime(),author=author))
1171: fob = self._getOb(id)
1172:
1173: # Now we "upload" the data. By doing this in two steps, we
1174: # can use a database trick to make the upload more efficient.
1175: if file and not from_tmp:
1176: fob.manage_upload(file)
1177: elif file and from_tmp:
1178: fob.manage_file_upload(file) # manage_upload_from_tmp doesn't exist in ExtFile2
1179: # fob.manage_upload_from_tmp(file) # manage_upload_from_tmp doesn't exist in ExtFile2
1180: fob.content_type=content_type
1181:
1182: self.lastVersionNumber = versNum
1183: self.lastVersionId = id
1184:
1.9 casties 1185: #logging.debug("addcontentobject: lastversion=%s"%self.getData())
1186: #logging.debug("addcontentobject: fob_data=%s"%fob.getData())
1.18 casties 1187: if index and self.default_catalog:
1188: logging.debug("reindex1: %s in %s"%(repr(self),repr(self.default_catalog)))
1189: self.reindex_object()
1.7 casties 1190:
1191: return fob
1192:
1.1 dwinter 1193:
1194: security.declareProtected('AUTHENTICATED_USER','addVersionedFileObjectForm')
1195: def addVersionedFileObjectForm(self):
1196: """add a new version"""
1197:
1198: if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
1199: return "please login first"
1200: if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
1201: ext=self.ZopeFind(self.aq_parent,obj_ids=["addNewVersion.dtml"])
1202: if ext:
1.7 casties 1203: return ext[0][1]('',globals(),version=self.getVersion(),lastComment=self.getContentObject().getVersionComment(),AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)
1.1 dwinter 1204: else:
1205: out=DTMLFile('dtml/fileAdd', globals(),Kind='VersionedFileObject',kind='versionedFileObject',version=self.getVersion()).__of__(self)
1206: return out()
1207: else:
1208: return "Sorry file is locked by somebody else"
1.7 casties 1209:
1.1 dwinter 1210:
1.7 casties 1211: def manage_addVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', from_tmp=False, RESPONSE=None):
1.1 dwinter 1212: """add"""
1213: try: #der ganze vC unsinn muss ueberarbeitet werden
1214: vC=self.REQUEST['vC']
1215: except:
1216: pass
1217:
1218: author=self.REQUEST['author']
1219:
1.7 casties 1220: ob = self.addContentObject(id, vC, author, file, title, changeName=changeName, newName=newName, from_tmp=from_tmp,
1221: precondition=precondition, content_type=content_type)
1222:
1.1 dwinter 1223: self.REQUEST.SESSION['objID_parent']=self.getId()
1224:
1225: if RESPONSE:
1.7 casties 1226: if ob.getSize()==0:
1227: self.REQUEST.SESSION['objID']=ob.getId()
1.1 dwinter 1228: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
1229: return pt()
1230:
1231: else:
1.19 casties 1232: RESPONSE.redirect(self.absolute_url()+'/history')
1.1 dwinter 1233: else:
1.7 casties 1234: return ob
1.6 casties 1235:
1.15 casties 1236:
1237: changeVersionedFileForm = PageTemplateFile('zpt/changeVersionedFile', globals())
1238:
1.35 ! casties 1239: def manage_changeVersionedFile(self,title,vC,author,comment,defaultAction='history',RESPONSE=None):
1.15 casties 1240: """Change VersionedFile metadata"""
1241: self.title = title
1242: self.author = author
1.35 ! casties 1243: self.defaultAction = defaultAction
1.15 casties 1244: cob = self.getContentObject()
1245: if cob:
1246: if vC:
1247: cob.vComment=vC
1248:
1249: if comment=='':
1250: cob.versionComment=None
1251: else:
1252: cob.versionComment=comment
1253:
1.16 casties 1254: if RESPONSE:
1255: RESPONSE.redirect('manage_main')
1256:
1.1 dwinter 1257:
1258: def download(self):
1.15 casties 1259: """download"""
1.26 dwinter 1260:
1261: txt=self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId()+'/download'
1262:
1263: self.REQUEST.RESPONSE.redirect(txt)
1.16 casties 1264:
1.1 dwinter 1265:
1266: security.declareProtected('AUTHENTICATED_USER','downloadLocked')
1267: def downloadLocked(self):
1268: """download and lock"""
1269:
1270: if repr(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
1271: return "please login first"
1272: if not self.lockedBy=="":
1273: return "cannot be locked because is already locked by %s"%self.lockedBy
1274: self.lockedBy=self.REQUEST['AUTHENTICATED_USER']
1.7 casties 1275: self.getContentObject().content_type="application/octet-stream"
1276: self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId())
1277:
1278:
1279: security.declareProtected('AUTHENTICATED_USER','fixVersionNumbers')
1280: def fixVersionNumbers(self):
1281: """check last version number and id"""
1282: if not hasattr(self, 'lastVersionId'):
1283: self.lastVersionNumber = 0
1284: self.lastVersionId = None
1285:
1286: lv = self.getContentObject()
1287: if lv is not None:
1288: lvn = lv.getVersionNumber()
1289: if lvn == 0:
1290: lvn = 1
1291: lv.versionNumber = 1
1292: self.lastVersionNumber = lvn
1293: self.lastVersionId = lv.getId()
1294: else:
1295: self.lastVersionNumber = 0
1296: self.lastVersionId = None
1297: logging.debug("fixing last version number of %s to %s (%s)"%(self.getId(),self.lastVersionNumber,self.lastVersionId))
1298:
1.1 dwinter 1299:
1300: def manage_addextVersionedFileForm(self):
1301: """interface for adding the OSAS_root"""
1302: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addextVersionedFile.zpt')).__of__(self)
1303: return pt()
1304:
1.35 ! casties 1305: def manage_addextVersionedFile(self,id,title,lockedBy, author=None, defaultAction='history', RESPONSE=None):
1.1 dwinter 1306: """add the OSAS_root"""
1.35 ! casties 1307: newObj=extVersionedFile(id,title,lockedBy,author,defaultAction=defaultAction)
1.1 dwinter 1308: self._setObject(id,newObj)
1.6 casties 1309:
1.1 dwinter 1310: if RESPONSE is not None:
1311: RESPONSE.redirect('manage_main')
1312:
1313:
1314: InitializeClass(extVersionedFile)
1315: InitializeClass(extVersionedFileFolder)
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>