File:  [Repository] / versionedFile / extVersionedFile.py
Revision 1.5: download - view: text, annotated - select for diffs - revision graph
Mon Jun 25 11:05:03 2007 UTC (17 years ago) by casties
Branches: MAIN
CVS tags: HEAD
fixed extVersionedFile's creation of files
new version.txt

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

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