from Products.ExternalFile.FileUtils import copy_file from Products.ExternalFile.ExternalFile import ExternalFile from OFS.Folder import Folder from OFS.Image import File from OFS.Image import cookId from Globals import DTMLFile, InitializeClass,package_home from Products.PageTemplates.PageTemplateFile import PageTemplateFile from AccessControl import getSecurityManager from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from AccessControl import ClassSecurityInfo import os.path import time def sortv(x,y): return cmp(x[0],y[0]) class externalVersionedFileFolder(Folder): """Folder with externalVersioned files""" meta_type = "externalVersionedFileFolder" security= ClassSecurityInfo() security.declareProtected('AUTHENTICATED_USER','addFileForm') manage_options = Folder.manage_options+( {'label':'Generate Index.html','action':'generateIndexHTML'}, {'label':'Generate history_template.html','action':'generateHistoryHTML'}, {'label':'Change Path to Folder','action':'changePathForm'}, ) def changePathForm(self): """change the path form""" pt=PageTemplateFile('Products/externalVersionedFile/zpt/changePath').__of__(self) return pt() def changePath(self,baseFolderPath,RESPONSE=None): """change the path""" self.baseFolderPath=baseFolderPath if RESPONSE is not None: return self.manage_main(self, RESPONSE) def helpDownload(self): """download help""" pt=PageTemplateFile('Products/externalVersionedFile/zpt/helpDownload').__of__(self) return pt() def generateIndexHTML(self,RESPONSE=None): """lege standard index.html an""" if not hasattr(self,'index.html'): zt=ZopePageTemplate('index.html') self._setObject('index.html',zt) default_content_fn = os.path.join(package_home(globals()), 'zpt/versionFileFolderMain.zpt') text = open(default_content_fn).read() zt.pt_edit(text, 'text/html') else: return "already exists!" if RESPONSE is not None: RESPONSE.redirect('manage_main') def generateHistoryHTML(self,RESPONSE=None): """lege standard index.html an""" if not hasattr(self,'history_template.html'): zt=ZopePageTemplate('history_template.html') self._setObject('history_template.html',zt) default_content_fn = os.path.join(package_home(globals()), 'zpt/versionHistory.zpt') text = open(default_content_fn).read() zt.pt_edit(text, 'text/html') else: return "already exists!" if RESPONSE is not None: RESPONSE.redirect('manage_main') def getVersionedFiles(self,sortField='title'): """get all versioned files""" def sortName(x,y): return cmp(x[1].title,y[1].title) def sortDate(x,y): return cmp(x[1].getLastVersion().getTime(),y[1].getLastVersion().getTime) def sortAuthor(x,y): return cmp(x[1].getLastVersion().lastEditor(),y[1].getLastVersion().lastEditor()) externalVersionedFiles=self.ZopeFind(self,obj_metatypes=['externalVersionedFile']) if sortField=='title': externalVersionedFiles.sort(sortName) elif sortField=='date': externalVersionedFiles.sort(sortDate) elif sortField=='author': externalVersionedFiles.sort(sortAuthor) return externalVersionedFiles def header_html(self): """zusätzlicher header""" ext=self.ZopeFind(self,obj_ids=["header.html"]) if ext: return ext[0][1]() else: return "" # security.declareProtected('index_html') def index_html(self): """main""" ext=self.ZopeFind(self,obj_ids=["index.html"]) if ext: return ext[0][1]() pt=PageTemplateFile('Products/externalVersionedFile/zpt/versionFileFolderMain').__of__(self) return pt() def addFileForm(self): """add a file""" out=DTMLFile('dtml/newFileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject',version='1').__of__(self) return out() def addFile(self,vC,file,author,newName='',content_type='',RESPONSE=None): """ add a new file""" if newName=='': id=file.filename else: id=newName vC=self.REQUEST.form['vC'] manage_addExternalVersionedFile(self,id,'','') ob=self._getOb(id) ob.title=id file2=file ob.manage_addExternalVersionedFileObject(id,vC,author,file2,content_type=content_type) RESPONSE.redirect(self.REQUEST['URL1']) manage_addExternalVersionedFileFolderForm=DTMLFile('dtml/folderAdd', globals()) def manage_addExternalVersionedFileFolder(self, id, baseFolderPath,title='', createPublic=0, createUserF=0, REQUEST=None): """Add a new Folder object with id *id*. If the 'createPublic' and 'createUserF' parameters are set to any true value, an 'index_html' and a 'UserFolder' objects are created respectively in the new folder. """ ob=externalVersionedFileFolder() ob.id=str(id) ob.title=title self._setObject(id, ob) ob=self._getOb(id) setattr(ob,'baseFolderPath',baseFolderPath) checkPermission=getSecurityManager().checkPermission if createUserF: if not checkPermission('Add User Folders', ob): raise Unauthorized, ( 'You are not authorized to add User Folders.' ) ob.manage_addUserFolder() if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1) class externalVersionedFileObject(ExternalFile): """File Object im Folder""" meta_type = "externalVersionedFileObject" manage_editForm =DTMLFile('dtml/fileEdit',globals(), Kind='File',kind='file') manage_editForm._setName('manage_editForm') def getTime(self): """getTime""" #return self.bobobase_modification_time().ISO() if hasattr(self,'time'): return time.strftime("%Y-%m-%d %H:%M:%S",self.time) else: return self.bobobase_modification_time().ISO() def download(self): """download and lock""" self.content_type="application/octet-stream" self.REQUEST.RESPONSE.redirect(self.absolute_url()) def downloadLocked(self): """download and lock""" if self.REQUEST['AUTHENTICATED_USER']=='Anonymous User': return "please login first" if not self.aq_parent.lockedBy=="": return "cannot be locked because is already locked by %s"%self.lockedBy self.aq_parent.lockedBy=self.REQUEST['AUTHENTICATED_USER'] self.content_type="application/octet-stream" self.REQUEST.RESPONSE.redirect(self.absolute_url()) def setVersionNumber(self,versionNumber): """set version""" self.versionNumber=versionNumber def getVersionNumber(self): """get version""" return self.versionNumber def lastEditor(self): """last Editor""" if hasattr(self,'author'): return self.author else: jar=self._p_jar oid=self._p_oid if jar is None or oid is None: return None return jar.db().history(oid)[0]['user_name'] manage_addExternalVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject', version='1') def manage_addExternalVersionedFileObject(self,id,vC='',author='', file='',title='',precondition='', content_type='', REQUEST=None): """ Factory method to actually create an instance of ExternalFile. ExternalFile. This method assumes all parameters are correct (it does no error checking). It is called from CreationDialog.py once all of the confirmation and error checking steps have been taken. You should call this method directly if you are creating an instance of ExternalFile programmatically and have 'vetted' all of your parameters for correctness. """ target_filepath=os.path.join(self.baseFolderPath,id) basedir='' if not id: raise Exception('Required fields must not be blank') fully_resolved_target_filepath = os.path.join(basedir,target_filepath) if file: copy_file(file, fully_resolved_target_filepath) self._setObject(id, externalVersionedFileObject(id, title, str(vC), fully_resolved_target_filepath)) self._getOb(id).reindex_object() self._getOb(id).versionComment=str(vC) setattr(self._getOb(id),'author',author) if REQUEST is not None: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main') def manage_addExternalVersionedFileObject_old(self,id,vC='',author='', file='',title='',precondition='', content_type='', REQUEST=None): """Add a new File object. Creates a new File object 'id' with the contents of 'file'""" id=str(id) title=str(title) content_type=str(content_type) precondition=str(precondition) id, title = cookId(id, title, file) self=self.this() # First, we create the file without data: self._setObject(id, externalVersionedFileObject(id,title,'',content_type, precondition)) self._getOb(id).versionComment=str(vC) self._getOb(id).time=time.localtime() setattr(self._getOb(id),'author',author) # 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: self._getOb(id).manage_upload(file) if content_type: self._getOb(id).content_type=content_type if REQUEST is not None: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main') class externalVersionedFile(Folder): """Versioniertes File""" def showDiffsForm(self): """showdiffs""" pt=PageTemplateFile('Products/externalVersionedFile/zpt/selectDiff').__of__(self) return pt() def showDiffs(self,fileList): """show""" self.REQUEST.SESSION['fileList']=fileList pt=PageTemplateFile('Products/externalVersionedFile/zpt/showDiffs').__of__(self) return pt() def formatDiffs(self,fileList): """generate diffs""" from difflib import context_diff import re v1=getattr(self,fileList[0])() v1=re.sub("\r","\n",v1) v1s=v1.split("\n") v2=getattr(self,fileList[1])() #print v2 v2=re.sub("\r","\n",v2) v2s=v2.split("\n") #print v1s xx=context_diff(v1s,v2s) #for x in xx: # print x list=[] counter=-1 toggle=0 for x in xx: if x[0:2]=="**": counter+=1 toggle=0 list.append(['','']) elif x[0:2]=="--": toggle=1 else: try: x=re.sub(">",">",x) x=re.sub("<","<",x) if x[0]=="!": x="""%s"""%x[1:] if x[0]=="+": x="""%s"""%x[1:] if x[0]=="-": x="""%s"""%x[1:] list[counter][toggle]+=x+"
" except: """none""" return list def __init__(self, id, title, lockedBy,author): """init""" self.id=id self.title=title self.lockedBy=lockedBy self.author=author security= ClassSecurityInfo() meta_type="externalVersionedFile" def getLastVersion(self): """Last Version""" tmp=0 lastVersion=None for version in self.ZopeFind(self): if hasattr(version[1],'versionNumber'): if int(version[1].versionNumber) > tmp: tmp=int(version[1].versionNumber,) lastVersion=version[1] return lastVersion def index_html(self): """main view""" lastVersion=self.getLastVersion() #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.bobobase_modification_time(),lastVersion.getSize(),lastVersion.lastEditor()) def getVersion(self): tmp=0 for version in self.ZopeFind(self): if hasattr(version[1],'versionNumber'): if int(version[1].versionNumber) > tmp: tmp=int(version[1].versionNumber,) return tmp+1 security.declareProtected('AUTHENTICATED_USER','unlock') def history(self): """history""" ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"]) if ext: return getattr(self,ext[0][1].getId())() pt=PageTemplateFile('Products/externalVersionedFile/zpt/versionHistory').__of__(self) return pt() def getVersions(self): """get all versions""" ret=[] for version in self.ZopeFind(self): if hasattr(version[1],'versionNumber'): ret.append((version[1].versionNumber,version[1])) ret.sort(sortv) return ret security.declareProtected('AUTHENTICATED_USER','unlock') def unlock(self,RESPONSE): """unlock""" if str(self.lockedBy) in [str(self.REQUEST['AUTHENTICATED_USER'])]: self.lockedBy='' RESPONSE.redirect(self.REQUEST['URL2']) else: return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER']) security.declareProtected('AUTHENTICATED_USER','addExternalVersionedFileObjectForm') def addExternalVersionedFileObjectForm(self): """add a new version""" if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]: return "please login first" if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''): out=DTMLFile('dtml/fileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject',version=self.getVersion()).__of__(self) return out() else: return "Sorry file is locked by somebody else" def manage_addExternalVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', RESPONSE=None): """add""" vC=self.REQUEST['vC'] author=self.REQUEST['author'] if changeName=="yes": self.title=file.filename[0:] if not newName=='': self.title=newName[0:] id="V%i"%self.getVersion()+"_"+self.title manage_addExternalVersionedFileObject(self,id,vC,author,file,"V%i"%self.getVersion()+"_"+self.title,precondition, content_type) print self.ZopeFind(self,obj_ids=[id])[0] objs=self.ZopeFind(self,obj_ids=[id])[0][1].setVersionNumber(int(self.getVersion())) if RESPONSE: RESPONSE.redirect(self.REQUEST['URL2']) security.declareProtected('AUTHENTICATED_USER','downloadLocked') def download(self): """download and lock""" self.getLastVersion().content_type="application/octet-stream" self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId()) def downloadLocked(self): """download and lock""" if self.REQUEST['AUTHENTICATED_USER']=='Anonymous User': return "please login first" if not self.lockedBy=="": return "cannot be locked because is already locked by %s"%self.lockedBy self.lockedBy=self.REQUEST['AUTHENTICATED_USER'] self.getLastVersion().content_type="application/octet-stream" self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId()) def manage_addExternalVersionedFileForm(self): """interface for adding the OSAS_root""" pt=PageTemplateFile('Products/externalVersionedFile/zpt/addExternalVersionedFile.zpt').__of__(self) return pt() def manage_addExternalVersionedFile(self,id,title,lockedBy, author=None, RESPONSE=None): """add the OSAS_root""" newObj=externalVersionedFile(id,title,lockedBy,author) self._setObject(id,newObj) if RESPONSE is not None: RESPONSE.redirect('manage_main') InitializeClass(externalVersionedFile) InitializeClass(externalVersionedFileFolder)