Annotation of versionedFile/extVersionedFile.py, revision 1.31

1.3       dwinter     1: """actual version of the versioned file folder with external filestorage, 
                      2: using the ExtFile Product, this version replaces externaVersionedFile.py
                      3: DW 11.10.2006
                      4: """
                      5: 
1.1       dwinter     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: from difflib import Differ
                     16: from pprint import pprint
                     17: from Products.ExtFile.ExtFile import * 
                     18: from Products.ZCatalog.CatalogPathAwareness import CatalogAware
                     19: 
                     20: try:
1.6       casties    21:     from Products.ImageArchive.ImageArchive import manage_AddImageZogiLib
1.1       dwinter    22: except:
1.6       casties    23:     print "no images"
1.1       dwinter    24: 
                     25: from threading import Thread
                     26: import shutil
                     27: import tempfile
                     28: import os.path
                     29: import urllib
1.5       casties    30: import time
                     31: import logging
1.9       casties    32: import types
1.1       dwinter    33: 
                     34: try:
                     35:     from Products.ECHO_content.ECHO_collection import ECHO_basis
                     36: except:
                     37:     print "ECHO Elements not imported"
                     38:     class ECHO_basis:
1.6       casties    39:         """leer"""
                     40:         manage_options=()
1.1       dwinter    41: 
                     42:    
                     43: def sortv(x,y):
                     44:     return cmp(x[0],y[0])
1.7       casties    45: 
1.1       dwinter    46: tdir = "/tmp/downloadVersionedFiles"
                     47: 
                     48: class generateDownloadZip:
                     49:     """generateDownloadSet"""
                     50: 
                     51:     def __init__(self,folderObject,url):
                     52:         """init downloadzip"""
                     53:         self.folder=folderObject
                     54:         self.done=None
                     55:         self.response=""
                     56:         self.url=url
                     57:         
                     58:     def __call__(self):
                     59:         """call generate download zip"""
                     60:         storeTempDir=tempfile.tempdir
1.6       casties    61:         tempfile.tempdir=tdir
1.1       dwinter    62: 
                     63:         tmpPath=tempfile.mktemp()
1.6       casties    64:         tmpZip=tempfile.mktemp()+".tgz"
1.1       dwinter    65:         tmpFn=os.path.split(tmpZip)[1]
                     66:         
                     67:         if not os.path.exists(tempfile.tempdir):
                     68:             os.mkdir(tempfile.tempdir) 
                     69: 
                     70:         if not os.path.exists(tmpPath):
1.6       casties    71:             os.mkdir(tmpPath) 
1.1       dwinter    72:        
1.6       casties    73:         self.response="<h3>1. step: getting the files</h3>"
1.1       dwinter    74: 
                     75:         for files in self.folder.ZopeFind(self.folder,obj_metatypes=['extVersionedFile']):
1.7       casties    76:             lastV=files[1].getContentObject()
1.1       dwinter    77:             self.response+=str("<p>Get File: %s<br>\n"%lastV.title)
                     78: 
                     79:             savePath=os.path.join(tmpPath,lastV.title)
                     80:             fh=file(savePath,"w")
1.2       dwinter    81:             fh.write(lastV.getData())
1.1       dwinter    82:             fh.close()
                     83: 
                     84:         self.response+="<h3>2. step: creating the downloadable file</h3>"
