File:  [Repository] / versionedFile / versionedFile.py
Revision 1.56: download - view: text, annotated - select for diffs - revision graph
Fri Feb 17 12:16:08 2006 UTC (18 years, 3 months ago) by dwinter
Branches: MAIN
CVS tags: HEAD
minor

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

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