File:  [Repository] / versionedFile / Attic / externalVersionedFile.py
Revision 1.6: download - view: text, annotated - select for diffs - revision graph
Fri Feb 2 14:45:17 2007 UTC (17 years, 5 months ago) by dwinter
Branches: MAIN
CVS tags: HEAD
minorCVS: ----------------------------------------------------------------------

    1: """this implementation of the is not supported anymore, it is replace by extVersionedFile
    2: DW 11.10.2006"""
    3: 
    4: from Products.ExternalFile.FileUtils import copy_file
    5: from Products.ExternalFile.ExternalFile import ExternalFile
    6: from OFS.Folder import Folder
    7: from OFS.Image import File
    8: from OFS.Image import cookId
    9: from Globals import DTMLFile, InitializeClass,package_home
   10: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
   11: from AccessControl import getSecurityManager
   12: from Products.PageTemplates.PageTemplate import PageTemplate
   13: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
   14: from AccessControl import ClassSecurityInfo
   15: import os.path
   16: import time
   17: 
   18: def sortv(x,y):
   19:     return cmp(x[0],y[0])
   20:  
   21: class externalVersionedFileFolder(Folder):
   22:     """Folder with externalVersioned files"""
   23: 
   24:     
   25:     meta_type = "externalVersionedFileFolder"
   26: 
   27:     security= ClassSecurityInfo()
   28:     security.declareProtected('AUTHENTICATED_USER','addFileForm')
   29:     
   30:     manage_options = Folder.manage_options+(
   31: 		{'label':'Generate Index.html','action':'generateIndexHTML'},
   32:                 {'label':'Generate history_template.html','action':'generateHistoryHTML'},
   33:                 {'label':'Change Path to Folder','action':'changePathForm'},
   34: 		)
   35: 
   36:     def changePathForm(self):
   37:         """change the path form"""
   38:         pt=PageTemplateFile('Products/externalVersionedFile/zpt/changePath').__of__(self)
   39:         return pt()
   40: 
   41:     def changePath(self,baseFolderPath,RESPONSE=None):
   42:         """change the path"""
   43:         self.baseFolderPath=baseFolderPath
   44:         if RESPONSE is not None:
   45:             return self.manage_main(self, RESPONSE)
   46: 
   47: 
   48:         
   49:     def helpDownload(self):
   50:         """download help"""
   51:         
   52:         pt=PageTemplateFile('Products/externalVersionedFile/zpt/helpDownload').__of__(self)
   53:         return pt()
   54: 
   55:   
   56:     def generateIndexHTML(self,RESPONSE=None):
   57:         """lege standard index.html an"""
   58: 
   59:         
   60: 
   61:   
   62:         if not hasattr(self,'index.html'):
   63:             zt=ZopePageTemplate('index.html')
   64:             self._setObject('index.html',zt)
   65:             default_content_fn = os.path.join(package_home(globals()),
   66:                                                'zpt/versionFileFolderMain.zpt')
   67:             text = open(default_content_fn).read()
   68:             zt.pt_edit(text, 'text/html')
   69: 
   70:         else:
   71:             return "already exists!"
   72:         
   73:         if RESPONSE is not None:
   74:             RESPONSE.redirect('manage_main')
   75: 
   76: 
   77:     def generateHistoryHTML(self,RESPONSE=None):
   78:         """lege standard index.html an"""
   79: 
   80:         
   81: 
   82:         
   83:         if not hasattr(self,'history_template.html'):
   84:             zt=ZopePageTemplate('history_template.html')
   85:             self._setObject('history_template.html',zt)
   86:             default_content_fn = os.path.join(package_home(globals()),
   87:                                                'zpt/versionHistory.zpt')
   88:             text = open(default_content_fn).read()
   89:             zt.pt_edit(text, 'text/html')
   90: 
   91:         else:
   92:             return "already exists!"
   93:         
   94:         if RESPONSE is not None:
   95:             RESPONSE.redirect('manage_main')
   96: 
   97:     def getVersionedFiles(self,sortField='title'):
   98:         """get all versioned files"""
   99: 
  100:         def sortName(x,y):
  101:             return cmp(x[1].title.lower(),y[1].title.lower())
  102: 
  103:         def sortDate(x,y):
  104:             return cmp(y[1].getLastVersion().getTime(),x[1].getLastVersion().getTime())
  105: 
  106: 
  107:         def sortAuthor(x,y):
  108:             
  109:             return cmp(x[1].getLastVersion().lastEditor(),y[1].getLastVersion().lastEditor())
  110:         
  111: 	externalVersionedFiles=self.ZopeFind(self,obj_metatypes=['externalVersionedFile'])
  112: 
  113:         if sortField=='title':
  114:             externalVersionedFiles.sort(sortName)
  115:         elif sortField=='date':
  116:             externalVersionedFiles.sort(sortDate)
  117:         elif sortField=='author':
  118:             externalVersionedFiles.sort(sortAuthor)
  119: 
  120:         return externalVersionedFiles
  121: 
  122: 
  123:     def header_html(self):
  124:         """zusätzlicher header"""
  125:         ext=self.ZopeFind(self,obj_ids=["header.html"])
  126:         if ext:
  127:             return ext[0][1]()
  128:         else:
  129:             return ""
  130: 
  131: #    security.declareProtected('index_html')
  132:     def index_html(self):
  133:         """main"""
  134:         ext=self.ZopeFind(self,obj_ids=["index.html"])
  135:         if ext:
  136:             return ext[0][1]()
  137:         
  138:         pt=PageTemplateFile('Products/externalVersionedFile/zpt/versionFileFolderMain').__of__(self)
  139:         return pt()
  140: 
  141: 
  142:     def addFileForm(self):
  143:         """add a file"""
  144:         out=DTMLFile('dtml/newFileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject',version='1').__of__(self)
  145:         return out()
  146: 
  147: 
  148:     def addFile(self,vC,file,author,newName='',content_type='',RESPONSE=None):
  149:         """ add a new file"""
  150:         if newName=='':
  151:             id=file.filename
  152:         else:
  153:             id=newName
  154:         
  155:         vC=self.REQUEST.form['vC']
  156:         manage_addExternalVersionedFile(self,id,'','')
  157:         ob=self._getOb(id)
  158:         ob.title=id
  159:         file2=file
  160:         ob.manage_addExternalVersionedFileObject(id,vC,author,file2,content_type=content_type)
  161: 
  162:         RESPONSE.redirect(self.REQUEST['URL1'])
  163: 
  164:         
  165: manage_addExternalVersionedFileFolderForm=DTMLFile('dtml/folderAdd', globals())
  166: 
  167: 
  168: def manage_addExternalVersionedFileFolder(self, id, baseFolderPath,title='',
  169:                      createPublic=0,
  170:                      createUserF=0,
  171:                      REQUEST=None):
  172:     """Add a new Folder object with id *id*.
  173: 
  174:     If the 'createPublic' and 'createUserF' parameters are set to any true
  175:     value, an 'index_html' and a 'UserFolder' objects are created respectively
  176:     in the new folder.
  177:     """
  178:     ob=externalVersionedFileFolder()
  179:     ob.id=str(id)
  180:     ob.title=title
  181:     self._setObject(id, ob)
  182:     ob=self._getOb(id)
  183:     setattr(ob,'baseFolderPath',baseFolderPath)
  184:     checkPermission=getSecurityManager().checkPermission
  185: 
  186:     if createUserF:
  187:         if not checkPermission('Add User Folders', ob):
  188:             raise Unauthorized, (
  189:                   'You are not authorized to add User Folders.'
  190:                   )
  191:         ob.manage_addUserFolder()
  192: 
  193:   
  194:     if REQUEST is not None:
  195:         return self.manage_main(self, REQUEST, update_menu=1)
  196: 
  197: 
  198: 
  199: class externalVersionedFileObject(ExternalFile):
  200:     """File Object im Folder"""
  201:     
  202:     meta_type = "externalVersionedFileObject"
  203:     
  204:     manage_editForm  =DTMLFile('dtml/fileEdit',globals(),
  205:                                Kind='File',kind='file')
  206:     manage_editForm._setName('manage_editForm')
  207: 
  208:     def getTime(self):
  209:         """getTime"""
  210:         #return self.bobobase_modification_time().ISO()
  211:         if hasattr(self,'time'):
  212:             return time.strftime("%Y-%m-%d %H:%M:%S",self.time)
  213:         else:
  214:             return self.bobobase_modification_time().ISO()
  215: 
  216:     def download(self):
  217:         """download and lock"""
  218:         
  219:         
  220:         self.content_type="application/octet-stream"
  221:         self.REQUEST.RESPONSE.redirect(self.absolute_url())
  222:     
  223:     def downloadLocked(self):
  224:         """download and lock"""
  225:         
  226:         
  227:         if self.REQUEST['AUTHENTICATED_USER']=='Anonymous User':
  228:             return "please login first"
  229:         if not self.aq_parent.lockedBy=="":
  230:             return "cannot be locked because is already locked by %s"%self.lockedBy
  231:         self.aq_parent.lockedBy=self.REQUEST['AUTHENTICATED_USER']
  232: 
  233:         self.content_type="application/octet-stream"
  234:         self.REQUEST.RESPONSE.redirect(self.absolute_url())
  235:     
  236:     def setVersionNumber(self,versionNumber):
  237:         """set version"""
  238:         self.versionNumber=versionNumber
  239: 
  240:     def getVersionNumber(self):
  241:         """get version"""
  242:         return self.versionNumber
  243: 
  244:     def lastEditor(self):
  245:         """last Editor"""
  246:         if hasattr(self,'author'):
  247:             return self.author            
  248:         else:
  249:             jar=self._p_jar
  250:             oid=self._p_oid
  251: 
  252:             if jar is None or oid is None: return None
  253: 
  254:             return jar.db().history(oid)[0]['user_name']
  255: 
  256:     
  257:     
  258:         
  259: manage_addExternalVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject', version='1')
  260: 
  261: def manage_addExternalVersionedFileObject(self,id,vC='',author='', file='',title='',precondition='', content_type='',
  262:                    REQUEST=None):
  263:     """
  264: 
  265:     Factory method to actually create an instance of ExternalFile.
  266:     ExternalFile.  This method assumes all parameters are correct (it
  267:     does no error checking).  It is called from CreationDialog.py once
  268:     all of the confirmation and error checking steps have been taken.
  269:     
  270:     You should call this method directly if you are creating an
  271:     instance of ExternalFile programmatically and have 'vetted' all of
  272:     your parameters for correctness.
  273: 
  274:     """
  275:     target_filepath=os.path.join(self.baseFolderPath,id)
  276:     basedir=''
  277:     if not id:
  278:         raise Exception('Required fields must not be blank')
  279: 
  280:     fully_resolved_target_filepath = os.path.join(basedir,target_filepath)    
  281:     if file:
  282:         copy_file(file, fully_resolved_target_filepath)        
  283:     
  284:     self._setObject(id, externalVersionedFileObject(id, title, str(vC),
  285:                                      fully_resolved_target_filepath))
  286:     self._getOb(id).reindex_object()
  287: 
  288:     self._getOb(id).versionComment=str(vC)
  289:     setattr(self._getOb(id),'author',author)
  290:     
  291:     if REQUEST is not None:
  292:         REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
  293: 
  294: def manage_addExternalVersionedFileObject_old(self,id,vC='',author='', file='',title='',precondition='', content_type='',
  295:                    REQUEST=None):
  296:     """Add a new File object.
  297: 
  298:     Creates a new File object 'id' with the contents of 'file'"""
  299: 
  300:     id=str(id)
  301:     title=str(title)
  302:     content_type=str(content_type)
  303:     precondition=str(precondition)
  304:     
  305:     id, title = cookId(id, title, file)
  306: 
  307:     self=self.this()
  308: 
  309:     # First, we create the file without data:
  310:     self._setObject(id, externalVersionedFileObject(id,title,'',content_type, precondition))
  311:     self._getOb(id).versionComment=str(vC)
  312:     self._getOb(id).time=time.localtime()
  313:     setattr(self._getOb(id),'author',author)
  314:     
  315:     # Now we "upload" the data.  By doing this in two steps, we
  316:     # can use a database trick to make the upload more efficient.
  317:     if file:
  318:         self._getOb(id).manage_upload(file)
  319:     if content_type:
  320:         self._getOb(id).content_type=content_type
  321: 
  322:     if REQUEST is not None:
  323:         REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
  324: 
  325: 
  326: 
  327: 
  328: class externalVersionedFile(Folder):
  329:     """Versioniertes File"""
  330: 
  331:     
  332: 
  333:     def showDiffsForm(self):
  334:         """showdiffs"""
  335:         pt=PageTemplateFile('Products/externalVersionedFile/zpt/selectDiff').__of__(self)
  336:         return pt()
  337: 
  338:     def showDiffs(self,fileList):
  339:         """show"""
  340:         self.REQUEST.SESSION['fileList']=fileList
  341:         pt=PageTemplateFile('Products/externalVersionedFile/zpt/showDiffs').__of__(self)
  342:         return pt()
  343: 
  344:     def formatDiffs(self,fileList):
  345:         """generate diffs"""
  346:         from difflib import context_diff
  347:         import re
  348:         
  349:         v1=getattr(self,fileList[0])()
  350:         v1=re.sub("\r","\n",v1)
  351:         v1s=v1.split("\n")
  352: 
  353:         v2=getattr(self,fileList[1])()
  354:         #print v2
  355:         v2=re.sub("\r","\n",v2)
  356:         v2s=v2.split("\n")
  357: 
  358:         #print v1s
  359:         xx=context_diff(v1s,v2s)
  360:         #for x in xx:
  361:         #    print x
  362: 
  363:         list=[]
  364:         counter=-1
  365:         toggle=0
  366:         
  367:         for x in xx:
  368:            
  369:             if x[0:2]=="**":
  370:                 counter+=1
  371:                 toggle=0
  372:                 list.append(['',''])
  373:             elif x[0:2]=="--":
  374:                 toggle=1
  375:             else:
  376:                 try:
  377:                     x=re.sub(">",">",x)
  378:                     x=re.sub("<","&lt;",x)
  379:                     if x[0]=="!":
  380:                         x="""<span style="color:brown;">%s</span>"""%x[1:]
  381:                     if x[0]=="+":
  382:                         x="""<span style="color:red;">%s</span>"""%x[1:]
  383:                     if x[0]=="-":
  384:                         x="""<span style="color:green;">%s</span>"""%x[1:]
  385:                     list[counter][toggle]+=x+"<br>"
  386:                 except:
  387:                     """none"""
  388:         return list
  389:     
  390:     def __init__(self, id, title, lockedBy,author):
  391:         """init"""
  392:         self.id=id
  393:         self.title=title
  394:         self.lockedBy=lockedBy
  395:         self.author=author
  396:         
  397:     security= ClassSecurityInfo()    
  398:     meta_type="externalVersionedFile"
  399: 
  400:     def getLastVersion(self):
  401:         """Last Version"""
  402:         tmp=0
  403:         lastVersion=None
  404:         
  405:         for version in self.ZopeFind(self):
  406:             
  407:             if hasattr(version[1],'versionNumber'):
  408:                 
  409:                 if int(version[1].versionNumber) > tmp:
  410:                     tmp=int(version[1].versionNumber,)
  411:                     lastVersion=version[1]
  412:         return lastVersion
  413:     
  414:     def index_html(self):
  415:         """main view"""
  416:         lastVersion=self.getLastVersion()
  417:         #return "File:"+self.title+"  Version:%i"%lastVersion.versionNumber," modified:",lastVersion.bobobase_modification_time()," size:",lastVersion.getSize(),"modified by:",lastVersion.lastEditor()
  418:         return "File: %s Version:%i modified:%s size:%s modified by:%s"%(self.title,lastVersion.versionNumber,lastVersion.bobobase_modification_time(),lastVersion.getSize(),lastVersion.lastEditor())
  419:                                                                          
  420:     def getVersion(self):
  421:         tmp=0
  422:         for version in self.ZopeFind(self):
  423:             
  424:             if hasattr(version[1],'versionNumber'):
  425:                 
  426:                 if int(version[1].versionNumber) > tmp:
  427:                     tmp=int(version[1].versionNumber,)
  428:         return tmp+1
  429: 
  430:     
  431:     security.declareProtected('AUTHENTICATED_USER','unlock')
  432: 
  433:     def history(self):
  434:         """history"""  
  435: 
  436:         ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
  437:         if ext:
  438:             return getattr(self,ext[0][1].getId())()
  439:         
  440:         pt=PageTemplateFile('Products/externalVersionedFile/zpt/versionHistory').__of__(self)
  441:         return pt()
  442: 
  443:     def getVersions(self):
  444:         """get all versions"""
  445:         ret=[]
  446:         for version in self.ZopeFind(self):
  447:             if hasattr(version[1],'versionNumber'):
  448:                 ret.append((version[1].versionNumber,version[1]))
  449:         ret.sort(sortv)
  450:         return ret
  451: 
  452:     security.declareProtected('AUTHENTICATED_USER','unlock')   
  453:     def unlock(self,RESPONSE):
  454:         """unlock"""
  455:         if str(self.lockedBy) in [str(self.REQUEST['AUTHENTICATED_USER'])]:
  456:             self.lockedBy=''
  457:             RESPONSE.redirect(self.REQUEST['URL2'])
  458:         else:
  459:             return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER'])
  460:         
  461:     
  462:     security.declareProtected('AUTHENTICATED_USER','addExternalVersionedFileObjectForm')
  463: 
  464:     def addExternalVersionedFileObjectForm(self):
  465:         """add a new version"""
  466:         
  467:         if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
  468:             return "please login first"
  469:         if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
  470:             out=DTMLFile('dtml/fileAdd', globals(),Kind='ExternalVersionedFileObject',kind='externalVersionedFileObject',version=self.getVersion()).__of__(self)
  471:             return out()
  472:         else:
  473:             return "Sorry file is locked by somebody else"
  474:         
  475:     def manage_addExternalVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', RESPONSE=None):
  476:         """add"""
  477:         
  478:         vC=self.REQUEST['vC']
  479:         author=self.REQUEST['author']
  480:         
  481:         if changeName=="yes":
  482:             self.title=file.filename[0:]
  483: 
  484:         if not newName=='':
  485:             self.title=newName[0:]
  486: 
  487:         id="V%i"%self.getVersion()+"_"+self.title
  488:         manage_addExternalVersionedFileObject(self,id,vC,author,file,"V%i"%self.getVersion()+"_"+self.title,precondition, content_type)
  489:         #print self.ZopeFind(self,obj_ids=[id])[0]
  490:         objs=self.ZopeFind(self,obj_ids=[id])[0][1].setVersionNumber(int(self.getVersion()))
  491: 
  492:         if RESPONSE:
  493:             RESPONSE.redirect(self.REQUEST['URL2'])
  494: 
  495:     security.declareProtected('AUTHENTICATED_USER','downloadLocked')
  496: 
  497:     def download(self):
  498:         """download and lock"""
  499:         self.getLastVersion().content_type="application/octet-stream"
  500:         self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId())
  501:     
  502:     def downloadLocked(self):
  503:         """download and lock"""
  504:         if self.REQUEST['AUTHENTICATED_USER']=='Anonymous User':
  505:             return "please login first"
  506:         if not self.lockedBy=="":
  507:             return "cannot be locked because is already locked by %s"%self.lockedBy
  508:         self.lockedBy=self.REQUEST['AUTHENTICATED_USER']
  509:         self.getLastVersion().content_type="application/octet-stream"
  510:         self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getLastVersion().getId())
  511:     
  512: def manage_addExternalVersionedFileForm(self):
  513:     """interface for adding the OSAS_root"""
  514:     pt=PageTemplateFile('Products/externalVersionedFile/zpt/addExternalVersionedFile.zpt').__of__(self)
  515:     return pt()
  516: 
  517: def manage_addExternalVersionedFile(self,id,title,lockedBy, author=None, RESPONSE=None):
  518:     """add the OSAS_root"""
  519:     newObj=externalVersionedFile(id,title,lockedBy,author)
  520:     self._setObject(id,newObj)
  521:    
  522:     if RESPONSE is not None:
  523:         RESPONSE.redirect('manage_main')
  524: 
  525: 
  526: InitializeClass(externalVersionedFile)
  527: InitializeClass(externalVersionedFileFolder)

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