Diff for /versionedFile/extVersionedFile.py between versions 1.1 and 1.23

version 1.1, 2006/10/04 07:35:27 version 1.23, 2008/06/27 17:49:17
Line 1 Line 1
   """actual version of the versioned file folder with external filestorage, 
   using the ExtFile Product, this version replaces externaVersionedFile.py
   DW 11.10.2006
   """
   
 from OFS.Folder import Folder  from OFS.Folder import Folder
 from OFS.Image import File  from OFS.Image import File
 from OFS.Image import cookId  from OFS.Image import cookId
Line 17  try: Line 22  try:
 except:  except:
  print "no images"   print "no images"
   
   
 from threading import Thread  from threading import Thread
 import shutil  import shutil
 import tempfile  import tempfile
 import os.path  import os.path
 import urllib  import urllib
   
 import time  import time
   import logging
   import types
   
 try:  try:
     from Products.ECHO_content.ECHO_collection import ECHO_basis      from Products.ECHO_content.ECHO_collection import ECHO_basis
 except:  except:
Line 36  except: Line 42  except:
           
 def sortv(x,y):  def sortv(x,y):
     return cmp(x[0],y[0])      return cmp(x[0],y[0])
   
 tdir = "/tmp/downloadVersionedFiles"  tdir = "/tmp/downloadVersionedFiles"
   
 class generateDownloadZip:  class generateDownloadZip:
Line 54  class generateDownloadZip: Line 61  class generateDownloadZip:
     tempfile.tempdir=tdir      tempfile.tempdir=tdir
   
         tmpPath=tempfile.mktemp()          tmpPath=tempfile.mktemp()
         tmpZip=tempfile.mktemp()+".gtz"          tmpZip=tempfile.mktemp()+".tgz"
         tmpFn=os.path.split(tmpZip)[1]          tmpFn=os.path.split(tmpZip)[1]
                   
         if not os.path.exists(tempfile.tempdir):          if not os.path.exists(tempfile.tempdir):
Line 66  class generateDownloadZip: Line 73  class generateDownloadZip:
     self.response="<h3>1. step: getting the files</h3>"      self.response="<h3>1. step: getting the files</h3>"
   
         for files in self.folder.ZopeFind(self.folder,obj_metatypes=['extVersionedFile']):          for files in self.folder.ZopeFind(self.folder,obj_metatypes=['extVersionedFile']):
             lastV=files[1].getLastVersion()              lastV=files[1].getContentObject()
             self.response+=str("<p>Get File: %s<br>\n"%lastV.title)              self.response+=str("<p>Get File: %s<br>\n"%lastV.title)
   
             savePath=os.path.join(tmpPath,lastV.title)              savePath=os.path.join(tmpPath,lastV.title)
             fh=file(savePath,"w")              fh=file(savePath,"w")
             fh.write(lastV.data)              fh.write(lastV.getData())
             fh.close()              fh.close()
   
         self.response+="<h3>2. step: creating the downloadable file</h3>"          self.response+="<h3>2. step: creating the downloadable file</h3>"
Line 85  class generateDownloadZip: Line 92  class generateDownloadZip:
             if c==")":              if c==")":
                 self.response+="<br>\n"                  self.response+="<br>\n"
                           
                   
   
           
         shutil.rmtree(tmpPath)          shutil.rmtree(tmpPath)
   
         self.response+="<p>finished<br>\n"          self.response+="<p>finished<br>\n"
Line 115  class generateDownloadZip: Line 119  class generateDownloadZip:
   
 class extVersionedFileFolder(Folder,ECHO_basis):  class extVersionedFileFolder(Folder,ECHO_basis):
     """Folder with versioned files"""      """Folder with versioned files"""
   
       
     meta_type = "extVersionedFileFolder"      meta_type = "extVersionedFileFolder"
   
     security= ClassSecurityInfo()      security= ClassSecurityInfo()
     security.declareProtected('AUTHENTICATED_USER','addFileForm')      security.declareProtected('AUTHENTICATED_USER','addFileForm')
     filesMetaType=['extVersionedFile']  
       file_meta_type=['extVersionedFile']
   
     if ECHO_basis:      if ECHO_basis:
         optTMP= Folder.manage_options+ECHO_basis.manage_options          optTMP= Folder.manage_options+ECHO_basis.manage_options
     else:      else:
Line 131  class extVersionedFileFolder(Folder,ECHO Line 135  class extVersionedFileFolder(Folder,ECHO
         {'label':'Generate Index.html','action':'generateIndexHTML'},          {'label':'Generate Index.html','action':'generateIndexHTML'},
                 {'label':'Generate Image Index.html','action':'generateIndexHTML_image'},                  {'label':'Generate Image Index.html','action':'generateIndexHTML_image'},
                 {'label':'Generate history_template.html','action':'generateHistoryHTML'},                  {'label':'Generate history_template.html','action':'generateHistoryHTML'},
                 {'label':'Import Folder','action':'importFolderForm'},          {'label':'Import directory','action':'importFolderForm'},
                 {'label':'Export Folder','action':'exportFolder'},          {'label':'Export as file','action':'exportFolder'},
           {'label':'Import versionedFileFolder','action':'importVersionedFileFolderForm'},
                 {'label':'Position of version number','action':'changeHistoryFileNamesForm'},                  {'label':'Position of version number','action':'changeHistoryFileNamesForm'},
                 )                  )
   