1.6       casties    85:         self.response+="<p>Create gtar<br>"
1.1       dwinter    86:         self.response+="<p>This can take a while....<br>\n"
                     87: 
                     88:         fh=os.popen2("tar zcvf %s %s/*"%(tmpZip,tmpPath),1)[1]
                     89:         self.response+="<br>"
                     90:         for c in fh.read():
                     91:             self.response+=c
                     92:             if c==")":
                     93:                 self.response+="<br>\n"
                     94:         
                     95:         shutil.rmtree(tmpPath)
                     96: 
                     97:         self.response+="<p>finished<br>\n"
                     98: 
                     99:         len=os.stat(tmpZip)[6]
                    100:         downloadUrl=self.url+"/downloadSet"
                    101:         self.response+="""<h1><a href="downloadSet?fn=%s">Click here for download ( %i Byte)</a></h1>\n"""%(tmpFn,len)
                    102:         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>"""
                    103:         self.response+="""<p>The file will be stored for a while, you can download it later, the URL is:</p>
                    104:            <p><a href="downloadSet?fn=%s">%s?fn=%s</a></h1>\n"""%(tmpFn,downloadUrl,tmpFn)
                    105: 
                    106:         self.done=True
                    107: 
1.6       casties   108:         
1.1       dwinter   109:     def getResult(self):
                    110:         """get result"""
                    111:         return self.response
                    112: 
                    113:     def isDone(self):
                    114:         if self.done:
                    115:             return True
                    116:         else:
                    117:             return False
                    118:         
                    119: 
                    120: class extVersionedFileFolder(Folder,ECHO_basis):
                    121:     """Folder with versioned files"""
                    122:     meta_type = "extVersionedFileFolder"
                    123: 
                    124:     security= ClassSecurityInfo()
                    125:     security.declareProtected('AUTHENTICATED_USER','addFileForm')
1.6       casties   126: 
1.7       casties   127:     file_meta_type=['extVersionedFile']
1.6       casties   128: 
1.1       dwinter   129:     if ECHO_basis:
                    130:         optTMP= Folder.manage_options+ECHO_basis.manage_options
                    131:     else:
                    132:         optTMP= Folder.manage_options
                    133: 
                    134:     manage_options =optTMP+(
1.6       casties   135:         {'label':'Generate Index.html','action':'generateIndexHTML'},
                    136:         {'label':'Generate Image Index.html','action':'generateIndexHTML_image'},
                    137:         {'label':'Generate history_template.html','action':'generateHistoryHTML'},
1.12      casties   138:         {'label':'Import directory','action':'importFolderForm'},
                    139:         {'label':'Export as file','action':'exportFolder'},
                    140:         {'label':'Import versionedFileFolder','action':'importVersionedFileFolderForm'},
1.6       casties   141:         {'label':'Position of version number','action':'changeHistoryFileNamesForm'},
                    142:         )
1.1       dwinter   143: 
1.6       casties   144:     
1.1       dwinter   145:     def changeHistoryFileNamesForm(self):
                    146:         """change position of version num"""
                    147:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeHistoryFileNamesForm.zpt')).__of__(self)
                    148:         return pt()
                    149:     
                    150:     
                    151:     def changeHistoryFileNames(self,positionVersionNum="front",RESPONSE=None):
                    152:         """change position of version num"""
                    153:         versions=self.ZopeFind(self,obj_metatypes=['extVersionedFileObject'],search_sub=1)
                    154:         
                    155:         if not (getattr(self,'positionVersionNum','front')==positionVersionNum):
                    156: 
                    157:             for version in versions:
1.6       casties   158:                 
1.1       dwinter   159:                 if positionVersionNum=="front":
1.6       casties   160:                     
1.1       dwinter   161:                     titleTmp=os.path.splitext(version[1].title)
                    162:                     titleTmp2="_".join(titleTmp[0].split("_")[0:-1])
                    163:                     if len(titleTmp)>1:
                    164:                         id=titleTmp[0].split("_")[-1]+"_"+titleTmp2+"."+titleTmp[1]
                    165:                     else:
                    166:                         id=titleTmp[0].split("_")[-1]+"_"+titleTmp2
                    167: 
                    168:                 else:
                    169:                     titleTmp="_".join(version[1].getId().split("_")[1:])
                    170:                     tmp=os.path.splitext(titleTmp)
                    171:                     if len(tmp)>1:
                    172:                         id=tmp[0]+"_"+version[1].getId().split("_")[0]+tmp[1]
                    173:                     else:
                    174:                         id=tmp[0]+"_"+version[1].getId().split("_")[0]
                    175:                 
                    176:                 version[1].aq_parent.manage_renameObjects(ids=[version[1].getId()],new_ids=[id])
                    177:                 version[1].title=id
                    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()
1.6       casties   189:     
1.1       dwinter   190:     def importFolder(self,path,comment="",author=None,lockedBy=None,RESPONSE=None):
1.8       casties   191:         """import contents of a folder on the server"""
1.1       dwinter   192:         for fileName in os.listdir(path):
1.8       casties   193:             fn = os.path.join(path,fileName)
                    194:             if os.path.isfile(fn):
                    195:                 f = file(fn)
                    196:                 self.addFile(vC=comment, file=f, author=author)
1.1       dwinter   197:         
                    198:         if RESPONSE:
                    199:             RESPONSE.redirect(self.REQUEST['URL1'])
                    200: 
1.10      casties   201:     def importVersionedFileFolderForm(self):
                    202:         """form fuer versionedFileFolder import"""
                    203:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','importVersionedFileFolderForm.zpt')).__of__(self)
                    204:         return pt()
                    205:     
                    206:     def importVersionedFileFolder(self,path,RESPONSE=None):
                    207:         """import contents of a versionedFileFolder on the server"""
                    208:         vff = getattr(self.aq_parent, path, None)
                    209:         if vff is None:
                    210:             return "SORRY, unable to import %s"%path
                    211:         
                    212:         tmpPath=tempfile.mktemp()
                    213:         if not os.path.exists(tempfile.tempdir):
                    214:             os.mkdir(tempfile.tempdir) 
                    215: 
                    216:         if not os.path.exists(tmpPath):
                    217:             os.mkdir(tmpPath) 
                    218: 
                    219:         for (vfn, vf) in vff.getVersionedFiles():
                    220:             if vf.meta_type == 'versionedFile':
1.11      casties   221:                 logging.error("importvff: importing %s of type %s!"%(vfn,vf.meta_type))
1.10      casties   222:                 title = vf.title
1.11      casties   223:                 fob = vf.getLastVersion()
                    224:                 author = fob.getLastEditor()
                    225:                 vc = fob.getVersionComment()
1.10      casties   226:                 # save file to filesystem
                    227:                 savePath=os.path.join(tmpPath,title)
                    228:                 fh=file(savePath,"w")
1.11      casties   229:                 data = vf.getLastVersion().data
                    230:                 if isinstance(data, str):
                    231:                     # simple data object
                    232:                     fh.write(data)
                    233:                 else:
                    234:                     # chained data objects
                    235:                     while data is not None:
                    236:                         fh.write(data.data)
                    237:                         data = data.next
1.10      casties   238:                 fh.close()
                    239:                 # and read in again
                    240:                 fh = file(savePath)
1.11      casties   241:                 logging.error("importvff: comment=%s author=%s!"%(vc,author))
1.10      casties   242:                 self.addFile(vC=vc, file=fh, author=author)
1.11      casties   243:                 # copy more fields
                    244:                 newfob = getattr(self, vfn).getContentObject()
                    245:                 newfob.vComment = fob.vComment
                    246:                 newfob.time = fob.time
                    247:                 logging.error("importvff: vc=%s time=%s of %s!"%(fob.vComment,fob.time,fob.getId()))
1.10      casties   248:                 
                    249:             else:
                    250:                 logging.error("importvff: unable to import %s of type %s!"%(vfn,vf.meta_type))
                    251:         
                    252:         shutil.rmtree(tmpPath)
                    253: 
                    254:         if RESPONSE:
                    255:             RESPONSE.redirect(self.REQUEST['URL1'])
                    256: 
1.1       dwinter   257:     zipThreads={}
                    258:     zipThreads2={}
                    259: 
                    260:     def refreshTxt(self):
                    261:         """txt fuer refresh"""
                    262:         tn=self.REQUEST.SESSION['threadName']
                    263:         return """ 2;url=%s?repeat=%s """%(self.absolute_url()+"/exportFolder",tn)
                    264: 
                    265:     def exportFolder(self,repeat=None):
                    266:         """exportiert alle akutellen files des folders"""
                    267:         threadName=repeat
                    268:         
                    269:         downloadZip=generateDownloadZip(self,self.absolute_url())
                    270:         downloadZip()
                    271:         return downloadZip.getResult()
1.8       casties   272:     
1.1       dwinter   273:        ##  if not threadName or threadName=="":
                    274: ##             threadStart=generateDownloadZip(self,self.absolute_url())
                    275: ##             thread=Thread(target=threadStart)
1.6       casties   276:     
1.1       dwinter   277: ##             thread.start()
                    278: 
1.6       casties   279:     
1.1       dwinter   280: ##             self.zipThreads[thread.getName()[0:]]=threadStart
                    281: ##             self.zipThreads2[thread.getName()[0:]]=thread
                    282: ##             self.REQUEST.SESSION['threadName']=thread.getName()[0:]
                    283: ##             wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['zip_wait_template'])
                    284: ##             if wait_template:
                    285: ##                 return wait_template[0][1]()
                    286: ##             pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait.zpt')).__of__(self)
                    287: ##             return pt()
1.6       casties   288:     
1.1       dwinter   289: ##         else:
                    290: ##             self.REQUEST.SESSION['threadName']=threadName
                    291: 
                    292: ##             if (self.zipThreads[threadName].getResult()==None):
                    293: 
                    294: ##                 wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
                    295: ##                 if wait_template:
                    296: ##                     return wait_template[0][1]()
                    297: 
                    298: ##                 pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait.zpt')).__of__(self)
                    299: ##                 return pt()
                    300: ##             else:
                    301: ##                 if self.zipThreads[threadName].isDone():
                    302: ##                     self.REQUEST.SESSION['result']=self.zipThreads[threadName].getResult()
                    303: ##                     self.zipThreads2[threadName].join()
                    304: ##                     del(self.zipThreads2[threadName])
                    305: ##                     del(self.zipThreads[threadName])
                    306: ##                     pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_result.zpt')).__of__(self)
                    307: ##                     return pt()
                    308: 
                    309: ##                 else:
                    310: ##                     self.REQUEST.SESSION['result']=self.zipThreads[threadName].getResult()
                    311: ##                     self.REQUEST.SESSION['threadName']=threadName
                    312: ##                     pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','zip_wait_result.zpt')).__of__(self)
                    313: ##                     return pt()
                    314: 
                    315:     def downloadSet(self,fn):
1.6       casties   316:         """download prepared set"""
                    317:         filename=os.path.join(tdir,fn)
1.1       dwinter   318: 
1.6       casties   319:         
                    320:         self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename="%s" """%"downloadFileFolder.tgz")
                    321:         self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
                    322:         len=os.stat(filename)[6]
                    323:         self.REQUEST.RESPONSE.setHeader("Content-Length",len)
                    324:         images=file(filename).read()
                    325:         self.REQUEST.RESPONSE.write(images)
                    326:         self.REQUEST.RESPONSE.close()
