Diff for /versionedFile/extVersionedFile.py between versions 1.7 and 1.34

version 1.7, 2007/09/10 16:34:16 version 1.34, 2009/08/31 14:07:35
Line 3  using the ExtFile Product, this version Line 3  using the ExtFile Product, this version
 DW 11.10.2006  DW 11.10.2006
 """  """
   
   import email
 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 29  import os.path Line 30  import os.path
 import urllib  import urllib
 import time  import time
 import logging  import logging
   import types
   
 try:  try:
     from Products.ECHO_content.ECHO_collection import ECHO_basis      from Products.ECHO_content.ECHO_collection import ECHO_basis
Line 134  class extVersionedFileFolder(Folder,ECHO Line 136  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'},
         )          )
   
           
       def redirect(self,RESPONSE,url):
           """mache ein redirect mit einem angehaengten time stamp um ein reload zu erzwingen"""
           
           timeStamp=time.time()
           
           if url.find("?")>-1: #giebt es schon parameter
               addStr="&time=%s"
           else:
               addStr="?time=%s"
               
           RESPONSE.setHeader('Last-Modified',email.Utils.formatdate().split("-")[0]+'GMT')
           logging.error(email.Utils.formatdate()+' GMT')
           RESPONSE.redirect(url+addStr%timeStamp)
     def changeHistoryFileNamesForm(self):      def changeHistoryFileNamesForm(self):
         """change position of version num"""          """change position of version num"""
         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeHistoryFileNamesForm.zpt')).__of__(self)          pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeHistoryFileNamesForm.zpt')).__of__(self)
