File:  [Repository] / versionedFile / extVersionedFile.py
Revision 1.8: download - view: text, annotated - select for diffs - revision graph
Mon Sep 10 17:40:37 2007 UTC (16 years, 8 months ago) by casties
Branches: MAIN
CVS tags: HEAD
some more cleanup

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>