1.1       dwinter   327: 
                    328:    
                    329: 
                    330:     def helpDownload(self):
                    331:         """download help"""
                    332:         
                    333:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','helpDownload')).__of__(self)
                    334:         return pt()
                    335:     
                    336:     def generateIndexHTML_image(self,RESPONSE=None):
                    337:         """lege standard index.html an"""
                    338: 
                    339: 
                    340:         if not self.ZopeFind(self,obj_ids=['index.html']):
                    341:             zt=ZopePageTemplate('index.html')
                    342:             self._setObject('index.html',zt)
                    343:             default_content_fn = os.path.join(package_home(globals()),
1.6       casties   344:                                               'zpt/versionFileFolderMain_image.zpt')
1.1       dwinter   345:             text = open(default_content_fn).read()
                    346:             zt.pt_edit(text, 'text/html')
                    347: 
                    348:         else:
                    349:             return "already exists!"
                    350:         
                    351:         if RESPONSE is not None:
                    352:             RESPONSE.redirect('manage_main')
                    353: 
                    354:     
                    355:     def generateAddFileForm(self,RESPONSE=None):
                    356:         """lege standard addfileform an"""
                    357:         #TODO: write generateaddfileform only a dummy at them moment
                    358: 
                    359:         if not self.ZopeFind(self,obj_ids=['addFileForm.dtml']):
                    360:             zt=ZopePageTemplate('index.html')
                    361:             self._setObject('index.html',zt)
                    362:             default_content_fn = os.path.join(package_home(globals()),
1.6       casties   363:                                               'zpt/versionFileFolderMain.zpt')
1.1       dwinter   364:             text = open(default_content_fn).read()
                    365:             zt.pt_edit(text, 'text/html')
                    366: 
                    367:         else:
                    368:             return "already exists!"
                    369:         
                    370:         if RESPONSE is not None:
                    371:             RESPONSE.redirect('manage_main')
                    372: 
                    373: 
                    374:     def generateIndexHTML(self,RESPONSE=None):
                    375:         """lege standard index.html an"""
                    376:         if not self.ZopeFind(self,obj_ids=['index.html']):
                    377:             zt=ZopePageTemplate('index.html')
                    378:             self._setObject('index.html',zt)
                    379:             default_content_fn = os.path.join(package_home(globals()),
1.6       casties   380:                                               'zpt/versionFileFolderMain.zpt')
1.1       dwinter   381:             text = open(default_content_fn).read()
                    382:             zt.pt_edit(text, 'text/html')
                    383: 
                    384:         else:
                    385:             return "already exists!"
                    386:         
                    387:         if RESPONSE is not None:
                    388:             RESPONSE.redirect('manage_main')
                    389: 
                    390: 
                    391:     def generateHistoryHTML(self,RESPONSE=None):
                    392:         """lege standard index.html an"""
                    393:         if not self.ZopeFind(self,obj_ids=['history_template.html']):
                    394:             zt=ZopePageTemplate('history_template.html')
                    395:             self._setObject('history_template.html',zt)
                    396:             default_content_fn = os.path.join(package_home(globals()),
1.6       casties   397:                                               'zpt/versionHistory.zpt')
1.1       dwinter   398:             text = open(default_content_fn).read()
                    399:             zt.pt_edit(text, 'text/html')
                    400: 
                    401:         else:
                    402:             return "already exists!"
                    403:         
                    404:         if RESPONSE is not None:
                    405:             RESPONSE.redirect('manage_main')
1.6       casties   406:             
1.1       dwinter   407: 
                    408:     def getVersionedFiles(self,sortField='title'):
                    409:         """get all versioned files"""
                    410: 
                    411:         def sortName(x,y):
                    412:             return cmp(x[1].title.lower(),y[1].title.lower())
                    413: 
                    414:         def sortDate(x,y):
1.7       casties   415:             return cmp(y[1].getContentObject().getTime(),x[1].getContentObject().getTime())
1.1       dwinter   416: 
                    417:         def sortComment(x,y):
1.6       casties   418:             try:
                    419:                 xc=getattr(x[1],'comment','ZZZZZZZZZZZZZ').lower()
                    420:             except:
                    421:                 xc='ZZZZZZZZZZZZZ'.lower()
                    422:                 
                    423:             try:
                    424:                 yc=getattr(y[1],'comment','ZZZZZZZZZZZZZ').lower()
                    425:             except:
                    426:                 yc='ZZZZZZZZZZZZZ'.lower()
                    427: 
                    428:             if (xc=='') or (xc=='ZZZZZZZZZZZZZ'.lower()):
                    429:                 try:
1.7       casties   430:                     xc=x[1].getContentObject().getVComment().lower()
1.6       casties   431:                 except:
                    432:                     xc='ZZZZZZZZZZZZZ'.lower()
                    433:                             
                    434:             if (yc=='') or (yc=='ZZZZZZZZZZZZZ'.lower()):
                    435:                 try:
1.7       casties   436:                     yc=y[1].getContentObject().getVComment().lower()
1.6       casties   437:                 except:
                    438:                     yc='ZZZZZZZZZZZZZ'.lower()
                    439:                                     
                    440:             return cmp(xc,yc)
1.1       dwinter   441: 
                    442:         def sortAuthor(x,y):
                    443:             
1.7       casties   444:             return cmp(x[1].getContentObject().lastEditor().lower(),y[1].getContentObject().lastEditor().lower())
1.1       dwinter   445:         
1.7       casties   446:         versionedFiles=self.objectItems(self.file_meta_type)
                    447:         logging.debug("versionedfiles: %s of type %s"%(repr(versionedFiles),repr(self.file_meta_type)))
1.1       dwinter   448:         
                    449:         if sortField=='title':
                    450:             versionedFiles.sort(sortName)
                    451:         elif sortField=='date':
                    452:             versionedFiles.sort(sortDate)
                    453:         elif sortField=='author':
                    454:             versionedFiles.sort(sortAuthor)
                    455:         elif sortField=='comment':
                    456:             versionedFiles.sort(sortComment)
                    457: 
                    458:         return versionedFiles
                    459: 
                    460: 
                    461:     def header_html(self):
1.5       casties   462:         """zusaetzlicher header"""
1.1       dwinter   463:         ext=self.ZopeFind(self,obj_ids=["header.html"])
                    464:         if ext:
                    465:             return ext[0][1]()
                    466:         else:
                    467:             return ""
                    468: 
                    469: 
                    470:     security.declareProtected('View','index_html')
                    471:     def index_html(self):
                    472:         """main"""
                    473:         ext=self.ZopeFind(self,obj_ids=["index.html"])
                    474:         if ext:
                    475:             return ext[0][1]()
                    476:         
                    477:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionFileFolderMain')).__of__(self)
                    478:         return pt()
                    479: 
                    480: 
                    481: 
                    482:     def addFileForm(self):
                    483:         """add a file"""
                    484:         ext=self.ZopeFind(self,obj_ids=["addFileForm.dtml"])
                    485:         if ext:
                    486:             return ext[0][1]('',globals(),version='1',AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)
                    487:         
                    488:         out=DTMLFile('dtml/newFileAdd', globals(),Kind='versionedFileObject',kind='versionedFileObject',version='1').__of__(self)
                    489:         return out()
                    490: 
                    491: 