Line 145  class extVersionedFileFolder(Folder,ECHO Line 150  class extVersionedFileFolder(Folder,ECHO
           
     def changeHistoryFileNames(self,positionVersionNum="front",RESPONSE=None):      def changeHistoryFileNames(self,positionVersionNum="front",RESPONSE=None):
         """change position of version num"""          """change position of version num"""
           
           
           
         versions=self.ZopeFind(self,obj_metatypes=['extVersionedFileObject'],search_sub=1)          versions=self.ZopeFind(self,obj_metatypes=['extVersionedFileObject'],search_sub=1)
                   
         if not (getattr(self,'positionVersionNum','front')==positionVersionNum):          if not (getattr(self,'positionVersionNum','front')==positionVersionNum):
Line 171  class extVersionedFileFolder(Folder,ECHO Line 173  class extVersionedFileFolder(Folder,ECHO
                     else:                      else:
                         id=tmp[0]+"_"+version[1].getId().split("_")[0]                          id=tmp[0]+"_"+version[1].getId().split("_")[0]
                                   
                   
                   
                 version[1].aq_parent.manage_renameObjects(ids=[version[1].getId()],new_ids=[id])                  version[1].aq_parent.manage_renameObjects(ids=[version[1].getId()],new_ids=[id])
                 version[1].title=id                  version[1].title=id
                                   
                   
         self.positionVersionNum=positionVersionNum                  self.positionVersionNum=positionVersionNum        
         if RESPONSE:          if RESPONSE:
             RESPONSE.redirect("manage_main")              RESPONSE.redirect("manage_main")
Line 189  class extVersionedFileFolder(Folder,ECHO Line 188  class extVersionedFileFolder(Folder,ECHO
         return pt()          return pt()
                   
     def importFolder(self,path,comment="",author=None,lockedBy=None,RESPONSE=None):      def importFolder(self,path,comment="",author=None,lockedBy=None,RESPONSE=None):
         """importiere inhalt eines folders"""          """import contents of a folder on the server"""
   
         for fileName in os.listdir(path):          for fileName in os.listdir(path):
             if os.path.isfile(os.path.join(path,fileName)):              fn = os.path.join(path,fileName)
                 manage_addextVersionedFile(self,fileName,'','')              if os.path.isfile(fn):
                 id=fileName                  f = file(fn)
                 ob=self._getOb(fileName)                  self.addFile(vC=comment, file=f, author=author)
                 ob.title=id          
                 file2=file(os.path.join(path,fileName))          if RESPONSE:
               RESPONSE.redirect(self.REQUEST['URL1'])
   
       def importVersionedFileFolderForm(self):
           """form fuer versionedFileFolder import"""
           pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','importVersionedFileFolderForm.zpt')).__of__(self)
           return pt()
       
       def importVersionedFileFolder(self,path,RESPONSE=None):
           """import contents of a versionedFileFolder on the server"""
           vff = getattr(self.aq_parent, path, None)
           if vff is None:
               return "SORRY, unable to import %s"%path
           
           tmpPath=tempfile.mktemp()
           if not os.path.exists(tempfile.tempdir):
               os.mkdir(tempfile.tempdir) 
   
           if not os.path.exists(tmpPath):
               os.mkdir(tmpPath) 
   
           for (vfn, vf) in vff.getVersionedFiles():
               if vf.meta_type == 'versionedFile':
                   logging.error("importvff: importing %s of type %s!"%(vfn,vf.meta_type))
                   title = vf.title
                   fob = vf.getLastVersion()
                   author = fob.getLastEditor()
                   vc = fob.getVersionComment()
                   # save file to filesystem
                   savePath=os.path.join(tmpPath,title)
                   fh=file(savePath,"w")
                   data = vf.getLastVersion().data
                   if isinstance(data, str):
                       # simple data object
                       fh.write(data)
                   else:
                       # chained data objects
                       while data is not None:
                           fh.write(data.data)
                           data = data.next
                   fh.close()
                   # and read in again
                   fh = file(savePath)
                   logging.error("importvff: comment=%s author=%s!"%(vc,author))
                   self.addFile(vC=vc, file=fh, author=author)
                   # copy more fields
                   newfob = getattr(self, vfn).getContentObject()
                   newfob.vComment = fob.vComment
                   newfob.time = fob.time
                   logging.error("importvff: vc=%s time=%s of %s!"%(fob.vComment,fob.time,fob.getId()))
                   
               else:
                   logging.error("importvff: unable to import %s of type %s!"%(vfn,vf.meta_type))
                   
                 obj=ob.manage_addextVersionedFileObject(id,comment,author,file2,content_type='')          shutil.rmtree(tmpPath)
   
         if RESPONSE:          if RESPONSE:
             RESPONSE.redirect(self.REQUEST['URL1'])              RESPONSE.redirect(self.REQUEST['URL1'])
Line 219  class extVersionedFileFolder(Folder,ECHO Line 269  class extVersionedFileFolder(Folder,ECHO
         downloadZip=generateDownloadZip(self,self.absolute_url())          downloadZip=generateDownloadZip(self,self.absolute_url())
         downloadZip()          downloadZip()
         return downloadZip.getResult()          return downloadZip.getResult()
       
        ##  if not threadName or threadName=="":         ##  if not threadName or threadName=="":
 ##             threadStart=generateDownloadZip(self,self.absolute_url())  ##             threadStart=generateDownloadZip(self,self.absolute_url())
 ##             thread=Thread(target=threadStart)  ##             thread=Thread(target=threadStart)
Line 322  class extVersionedFileFolder(Folder,ECHO Line 373  class extVersionedFileFolder(Folder,ECHO
   
     def generateIndexHTML(self,RESPONSE=None):      def generateIndexHTML(self,RESPONSE=None):
         """lege standard index.html an"""          """lege standard index.html an"""
   
   
         if not self.ZopeFind(self,obj_ids=['index.html']):          if not self.ZopeFind(self,obj_ids=['index.html']):
             zt=ZopePageTemplate('index.html')              zt=ZopePageTemplate('index.html')
             self._setObject('index.html',zt)              self._setObject('index.html',zt)
Line 341  class extVersionedFileFolder(Folder,ECHO Line 390  class extVersionedFileFolder(Folder,ECHO
   
     def generateHistoryHTML(self,RESPONSE=None):      def generateHistoryHTML(self,RESPONSE=None):
         """lege standard index.html an"""          """lege standard index.html an"""
   
           
   
         if not self.ZopeFind(self,obj_ids=['history_template.html']):          if not self.ZopeFind(self,obj_ids=['history_template.html']):
             zt=ZopePageTemplate('history_template.html')              zt=ZopePageTemplate('history_template.html')
             self._setObject('history_template.html',zt)              self._setObject('history_template.html',zt)
Line 359  class extVersionedFileFolder(Folder,ECHO Line 405  class extVersionedFileFolder(Folder,ECHO
             RESPONSE.redirect('manage_main')              RESPONSE.redirect('manage_main')
   
           
          
   
     def getVersionedFiles(self,sortField='title'):      def getVersionedFiles(self,sortField='title'):
         """get all versioned files"""          """get all versioned files"""
   
Line 368  class extVersionedFileFolder(Folder,ECHO Line 412  class extVersionedFileFolder(Folder,ECHO
             return cmp(x[1].title.lower(),y[1].title.lower())              return cmp(x[1].title.lower(),y[1].title.lower())
   
         def sortDate(x,y):          def sortDate(x,y):
             return cmp(y[1].getLastVersion().getTime(),x[1].getLastVersion().getTime())              return cmp(y[1].getContentObject().getTime(),x[1].getContentObject().getTime())
   
                   
         def sortComment(x,y):          def sortComment(x,y):
   
           
               
      try:       try:
         xc=getattr(x[1],'comment','ZZZZZZZZZZZZZ').lower()          xc=getattr(x[1],'comment','ZZZZZZZZZZZZZ').lower()
      except:       except:
         xc='ZZZZZZZZZZZZZ'.lower()          xc='ZZZZZZZZZZZZZ'.lower()
                   
      try:       try:
         yc=getattr(y[1],'comment','ZZZZZZZZZZZZZ').lower()          yc=getattr(y[1],'comment','ZZZZZZZZZZZZZ').lower()
          except:           except:
             yc='ZZZZZZZZZZZZZ'.lower()              yc='ZZZZZZZZZZZZZ'.lower()
   
   
          if (xc=='') or (xc=='ZZZZZZZZZZZZZ'.lower()):           if (xc=='') or (xc=='ZZZZZZZZZZZZZ'.lower()):
                
              try:               try:
                  xc=x[1].getLastVersion().getVComment().lower()                      xc=x[1].getContentObject().getVComment().lower()
              except:               except:
                  xc='ZZZZZZZZZZZZZ'.lower()                   xc='ZZZZZZZZZZZZZ'.lower()
                                     
          if (yc=='') or (yc=='ZZZZZZZZZZZZZ'.lower()):           if (yc=='') or (yc=='ZZZZZZZZZZZZZ'.lower()):
              try:               try:
                  yc=y[1].getLastVersion().getVComment().lower()                      yc=y[1].getContentObject().getVComment().lower()
              except:               except:
                  yc='ZZZZZZZZZZZZZ'.lower()                   yc='ZZZZZZZZZZZZZ'.lower()
   
            
          return cmp(xc,yc)           return cmp(xc,yc)
   
         def sortAuthor(x,y):          def sortAuthor(x,y):
                           
             return cmp(x[1].getLastVersion().lastEditor().lower(),y[1].getLastVersion().lastEditor().lower())              return cmp(x[1].getContentObject().lastEditor().lower(),y[1].getContentObject().lastEditor().lower())
           
         versionedFiles=self.ZopeFind(self,obj_metatypes=self.filesMetaType)  
                   
           versionedFiles=self.objectItems(self.file_meta_type)
           logging.debug("versionedfiles: %s of type %s"%(repr(versionedFiles),repr(self.file_meta_type)))
                   
         if sortField=='title':          if sortField=='title':
             versionedFiles.sort(sortName)              versionedFiles.sort(sortName)
Line 421  class extVersionedFileFolder(Folder,ECHO Line 459  class extVersionedFileFolder(Folder,ECHO
   
   
     def header_html(self):      def header_html(self):
         """zusätzlicher header"""          """zusaetzlicher header"""
         ext=self.ZopeFind(self,obj_ids=["header.html"])          ext=self.ZopeFind(self,obj_ids=["header.html"])
         if ext:          if ext:
             return ext[0][1]()              return ext[0][1]()
Line 451  class extVersionedFileFolder(Folder,ECHO Line 489  class extVersionedFileFolder(Folder,ECHO
         return out()          return out()
   
   
     def addFile(self,vC,file,author,newName='',content_type='',RESPONSE=None):      def addFile(self,vC,file,author='',newName='',content_type='',RESPONSE=None):
         """ add a new file"""          """ add a new file"""
           # is file is a real file or a zope download object?
           isRealFile = type(file) is types.FileType
   
         if newName=='':          if newName=='':
               logging.debug("fileobject: %s real:%s"%(repr(file),repr(isRealFile)))
               if isRealFile:
                   filename = file.name
               else:
             filename=file.filename              filename=file.filename
   
             id=filename[max(filename.rfind('/'),              id=filename[max(filename.rfind('/'),
                                     filename.rfind('\\'),                                      filename.rfind('\\'),
                                     filename.rfind(':'),                                      filename.rfind(':'),
Line 463  class extVersionedFileFolder(Folder,ECHO Line 509  class extVersionedFileFolder(Folder,ECHO
         else:          else:
             id=newName              id=newName
                   
           if vC is None:
         vC=self.REQUEST.form['vC']          vC=self.REQUEST.form['vC']
         manage_addextVersionedFile(self,id,'','')  
         #if (getattr(self,'commentNonEmpty',0)==1) and vC.strip()=="":  
                           
           # get new extVersionedFile
           vf = self._newVersionedFile(id,title=id)
           logging.debug("addFile id=%s vf=%s of %s"%(repr(id),repr(vf),repr(self)))
           # add its content (and don't index)
           obj=vf.addContentObject(id,vC,author=author,file=file,content_type=content_type,from_tmp=isRealFile,index=False)
           # add file to this folder (this should do the indexing)
           self._setObject(id,vf)
                           
         ob=self._getOb(id)          try:
         ob.title=id              self.REQUEST.SESSION['objID']=vf.getId()
         file2=file  
           
         obj=ob.manage_addextVersionedFileObject(id,vC,author,file2,content_type=content_type)  
         self.REQUEST.SESSION['objID']=ob.getId()  
         self.REQUEST.SESSION['objID_parent']=None          self.REQUEST.SESSION['objID_parent']=None
           except:
               pass
   
         if obj.getSize()==0:          if obj.getSize()==0:
             pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)              pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
             return pt()              return pt()
                   
           if RESPONSE is not None:
         RESPONSE.redirect(self.REQUEST['URL1'])          RESPONSE.redirect(self.REQUEST['URL1'])
   
   
       def _newVersionedFile(self, id, title='', lockedBy=None, author=None):
           """factory for versioned files. to be overridden in derived classes."""
           return extVersionedFile(id, title, lockedBy=lockedBy, author=author)
   
   
     def deleteEmptyObject(self,submit,RESPONSE=None):      def deleteEmptyObject(self,submit,RESPONSE=None):
         """deleteemptyobject"""          """deleteemptyobject"""
         if submit=="delete it":          if submit=="delete it":
Line 496  class extVersionedFileFolder(Folder,ECHO Line 552  class extVersionedFileFolder(Folder,ECHO
         RESPONSE.redirect(self.REQUEST['URL1'])          RESPONSE.redirect(self.REQUEST['URL1'])
                   
                   
       security.declareProtected('AUTHENTICATED_USER','fixVersionNumbers')    
       def fixVersionNumbers(self):
           """fix last version number of all files"""
           for (id,vf) in self.getVersionedFiles():
               vf.fixVersionNumbers()
           # recursively
           for (id,vf) in self.objectItems(self.meta_type):
               vf.fixVersionNumbers()
           
   
 manage_addextVersionedFileFolderForm=DTMLFile('dtml/extfolderAdd', globals())  manage_addextVersionedFileFolderForm=DTMLFile('dtml/extfolderAdd', globals())
   
   
Line 539  class extVersionedFileObject(ExtFile): Line 605  class extVersionedFileObject(ExtFile):
                                Kind='File',kind='file')                                 Kind='File',kind='file')
     manage_editForm._setName('manage_editForm')      manage_editForm._setName('manage_editForm')
   
       def __init__(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
           """Initialize a new instance of extVersionedFileObject (taken from ExtFile)"""
           ExtFile.__init__(self,id,title)
           self.versionNumber = versionNumber
           self.versionComment= versionComment
           self.time = time
           self.author = author
   
           security.declareProtected('manage','changeObject')
       def changeObject(self,**args):
           """modify any of the objects attributes"""
           for arg in args:
               if hasattr(self, arg):
                   logging.debug("changeObject %s: %s = %s"%(self,arg,args[arg]))
                   setattr(self, arg, args[arg])
     
     security.declarePublic('getTitle')      security.declarePublic('getTitle')
   
     def getTitle(self):      def getTitle(self):
         """get title"""          """get title"""
         return self.title          return self.title
     
       def getData(self):
           """returns object content (calls ExtFile.index_html)"""
           return ExtFile.index_html(self)
       
     security.declarePublic('getVComment')      security.declarePublic('getVComment')
     def getVComment(self):      def getVComment(self):
         """get the comment of this file"""          """get the comment of this file"""
Line 559  class extVersionedFileObject(ExtFile): Line 641  class extVersionedFileObject(ExtFile):
                           
     def manageVCommentForm(self):      def manageVCommentForm(self):
         """add a comment"""          """add a comment"""
   
         self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']          self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
   
   
           
         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addVComment')).__of__(self)          pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addVComment')).__of__(self)
         return pt()          return pt()
   
Line 590  class extVersionedFileObject(ExtFile): Line 668  class extVersionedFileObject(ExtFile):
         return self.versionComment          return self.versionComment
           
     security.declarePublic('getTime')      security.declarePublic('getTime')
   
     def getTime(self):      def getTime(self):
         """getTime"""          """getTime"""
         #return self.bobobase_modification_time().ISO()          #return self.bobobase_modification_time().ISO()
Line 602  class extVersionedFileObject(ExtFile): Line 679  class extVersionedFileObject(ExtFile):
             setattr(self,'timefixed',self.bobobase_modification_time().ISO())              setattr(self,'timefixed',self.bobobase_modification_time().ISO())
             return self.bobobase_modification_time().ISO()              return self.bobobase_modification_time().ISO()
   
   
   
       
   
     def download(self,REQUEST=None,RESPONSE=None):      def download(self,REQUEST=None,RESPONSE=None):
         """download and lock"""          """download and lock"""
                   
Line 626  class extVersionedFileObject(ExtFile): Line 699  class extVersionedFileObject(ExtFile):
   
         #self.REQUEST.close()          #self.REQUEST.close()
           
       view = download
       
     security.declareProtected('AUTHENTICATED_USER','downloadLocked')          security.declareProtected('AUTHENTICATED_USER','downloadLocked')    
     def downloadLocked(self):      def downloadLocked(self):
         """download and lock"""          """download and lock"""
Line 640  class extVersionedFileObject(ExtFile): Line 715  class extVersionedFileObject(ExtFile):
         self.content_type="application/octet-stream"          self.content_type="application/octet-stream"
         self.REQUEST.RESPONSE.redirect(self.absolute_url())          self.REQUEST.RESPONSE.redirect(self.absolute_url())
           
     def setVersionNumber(self,versionNumber):  
         """set version"""  
         self.versionNumber=versionNumber  
   
   
     security.declarePublic('getVersionNumber')                                                    security.declarePublic('getVersionNumber')                                              
   
     def getVersionNumber(self):      def getVersionNumber(self):
         """get version"""          """get version"""
         return self.versionNumber          return self.versionNumber
Line 656  class extVersionedFileObject(ExtFile): Line 725  class extVersionedFileObject(ExtFile):
         """get version"""          """get version"""
         return self.versionComment          return self.versionComment
   
      
   
     security.declarePublic('lastEditor')                                                      security.declarePublic('lastEditor')                                                
   
     def lastEditor(self):      def lastEditor(self):
         """last Editor"""          """last Editor"""
         if hasattr(self,'author'):          if hasattr(self,'author'):
Line 679  class extVersionedFileObject(ExtFile): Line 745  class extVersionedFileObject(ExtFile):
             return jar.db().history(oid)[0]['user_name']              return jar.db().history(oid)[0]['user_name']
   
           
       
           
 manage_addextVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='extVersionedFileObject',kind='extVersionedFileObject', version='1')  manage_addextVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='extVersionedFileObject',kind='extVersionedFileObject', version='1')
   
 def manage_addextVersionedFileObject(self,id,vC='',author='', file='',title='',precondition='', content_type='',  def manage_addextVersionedFileObject(self,id,vC='',author='', file='',title='',versionNumber=0,
                    REQUEST=None):                                       precondition='', content_type='', REQUEST=None):
     """Add a new File object.      """Add a new File object.
   
     Creates a new File object 'id' with the contents of 'file'"""      Creates a new File object 'id' with the contents of 'file'"""
Line 699  def manage_addextVersionedFileObject(sel Line 763  def manage_addextVersionedFileObject(sel
     self=self.this()      self=self.this()
   
     # First, we create the file without data:      # First, we create the file without data:
     self._setObject(id, extVersionedFileObject(id,title,'',content_type, precondition))      self._setObject(id, extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=str(vC),author=author))
     self._getOb(id).versionComment=str(vC)      fob = self._getOb(id)
     self._getOb(id).time=time.localtime()  
       
     setattr(self._getOb(id),'author',author)  
           
     # Now we "upload" the data.  By doing this in two steps, we      # Now we "upload" the data.  By doing this in two steps, we
     # can use a database trick to make the upload more efficient.      # can use a database trick to make the upload more efficient.
     if file:      if file:
         self._getOb(id).manage_upload(file)          fob.manage_upload(file)
     if content_type:      if content_type:
         self._getOb(id).content_type=content_type          fob.content_type=content_type
   
     if REQUEST is not None:      if REQUEST is not None:
         REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')          REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
   
   
   
   
 class extVersionedFile(CatalogAware,Folder):  class extVersionedFile(CatalogAware,Folder):
     """Versioniertes File"""      """Versioniertes File"""
   
       meta_type = 'extVersionedFile'
       # meta_type of contained objects
       content_meta_type = ['extVersionedFileObject']
       # default catalog for extVersionedFile objects
     default_catalog='fileCatalog'      default_catalog='fileCatalog'
           
       manage_options = Folder.manage_options+({'label':'Main Config','action':'changeVersionedFileForm'},)
   
       
     security= ClassSecurityInfo()         security= ClassSecurityInfo()   
           
       def __init__(self, id, title, lockedBy,author):
           """init"""
           self.id=id
           self.title=title
           self.lockedBy=lockedBy
           self.author=author
           self.lastVersionNumber=0
           self.lastVersionId=None
   
     security.declarePublic('getTitle')      security.declarePublic('getTitle')
     def getTitle(self):      def getTitle(self):
         """get title"""          """get title"""
Line 734  class extVersionedFile(CatalogAware,Fold Line 810  class extVersionedFile(CatalogAware,Fold
            """Return cataloguable key for ourselves."""             """Return cataloguable key for ourselves."""
            return str(self)             return str(self)
                 
     def __init__(self, id, title, lockedBy,author):  
         """init"""  
         self.id=id  
         self.title=title  
         self.lockedBy=lockedBy  
         self.author=author  
   
     def manageImagesForm(self):      def manageImagesForm(self):
         """manage Images attached to the file"""          """manage Images attached to the file"""
   
Line 759  class extVersionedFile(CatalogAware,Fold Line 828  class extVersionedFile(CatalogAware,Fold
             return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])              return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
         return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())          return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
           
       
       
     def changeImages(self,caption=None,submit=None,id=None,REQUEST=None):      def changeImages(self,caption=None,submit=None,id=None,REQUEST=None):
         """manage URL"""          """manage URL"""
         if submit=="change caption":          if submit=="change caption":
Line 773  class extVersionedFile(CatalogAware,Fold Line 840  class extVersionedFile(CatalogAware,Fold
             if image:              if image:
                 self.manage_delObjects([image[0][1].getId()])                  self.manage_delObjects([image[0][1].getId()])
   
   
         if self.REQUEST.SESSION.has_key('refer'):          if self.REQUEST.SESSION.has_key('refer'):
   
             return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])              return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
         return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())  
       
           
   
           return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
   
     def getImages(self):      def getImages(self):
         """get Images"""          """get Images"""
Line 795  class extVersionedFile(CatalogAware,Fold Line 858  class extVersionedFile(CatalogAware,Fold
         """get the comment of this file"""          """get the comment of this file"""
         if not hasattr(self,'comment') or (not self.comment) or (self.comment.lstrip()==""):          if not hasattr(self,'comment') or (not self.comment) or (self.comment.lstrip()==""):
             return "Add comment"              return "Add comment"
   
         else:          else:
             return self.comment              return self.comment
                           
           
     meta_type="extVersionedFile"  
   
     def manageCommentForm(self):      def manageCommentForm(self):
         """add a comment"""          """add a comment"""
         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addComment')).__of__(self)          pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addComment')).__of__(self)
Line 821  class extVersionedFile(CatalogAware,Fold Line 880  class extVersionedFile(CatalogAware,Fold
         return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())          return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
                   
     security.declarePublic('getLastChangeDate')      security.declarePublic('getLastChangeDate')
       
     def getLastChangeDate(self):      def getLastChangeDate(self):
         """get last change date"""          """get last change date"""
         lv=self.getLastVersion()          lv=self.getContentObject()
           if lv:
         time=lv.getTime()          time=lv.getTime()
         return time          return time
           return None
           
     def getLastEditor(self):      def getLastEditor(self):
         """get last change date"""          """get last change date"""
         lv=self.getLastVersion()          lv=self.getContentObject()
         le=lv.lastEditor()          le=lv.lastEditor()
         return le          return le
           
Line 838  class extVersionedFile(CatalogAware,Fold Line 898  class extVersionedFile(CatalogAware,Fold
         """get locked by"""          """get locked by"""
         return str(self.lockedBy)          return str(self.lockedBy)
                   
       def getLastVersionNumber(self):
           """returns the highest version number of all included objects"""
           lv = self.findLastVersion()
           if lv:
               return lv.getVersionNumber()
           else:
               return 0
   
       def findLastVersion(self):
           """finds and returns the object with the highest version number"""
           lvn=0
           lv=None
           
           for v in self.objectValues(self.content_meta_type):
               logging.debug("findlastversion: check %s"%v.getId())
               if v.getVersionNumber() > lvn:
                       lvn=v.getVersionNumber()
                       lv=v
           
           if lv:
               logging.debug("findlastversion: got %s"%lv.getId())
           return lv
   
     security.declarePublic('getLastVersion')      security.declarePublic('getLastVersion')
     def getLastVersion(self):      def getLastVersion(self):
         """Last Version"""          """Last Version (old)"""
         tmp=0          tmp=0
         lastVersion=None          lv=None
                   
           for v in self.objectValues(self.content_meta_type):
               logging.debug("getlastversion: check %s"%v.getId())
               if v.getVersionNumber() > tmp:
                       tmp=v.getVersionNumber()
                       lv=v
           
           logging.debug("getlastversion: got %s"%lv.getId())
           return lv
   
       def getContentObject(self):
           """returns the last version object"""
           if not getattr(self, 'lastVersionId', None):
               # find last version and save it
               lv = self.findLastVersion()
               if lv is None:
                   return None
               self.lastVersionNumber = lv.getVersionNumber()
               self.lastVersionId = lv.getId()
                   
         for version in self.ZopeFind(self):          return getattr(self, self.lastVersionId, None)
                           
             if hasattr(version[1],'versionNumber'):      security.declarePublic('getData')
                       def getData(self):
                 if int(version[1].versionNumber) > tmp:          """Returns the content of the last version"""
                     tmp=int(version[1].versionNumber,)          ob = self.getContentObject()
                     lastVersion=version[1]          if ob is not None:
             if lastVersion==None:              return ob.getData()
                 lastVersion=version[1]          else:
                 lastVersion.versionNumber=1              return None
         return lastVersion  
           
       security.declarePublic('view')
       def view(self,REQUEST=None,RESPONSE=None):
           """Returns the last version's view"""
           ob = self.getContentObject()
           if ob is not None:
               return ob.view(REQUEST=REQUEST,RESPONSE=RESPONSE)
           else:
               return None
           
     def diff(self,data):      def diff(self,data):
         """differenz between lastversion and data"""          """differenz between lastversion and data"""
         d=Differ()          d=Differ()
         tmp=self.getLastVersion().data          tmp=self.getData()
         #print "XX",data,tmp          #print "XX",data,tmp
         try:          try:
          l=list(d.compare(data.splitlines(1),tmp.splitlines(1)))           l=list(d.compare(data.splitlines(1),tmp.splitlines(1)))
Line 875  class extVersionedFile(CatalogAware,Fold Line 983  class extVersionedFile(CatalogAware,Fold
             if a[0]=='-':              if a[0]=='-':
                 minus+=1                  minus+=1
                   
           
         return max([plus,minus]),l          return max([plus,minus]),l
   
   
     security.declarePublic('index_html')      security.declarePublic('index_html')
     def index_html(self):      def index_html(self):
         """main view"""          """main view"""
         lastVersion=self.getLastVersion()          #lastVersion=self.getContentObject()
         #return "File:"+self.title+"  Version:%i"%lastVersion.versionNumber," modified:",lastVersion.bobobase_modification_time()," size:",lastVersion.getSize(),"modified by:",lastVersion.lastEditor()          #return "File:"+self.title+"  Version:%i"%lastVersion.versionNumber," modified:",lastVersion.bobobase_modification_time()," size:",lastVersion.getSize(),"modified by:",lastVersion.lastEditor()
         return "File: %s Version:%i modified:%s size:%s modified by:%s"%(self.title,lastVersion.versionNumber,lastVersion.getTime(),lastVersion.getSize(),lastVersion.lastEditor())          #return "File: %s Version:%i modified:%s size:%s modified by:%s"%(self.title,lastVersion.versionNumber,lastVersion.getTime(),lastVersion.getSize(),lastVersion.lastEditor())
           return self.history()
   
             
     security.declarePublic('getVersion')                                                    security.declarePublic('getVersion')                                              
     def getVersion(self):      def getVersion(self):
           # TODO: this is ugly and it returns the next version number 
         tmp=0          tmp=0
         for version in self.ZopeFind(self):          for version in self.ZopeFind(self):
                           
Line 897  class extVersionedFile(CatalogAware,Fold Line 1007  class extVersionedFile(CatalogAware,Fold
                     tmp=int(version[1].versionNumber,)                      tmp=int(version[1].versionNumber,)
         return tmp+1          return tmp+1
   
   
     security.declareProtected('AUTHENTICATED_USER','unlock')  
   
     def history(self):      def history(self):
         """history"""            """history"""  
   
         ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])          ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
         if ext:          if ext:
             return getattr(self,ext[0][1].getId())()              return getattr(self,ext[0][1].getId())()
Line 919  class extVersionedFile(CatalogAware,Fold Line 1025  class extVersionedFile(CatalogAware,Fold
         ret.sort(sortv)          ret.sort(sortv)
         return ret          return ret
   
       def getVersionList(self):
           """get a list of dicts with author, comment, filename, etc, of all versions"""
           vl = []
           for v in self.objectValues(self.content_meta_type):
               vl.append({'versionNumber':getattr(v,'versionNumber',0),
                         'title':v.getTitle(),
                         'id':v.getId(),
                         'date':v.getTime(),
                         'author':getattr(v,'author',''),
                         'comment':getattr(v,'versionComment','')
                         })
           return vl
   
     security.declareProtected('AUTHENTICATED_USER','forceunlock')         security.declareProtected('AUTHENTICATED_USER','forceunlock')   
     def forceunlock(self,RESPONSE=None):      def forceunlock(self,RESPONSE=None):
         """unlock"""          """unlock"""
Line 940  class extVersionedFile(CatalogAware,Fold Line 1059  class extVersionedFile(CatalogAware,Fold
             return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER'])              return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER'])
                   
   
       def _newContentObject(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
           """factory for content objects. to be overridden in derived classes."""
           return extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=versionComment,time=time,author=author)
           
     security.declareProtected('AUTHENTICATED_USER','addVersionedFileObjectForm')  
   
       def addContentObject(self,id,vC,author=None,file=None,title='',changeName='no',newName='',from_tmp=False,index=True,
                            precondition='', content_type=''):
           """add"""
           
           if changeName=="yes":
               filename=file.filename
               self.title=filename[max(filename.rfind('/'),
                                       filename.rfind('\\'),
                                       filename.rfind(':'),
                                       )+1:]
   
           if not newName=='':
               self.title=newName[0:]
           
           posVersNum=getattr(self,'positionVersionNum','front')
           
           versNum = self.getLastVersionNumber() + 1
           
           if posVersNum=='front':
               id="V%i_%s"%(versNum,self.title)
           else:
               fn=os.path.splitext(self.title)
               if len(fn)>1:
                   id=fn[0]+"_V%i%s"%(versNum,fn[1])
               else:
                   id=fn[0]+"_V%i"%versNum
   
           # what does this do?
           id, title = cookId(id, title, file)
           self=self.this()
       
           # First, we create the file without data:
           self._setObject(id, self._newContentObject(id,title,versionNumber=versNum,versionComment=str(vC),
                                                 time=time.localtime(),author=author))
           fob = self._getOb(id)
           
           # Now we "upload" the data.  By doing this in two steps, we
           # can use a database trick to make the upload more efficient.
           if file and not from_tmp:
               fob.manage_upload(file)
           elif file and from_tmp:
               fob.manage_file_upload(file) # manage_upload_from_tmp doesn't exist in ExtFile2
           #    fob.manage_upload_from_tmp(file) # manage_upload_from_tmp doesn't exist in ExtFile2
           fob.content_type=content_type
           
           self.lastVersionNumber = versNum
           self.lastVersionId = id
           
           #logging.debug("addcontentobject: lastversion=%s"%self.getData())
           #logging.debug("addcontentobject: fob_data=%s"%fob.getData())
           if index and self.default_catalog:
               logging.debug("reindex1: %s in %s"%(repr(self),repr(self.default_catalog)))
               self.reindex_object()
           
           return fob
               
       
       security.declareProtected('AUTHENTICATED_USER','addVersionedFileObjectForm')
     def addVersionedFileObjectForm(self):      def addVersionedFileObjectForm(self):
         """add a new version"""          """add a new version"""
                   
Line 951  class extVersionedFile(CatalogAware,Fold Line 1130  class extVersionedFile(CatalogAware,Fold
         if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):          if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
             ext=self.ZopeFind(self.aq_parent,obj_ids=["addNewVersion.dtml"])              ext=self.ZopeFind(self.aq_parent,obj_ids=["addNewVersion.dtml"])
             if ext:              if ext:
                 return ext[0][1]('',globals(),version=self.getVersion(),lastComment=self.getLastVersion().getVersionComment(),AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)                  return ext[0][1]('',globals(),version=self.getVersion(),lastComment=self.getContentObject().getVersionComment(),AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)
             else:              else:
                 out=DTMLFile('dtml/fileAdd', globals(),Kind='VersionedFileObject',kind='versionedFileObject',version=self.getVersion()).__of__(self)                  out=DTMLFile('dtml/fileAdd', globals(),Kind='VersionedFileObject',kind='versionedFileObject',version=self.getVersion()).__of__(self)
                 return out()                  return out()
         else:          else:
             return "Sorry file is locked by somebody else"              return "Sorry file is locked by somebody else"
                   
     def manage_addVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', RESPONSE=None):          
       def manage_addVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', from_tmp=False, RESPONSE=None):
         """add"""          """add"""
         try: #der ganze vC unsinn muss ueberarbeitet werden          try: #der ganze vC unsinn muss ueberarbeitet werden
             vC=self.REQUEST['vC']              vC=self.REQUEST['vC']
Line 967  class extVersionedFile(CatalogAware,Fold Line 1147  class extVersionedFile(CatalogAware,Fold
                   
         author=self.REQUEST['author']          author=self.REQUEST['author']
                   
         if changeName=="yes":          ob = self.addContentObject(id, vC, author, file, title, changeName=changeName, newName=newName, from_tmp=from_tmp,
             filename=file.filename                                     precondition=precondition, content_type=content_type)
             self.title=filename[max(filename.rfind('/'),  
                         filename.rfind('\\'),  
                         filename.rfind(':'),  
                         )+1:]  
   
   
         if not newName=='':  
             self.title=newName[0:]  
           
           
   
           
           
         positionVersionNum=getattr(self,'positionVersionNum','front')  
           
         if positionVersionNum=='front':  
             id="V%i"%self.getVersion()+"_"+self.title  
         else:  
             tmp=os.path.splitext(self.title)  
             if len(tmp)>1:  
                 id=tmp[0]+"_V%i"%self.getVersion()+tmp[1]  
             else:  
                 id=tmp[0]+"_V%i"%self.getVersion()  
                           
           
         manage_addextVersionedFileObject(self,id,vC,author,file,id,precondition, content_type)  
         objs=self.ZopeFind(self,obj_ids=[id])[0][1].setVersionNumber(int(self.getVersion()))  
         self.REQUEST.SESSION['objID_parent']=self.getId()          self.REQUEST.SESSION['objID_parent']=self.getId()
   
         if getattr(self,'defaultFileCatalog',None):  
               
             self.reindex_object()  
               
         if RESPONSE:          if RESPONSE:
             obj=self.ZopeFind(self,obj_ids=[id])[0][1]              if ob.getSize()==0:
             if obj.getSize()==0:                  self.REQUEST.SESSION['objID']=ob.getId()
                 self.REQUEST.SESSION['objID']=obj.getId()  
                 pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)                  pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
                 return pt()                  return pt()
   
             else:              else:
                 RESPONSE.redirect(self.REQUEST['URL2'])                  RESPONSE.redirect(self.absolute_url()+'/history')
   
         else:          else:
             return self.ZopeFind(self,obj_ids=[id])[0][1]              return ob
                   
     security.declareProtected('AUTHENTICATED_USER','downloadLocked')  
   
     def download(self):      changeVersionedFileForm = PageTemplateFile('zpt/changeVersionedFile', globals())
         """download and lock"""  
   
         self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getLastVersion().getId())      def manage_changeVersionedFile(self,title,vC,author,comment,RESPONSE=None):
         self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")          """Change VersionedFile metadata"""
           self.title = title
           self.author = author
           cob = self.getContentObject()
           if cob:
               if vC:
                   cob.vComment=vC
               
     #try:                 if comment=='':
     #   txt=self.getLastVersion.index_html()                  cob.versionComment=None
     #except:              else:
     #   txt=self.getLastVersion.index_html(REQUEST,RESPONSE)                  cob.versionComment=comment
   
           if RESPONSE:
               RESPONSE.redirect('manage_main')
   
     #self.REQUEST.RESPONSE.setHeader("Content-Length","str(len(txt)+1000)")  
                   
       def download(self):
           """download"""
           self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getContentObject().getId())
           self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
         self.content_type="application/octet-stream"          self.content_type="application/octet-stream"
         #self.REQUEST.RESPONSE.write("bl")          self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId())
         #self.REQUEST.RESPONSE.write(txt)  
         #self.REQUEST.close()  
   
         #self.getLastVersion().content_type="application/octet-stream"  
         self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId())  
           
     security.declareProtected('AUTHENTICATED_USER','downloadLocked')          security.declareProtected('AUTHENTICATED_USER','downloadLocked')    
     def downloadLocked(self):      def downloadLocked(self):
Line 1047  class extVersionedFile(CatalogAware,Fold Line 1201  class extVersionedFile(CatalogAware,Fold
         if not self.lockedBy=="":          if not self.lockedBy=="":
             return "cannot be locked because is already locked by %s"%self.lockedBy              return "cannot be locked because is already locked by %s"%self.lockedBy
         self.lockedBy=self.REQUEST['AUTHENTICATED_USER']          self.lockedBy=self.REQUEST['AUTHENTICATED_USER']
         self.getLastVersion().content_type="application/octet-stream"          self.getContentObject().content_type="application/octet-stream"
         self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId())          self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId())
       
   
       security.declareProtected('AUTHENTICATED_USER','fixVersionNumbers')    
       def fixVersionNumbers(self):
           """check last version number and id"""
           if not hasattr(self, 'lastVersionId'):
               self.lastVersionNumber = 0
               self.lastVersionId = None
               
           lv = self.getContentObject()
           if lv is not None:
               lvn = lv.getVersionNumber()
               if lvn == 0:
                   lvn = 1
                   lv.versionNumber = 1
               self.lastVersionNumber = lvn
               self.lastVersionId = lv.getId()
           else:
               self.lastVersionNumber = 0
               self.lastVersionId = None
           logging.debug("fixing last version number of %s to %s (%s)"%(self.getId(),self.lastVersionNumber,self.lastVersionId))
       
           
 def manage_addextVersionedFileForm(self):  def manage_addextVersionedFileForm(self):
     """interface for adding the OSAS_root"""      """interface for adding the OSAS_root"""

Removed from v.1.1  
changed lines
  Added in v.1.23


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