Line 186  class extVersionedFileFolder(Folder,ECHO Line 202  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 216  class extVersionedFileFolder(Folder,ECHO Line 283  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 435  class extVersionedFileFolder(Folder,ECHO Line 503  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 447  class extVersionedFileFolder(Folder,ECHO Line 523  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()=="":  
                   
         ob=self._getOb(id)          # get new extVersionedFile
         ob.title=id          vf = self._newVersionedFile(id,title=id)
         file2=file          logging.error("addFile id=%s vf=%s of %s"%(repr(id),repr(vf),repr(self)))
           # add its content (and don't index)
           self._setObject(id,vf)
           vf=getattr(self,id)
   
           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)
                   
         logging.info("ADD: %s"%repr(ob))          try:
         obj=ob.manage_addVersionedFileObject(id,vC,author,file2,content_type=content_type)              self.REQUEST.SESSION['objID']=vf.getId()
         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 485  class extVersionedFileFolder(Folder,ECHO Line 574  class extVersionedFileFolder(Folder,ECHO
         """fix last version number of all files"""          """fix last version number of all files"""
         for (id,vf) in self.getVersionedFiles():          for (id,vf) in self.getVersionedFiles():
             vf.fixVersionNumbers()              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 537  class extVersionedFileObject(ExtFile): Line 630  class extVersionedFileObject(ExtFile):
         self.time = time          self.time = time
         self.author = author          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"%(repr(self),arg,args[arg]))
                   setattr(self, arg, args[arg])
   
     security.declarePublic('getTitle')      security.declarePublic('getTitle')
     def getTitle(self):      def getTitle(self):
Line 545  class extVersionedFileObject(ExtFile): Line 645  class extVersionedFileObject(ExtFile):
           
     def getData(self):      def getData(self):
         """returns object content (calls ExtFile.index_html)"""          """returns object content (calls ExtFile.index_html)"""
           #logging.debug("+++++++getData1:"+repr(self.get_filename()))
           filename = self.get_filename()
           #return ExtFile.index_html(self)
           try:
               logging.info("readfile:"+filename)
               return file(filename).read()
           except:
               logging.info("cannot readfile:"+filename)
         return ExtFile.index_html(self)          return ExtFile.index_html(self)
           
       
       def getFileName(self):
           """return filename"""
           return self.get_filename()
       
       def addToFile(self,filehandle):
           filehandle.write(self.getData())
           
       def addToFile2(self,filename):   
            str="cat %s > %s"%(self.get_filename(),filename)
            os.popen(str)
            
     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 609  class extVersionedFileObject(ExtFile): Line 729  class extVersionedFileObject(ExtFile):
     #self.REQUEST.RESPONSE.setHeader("Content-Length","str(len(txt)+1000)")      #self.REQUEST.RESPONSE.setHeader("Content-Length","str(len(txt)+1000)")
                   
         self.content_type="application/octet-stream"          self.content_type="application/octet-stream"
         self.REQUEST.RESPONSE.redirect(self.absolute_url())          return self.getData()
           #self.REQUEST.RESPONSE.redirect(self.absolute_url())
         #txt=urllib.urlopen(self.absolute_url()).read()          #txt=urllib.urlopen(self.absolute_url()).read()
         #self.REQUEST.RESPONSE.write(txt)          #self.REQUEST.RESPONSE.write(txt)
           
   
         #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 699  class extVersionedFile(CatalogAware,Fold Line 822  class extVersionedFile(CatalogAware,Fold
     meta_type = 'extVersionedFile'      meta_type = 'extVersionedFile'
     # meta_type of contained objects      # meta_type of contained objects
     content_meta_type = ['extVersionedFileObject']      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):      def __init__(self, id, title, lockedBy,author):
Line 708  class extVersionedFile(CatalogAware,Fold Line 835  class extVersionedFile(CatalogAware,Fold
         self.id=id          self.id=id
         self.title=title          self.title=title
         self.lockedBy=lockedBy          self.lockedBy=lockedBy
           if self.lockedBy is None:
               self.lockedBy = ''
         self.author=author          self.author=author
         self.lastVersionNumber=0          self.lastVersionNumber=0
         self.lastVersionId=None          self.lastVersionId=None
Line 794  class extVersionedFile(CatalogAware,Fold Line 923  class extVersionedFile(CatalogAware,Fold
     def getLastChangeDate(self):      def getLastChangeDate(self):
         """get last change date"""          """get last change date"""
         lv=self.getContentObject()          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"""
Line 805  class extVersionedFile(CatalogAware,Fold Line 936  class extVersionedFile(CatalogAware,Fold
           
     def getLockedBy(self):      def getLockedBy(self):
         """get locked by"""          """get locked by"""
           if self.lockedBy is None:
               self.lockedBy = ''
         return str(self.lockedBy)          return str(self.lockedBy)
           
     def getLastVersionNumber(self):      def getLastVersionNumber(self):
Line 837  class extVersionedFile(CatalogAware,Fold Line 970  class extVersionedFile(CatalogAware,Fold
         lv=None          lv=None
                   
         for v in self.objectValues(self.content_meta_type):          for v in self.objectValues(self.content_meta_type):
             logging.debug("getlastversion: check %s"%v.getId())              #logging.debug("getlastversion: check %s"%v.getId())
             if v.getVersionNumber() > tmp:              if v.getVersionNumber() > tmp:
                     tmp=v.getVersionNumber()                      tmp=v.getVersionNumber()
                     lv=v                      lv=v
                   
         logging.debug("getlastversion: got %s"%lv.getId())          #ogging.debug("getlastversion: got %s"%lv.getId())
         return lv          return lv
   
     def getContentObject(self):      def getContentObject(self):
         """returns the last version object"""          """returns the last version object"""
         if not self.lastVersionId:          if not getattr(self, 'lastVersionId', None):
               # find last version and save it
             lv = self.findLastVersion()              lv = self.findLastVersion()
             if lv is None:              if lv is None:
                 return None                  return None
             self.lastVersionNumber = lv.getVersionNumber()              self.lastVersionNumber = lv.getVersionNumber()
             self.lastVersionId = lv.getId()              self.lastVersionId = lv.getId()
                           
         return getattr(self, self.lastVersionId)          return getattr(self, self.lastVersionId, None)
   
     security.declarePublic('getData')      security.declarePublic('getData')
     def getData(self):      def getData(self):
         """Returns the content of the last version"""          """Returns the content of the last version"""
           logging.debug("+++++++getData2")
         ob = self.getContentObject()          ob = self.getContentObject()
         if ob is not None:          if ob is not None:
             return ob.getData()              return ob.getData()
         else:          else:
             return None              return None
           
       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()
Line 893  class extVersionedFile(CatalogAware,Fold Line 1037  class extVersionedFile(CatalogAware,Fold
         #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()          return self.history()
   
       def getVersionNr(self,nr):
           """get version with number nr"""
           tmp=0
           lastVersion=None
           
           
           for version in self.ZopeFind(self):
               
               if hasattr(version[1],'versionNumber'):
           
                   if int(version[1].versionNumber) ==nr :
                       return version[1]
              
           return None
     security.declarePublic('getVersion')                                                    security.declarePublic('getVersion')                                              
     def getVersion(self):      def getVersion(self):
         # TODO: this is ugly and it returns the next version number           # TODO: this is ugly and it returns the next version number 
Line 924  class extVersionedFile(CatalogAware,Fold Line 1081  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,user=None):
         """unlock"""          """unlock"""
         #safe who had the lock          #safe who had the lock
           logging.debug("extVersionFile: (forceunlock)"+str(user))
         if self.lockedBy:          if self.lockedBy:
               if user is not None:
                   if str(self.lockedBy)==user:
             self.brokenLock=str(self.lockedBy)              self.brokenLock=str(self.lockedBy)
                       self.lockedBy=''
         else:          else:
             self.brokenLock=""              self.brokenLock=""
               else:
                   self.brokenLock=str(self.lockedBy)
         self.lockedBy=''          self.lockedBy=''
           else:
               self.brokenLock=""
           
         return self.brokenLock          return self.brokenLock
   
     security.declareProtected('AUTHENTICATED_USER','unlock')         security.declareProtected('AUTHENTICATED_USER','unlock')   
Line 945  class extVersionedFile(CatalogAware,Fold Line 1124  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):      def _newContentObject(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
         """factory for content objects. to be overridden in derived classes."""          """factory for content objects. to be overridden in derived classes."""
         return extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=versionComment,time=time,author=author)          return extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=versionComment,time=time,author=author)
   
   
     def addContentObject(self,id,vC,author=None,file=None,title='',changeName='no',newName='',from_tmp=False,      def addContentObject(self,id,vC,author=None,file=None,title='',changeName='no',newName='',from_tmp=False,index=True,
                          precondition='', content_type=''):                           precondition='', content_type=''):
         """add"""          """add"""
                   
Line 998  class extVersionedFile(CatalogAware,Fold Line 1178  class extVersionedFile(CatalogAware,Fold
         self.lastVersionNumber = versNum          self.lastVersionNumber = versNum
         self.lastVersionId = id          self.lastVersionId = id
                   
         logging.debug("addcontentobject: lastversion=%s"%self.getData())          #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)))          logging.debug("reindex1: %s in %s"%(repr(self),repr(self.default_catalog)))
         self.reindex_object()          self.reindex_object()
         logging.debug("addcontentobject: fob_data=%s"%fob.getData())  
                   
         return fob          return fob
                           
Line 1044  class extVersionedFile(CatalogAware,Fold Line 1225  class extVersionedFile(CatalogAware,Fold
                 return pt()                  return pt()
   
             else:              else:
                 RESPONSE.redirect(self.REQUEST['URL2'])                  RESPONSE.redirect(self.absolute_url()+'/history')
         else:          else:
             return ob              return ob
   
                   
       changeVersionedFileForm = PageTemplateFile('zpt/changeVersionedFile', globals())
       
       def manage_changeVersionedFile(self,title,vC,author,comment,RESPONSE=None):
           """Change VersionedFile metadata"""
           self.title = title
           self.author = author
           cob = self.getContentObject()
           if cob:
               if vC:
                   cob.vComment=vC
   
               if comment=='':
                   cob.versionComment=None
               else:
                   cob.versionComment=comment
   
           if RESPONSE:
               RESPONSE.redirect('manage_main')
   
           
     def download(self):      def download(self):
         """download and lock"""          """download"""
         self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getContentObject().getId())      
         self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")          txt=self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId()+'/download'
         self.content_type="application/octet-stream"          
         self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId())          self.REQUEST.RESPONSE.redirect(txt)
   
           
     security.declareProtected('AUTHENTICATED_USER','downloadLocked')          security.declareProtected('AUTHENTICATED_USER','downloadLocked')    
     def downloadLocked(self):      def downloadLocked(self):

Removed from v.1.7  
changed lines
  Added in v.1.34


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