1.8       casties   492:     def addFile(self,vC,file,author='',newName='',content_type='',RESPONSE=None):
1.1       dwinter   493:         """ add a new file"""
1.9       casties   494:         # is file is a real file or a zope download object?
                    495:         isRealFile = type(file) is types.FileType
                    496: 
1.1       dwinter   497:         if newName=='':
1.9       casties   498:             logging.debug("fileobject: %s real:%s"%(repr(file),repr(isRealFile)))
                    499:             if isRealFile:
                    500:                 filename = file.name
                    501:             else:
                    502:                 filename=file.filename
                    503: 
1.1       dwinter   504:             id=filename[max(filename.rfind('/'),
1.6       casties   505:                             filename.rfind('\\'),
                    506:                             filename.rfind(':'),
                    507:                             )+1:]
1.1       dwinter   508: 
                    509:         else:
                    510:             id=newName
                    511:         
1.11      casties   512:         if vC is None:
1.9       casties   513:             vC=self.REQUEST.form['vC']
1.8       casties   514:         
                    515:         # get new extVersionedFile
                    516:         vf = self._newVersionedFile(id,title=id)
1.26      dwinter   517:         logging.error("addFile id=%s vf=%s of %s"%(repr(id),repr(vf),repr(self)))
1.18      casties   518:         # add its content (and don't index)
                    519:         obj=vf.addContentObject(id,vC,author=author,file=file,content_type=content_type,from_tmp=isRealFile,index=False)
                    520:         # add file to this folder (this should do the indexing)
1.8       casties   521:         self._setObject(id,vf)
1.1       dwinter   522:         
1.18      casties   523:         try:
                    524:             self.REQUEST.SESSION['objID']=vf.getId()
                    525:             self.REQUEST.SESSION['objID_parent']=None
                    526:         except:
                    527:             pass
1.1       dwinter   528: 
                    529:         if obj.getSize()==0:
                    530:             pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
                    531:             return pt()
                    532:         
1.9       casties   533:         if RESPONSE is not None:
                    534:             RESPONSE.redirect(self.REQUEST['URL1'])
1.1       dwinter   535: 
                    536: 
1.8       casties   537:     def _newVersionedFile(self, id, title='', lockedBy=None, author=None):
                    538:         """factory for versioned files. to be overridden in derived classes."""
                    539:         return extVersionedFile(id, title, lockedBy=lockedBy, author=author)
                    540: 
                    541: 
1.1       dwinter   542:     def deleteEmptyObject(self,submit,RESPONSE=None):
                    543:         """deleteemptyobject"""
                    544:         if submit=="delete it":
                    545:             if self.REQUEST.SESSION['objID_parent']:
                    546:                 obj=getattr(self,self.REQUEST.SESSION['objID_parent'])
                    547: 
                    548:             else:
                    549:                 obj=self
                    550:             obj.manage_delObjects([self.REQUEST.SESSION['objID']])
                    551: 
                    552:         RESPONSE.redirect(self.REQUEST['URL1'])
                    553:         
1.7       casties   554: 
                    555:     security.declareProtected('AUTHENTICATED_USER','fixVersionNumbers')    
                    556:     def fixVersionNumbers(self):
                    557:         """fix last version number of all files"""
                    558:         for (id,vf) in self.getVersionedFiles():
                    559:             vf.fixVersionNumbers()
1.13      casties   560:         # recursively
                    561:         for (id,vf) in self.objectItems(self.meta_type):
                    562:             vf.fixVersionNumbers()
1.1       dwinter   563:         
1.8       casties   564: 
1.1       dwinter   565: manage_addextVersionedFileFolderForm=DTMLFile('dtml/extfolderAdd', globals())
                    566: 
                    567: 
                    568: def manage_addextVersionedFileFolder(self, id, title='',
1.6       casties   569:                                      createPublic=0,
                    570:                                      createUserF=0,
                    571:                                      REQUEST=None):
1.1       dwinter   572:     """Add a new Folder object with id *id*.
                    573: 
                    574:     If the 'createPublic' and 'createUserF' parameters are set to any true
                    575:     value, an 'index_html' and a 'UserFolder' objects are created respectively
                    576:     in the new folder.
                    577:     """
                    578:     ob=extVersionedFileFolder()
                    579:     ob.id=str(id)
                    580:     ob.title=title
                    581:     self._setObject(id, ob)
                    582:     ob=self._getOb(id)
                    583: 
                    584:     checkPermission=getSecurityManager().checkPermission
                    585: 
                    586:     if createUserF:
                    587:         if not checkPermission('Add User Folders', ob):
                    588:             raise Unauthorized, (
1.6       casties   589:                 'You are not authorized to add User Folders.'
                    590:                 )
1.1       dwinter   591:         ob.manage_addUserFolder()
                    592: 
1.6       casties   593:         
1.1       dwinter   594:     if REQUEST is not None:
                    595:         return self.manage_main(self, REQUEST, update_menu=1)
                    596: 
                    597: 
                    598: 
                    599: class extVersionedFileObject(ExtFile):
                    600:     """File Object im Folder"""
                    601:     security= ClassSecurityInfo()
                    602:     meta_type = "extVersionedFileObject"
                    603:     
1.7       casties   604:     manage_editForm=DTMLFile('dtml/fileEdit',globals(),
1.1       dwinter   605:                                Kind='File',kind='file')
                    606:     manage_editForm._setName('manage_editForm')
                    607: 
1.7       casties   608:     def __init__(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
                    609:         """Initialize a new instance of extVersionedFileObject (taken from ExtFile)"""
                    610:         ExtFile.__init__(self,id,title)
                    611:         self.versionNumber = versionNumber
                    612:         self.versionComment= versionComment
                    613:         self.time = time
                    614:         self.author = author
                    615: 
1.22      casties   616:     security.declareProtected('manage','changeObject')
                    617:     def changeObject(self,**args):
1.23      casties   618:         """modify any of the objects attributes"""
1.22      casties   619:         for arg in args:
                    620:             if hasattr(self, arg):
1.24      casties   621:                 logging.debug("changeObject %s: %s=%s"%(repr(self),arg,args[arg]))
1.22      casties   622:                 setattr(self, arg, args[arg])
1.7       casties   623: 
1.1       dwinter   624:     security.declarePublic('getTitle')
                    625:     def getTitle(self):
                    626:         """get title"""
                    627:         return self.title
1.6       casties   628:     
                    629:     def getData(self):
                    630:         """returns object content (calls ExtFile.index_html)"""
1.27      dwinter   631:         #logging.debug("+++++++getData1:"+repr(self.get_filename()))
                    632:         filename = self.get_filename()
                    633:         #return ExtFile.index_html(self)
1.29      dwinter   634:         try:
                    635:             return file(filename).read()
                    636:         except:
                    637:             return ExtFile.index_html(self)
                    638: 
1.27      dwinter   639:     
                    640:     def getFileName(self):
                    641:         """return filename"""
                    642:         return self.get_filename()
                    643:     
                    644:     def addToFile(self,filehandle):
                    645:         filehandle.write(self.getData())
                    646:         
                    647:     def addToFile2(self,filename):   
                    648:          str="cat %s > %s"%(self.get_filename(),filename)
                    649:          os.popen(str)
                    650:          
1.1       dwinter   651:     security.declarePublic('getVComment')
                    652:     def getVComment(self):
                    653:         """get the comment of this file"""
                    654:         if not hasattr(self,'vComment') or (not self.vComment) or (self.vComment.lstrip()==""):
                    655:             return "Add comment"
                    656: 
                    657:         else:
                    658:             return self.vComment
1.6       casties   659:         
1.1       dwinter   660:     def manageVCommentForm(self):
                    661:         """add a comment"""
                    662:         self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
                    663:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addVComment')).__of__(self)
                    664:         return pt()
                    665: 
                    666:     def manageVComment(self,text,comment_author,submit,REQUEST=None):
                    667:         """manage comments"""
                    668:         if submit =='change':
                    669:             if text=='':
                    670:                 self.vComment=None
                    671:             else:
                    672:                 self.vComment=text
                    673:                 self.vComment_author=comment_author
                    674: 
                    675:                 self.vComment_date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                    676: 
                    677:         if self.REQUEST.SESSION.has_key('refer'):
                    678: 
                    679:             return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
                    680:         return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url()+"/history")
                    681:     
                    682: 
                    683:     security.declarePublic('getVersionComment')
                    684:     def getVersionComment(self):
                    685:         """getversioncomment"""
                    686:         return self.versionComment
                    687:     
                    688:     security.declarePublic('getTime')
                    689:     def getTime(self):
                    690:         """getTime"""
                    691:         #return self.bobobase_modification_time().ISO()
                    692:         if hasattr(self,'time'):
                    693:             return time.strftime("%Y-%m-%d %H:%M:%S",self.time)
                    694:         elif hasattr(self,'timefixed'):
1.6       casties   695:             return self.timefixed
1.1       dwinter   696:         else:
                    697:             setattr(self,'timefixed',self.bobobase_modification_time().ISO())
                    698:             return self.bobobase_modification_time().ISO()
                    699: 
                    700:     def download(self,REQUEST=None,RESPONSE=None):
                    701:         """download and lock"""
                    702:         
                    703:         self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getId())
                    704:         self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
                    705:    #try:
                    706:    #   txt=self.index_html()
                    707:    #except:
                    708:    #   txt=self.index_html(REQUEST,RESPONSE)
                    709:    #
                    710:    #self.REQUEST.RESPONSE.setHeader("Content-Length","str(len(txt)+1000)")
                    711:        
                    712:         self.content_type="application/octet-stream"
1.26      dwinter   713:         return self.getData()
                    714:         #self.REQUEST.RESPONSE.redirect(self.absolute_url())
1.1       dwinter   715:         #txt=urllib.urlopen(self.absolute_url()).read()
                    716:         #self.REQUEST.RESPONSE.write(txt)
                    717:    
                    718: 
                    719:         #self.REQUEST.close()
                    720:     
1.19      casties   721:     view = download
                    722:     
1.1       dwinter   723:     security.declareProtected('AUTHENTICATED_USER','downloadLocked')    
                    724:     def downloadLocked(self):
                    725:         """download and lock"""
                    726:         
                    727:         
                    728:         if repr(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
                    729:             return "please login first"
                    730:         if not self.aq_parent.lockedBy=="":
                    731:             return "cannot be locked because is already locked by %s"%self.lockedBy
                    732:         self.aq_parent.lockedBy=self.REQUEST['AUTHENTICATED_USER']
                    733: 
                    734:         self.content_type="application/octet-stream"
                    735:         self.REQUEST.RESPONSE.redirect(self.absolute_url())
                    736:     
                    737:     security.declarePublic('getVersionNumber')                                              
                    738:     def getVersionNumber(self):
                    739:         """get version"""
                    740:         return self.versionNumber
                    741: 
                    742:     security.declarePublic('getVersionComment')                                              
                    743:     def getVersionComment(self):
                    744:         """get version"""
                    745:         return self.versionComment
                    746: 
                    747:     security.declarePublic('lastEditor')                                               
                    748:     def lastEditor(self):
                    749:         """last Editor"""
                    750:         if hasattr(self,'author'):
                    751:             try:
                    752:                 ret=self.author.replace("-","\n")
                    753:             except:#old version of versionded file sometimes stored the user object and not only the name the following corrects this
                    754:                 ret=str(self.author).replace("-","\n")
                    755:             ret=ret.replace("\r","\n")
                    756:             return ret.lstrip().rstrip()
                    757: 
                    758:         else:
                    759:             jar=self._p_jar
                    760:             oid=self._p_oid
                    761: 
                    762:             if jar is None or oid is None: return None
                    763: 
                    764:             return jar.db().history(oid)[0]['user_name']
                    765:     
                    766:         
                    767: manage_addextVersionedFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='extVersionedFileObject',kind='extVersionedFileObject', version='1')
                    768: 
1.7       casties   769: def manage_addextVersionedFileObject(self,id,vC='',author='', file='',title='',versionNumber=0,
                    770:                                      precondition='', content_type='', REQUEST=None):
1.1       dwinter   771:     """Add a new File object.
                    772: 
                    773:     Creates a new File object 'id' with the contents of 'file'"""
                    774: 
                    775:     id=str(id)
                    776:     title=str(title)
                    777:     content_type=str(content_type)
                    778:     precondition=str(precondition)
                    779:     
                    780:     id, title = cookId(id, title, file)
                    781: 
                    782:     self=self.this()
                    783: 
                    784:     # First, we create the file without data:
1.7       casties   785:     self._setObject(id, extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=str(vC),author=author))
                    786:     fob = self._getOb(id)
1.1       dwinter   787:     
                    788:     # Now we "upload" the data.  By doing this in two steps, we
                    789:     # can use a database trick to make the upload more efficient.
                    790:     if file:
1.7       casties   791:         fob.manage_upload(file)
1.1       dwinter   792:     if content_type:
1.7       casties   793:         fob.content_type=content_type
1.1       dwinter   794: 
                    795:     if REQUEST is not None:
                    796:         REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
                    797: 
                    798: 
                    799: 
                    800: class extVersionedFile(CatalogAware,Folder):
                    801:     """Versioniertes File"""
                    802: 
1.7       casties   803:     meta_type = 'extVersionedFile'
                    804:     # meta_type of contained objects
                    805:     content_meta_type = ['extVersionedFileObject']
1.15      casties   806:     # default catalog for extVersionedFile objects
1.7       casties   807:     default_catalog = 'fileCatalog'
1.1       dwinter   808:     
1.15      casties   809:     manage_options = Folder.manage_options+({'label':'Main Config','action':'changeVersionedFileForm'},)
                    810: 
                    811:     
1.7       casties   812:     security=ClassSecurityInfo()   
1.1       dwinter   813:     
1.7       casties   814:     def __init__(self, id, title, lockedBy,author):
                    815:         """init"""
                    816:         self.id=id
                    817:         self.title=title
                    818:         self.lockedBy=lockedBy
1.25      casties   819:         if self.lockedBy is None:
                    820:             self.lockedBy = ''
1.7       casties   821:         self.author=author
                    822:         self.lastVersionNumber=0
                    823:         self.lastVersionId=None
                    824: 
1.1       dwinter   825:     security.declarePublic('getTitle')
                    826:     def getTitle(self):
                    827:         """get title"""
                    828:         return self.title
                    829:     
                    830:     def PrincipiaSearchSource(self):
1.6       casties   831:         """Return cataloguable key for ourselves."""
                    832:         return str(self)
1.1       dwinter   833: 
                    834:     def manageImagesForm(self):
                    835:         """manage Images attached to the file"""
                    836: 
                    837:         self.REQUEST.SESSION['refer']=self.REQUEST['HTTP_REFERER']
                    838:         
                    839:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','manageImage')).__of__(self)
                    840:         return pt()
                    841: 
                    842:     def manageImages(self,imageUrl=None,caption=None,REQUEST=None):
                    843:         """manage URL"""
                    844:         if imageUrl and (not imageUrl==""):
                    845:             manage_AddImageZogiLib(self,libPath=imageUrl,caption=caption)
                    846: 
                    847:         if self.REQUEST.SESSION.has_key('refer'):
                    848: 
                    849:             return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
                    850:         return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
                    851:     
                    852:     def changeImages(self,caption=None,submit=None,id=None,REQUEST=None):
                    853:         """manage URL"""
                    854:         if submit=="change caption":
                    855:             image=self.ZopeFind(self,obj_ids=[id])
                    856:             if image:
                    857:                 image[0][1].caption=caption[0:]
                    858:         
                    859:         elif submit=="delete":
                    860:             image=self.ZopeFind(self,obj_ids=[id])
                    861:             if image:
                    862:                 self.manage_delObjects([image[0][1].getId()])
                    863: 
                    864:         if self.REQUEST.SESSION.has_key('refer'):
1.7       casties   865:             return REQUEST.RESPONSE.redirect(self.REQUEST.SESSION['refer'])
1.1       dwinter   866: 
                    867:         return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
                    868: 
                    869:     def getImages(self):
                    870:         """get Images"""
                    871:         images=self.ZopeFind(self,obj_metatypes=["ImageZogiLib"])
                    872:         if not images:
                    873:             return None
                    874:         else:
                    875:             return images
1.6       casties   876:         
1.1       dwinter   877:     security.declarePublic('getComment')
                    878:     def getComment(self):
                    879:         """get the comment of this file"""
                    880:         if not hasattr(self,'comment') or (not self.comment) or (self.comment.lstrip()==""):
                    881:             return "Add comment"
                    882:         else:
                    883:             return self.comment
                    884: 
                    885:     def manageCommentForm(self):
                    886:         """add a comment"""
                    887:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addComment')).__of__(self)
                    888:         return pt()
                    889: 
                    890:     def manageComment(self,text,comment_author,submit,REQUEST=None):
                    891:         """manage comments"""
                    892:         if submit =='change':
                    893:             if text=='':
                    894:                 self.comment=None
                    895:             else:
                    896:                 self.comment=text
                    897:                 self.comment_author=comment_author
                    898: 
                    899:                 self.comment_date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                    900: 
                    901:         return REQUEST.RESPONSE.redirect(self.aq_parent.absolute_url())
1.6       casties   902:     
1.1       dwinter   903:     security.declarePublic('getLastChangeDate')
                    904:     def getLastChangeDate(self):
                    905:         """get last change date"""
1.7       casties   906:         lv=self.getContentObject()
1.18      casties   907:         if lv:
                    908:             time=lv.getTime()
                    909:             return time
                    910:         return None
1.1       dwinter   911:     
                    912:     def getLastEditor(self):
                    913:         """get last change date"""
1.7       casties   914:         lv=self.getContentObject()
1.1       dwinter   915:         le=lv.lastEditor()
                    916:         return le
                    917:     
                    918:     def getLockedBy(self):
                    919:         """get locked by"""
1.25      casties   920:         if self.lockedBy is None:
                    921:             self.lockedBy = ''
1.1       dwinter   922:         return str(self.lockedBy)
1.6       casties   923:     
1.7       casties   924:     def getLastVersionNumber(self):
                    925:         """returns the highest version number of all included objects"""
                    926:         lv = self.findLastVersion()
                    927:         if lv:
                    928:             return lv.getVersionNumber()
                    929:         else:
                    930:             return 0
                    931: 
                    932:     def findLastVersion(self):
                    933:         """finds and returns the object with the highest version number"""
                    934:         lvn=0
                    935:         lv=None
                    936:         
                    937:         for v in self.objectValues(self.content_meta_type):
                    938:             logging.debug("findlastversion: check %s"%v.getId())
                    939:             if v.getVersionNumber() > lvn:
                    940:                     lvn=v.getVersionNumber()
                    941:                     lv=v
                    942:         
                    943:         if lv:
                    944:             logging.debug("findlastversion: got %s"%lv.getId())
                    945:         return lv
                    946: 
1.1       dwinter   947:     security.declarePublic('getLastVersion')
                    948:     def getLastVersion(self):
1.7       casties   949:         """Last Version (old)"""
1.1       dwinter   950:         tmp=0
1.7       casties   951:         lv=None
1.1       dwinter   952:         
1.7       casties   953:         for v in self.objectValues(self.content_meta_type):
1.28      dwinter   954:             #logging.debug("getlastversion: check %s"%v.getId())
1.7       casties   955:             if v.getVersionNumber() > tmp:
                    956:                     tmp=v.getVersionNumber()
                    957:                     lv=v
                    958:         
1.28      dwinter   959:         #ogging.debug("getlastversion: got %s"%lv.getId())
1.7       casties   960:         return lv
                    961: 
                    962:     def getContentObject(self):
                    963:         """returns the last version object"""
1.18      casties   964:         if not getattr(self, 'lastVersionId', None):
1.14      casties   965:             # find last version and save it
1.7       casties   966:             lv = self.findLastVersion()
                    967:             if lv is None:
                    968:                 return None
                    969:             self.lastVersionNumber = lv.getVersionNumber()
                    970:             self.lastVersionId = lv.getId()
1.1       dwinter   971:             
1.18      casties   972:         return getattr(self, self.lastVersionId, None)
1.7       casties   973: 
                    974:     security.declarePublic('getData')
                    975:     def getData(self):
                    976:         """Returns the content of the last version"""
1.27      dwinter   977:         logging.debug("+++++++getData2")
1.7       casties   978:         ob = self.getContentObject()
                    979:         if ob is not None:
                    980:             return ob.getData()
                    981:         else:
                    982:             return None
1.1       dwinter   983:     
1.19      casties   984:     security.declarePublic('view')
                    985:     def view(self,REQUEST=None,RESPONSE=None):
                    986:         """Returns the last version's view"""
                    987:         ob = self.getContentObject()
                    988:         if ob is not None:
                    989:             return ob.view(REQUEST=REQUEST,RESPONSE=RESPONSE)
                    990:         else:
                    991:             return None
                    992:     
1.1       dwinter   993:     def diff(self,data):
                    994:         """differenz between lastversion and data"""
                    995:         d=Differ()
1.7       casties   996:         tmp=self.getData()
1.1       dwinter   997:         #print "XX",data,tmp
                    998:         try:
1.6       casties   999:             l=list(d.compare(data.splitlines(1),tmp.splitlines(1)))
1.1       dwinter  1000:         except:
                   1001:             return 0,""
                   1002:         plus=0
                   1003:         minus=0
                   1004:         for a in l:
                   1005:             if a[0]=='+':
                   1006:                 plus+=1
                   1007:             if a[0]=='-':
                   1008:                 minus+=1
                   1009:         
                   1010:         return max([plus,minus]),l
1.6       casties  1011: 
                   1012: 
1.1       dwinter  1013:     security.declarePublic('index_html')
                   1014:     def index_html(self):
                   1015:         """main view"""
1.7       casties  1016:         #lastVersion=self.getContentObject()
1.1       dwinter  1017:         #return "File:"+self.title+"  Version:%i"%lastVersion.versionNumber," modified:",lastVersion.bobobase_modification_time()," size:",lastVersion.getSize(),"modified by:",lastVersion.lastEditor()
1.4       dwinter  1018:         #return "File: %s Version:%i modified:%s size:%s modified by:%s"%(self.title,lastVersion.versionNumber,lastVersion.getTime(),lastVersion.getSize(),lastVersion.lastEditor())
                   1019:         return self.history()
1.1       dwinter  1020: 
1.30      dwinter  1021:     def getVersionNr(self,nr):
                   1022:         """get version with number nr"""
                   1023:         tmp=0
                   1024:         lastVersion=None
                   1025:         
                   1026:         
                   1027:         for version in self.ZopeFind(self):
                   1028:             
                   1029:             if hasattr(version[1],'versionNumber'):
                   1030:                 
                   1031:                 if int(version[1].versionNumber) ==nr :
                   1032:                     return version[1]
                   1033:            
                   1034:         return None
1.1       dwinter  1035:     security.declarePublic('getVersion')                                              
                   1036:     def getVersion(self):
1.7       casties  1037:         # TODO: this is ugly and it returns the next version number 
1.1       dwinter  1038:         tmp=0
                   1039:         for version in self.ZopeFind(self):
                   1040:             
                   1041:             if hasattr(version[1],'versionNumber'):
                   1042:                 
                   1043:                 if int(version[1].versionNumber) > tmp:
                   1044:                     tmp=int(version[1].versionNumber,)
1.7       casties  1045:         return tmp+1        
1.1       dwinter  1046: 
                   1047:     def history(self):
                   1048:         """history"""  
                   1049:         ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
                   1050:         if ext:
                   1051:             return getattr(self,ext[0][1].getId())()
                   1052:         
                   1053:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionHistory')).__of__(self)
                   1054:         return pt()
                   1055: 
                   1056:     def getVersions(self):
                   1057:         """get all versions"""
                   1058:         ret=[]
                   1059:         for version in self.ZopeFind(self):
                   1060:             if hasattr(version[1],'versionNumber'):
                   1061:                 ret.append((version[1].versionNumber,version[1]))
                   1062:         ret.sort(sortv)
                   1063:         return ret
                   1064: 
1.20      casties  1065:     def getVersionList(self):
                   1066:         """get a list of dicts with author, comment, filename, etc, of all versions"""
                   1067:         vl = []
                   1068:         for v in self.objectValues(self.content_meta_type):
1.21      casties  1069:             vl.append({'versionNumber':getattr(v,'versionNumber',0),
1.20      casties  1070:                       'title':v.getTitle(),
1.21      casties  1071:                       'id':v.getId(),
1.20      casties  1072:                       'date':v.getTime(),
1.21      casties  1073:                       'author':getattr(v,'author',''),
                   1074:                       'comment':getattr(v,'versionComment','')
1.20      casties  1075:                       })
1.21      casties  1076:         return vl
1.20      casties  1077: 
1.1       dwinter  1078:     security.declareProtected('AUTHENTICATED_USER','forceunlock')   
1.31    ! dwinter  1079:     def forceunlock(self,RESPONSE=None,user=None):
1.1       dwinter  1080:         """unlock"""
                   1081:         #safe who had the lock
1.31    ! dwinter  1082:         logging.debug("extVersionFile: (forceunlock)"+str(user))
1.1       dwinter  1083:         if self.lockedBy:
1.31    ! dwinter  1084:             if user is not None:
        !          1085:                 if str(self.lockedBy)==user:
        !          1086:                     self.brokenLock=str(self.lockedBy)
        !          1087:                     self.lockedBy=''
        !          1088:                 else:
        !          1089:                     self.brokenLock=""
        !          1090:             else:
        !          1091:                 self.brokenLock=str(self.lockedBy)
        !          1092:                 self.lockedBy=''
1.1       dwinter  1093:         else:
                   1094:             self.brokenLock=""
1.31    ! dwinter  1095:         
1.1       dwinter  1096:         return self.brokenLock
                   1097: 
                   1098:     security.declareProtected('AUTHENTICATED_USER','unlock')   
                   1099:     def unlock(self,RESPONSE):
                   1100:         """unlock"""
                   1101:         if str(self.lockedBy) in [str(self.REQUEST['AUTHENTICATED_USER'])]:
                   1102:             self.lockedBy=''
                   1103:             RESPONSE.redirect(self.REQUEST['HTTP_REFERER'])
                   1104:         else:
                   1105:             return "Sorry, not locked by you! (%s,%s)"%(self.lockedBy,self.REQUEST['AUTHENTICATED_USER'])
                   1106:         
1.7       casties  1107:     
                   1108:     def _newContentObject(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
                   1109:         """factory for content objects. to be overridden in derived classes."""
                   1110:         return extVersionedFileObject(id,title,versionNumber=versionNumber,versionComment=versionComment,time=time,author=author)
                   1111: 
                   1112: 
1.18      casties  1113:     def addContentObject(self,id,vC,author=None,file=None,title='',changeName='no',newName='',from_tmp=False,index=True,
1.7       casties  1114:                          precondition='', content_type=''):
                   1115:         """add"""
                   1116:         
                   1117:         if changeName=="yes":
                   1118:             filename=file.filename
                   1119:             self.title=filename[max(filename.rfind('/'),
                   1120:                                     filename.rfind('\\'),
                   1121:                                     filename.rfind(':'),
                   1122:                                     )+1:]
                   1123: 
                   1124:         if not newName=='':
                   1125:             self.title=newName[0:]
                   1126:         
                   1127:         posVersNum=getattr(self,'positionVersionNum','front')
                   1128:         
                   1129:         versNum = self.getLastVersionNumber() + 1
                   1130:         
                   1131:         if posVersNum=='front':
                   1132:             id="V%i_%s"%(versNum,self.title)
                   1133:         else:
                   1134:             fn=os.path.splitext(self.title)
                   1135:             if len(fn)>1:
                   1136:                 id=fn[0]+"_V%i%s"%(versNum,fn[1])
                   1137:             else:
                   1138:                 id=fn[0]+"_V%i"%versNum
1.1       dwinter  1139: 
1.7       casties  1140:         # what does this do?
                   1141:         id, title = cookId(id, title, file)
                   1142:         self=self.this()
                   1143:     
                   1144:         # First, we create the file without data:
                   1145:         self._setObject(id, self._newContentObject(id,title,versionNumber=versNum,versionComment=str(vC),
                   1146:                                               time=time.localtime(),author=author))
                   1147:         fob = self._getOb(id)
                   1148:         
                   1149:         # Now we "upload" the data.  By doing this in two steps, we
                   1150:         # can use a database trick to make the upload more efficient.
                   1151:         if file and not from_tmp:
                   1152:             fob.manage_upload(file)
                   1153:         elif file and from_tmp:
                   1154:             fob.manage_file_upload(file) # manage_upload_from_tmp doesn't exist in ExtFile2
                   1155:         #    fob.manage_upload_from_tmp(file) # manage_upload_from_tmp doesn't exist in ExtFile2
                   1156:         fob.content_type=content_type
                   1157:         
                   1158:         self.lastVersionNumber = versNum
                   1159:         self.lastVersionId = id
                   1160:         
1.9       casties  1161:         #logging.debug("addcontentobject: lastversion=%s"%self.getData())
                   1162:         #logging.debug("addcontentobject: fob_data=%s"%fob.getData())
1.18      casties  1163:         if index and self.default_catalog:
                   1164:             logging.debug("reindex1: %s in %s"%(repr(self),repr(self.default_catalog)))
                   1165:             self.reindex_object()
1.7       casties  1166:         
                   1167:         return fob
                   1168:             
1.1       dwinter  1169:     
                   1170:     security.declareProtected('AUTHENTICATED_USER','addVersionedFileObjectForm')
                   1171:     def addVersionedFileObjectForm(self):
                   1172:         """add a new version"""
                   1173:         
                   1174:         if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
                   1175:             return "please login first"
                   1176:         if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
                   1177:             ext=self.ZopeFind(self.aq_parent,obj_ids=["addNewVersion.dtml"])
                   1178:             if ext:
1.7       casties  1179:                 return ext[0][1]('',globals(),version=self.getVersion(),lastComment=self.getContentObject().getVersionComment(),AUTHENTICATED_USER=self.REQUEST.AUTHENTICATED_USER)
1.1       dwinter  1180:             else:
                   1181:                 out=DTMLFile('dtml/fileAdd', globals(),Kind='VersionedFileObject',kind='versionedFileObject',version=self.getVersion()).__of__(self)
                   1182:                 return out()
                   1183:         else:
                   1184:             return "Sorry file is locked by somebody else"
1.7       casties  1185: 
1.1       dwinter  1186:         
1.7       casties  1187:     def manage_addVersionedFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', from_tmp=False, RESPONSE=None):
1.1       dwinter  1188:         """add"""
                   1189:         try: #der ganze vC unsinn muss ueberarbeitet werden
                   1190:             vC=self.REQUEST['vC']
                   1191:         except:
                   1192:             pass
                   1193:         
                   1194:         author=self.REQUEST['author']
                   1195: 
1.7       casties  1196:         ob = self.addContentObject(id, vC, author, file, title, changeName=changeName, newName=newName, from_tmp=from_tmp,
                   1197:                                    precondition=precondition, content_type=content_type)
                   1198:             
1.1       dwinter  1199:         self.REQUEST.SESSION['objID_parent']=self.getId()
                   1200: 
                   1201:         if RESPONSE:
1.7       casties  1202:             if ob.getSize()==0:
                   1203:                 self.REQUEST.SESSION['objID']=ob.getId()
1.1       dwinter  1204:                 pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
                   1205:                 return pt()
                   1206: 
                   1207:             else:
1.19      casties  1208:                 RESPONSE.redirect(self.absolute_url()+'/history')
1.1       dwinter  1209:         else:
1.7       casties  1210:             return ob
1.6       casties  1211: 
1.15      casties  1212: 
                   1213:     changeVersionedFileForm = PageTemplateFile('zpt/changeVersionedFile', globals())
                   1214:     
1.17      casties  1215:     def manage_changeVersionedFile(self,title,vC,author,comment,RESPONSE=None):
1.15      casties  1216:         """Change VersionedFile metadata"""
                   1217:         self.title = title
                   1218:         self.author = author
                   1219:         cob = self.getContentObject()
                   1220:         if cob:
                   1221:             if vC:
                   1222:                 cob.vComment=vC
                   1223: 
                   1224:             if comment=='':
                   1225:                 cob.versionComment=None
                   1226:             else:
                   1227:                 cob.versionComment=comment
                   1228: 
1.16      casties  1229:         if RESPONSE:
                   1230:             RESPONSE.redirect('manage_main')
                   1231: 
1.1       dwinter  1232:         
                   1233:     def download(self):
1.15      casties  1234:         """download"""
1.26      dwinter  1235:     
                   1236:         txt=self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId()+'/download'
                   1237:         
                   1238:         self.REQUEST.RESPONSE.redirect(txt)
1.16      casties  1239: 
1.1       dwinter  1240:     
                   1241:     security.declareProtected('AUTHENTICATED_USER','downloadLocked')    
                   1242:     def downloadLocked(self):
                   1243:         """download and lock"""
                   1244: 
                   1245:         if repr(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
                   1246:             return "please login first"
                   1247:         if not self.lockedBy=="":
                   1248:             return "cannot be locked because is already locked by %s"%self.lockedBy
                   1249:         self.lockedBy=self.REQUEST['AUTHENTICATED_USER']
1.7       casties  1250:         self.getContentObject().content_type="application/octet-stream"
                   1251:         self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'/'+self.getId()+'/'+self.getContentObject().getId())
                   1252:     
                   1253: 
                   1254:     security.declareProtected('AUTHENTICATED_USER','fixVersionNumbers')    
                   1255:     def fixVersionNumbers(self):
                   1256:         """check last version number and id"""
                   1257:         if not hasattr(self, 'lastVersionId'):
                   1258:             self.lastVersionNumber = 0
                   1259:             self.lastVersionId = None
                   1260:             
                   1261:         lv = self.getContentObject()
                   1262:         if lv is not None:
                   1263:             lvn = lv.getVersionNumber()
                   1264:             if lvn == 0:
                   1265:                 lvn = 1
                   1266:                 lv.versionNumber = 1
                   1267:             self.lastVersionNumber = lvn
                   1268:             self.lastVersionId = lv.getId()
                   1269:         else:
                   1270:             self.lastVersionNumber = 0
                   1271:             self.lastVersionId = None
                   1272:         logging.debug("fixing last version number of %s to %s (%s)"%(self.getId(),self.lastVersionNumber,self.lastVersionId))
                   1273:     
1.1       dwinter  1274:     
                   1275: def manage_addextVersionedFileForm(self):
                   1276:     """interface for adding the OSAS_root"""
                   1277:     pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addextVersionedFile.zpt')).__of__(self)
                   1278:     return pt()
                   1279: 
                   1280: def manage_addextVersionedFile(self,id,title,lockedBy, author=None, RESPONSE=None):
                   1281:     """add the OSAS_root"""
                   1282:     newObj=extVersionedFile(id,title,lockedBy,author)
                   1283:     self._setObject(id,newObj)
1.6       casties  1284:     
1.1       dwinter  1285:     if RESPONSE is not None:
                   1286:         RESPONSE.redirect('manage_main')
                   1287: 
                   1288: 
                   1289: InitializeClass(extVersionedFile)
                   1290: InitializeClass(extVersionedFileFolder)

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