Annotation of cdli/cdli_files.py, revision 1.119
1.22 dwinter 1: """CDLI extensions of the filearchive"""
1.47 dwinter 2: from Products.versionedFile.extVersionedFile import *
1.1 dwinter 3: from Products.ZCatalog.CatalogPathAwareness import CatalogAware
4: import os.path
5: import os
1.3 dwinter 6: import urlparse
1.49 dwinter 7: import urllib
8: import cgi
1.4 dwinter 9: from OFS.OrderedFolder import OrderedFolder
10: from OFS.SimpleItem import SimpleItem
11: import time
1.12 dwinter 12: from OFS.Folder import manage_addFolder
13: import re
1.19 dwinter 14: from AccessControl import ClassSecurityInfo
15: from Acquisition import Implicit
1.39 dwinter 16: from Globals import Persistent
1.19 dwinter 17: from threading import Thread
18: from ZPublisher.HTTPRequest import HTTPRequest
19: from ZPublisher.HTTPResponse import HTTPResponse
20: from ZPublisher.BaseRequest import RequestContainer
1.20 dwinter 21: import threading
1.57 dwinter 22: import logging
1.58 dwinter 23: import transaction
1.61 dwinter 24: import copy
1.66 dwinter 25: import codecs
1.76 dwinter 26: import sys
1.83 dwinter 27: from BTrees.IOBTree import IOBTree
1.107 dwinter 28: from BTrees.OOBTree import OOBTree
1.81 casties 29: import cdliSplitter
1.83 dwinter 30: from sets import Set
31: import md5
1.87 dwinter 32: from DownloadBasket import DownloadBasketFinallyThread
1.102 dwinter 33: from types import *
1.103 dwinter 34: import pickle
1.104 dwinter 35: import tempfile
36:
1.105 dwinter 37: from cdli_helpers import *
1.87 dwinter 38:
1.46 dwinter 39: class CDLIFileObject(CatalogAware,extVersionedFileObject):
1.1 dwinter 40: """CDLI file object"""
41:
42: meta_type="CDLI File Object"
1.25 dwinter 43: default_catalog='CDLIObjectsCatalog'
1.1 dwinter 44:
1.12 dwinter 45: security=ClassSecurityInfo()
46:
1.78 dwinter 47: security.declareProtected('manage','index_html')
1.81 casties 48:
49: security.declarePublic('view')
50: view = PageTemplateFile('zpt/viewCDLIFile.zpt', globals())
51:
52: security.declarePublic('editATF')
53: editATF = PageTemplateFile('zpt/editATFFile.zpt', globals())
54:
1.28 dwinter 55: def PrincipiaSearchSource(self):
56: """Return cataloguable key for ourselves."""
57: return str(self)
58:
1.89 dwinter 59: def setAuthor(self, author):
60: """change the author"""
61: self.author = author
62:
1.26 dwinter 63: def makeThisVersionCurrent_html(self):
1.85 dwinter 64: """form for mthis version current"""
1.26 dwinter 65:
66: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','makeThisVersionCurrent.zpt')).__of__(self)
67: return pt()
1.81 casties 68:
69: security.declarePublic('makeThisVersionCurrent')
1.27 dwinter 70: def makeThisVersionCurrent(self,comment,author,RESPONSE=None):
1.26 dwinter 71: """copy this version to current"""
72: parent=self.aq_parent
1.81 casties 73: parent.manage_addVersionedFileObject(id=None,vC=comment,author=author,file=self.getData(),RESPONSE=RESPONSE)
74: #newversion=parent.manage_addCDLIFileObject('',comment,author)
75: #newversion.manage_upload(self.getData())
1.27 dwinter 76:
1.81 casties 77: #if RESPONSE is not None:
78: # RESPONSE.redirect(self.aq_parent.absolute_url()+'/history')
1.27 dwinter 79:
1.26 dwinter 80: return True
81:
1.52 dwinter 82: def getFormattedData(self):
83: """fromat text"""
84: data=self.getData()
1.70 dwinter 85: # return re.sub("\s\#lem"," #lem",data) #remove return vor #lem
86: return re.sub("#lem"," #lem",data) #remove return vor #lem
1.52 dwinter 87:
1.1 dwinter 88:
1.40 dwinter 89: security.declarePublic('getPNumber')
90: def getPNumber(self):
1.46 dwinter 91: """get the pnumber"""
92: try:
1.115 casties 93: txt=re.match("&[PpSs](\d*)\s*=([^\r\n]*)",self.getData()[0:])
1.40 dwinter 94: except:
1.49 dwinter 95: txt=self.getData()[0:]
1.40 dwinter 96:
97: return "ERROR"
98: try:
99: return "P"+txt.group(1)
100: except:
101: return "ERROR"
102:
1.12 dwinter 103: security.declarePublic('getDesignation')
104: def getDesignation(self):
105: """get the designation out of the file"""
1.16 dwinter 106: try:
1.115 casties 107: txt=re.match("&[PpSs](\d*)\s*=([^\r\n]*)",self.getData()[0:])
1.13 dwinter 108: except:
1.46 dwinter 109: txt=self.getData()[0:]
1.16 dwinter 110:
111: return "ERROR"
1.12 dwinter 112: try:
113: return txt.group(2)
114: except:
115: return "ERROR"
1.81 casties 116:
1.12 dwinter 117:
1.1 dwinter 118: manage_addCDLIFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='CDLIFileObject',kind='CDLIFileObject', version='1')
119:
1.81 casties 120: def manage_addCDLIFileObject(self,id,vC='',author='', file='',title='',versionNumber=0,
121: precondition='', content_type='',
1.48 dwinter 122: from_tmp=False,REQUEST=None):
1.1 dwinter 123: """Add a new File object.
124: Creates a new File object 'id' with the contents of 'file'"""
1.48 dwinter 125:
1.1 dwinter 126: id=str(id)
127: title=str(title)
128: content_type=str(content_type)
129: precondition=str(precondition)
130:
131: id, title = cookId(id, title, file)
132:
133: self=self.this()
134:
135: # First, we create the file without data:
1.81 casties 136: self._setObject(id, CDLIFileObject(id,title,versionNumber=versionNumber,versionComment=vC,time=time.localtime(),author=author))
1.80 casties 137: fob = self._getOb(id)
1.45 dwinter 138:
1.1 dwinter 139: # Now we "upload" the data. By doing this in two steps, we
140: # can use a database trick to make the upload more efficient.
1.48 dwinter 141:
142: if file and not from_tmp:
1.80 casties 143: fob.manage_upload(file)
1.48 dwinter 144: elif file and from_tmp:
1.81 casties 145: fob.manage_file_upload(file) # manage_upload_from_tmp doesn't exist in ExtFile2
146: # fob.manage_upload_from_tmp(file) # manage_upload_from_tmp doesn't exist in ExtFile2
1.1 dwinter 147: if content_type:
1.80 casties 148: fob.content_type=content_type
1.1 dwinter 149:
1.81 casties 150: #logging.debug("manage_add: lastversion=%s"%self.getData())
151: logging.debug("reindex1: %s in %s"%(repr(self),repr(self.default_catalog)))
1.45 dwinter 152: self.reindex_object()
1.81 casties 153: #logging.debug("manage_add: fob_data=%s"%fob.getData())
1.80 casties 154: logging.debug("reindex2: %s in %s"%(repr(fob), repr(fob.default_catalog)))
1.81 casties 155: fob.index_object()
1.49 dwinter 156:
1.85 dwinter 157: self.CDLIRoot.updateOrAddToFileBTree(ob)
1.1 dwinter 158: if REQUEST is not None:
159: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
1.3 dwinter 160:
1.80 casties 161:
1.46 dwinter 162: class CDLIFile(extVersionedFile,CatalogAware):
1.3 dwinter 163: """CDLI file"""
164:
1.77 dwinter 165: security=ClassSecurityInfo()
1.3 dwinter 166: meta_type="CDLI file"
1.81 casties 167: content_meta_type = ["CDLI File Object"]
168:
1.3 dwinter 169: default_catalog='CDLICatalog'
1.81 casties 170:
1.78 dwinter 171: security.declareProtected('manage','index_html')
1.81 casties 172:
1.51 dwinter 173: def getLastVersionData(self):
174: """get last version data"""
1.81 casties 175: return self.getData()
1.51 dwinter 176:
1.52 dwinter 177: def getLastVersionFormattedData(self):
178: """get last version data"""
1.81 casties 179: return self.getContentObject().getFormattedData()
180:
181: def getTextId(self):
182: """returns P-number of text"""
183: # assuming that its the beginning of the title
184: return self.title[:7]
1.52 dwinter 185:
1.51 dwinter 186: #security.declarePublic('history')
1.26 dwinter 187: def history(self):
188: """history"""
189:
190: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
191: if ext:
192: return getattr(self,ext[0][1].getId())()
193:
194: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionHistory')).__of__(self)
195: return pt()
196:
197:
1.44 dwinter 198: def getBasketFromId(self,basketid, context=None):
199: """get basket from id"""
200:
201: if not context:
202: context=self
203:
204: for basket in self.ZopeFind(context,obj_metatypes=["CDLIBasket"]):
205: if basket[0]==basketid:
206: return basket[1]
207: else:
208: None
209:
1.12 dwinter 210:
1.8 dwinter 211: def isContainedInBaskets(self,context=None):
212: """check is this file is part of any basket
213: @param context: (optional) necessessary if CDLIBasketCatalog is not an (inherited) attribute of self, context.CDLIBasketCatalog
214: has to exist.
215: """
216:
217: if not context:
218: context=self
1.12 dwinter 219:
220: ret=[]
221: for x in context.CDLIBasketCatalog.search({'getFileNamesInLastVersion':self.getId()}):
222: #if the basket x is deleted it seemes to be that x is sometimes still in the Catalog, why?
223: try:
224: ret.append(x.getObject())
225: except:
226: pass
227: return ret
228: #return [x.getObject() for x in context.CDLIBasketCatalog.search({'getFileNamesInLastVersion':self.getId()})]
1.5 dwinter 229:
230:
1.81 casties 231: def _newContentObject(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
232: """factory for content objects. to be overridden in derived classes."""
233: logging.debug("_newContentObject(CDLI)")
234: return CDLIFileObject(id,title,versionNumber=versionNumber,versionComment=versionComment,time=time,author=author)
235:
236:
1.5 dwinter 237: def addCDLIFileObjectForm(self):
238: """add a new version"""
239:
240: if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
241: return "please login first"
242: if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
243: out=DTMLFile('dtml/fileAdd', globals(),Kind='CDLIFileObject',kind='CDLIFileObject',version=self.getVersion()).__of__(self)
244: return out()
245: else:
246: return "Sorry file is locked by somebody else"
247:
1.37 dwinter 248: def manage_addCDLIFileObject(self,id,vC,author,
249: file='',title='',
250: precondition='',
251: content_type='',
252: changeName='no',newName='',
1.48 dwinter 253: come_from=None,
254: from_tmp=False,RESPONSE=None):
1.3 dwinter 255: """add"""
1.48 dwinter 256:
1.3 dwinter 257: try: #TODO: der ganze vC unsinn muss ueberarbeitet werden
258: vC=self.REQUEST['vC']
259: except:
260: pass
261:
1.81 casties 262: ob = self.addContentObject(id, vC, author, file, title, changeName=changeName, newName=newName, from_tmp=from_tmp,
263: precondition=precondition, content_type=content_type)
1.3 dwinter 264:
1.22 dwinter 265: try:
1.81 casties 266: #FIXME: wozu ist das gut?
267: self.REQUEST.SESSION['objID_parent']=self.getId()
1.22 dwinter 268: except:
1.81 casties 269: pass
1.37 dwinter 270:
1.85 dwinter 271: #self.cdliRoot.updateOrAddToFileBTree(self)# now update the object in the cache
272:
273:
1.3 dwinter 274: if RESPONSE:
1.81 casties 275: if ob.getSize()==0:
276: self.REQUEST.SESSION['objID']=ob.getId()
1.3 dwinter 277: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
278: return pt()
279: else:
1.37 dwinter 280: if come_from and (come_from!=""):
1.81 casties 281: RESPONSE.redirect(come_from+"?change="+self.getId())
1.37 dwinter 282: else:
283: RESPONSE.redirect(self.REQUEST['URL2']+'?uploaded=%s'%self.title)
1.3 dwinter 284: else:
1.81 casties 285: return ob
1.3 dwinter 286:
287:
288: def manage_addCDLIFileForm(self):
289: """interface for adding the OSAS_root"""
290: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addCDLIFile.zpt')).__of__(self)
291: return pt()
292:
293: def manage_addCDLIFile(self,id,title,lockedBy, author=None, RESPONSE=None):
294: """add the OSAS_root"""
295: newObj=CDLIFile(id,title,lockedBy,author)
1.22 dwinter 296:
297: tryToggle=True
298: tryCount=0
299:
300: self._setObject(id,newObj)
1.45 dwinter 301: getattr(self,id).reindex_object()
1.22 dwinter 302:
1.3 dwinter 303: if RESPONSE is not None:
304: RESPONSE.redirect('manage_main')
305:
1.81 casties 306:
1.69 dwinter 307: def checkUTF8(data):
308: """check utf 8"""
1.117 casties 309: if not isinstance(data, str):
310: logging.error("checkUTF8 data is not string! (%s)"%repr(data))
311:
1.69 dwinter 312: try:
1.117 casties 313: data.decode('utf-8')
314: logging.debug("checkUTF8: ok!")
1.69 dwinter 315: return True
316: except:
1.117 casties 317: logging.debug("checkUTF8: false!")
1.69 dwinter 318: return False
319:
1.1 dwinter 320:
1.45 dwinter 321: def checkFile(filename,data,folder):
322: """check the files"""
323: # first check the file name
324: fn=filename.split(".") # no extension
1.48 dwinter 325:
1.115 casties 326: if not (fn[0][0]=="P" or fn[0][0]=="S"):
327: return False,"P/S missing in the filename"
1.45 dwinter 328: elif len(fn[0])!=7:
1.46 dwinter 329: return False,"P number has not the right length 6"
1.69 dwinter 330: elif not checkUTF8(data):
331: return False,"not utf-8"
1.45 dwinter 332: else:
1.69 dwinter 333: return True,""
334:
1.45 dwinter 335:
1.25 dwinter 336: def splitatf(fh,dir=None,ext=None):
1.2 dwinter 337: """split it"""
1.4 dwinter 338: ret=None
1.2 dwinter 339: nf=None
1.25 dwinter 340: i=0
1.49 dwinter 341:
1.81 casties 342: #ROC: why split \n first and then \r???
1.117 casties 343: if isinstance(fh, basestring):
1.73 dwinter 344: iter=fh.split("\n")
345: else:
346: iter=fh.readlines()
347:
348: for lineTmp in iter:
1.66 dwinter 349: lineTmp=lineTmp.replace(codecs.BOM_UTF8,'') # make sure that all BOM are removed..
350: for line in lineTmp.split("\r"):
1.111 dwinter 351: #logging.info("Deal with: %s"%line)
1.66 dwinter 352: if ext:
353: i+=1
354: if (i%100)==0:
355: ext.result+="."
356: if i==10000:
357: i=0
358: ext.result+="<br>"
359: #check if basket name is in the first line
360: if line.find("#atf basket")>=0: #old convention
361: ret=line.replace('#atf basket ','')
362: ret=ret.split('_')[0]
363: elif line.find("#basket:")>=0: #new convention
364: ret=line.replace('#basket: ','')
365: ret=ret.split('_')[0]
366:
367: else:
368: if (len(line.lstrip())>0) and (line.lstrip()[0]=="&"): #newfile
369: if nf:
370: nf.close() #close last file
371:
1.49 dwinter 372:
1.66 dwinter 373: filename=line[1:].split("=")[0].rstrip()+".atf"
374: if dir:
375: filename=os.path.join(dir,filename)
376: nf=file(filename,"w")
1.117 casties 377: logging.debug("open %s"%filename)
1.66 dwinter 378: if nf:
379: nf.write(line.replace("\n","")+"\n")
380:
381: try:
382: nf.close()
1.61 dwinter 383: except:
1.66 dwinter 384: pass
1.73 dwinter 385:
1.117 casties 386: if not isinstance(fh, basestring):
1.73 dwinter 387: fh.close()
1.117 casties 388:
1.5 dwinter 389: return ret,len(os.listdir(dir))
1.4 dwinter 390:
1.19 dwinter 391:
1.46 dwinter 392: class CDLIFileFolder(extVersionedFileFolder):
1.4 dwinter 393: """CDLI File Folder"""
1.1 dwinter 394:
1.19 dwinter 395: security=ClassSecurityInfo()
1.1 dwinter 396: meta_type="CDLI Folder"
1.81 casties 397: file_meta_type=['CDLI file']
398: folder_meta_type=['CDLI Folder']
399:
400: file_catalog='CDLICatalog'
401:
1.45 dwinter 402: #downloadCounter=0 # counts how many download for all files currently run, be mehr als 5 wird verweigert.
1.24 dwinter 403: tmpStore2={}
1.81 casties 404:
405: def _newVersionedFile(self, id, title='', lockedBy=None, author=None):
406: """factory for versioned files. to be overridden in derived classes."""
407: logging.debug("_newVersionedFile(CDLI)")
408: return CDLIFile(id, title, lockedBy=lockedBy, author=author)
409:
1.19 dwinter 410: def setTemp(self,name,value):
411: """set tmp"""
412:
413: setattr(self,name,value)
414:
1.81 casties 415: deleteFileForm = PageTemplateFile("zpt/doDeleteFile", globals())
1.19 dwinter 416:
1.81 casties 417: def delete(self,ids,REQUEST=None):
418: """delete these files"""
1.12 dwinter 419: if type(ids) is not ListType:
420: ids=[ids]
1.81 casties 421:
422: self.manage_delObjects(ids)
1.12 dwinter 423:
1.81 casties 424: if REQUEST is not None:
425: return self.index_html()
426:
427:
1.4 dwinter 428: def getVersionNumbersFromIds(self,ids):
429: """get the numbers of the current versions of documents described by their ids"""
430:
431: ret=[]
432: searchStr=" OR ".join(ids)
433:
1.9 dwinter 434: founds=self.CDLICatalog.search({'title':searchStr})
1.4 dwinter 435:
436: for found in founds:
1.81 casties 437: lastVersion=found.getObject().getContentObject()
1.4 dwinter 438: ret.append((found.getId,lastVersion))
439:
440: return ret
441:
1.67 dwinter 442: def getFile(self,fn):
443: """get the content of the file fn"""
1.81 casties 444: logging.debug("getFile: %s"%repr(fn))
445: if not self.hasObject(fn):
446: # search deeper
447: founds=getattr(self, self.file_catalog).search({'textid':fn})
448: if founds:
449: obj=founds[0].getObject().getContentObject()
450: else:
451: return ""
1.67 dwinter 452: else:
1.81 casties 453: obj = self[fn].getContentObject()
1.68 dwinter 454:
1.81 casties 455: return obj.getData()[0:]
456:
1.67 dwinter 457:
1.14 dwinter 458: def checkCatalog(self,fn):
459: """check if fn is in the catalog"""
1.19 dwinter 460: #TODO add checkCatalog
1.14 dwinter 461:
1.19 dwinter 462:
1.45 dwinter 463: def findObjectsFromListWithVersion(self,list,author=None):
1.26 dwinter 464: """find objects from a list with versions
465: @param list: list of tuples (cdliFile,version)
466: """
467: #self.REQUEST.SESSION['fileIds']=list#store fieldIds in session for further usage
468: #self.REQUEST.SESSION['searchList']=self.REQUEST.SESSION['fileIds']
469:
470: pt=getattr(self,'filelistVersioned.html')
471:
1.45 dwinter 472: return pt(search=list,author=author)
1.26 dwinter 473:
474:
1.67 dwinter 475: def getAllPNumbers(self):
476: """get a list of all files (resp their p-numbers) stored"""
477:
478: ret=[x.getId for x in self.CDLICatalog()]
479:
480: return ret
481:
1.83 dwinter 482: def expandFile(self,fileId,fileTree):
483: """wildcard in fileID suche alle Treffer"""
484: founds=self.CDLICatalog({'title':fileId})
485: for found in founds:
486: fileTree.add(found.getId)
487: logging.debug("ADDD:"+found.getId)
488:
1.85 dwinter 489: def findObjectsFromList(self,enterList=None,display=False,start=None,upload=None,list=None,basketName=None,numberOfObjects=None,RESPONSE=None,REQUEST=None,returnHash=False,hash=None):
1.1 dwinter 490: """findObjectsFromList (, TAB oder LINE separated)"""
1.15 dwinter 491:
1.83 dwinter 492: logging.debug("start: findObjectsFromList")
1.85 dwinter 493: #logging.debug("start: findObjectsFromList"+repr(list))
494:
495:
1.6 dwinter 496: if upload: # list from file upload
497: txt=upload.read()
1.35 dwinter 498:
499: if enterList:
500: txt=enterList
501:
502: if upload or enterList:
1.6 dwinter 503: txt=txt.replace(",","\n")
504: txt=txt.replace("\t","\n")
1.12 dwinter 505: txt=txt.replace("\r","\n")
1.6 dwinter 506: idsTmp=txt.split("\n")
507: ids=[]
508: for id in idsTmp: # make sure that no empty lines
509: idTmp=id.lstrip().rstrip()
510: if len(idTmp)>0:
511:
512: ids.append(idTmp)
513:
514: #self.REQUEST.SESSION['ids']=" OR ".join(ids)
1.12 dwinter 515:
1.6 dwinter 516: pt=getattr(self,'filelist.html')
1.7 dwinter 517: self.REQUEST.SESSION['searchList']=ids
1.6 dwinter 518: return pt(search=ids)
1.7 dwinter 519:
1.6 dwinter 520: if basketName:
1.7 dwinter 521: #TODO: get rid of one of these..
522:
1.6 dwinter 523: pt=getattr(self,'filelist.html')
1.7 dwinter 524: return pt(basketName=basketName,numberOfObjects=numberOfObjects)
1.6 dwinter 525:
1.102 dwinter 526:
527: result =self.CDLICache.retrieve(hash)
528: if result:
529: logging.debug("give result from storage2")
530: return hash,result
531:
1.15 dwinter 532: if list is not None: # got already a list
1.83 dwinter 533:
534: logging.debug(" ----List version")
1.6 dwinter 535: ret=[]
1.83 dwinter 536: fileTree=Set()
537:
1.6 dwinter 538: for fileId in list:
1.83 dwinter 539:
540: if fileId.find("*")>-1: #check for wildcards
541: self.expandFile(fileId,fileTree)
542:
1.35 dwinter 543: elif len(fileId.split("."))==1:
1.6 dwinter 544: fileId=fileId+".atf"
1.83 dwinter 545: fileTree.add(fileId)
546: #logging.debug(" -----:"+fileId)
547: #ret+=self.CDLICatalog({'title':fileId})
548: #x =self.getFileObject(fileId)
549: #if x is not None:
550: # ret.append(x)
1.35 dwinter 551:
1.83 dwinter 552:
553:
554: ids = fileTree & self.v_file_ids
1.85 dwinter 555: #self.REQUEST.SESSION['fileIds']=ids#store fieldIds in session for further usage
556: l=makelist(fileTree)[0:]
1.93 dwinter 557: #logging.debug("l-list:"+repr(l))
1.85 dwinter 558: self.REQUEST.SESSION['fileIds']=l#store fieldIds in session for further usage
559: self.REQUEST.SESSION['searchList']=l
560: #self.REQUEST.SESSION['searchList']=['P000001.atf']
561:
1.83 dwinter 562:
1.85 dwinter 563: hash = md5.new(repr(makelist(fileTree))).hexdigest() # erzeuge hash als identification
564: self.REQUEST.SESSION['hash']=hash
565: #TODO: do I need garbage collection for v_tmpStore ?
1.83 dwinter 566:
1.84 dwinter 567: #logging.debug("Hash:"+repr(hash))
1.85 dwinter 568: #
569: # if hasattr(self.cdliRoot,'v_tmpStore') and self.cdliRoot.v_tmpStore.has_key(hash):
570: # logging.debug("asking for storage")
571: # res=self.cdliRoot.v_tmpStore[hash]
572: # if res:
573: # if returnHash == True:
574: # return hash,res
575: # return res
1.83 dwinter 576:
1.7 dwinter 577: #TODO: get rid of one of these..
1.83 dwinter 578: #ids=[x.getObject().getId() for x in ret]
579: ret=[(self.getFileObject(x),self.getFileObjectLastVersion(x)) for x in ids]
1.84 dwinter 580:
581: #self.REQUEST.SESSION['fileIds']=ids#store fieldIds in session for further usage
582: #self.REQUEST.SESSION['searchList']=self.REQUEST.SESSION['fileIds']
1.85 dwinter 583:
1.25 dwinter 584: if display:
585: pt=getattr(self,'filelist.html')
586:
587: return pt(search=ids)
1.83 dwinter 588: else:
589: #self.REQUEST.SESSION['hash'] = ret # store in session
1.102 dwinter 590:
1.83 dwinter 591: #logging.debug("HHHHHHNEU:"+repr(self.makelist(ids)))
1.84 dwinter 592: #logging.debug("HHHHHHNEU:"+repr(hash))
1.102 dwinter 593: self.CDLICache.store(hash,ret)
594:
1.85 dwinter 595: if returnHash == True:
596: return hash,ret
1.25 dwinter 597: return ret
598:
599:
1.1 dwinter 600:
1.7 dwinter 601: if start:
602: RESPONSE.redirect("filelist.html?start:int="+str(start))
1.85 dwinter 603:
1.19 dwinter 604: security.declareProtected('Manage','createAllFilesAsSingleFile')
1.1 dwinter 605: def createAllFilesAsSingleFile(self,RESPONSE=None):
606: """download all files"""
607:
608: def sortF(x,y):
609: return cmp(x[0],y[0])
610:
1.81 casties 611: catalog=getattr(self,self.file_catalog)
1.1 dwinter 612: #tf,tfilename=mkstemp()
1.66 dwinter 613: if not hasattr(self.temp_folder,'downloadCounter'):
614: self.temp_folder.downloadCounter=0
1.49 dwinter 615:
616: if getattr(self.temp_folder,'downloadCounter',0) > 5:
1.46 dwinter 617: return """I am sorry, currently the server has to many requests for downloads, please come back later!"""
1.45 dwinter 618:
1.46 dwinter 619: self.temp_folder.downloadCounter+=1
620: self._p_changed=1
1.58 dwinter 621: transaction.get().commit()
1.45 dwinter 622:
1.1 dwinter 623: list=[(x.getId,x) for x in catalog()]
624: list.sort(sortF)
1.46 dwinter 625:
1.45 dwinter 626:
1.1 dwinter 627:
628: RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%"all.atf")
629: RESPONSE.setHeader("Content-Type","application/octet-stream")
1.46 dwinter 630: tmp=""
1.1 dwinter 631: for l in list:
632: obj=l[1].getObject()
633:
634: if obj.meta_type=="CDLI file":
635:
636: #os.write(tf,obj.getLastVersion().data)
637: if RESPONSE:
1.81 casties 638: RESPONSE.write(obj.getData()[0:])
1.71 dwinter 639: RESPONSE.write("\n")
1.46 dwinter 640: self.temp_folder.downloadCounter-=1
641: self._p_changed=1
1.58 dwinter 642: transaction.get().commit()
1.1 dwinter 643: #os.close(tf)
644: #RESPONSE.redirect(self.absolute_url()+"/downloadFile?fn="%tfilename)
645: return True
646:
647: def downloadFile(self,fn):
648: """download fn - not used yet"""
649: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getLastVersion().getId())
650: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
651: self.REQUEST.RESPONSE.write(file(fn).read())
652:
653:
654:
655: def hasParent(self):
656: """returns true falls subfolder"""
657:
1.81 casties 658: if self.aq_parent.meta_type in self.folder_meta_type:
1.1 dwinter 659: return True
660: else:
661: return False
662:
663: def getFolders(self):
664: """get all subfolders"""
665: ret=[]
1.81 casties 666: folders=self.ZopeFind(self,obj_metatypes=self.folder_meta_type)
1.1 dwinter 667: for folder in folders:
668: ret.append((folder[1],
1.81 casties 669: len(self.ZopeFind(folder[1],obj_metatypes=self.folder_meta_type)),
670: len(self.ZopeFind(folder[1],obj_metatypes=self.file_meta_type))
1.1 dwinter 671: ))
672: return ret
673:
674:
1.77 dwinter 675: security.declareProtected('manage','index_html')
1.1 dwinter 676: def index_html(self):
677: """main"""
678: ext=self.ZopeFind(self,obj_ids=["index.html"])
679: if ext:
680: return ext[0][1]()
681:
682: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','CDLIFileFolderMain')).__of__(self)
683: return pt()
684:
1.22 dwinter 685:
686: manage_addCDLIFileFolderForm=DTMLFile('dtml/folderAdd', globals())
687:
688:
689: def manage_addCDLIFileFolder(self, id, title='',
690: createPublic=0,
691: createUserF=0,
692: REQUEST=None):
693: """Add a new Folder object with id *id*.
694:
695: If the 'createPublic' and 'createUserF' parameters are set to any true
696: value, an 'index_html' and a 'UserFolder' objects are created respectively
697: in the new folder.
698: """
699: ob=CDLIFileFolder()
700: ob.id=str(id)
701: ob.title=title
702: self._setObject(id, ob)
703: ob=self._getOb(id)
704:
705: checkPermission=getSecurityManager().checkPermission
706:
707: if createUserF:
708: if not checkPermission('Add User Folders', ob):
709: raise Unauthorized, (
710: 'You are not authorized to add User Folders.'
711: )
712: ob.manage_addUserFolder()
713:
714:
715: if REQUEST is not None:
716: return self.manage_main(self, REQUEST, update_menu=1)
717:
718: class CDLIRoot(Folder):
719: """main folder for cdli"""
720:
721: meta_type="CDLIRoot"
1.81 casties 722: downloadCounterBaskets=0 # counts the current basket downloads if counter > 10 no downloads are possible
723:
724: file_catalog = 'CDLICatalog'
725:
726: # word splitter for search
727: splitter = {'words':cdliSplitter.wordSplitter(),
728: 'graphemes':cdliSplitter.graphemeSplitter()}
729:
1.110 dwinter 730: def redirect(self,RESPONSE,url):
731: """mache ein redirect mit einem angehaengten time stamp um ein reload zu erzwingen"""
732:
733: timeStamp=time.time()
734:
735: if url.find("?")>-1: #giebt es schon parameter
736: addStr="&time=%s"
737: else:
738: addStr="?time=%s"
739:
740: RESPONSE.setHeader('Last-Modified',email.Utils.formatdate().split("-")[0]+'GMT')
741: logging.error(email.Utils.formatdate()+' GMT')
742: RESPONSE.redirect(url+addStr%timeStamp)
1.51 dwinter 743:
1.102 dwinter 744: def unicodify(self,txt):
745: return unicodify(txt)
746: def invalidateOldCacheVersion(self):
747: """loescht die alte Version des Cache"""
748: del self.v_tmpStore
749: return "done"
750:
1.86 dwinter 751: def viewATF(self,id,RESPONSE):
752: """view an Object"""
753: ob = self.CDLICatalog({'title':id})
754: logging.debug(ob[0].getObject().getLastVersion().absolute_url()+"/view")
755: if len(ob)>0:
756: RESPONSE.redirect(ob[0].getObject().getLastVersion().absolute_url()+"/view")
757: return "not found"
758:
759: def history(self,id,RESPONSE):
760: """view an Object"""
761: ob = self.CDLICatalog({'title':id})
762: if len(ob)>0:
763: RESPONSE.redirect(ob[0].absolute_url+"/history")
764: return "not found"
765:
766:
767: def downloadLocked(self,id,RESPONSE):
768: """view an Object"""
769: ob = self.CDLICatalog({'title':id})
770: if len(ob)>0:
771: RESPONSE.redirect(ob[0].absolute_url+"/downloadLocked")
772: return "not found"
773:
774: def download(self,id,RESPONSE):
775: """view an Object"""
776: ob = self.CDLICatalog({'title':id})
777: if len(ob)>0:
1.109 dwinter 778: logging.info("objekt:"+repr(ob[0]))
779: #RESPONSE.redirect(ob[0].getLastVersion().absolute_url())
780: RESPONSE.redirect(ob[0].absolute_url+"/download")
1.86 dwinter 781: return "not found"
782: def addCDLIFileObjectForm(self,id,RESPONSE):
783: """view an Object"""
784: ob = self.CDLICatalog({'title':id})
785: if len(ob)>0:
786: RESPONSE.redirect(ob[0].absolute_url+"/addCDLIFileObjectForm")
787: return "not found"
788:
789: def addVersionedFileObjectForm(self,id,RESPONSE):
790: """view an Object"""
791: ob = self.CDLICatalog({'title':id})
792: if len(ob)>0:
793: RESPONSE.redirect(ob[0].absolute_url+"/addVersionedFileObjectForm")
794: return "not found"
795:
796: def unlock(self,id,RESPONSE):
797: """view an Object"""
798: ob = self.CDLICatalog({'title':id})
799: if len(ob)>0:
800: RESPONSE.redirect(ob[0].absolute_url+"/unlock")
801: return "not found"
802:
1.112 dwinter 803:
1.83 dwinter 804: def getFileObject(self,fileId):
1.85 dwinter 805: """get an object"""
1.112 dwinter 806: logging.debug("getFileObj:"+repr(fileId))
807: if isinstance(fileId,CDLIFileObject): # support for old baskets
808: return fileId
1.83 dwinter 809: x=self.v_files.get(fileId)
1.113 dwinter 810: logging.debug("obj: "+repr(x))
1.119 ! dwinter 811: if x is None:
! 812: logging.debug("fileId"+repr(fileId))
1.113 dwinter 813: folder=fileId[0:3]
814: f2=fileId[0:5]
815: fObj = getattr(self.cdliRoot.cdli_main,folder);
816: f2Obj = getattr(fObj,f2)
817:
818: o = getattr(f2Obj,fileId)
819: logging.debug(o);
820: self.updateOrAddToFileBTree(o)
821: return o
1.83 dwinter 822: return x
823:
824: def getFileObjectLastVersion(self,fileId):
1.85 dwinter 825: """get an object"""
1.83 dwinter 826: x=self.v_files_lastVersion.get(fileId)
1.113 dwinter 827: logging.debug("lastVersion: "+repr(x))
828: if x==None:
829: folder=fileId[0:3]
830: f2=fileId[0:5]
831: fObj = getattr(self.cdliRoot.cdli_main,folder);
832: f2Obj = getattr(fObj,f2)
833:
834: o =getattr(f2Obj,fileId)
835: logging.debug(o);
836: return o.getLastVersion()
837:
838:
1.83 dwinter 839: return x
840:
1.85 dwinter 841: def showFileIds(self):
842: """showIds"""
843: return self.v_file_ids
844:
1.83 dwinter 845: def generateFileBTree(self):
846: """erzeuge einen Btree aus allen Files"""
847: self.v_files = OOBTree()
848: self.v_files_lastVersion = OOBTree()
849: self.v_file_ids = Set()
850:
851: for x in self.CDLICatalog.searchResults():
852:
853: self.v_files.update({x.getId:x.getObject()})
854: self.v_files_lastVersion.update({x.getId:x.getObject().getLastVersion()})
855: self.v_file_ids.add(x.getId)
856: logging.debug("add:"+x.getId+"XXX"+repr(x.getObject()))
857:
1.85 dwinter 858: return True
859:
860:
861: def updateOrAddToFileBTree(self,obj):
862: """update a BTree"""
863: self.v_files.update({obj.getId():obj})
864: self.v_files_lastVersion.update({obj.getId():obj.getLastVersion()})
865:
866: self.v_file_ids.add(obj.getId())
1.114 dwinter 867: #change everthing around to make it persistent...
868: tmp = self.v_files
869: self.v_files=tmp
870:
871: tmp2=self.v_file_ids
872: self.v_file_ids=tmp2
873:
874: self.CDLICache.cleanCache() #be sure that the cache is clean
1.85 dwinter 875: logging.debug("update:"+obj.getId()+"XXX"+repr(obj))
1.114 dwinter 876:
877:
1.85 dwinter 878: def deleteFromBTree(self,objId):
879: """delete an obj"""
880: self.v_files.pop(objId)
881: self.v_files_lastVersion.pop(objId)
882: self.v_file_ids.remove(objId)
883:
884:
885:
1.73 dwinter 886: def deleteFiles(self,ids):
1.81 casties 887: """delete files"""
1.73 dwinter 888: for id in ids:
889: founds=self.CDLICatalog.search({'title':id.split(".")[0]})
890: if founds:
1.81 casties 891: logging.debug("deleting %s"%founds)
1.73 dwinter 892: folder=founds[0].getObject().aq_parent #get the parent folder of the object
1.81 casties 893: logging.debug("deleting from %s"%folder)
894: cut=folder.delete([founds[0].getId]) #cut it out
895:
1.73 dwinter 896:
897:
1.116 casties 898: def searchText(self, query, index='graphemes', resultFilter=None):
899: """searches query in the fulltext index and returns a list of file IDs/P-numbers
900: resultFilter is matched against the beginning of the file ID"""
1.81 casties 901: # see also: http://www.plope.com/Books/2_7Edition/SearchingZCatalog.stx#2-13
902: logging.debug("searchtext for '%s' in index %s"%(query,index))
903: #import Products.ZCTextIndex.QueryParser
904: #qp = QueryParser.QueryParser()
905: #logging.debug()
906: idxQuery = {index:{'query':query}}
907: idx = getattr(self, self.file_catalog)
908: # do search
909: resultset = idx.search(query_request=idxQuery,sort_index='textid')
1.116 casties 910: # put only the P-Number in the result
911: if resultFilter is None:
912: results = [res.getId[:7] for res in resultset]
913: else:
914: results = [res.getId[:7] for res in resultset if res.getId.startswith(resultFilter)]
1.81 casties 915: logging.debug("searchtext: found %d texts"%len(results))
916: return results
917:
918:
919: def getFile(self, pnum):
920: """get the translit file with the given pnum"""
921: f = getattr(self, self.file_catalog).search({'textid':pnum})
922: if not f:
923: return ""
1.71 dwinter 924:
1.81 casties 925: return f[0].getObject().getData()
926:
1.57 dwinter 927:
1.74 dwinter 928: def showFile(self,fileId,wholePage=False):
1.71 dwinter 929: """show a file
930: @param fileId: P-Number of the document to be displayed
931: """
1.81 casties 932: f=getattr(self, self.file_catalog).search({'textid':fileId})
1.51 dwinter 933: if not f:
934: return ""
935:
1.74 dwinter 936: if wholePage:
1.81 casties 937: logging.debug("show whole page")
938: return f[0].getObject().getContentObject().view()
1.74 dwinter 939: else:
940: return f[0].getObject().getLastVersionFormattedData()
1.55 dwinter 941:
1.56 dwinter 942:
1.81 casties 943: def showWordInFile(self,fileId,word,indexName='graphemes',regExp=False,):
944: """get lines with word from FileId"""
945: logging.debug("showwordinfile word='%s' index=%s file=%s"%(word,indexName,fileId))
1.56 dwinter 946:
1.81 casties 947: file = formatAtfFullLineNum(self.getFile(fileId))
1.66 dwinter 948: ret=[]
1.71 dwinter 949:
1.81 casties 950: # add whitespace before and whitespace and line-end to splitter bounds expressions
951: bounds = self.splitter[indexName].bounds
952: splitexp = "(%s|\s)(%%s)(%s|\s|\Z)"%(bounds,bounds)
953: # clean word expression
954: # TODO: this should use QueryParser itself
955: # take out double quotes
956: word = word.replace('"','')
957: # take out ignorable signs
958: ignorable = self.splitter[indexName].ignorex
959: word = ignorable.sub('', word)
960: # compile into regexp objects and escape parens
961: wordlist = [re.compile(splitexp%re.escape(w)) for w in word.split(' ')]
962:
963: for line in file.splitlines():
1.71 dwinter 964: for word in wordlist:
1.81 casties 965: #logging.debug("showwordinfile: searching for %s in %s"%(word.pattern,ignoreable.sub('',line)))
966: if word.search(ignorable.sub('',line)):
967: line = formatAtfLineHtml(line)
968: ret.append(line)
969: break
970:
1.66 dwinter 971: return ret
1.56 dwinter 972:
1.81 casties 973:
974: def showWordInFiles(self,fileIds,word,indexName='graphemes',regExp=False):
975: """
976: get lines with word from all ids in list FileIds.
977: returns dict with id:lines pairs.
978: """
979: logging.debug("showwordinfiles word='%s' index=%s file=%s"%(word,indexName,fileIds))
1.51 dwinter 980:
1.81 casties 981: return dict([(id,self.showWordInFile(id, word, indexName, regExp)) for id in fileIds])
982:
983:
984: def tagWordInFile(self,fileId,word,indexName='graphemes',regExp=False):
985: """get text with word highlighted from FileId"""
986: logging.debug("tagwordinfile word='%s' index=%s file=%s"%(word,indexName,fileId))
987:
988: file=self.getFile(fileId)
989: tagStart=u'<span class="found">'
990: tagEnd=u'</span>'
991: tagStr=tagStart + u'%%s' + tagEnd
1.66 dwinter 992: ret=[]
1.71 dwinter 993:
1.81 casties 994: # add whitespace to splitter bounds expressions and compile into regexp object
995: bounds = self.splitter[indexName].bounds
996: wordsplit = re.compile("(%s|\s)"%bounds)
997: # clean word expression
998: # TODO: this should use QueryParser itself
999: word = word.replace('"','') # take out double quotes
1000: # take out ignoreable signs
1001: ignorable = self.splitter[indexName].ignorex
1002: word = ignorable.sub('', word)
1003: # split search terms by blanks
1004: words = word.split(' ')
1005: # split search terms again (for grapheme search with words)
1006: splitwords = dict(((w,self.splitter[indexName].process([w])) for w in words))
1.71 dwinter 1007:
1.81 casties 1008: for line in file.splitlines():
1.79 casties 1009: line = unicodify(line)
1.81 casties 1010: # ignore lemma and other lines
1011: if line.lstrip().startswith('#lem:'):
1012: continue
1013: # ignore p-num line
1.115 casties 1014: if line.startswith('&P') or line.startswith('&S'):
1.81 casties 1015: continue
1016: # ignore version lines
1017: if line.startswith('#version'):
1018: continue
1019: # ignore atf type lines
1020: if line.startswith('#atf:'):
1021: continue
1022:
1023: # first scan
1024: hitwords = []
1025: for w in words:
1026: if ignorable.sub('',line).find(w) > -1:
1027: # word is in line
1028: # append split word for grapheme search with words
1029: hitwords.extend(splitwords[w])
1030: #hitwords.extend(wordsplit.split(w))
1031:
1032: # examine hits closer
1033: if hitwords:
1034: # split line into words
1035: parts = wordsplit.split(line)
1036: line = ""
1037: for p in parts:
1038: #logging.debug("tagwordinfile: searching for %s in %s"%(p,hitwords))
1039: # reassemble line
1040: if ignorable.sub('', p) in hitwords:
1041: #logging.debug("tagwordinfile: found %s in %s"%(p,hitwords))
1042: # this part was found
1043: line += tagStart + formatAtfHtml(p) + tagEnd
1044: else:
1045: line += formatAtfHtml(p)
1046:
1047: else:
1048: # no hits
1049: line = formatAtfHtml(line)
1050:
1051: ret.append(line)
1052:
1053: return u'<br>\n'.join(ret)
1054:
1.66 dwinter 1055:
1056:
1.81 casties 1057: def tagWordInFiles(self,fileIds,word,indexName='graphemes',regExp=False):
1058: """
1059: get texts with highlighted word from all ids in list FileIds.
1060: returns dict with id:text pairs.
1061: """
1062: logging.debug("tagwordinfiles word='%s' index=%s file=%s"%(word,indexName,fileIds))
1063: return dict([(id,self.tagWordInFile(id, word, indexName, regExp)) for id in fileIds])
1064:
1.56 dwinter 1065:
1.82 casties 1066: def getFileVersionList(self, pnum):
1067: """get the version history as a list for the translit file with the given pnum"""
1068: f = getattr(self, self.file_catalog).search({'textid':pnum})
1069: if not f:
1070: return []
1071:
1072: return f[0].getObject().getVersionList()
1073:
1074:
1.37 dwinter 1075: def URLquote(self,str):
1076: """quote url"""
1077: return urllib.quote(str)
1078:
1079: def URLunquote(self,str):
1080: """unquote url"""
1081: return urllib.unquote(str)
1082:
1.58 dwinter 1083: def URLquote_plus(self,str):
1084: """quote url"""
1085: return urllib.quote_plus(str)
1086:
1087: def URLunquote_plus(self,str):
1088: """unquote url"""
1089: return urllib.unquote_plus(str)
1090:
1.106 dwinter 1091: def changeUserForPObjectFromFile(self,user,fname):
1092: """aendere user fuer alle p in fiele"""
1.107 dwinter 1093: pns = file(os.path.join(package_home(globals()),'inputs',fname),"r")
1094: for p in pns.readlines():
1095: p=p.lstrip().rstrip()
1096: logging.info(str(p+".atf"))
1097: pObj=self.getFileObject(p+".atf")
1098: if pObj is not None:
1099: logging.info(pObj)
1100: lv=pObj.getContentObject()
1101: logging.info("author:"+lv.author)
1102: lv.author=user
1103: lv.versionComment="XXXXXXX"
1.37 dwinter 1104:
1.112 dwinter 1105: def forceunlock(self,REQUEST=None,user=None,fid=None):
1.26 dwinter 1106: "break all locks"
1.112 dwinter 1107: if fid is not None:
1108: self.getFileObject(fid).forceunlock()
1109: return fid
1.26 dwinter 1110: ret=[]
1.105 dwinter 1111:
1.26 dwinter 1112: for f in self.ZopeFind(self,obj_metatypes="CDLI file",search_sub=1):
1.105 dwinter 1113: un=f[1].forceunlock(user=user)
1114: logging.info("check:"+f[0])
1.26 dwinter 1115: if un and un !="":
1116: ret.append((f[0],un))
1.46 dwinter 1117:
1.105 dwinter 1118: if REQUEST is not None:
1119: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','breakLockResponse.zpt')).__of__(self)
1120:
1121: return pt(ret=ret)
1122:
1.61 dwinter 1123: return ret
1.71 dwinter 1124:
1.61 dwinter 1125:
1.105 dwinter 1126: def getLockedFiles(self,REQUEST=None,user=None):
1127: """hole alle gesperrten files"""
1128: ret={}
1129:
1.112 dwinter 1130: for nm,f in self.v_files.items():
1131: lb = str(f.lockedBy)
1.105 dwinter 1132: add=False
1133: if (lb is not None) and (lb!=""):
1134:
1135: if user is None:
1136: add=True
1137: else:
1138: if str(lb)==user:
1139: add=True
1140: if add==True:
1141: if not ret.has_key(lb):
1142: ret[lb]=[]
1.112 dwinter 1143: ret[lb].append(nm)
1.105 dwinter 1144:
1145:
1146: if REQUEST is not None:
1147: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','showlockResponse.zpt')).__of__(self)
1148:
1149: return pt(ret=ret)
1150:
1151: return ret
1152:
1.26 dwinter 1153: def getChangesByAuthor(self,author,n=100):
1.25 dwinter 1154: """getChangesByAuthor"""
1.26 dwinter 1155: zcat=self.CDLIObjectsCatalog
1156: res=zcat({'lastEditor':author,
1.25 dwinter 1157: 'sort_on':'getTime',
1158: 'sort_order':'descending',
1159: 'sort_limit':n})[:n ]
1.26 dwinter 1160:
1161: return res
1162:
1163: def getChangesByAuthor_html(self,author,n=100):
1164: """html output for changes by author"""
1165: tmp={}
1166: list=[]
1167: for x in self.getChangesByAuthor(author):
1168: nr=x.getObject().getVersionNumber()
1169: id=x.getObject().aq_parent.getId()
1170: #hinzufuegen, wenn Version neuer als die
1171: if tmp.get(id,(0,0))[1] < nr:
1172: tmp[id]=(x.getObject().aq_parent,nr)
1173:
1174:
1.45 dwinter 1175: return self.cdli_main.findObjectsFromListWithVersion(list=tmp.values(),author=author)
1.26 dwinter 1176:
1.25 dwinter 1177: def getLastChanges(self,n=100):
1178: """get the last n changes"""
1179: n=int(n)
1180: zcat=self.CDLICatalog
1181: return zcat({'sort_on':'getLastChangeDate',
1182: 'sort_order':'descending',
1183: 'sort_limit':n})[:n ]
1184:
1185:
1186: def getLastChanges_html(self,n=100):
1187: """get the last n changes"""
1188: list = [x.getId for x in self.getLastChanges(n)]
1189: return self.cdli_main.findObjectsFromList(list=list,display=True)
1190:
1.24 dwinter 1191: def refreshTxt(self,txt="",threadName=None):
1.22 dwinter 1192: """txt fuer refresh"""
1193:
1.24 dwinter 1194: return """ 2;url=%s?repeat=%s """%(self.absolute_url()+txt,threadName)
1.22 dwinter 1195:
1.87 dwinter 1196: def refreshTxtBasket(self,txt="",threadName=None):
1197: """txt fuer refresh"""
1198:
1199: return """ 2;url=%s?repeat=%s """%(txt,threadName)
1200:
1.22 dwinter 1201:
1.24 dwinter 1202: def getResult(self,threadName=None):
1.22 dwinter 1203: """result of thread"""
1204: try:
1.24 dwinter 1205: return self._v_uploadATF[threadName].getResult()
1.22 dwinter 1206: except:
1207: return "One moment, please"
1208:
1.24 dwinter 1209:
1210: def checkThreads(self):
1211: """check threads"""
1.42 dwinter 1212: ret="<html><body>"
1213: for thread in threading.enumerate():
1.45 dwinter 1214: ret+="<p>%s (%s): %s</p>"%(repr(thread),thread.getName(),thread.isAlive())
1.42 dwinter 1215:
1216: return ret
1217:
1218:
1.73 dwinter 1219: def uploadATFRPC(self,data,username):
1220: """upload an atffile via xml-rpc"""
1221: uploader=uploadATFThread()
1222:
1223: #generate an random id for the upload object
1224: from random import randint
1225: if (not self.REQUEST.SESSION.get('idTmp',None)):
1226:
1227: idTmp=str(randint(0,1000000000))
1228: self.REQUEST.SESSION['idTmp']=idTmp
1229: else:
1230: idTmp=self.REQUEST.SESSION.get('idTmp',None)
1231:
1232:
1233: uploader.set(data,0,username,idTmp)
1234:
1235: stObj=uploader.run()
1236:
1237: processor=uploadATFfinallyThread()
1238:
1239: basketname=stObj.returnValue['basketNameFromFile']
1240:
1241: processor.set("uploadchanged",basketname=basketname,SESSION=stObj.returnValue,username=username,serverport=self.REQUEST['SERVER_PORT'])
1242:
1243: processor.run()
1244:
1245:
1246: return generateXMLReturn(stObj.returnValue)
1.118 dwinter 1247:
1248: def uploadATFAsync(self,repeat=None,upload=None,basketId=0,RESPONSE=None):
1249: """upload an atf file / basket file"""
1250: #self._v_uploadATF.returnValue=None
1251:
1252:
1253: idTmp=str(randint(0,1000000000))
1254:
1255: if upload is None:
1256: return "ERROR NO FILE!"
1257:
1258: tmpFile = File("/tmp/idTmp","w")
1259: # sicher basket in file
1260: for x in upload.read():
1261: tmpFile.write(x)
1262:
1263: tmpFile.close();
1264: uploadATFAsync(baskerId,idTmp,basketId,self.REQUEST['AUTHENTICATED_USER'],idTmp,serverport=self.REQUEST['SERVER_PORT'])
1.73 dwinter 1265:
1.118 dwinter 1266: return idTMP
1267:
1268: def viewTicketAsync(self,ticketNr=1):
1269: """viewticket"""
1270:
1271: tmp = pickle.load(file("/tmp/"+str(ticketNr)+".result"))
1272:
1273: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadCheckAsync.zpt')).__of__(self)
1274:
1275: return pt(changed=tmp['changed'],lockerrors=tmp['lockerrors'],errors=tmp['errors'],dir=tmp['dir'],newPs=tmp['newPs'],basketLen=tmp['basketLen'],numberOfFiles=tmp['numberOfFiles'],
1276: basketNameFromId=tmp['basketNameFromId'],basketNameFromFile=tmp['basketNameFromFile'],basketId=tmp['basketId'])
1277:
1278:
1279:
1.22 dwinter 1280: def uploadATF(self,repeat=None,upload=None,basketId=0,RESPONSE=None):
1.69 dwinter 1281: """upload an atf file / basket file"""
1.22 dwinter 1282: #self._v_uploadATF.returnValue=None
1.71 dwinter 1283:
1284: #generate an random id for the upload thread
1.60 dwinter 1285: from random import randint
1.61 dwinter 1286: if (not self.REQUEST.SESSION.get('idTmp',None)):
1.22 dwinter 1287:
1.60 dwinter 1288: idTmp=str(randint(0,1000000000))
1289: self.REQUEST.SESSION['idTmp']=idTmp
1290: else:
1291: idTmp=self.REQUEST.SESSION.get('idTmp',None)
1292:
1.71 dwinter 1293:
1.22 dwinter 1294: threadName=repeat
1295: if not threadName or threadName=="":
1.71 dwinter 1296: #new thread not called from the waiting page
1.22 dwinter 1297: tmpVar=False
1.24 dwinter 1298:
1.22 dwinter 1299: thread=uploadATFThread()
1.24 dwinter 1300: threadName=thread.getName()[0:]
1.36 dwinter 1301: if (not hasattr(self,'_v_uploadATF')):
1.24 dwinter 1302: self._v_uploadATF={}
1303:
1304: self._v_uploadATF[threadName]=thread
1.22 dwinter 1305: #self._xmltrans.start()
1306: #thread=Thread(target=self._v_uploadATF)
1.60 dwinter 1307: logging.info("set thread. extern")
1308: self._v_uploadATF[threadName].set(upload,basketId,self.REQUEST['AUTHENTICATED_USER'],idTmp,serverport=self.REQUEST['SERVER_PORT'])
1.22 dwinter 1309: #thread.start()
1.60 dwinter 1310: logging.info("start thread. extern")
1.24 dwinter 1311: self._v_uploadATF[threadName].start()
1.22 dwinter 1312:
1313:
1.24 dwinter 1314: self.threadName=self._v_uploadATF[threadName].getName()[0:]
1.22 dwinter 1315: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1316:
1317: if wait_template:
1318: return wait_template[0][1]()
1319: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1.24 dwinter 1320: return pt(txt='/uploadATF',threadName=threadName)
1.22 dwinter 1321: #_v_xmltrans.run()
1322:
1323: else:
1324: #recover thread, if lost
1.36 dwinter 1325: if (not hasattr(self,'_v_uploadATF')):
1.24 dwinter 1326: self._v_uploadATF={}
1327: if not self._v_uploadATF.get(threadName,None):
1.22 dwinter 1328: for thread in threading.enumerate():
1329: if threadName == thread.getName():
1.24 dwinter 1330: self._v_uploadATF[threadName]=thread
1331:
1.60 dwinter 1332: if self._v_uploadATF.get(threadName,None) and (not self._v_uploadATF[threadName].returnValue):
1.22 dwinter 1333:
1334:
1335: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1336: if wait_template:
1337: return wait_template[0][1]()
1338:
1339: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1340:
1.24 dwinter 1341: return pt(txt='/uploadATF',threadName=threadName)
1.22 dwinter 1342:
1343: else:
1.60 dwinter 1344: tmp=getattr(self.temp_folder,idTmp).returnValue
1.71 dwinter 1345:
1.22 dwinter 1346: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadCheck.zpt')).__of__(self)
1.39 dwinter 1347:
1.47 dwinter 1348: return pt(changed=tmp['changed'],lockerrors=tmp['lockerrors'],errors=tmp['errors'],dir=tmp['dir'],newPs=tmp['newPs'],basketLen=tmp['basketLen'],numberOfFiles=tmp['numberOfFiles'],
1.22 dwinter 1349: basketNameFromId=tmp['basketNameFromId'],basketNameFromFile=tmp['basketNameFromFile'],basketId=tmp['basketId'])
1.30 dwinter 1350:
1.118 dwinter 1351:
1.30 dwinter 1352: def redoUpload(self,threadName):
1353: """redo the upload"""
1354: tmp=self.cdli_main.tmpStore2[threadName]
1355: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadCheck.zpt')).__of__(self)
1.45 dwinter 1356: return pt(changed=tmp['changed'],lockerrors=tmp['lockerrors'],errors=tmp['errors'],dir=tmp['dir'],newPs=tmp['newPs'],basketLen=tmp['basketLen'],numberOfFiles=tmp['numberOfFiles'],
1.30 dwinter 1357: basketNameFromId=tmp['basketNameFromId'],basketNameFromFile=tmp['basketNameFromFile'],basketId=tmp['basketId'])
1358:
1.22 dwinter 1359: def uploadATFfinally(self,procedure='',comment="",basketname='',unlock=None,repeat=None,RESPONSE=None):
1360: """nowupload the files"""
1361: threadName=repeat
1362: if not threadName or threadName=="":
1.24 dwinter 1363: thread=uploadATFfinallyThread()
1364: threadName=thread.getName()[0:]
1.36 dwinter 1365:
1.35 dwinter 1366: if (not hasattr(self,'_v_uploadATF')):
1.46 dwinter 1367: self._v_uploadATF={}
1.36 dwinter 1368:
1.43 dwinter 1369:
1.24 dwinter 1370: self._v_uploadATF[threadName]=thread
1.22 dwinter 1371:
1.60 dwinter 1372: idTmp=self.REQUEST.SESSION['idTmp']
1373: stObj=getattr(self.temp_folder,idTmp)
1374: self._v_uploadATF[threadName].set(procedure,comment=comment,basketname=basketname,unlock=unlock,SESSION=stObj.returnValue,username=self.REQUEST['AUTHENTICATED_USER'],serverport=self.REQUEST['SERVER_PORT'])
1.22 dwinter 1375:
1.24 dwinter 1376: self._v_uploadATF[threadName].start()
1.22 dwinter 1377:
1378:
1.24 dwinter 1379:
1.22 dwinter 1380: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1381:
1382: if wait_template:
1383: return wait_template[0][1]()
1384: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1385:
1.24 dwinter 1386: return pt(txt='/uploadATFfinally',threadName=threadName)
1.22 dwinter 1387: #_v_xmltrans.run()
1388:
1389: else:
1390: #recover thread, if lost
1391: if not hasattr(self,'_v_uploadATF'):
1.24 dwinter 1392: self._v_uploadATF={}
1393: if not self._v_uploadATF.get(threadName,None):
1.22 dwinter 1394: for thread in threading.enumerate():
1395: if threadName == thread.getName():
1.24 dwinter 1396: self._v_uploadATF[threadName]=thread
1.22 dwinter 1397:
1.24 dwinter 1398: if self._v_uploadATF.get(threadName,None) and (self._v_uploadATF[threadName] is not None) and (not self._v_uploadATF[threadName].end) :
1.22 dwinter 1399:
1400: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1401: if wait_template:
1402: return wait_template[0][1]()
1403:
1404: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1.24 dwinter 1405: return pt(txt='/uploadATFfinally',threadName=threadName)
1.22 dwinter 1406: else:
1.85 dwinter 1407:
1408:
1409: idTmp=self.REQUEST.SESSION['idTmp']
1410: stObj=getattr(self.temp_folder,idTmp)
1.60 dwinter 1411: self.REQUEST.SESSION['idTmp']=None
1.85 dwinter 1412:
1413: #update changed
1414: logging.debug("dir:"+repr(stObj.returnValue['changed']))
1415: for x in stObj.returnValue['changed']:
1416: ob=self.CDLICatalog.search({'title':x[0]})
1.104 dwinter 1417: try:
1418: self.cdliRoot.updateOrAddToFileBTree(ob[0].getObject())
1419: except:
1.113 dwinter 1420:
1.104 dwinter 1421: logging.error("uploadATFfinally - cannot update Object %s Error: %s %s"%(ob[1],sys.exc_info()[0],sys.exc_info()[1]))
1.113 dwinter 1422: for x in stObj.returnValue['newPs']:
1.114 dwinter 1423: obj=self.getFileObject(x) #updates the object in the cache
1424: logging.debug("Got:"+repr(obj))
1.22 dwinter 1425: if RESPONSE is not None:
1426: RESPONSE.redirect(self.absolute_url())
1427:
1.49 dwinter 1428: def importFiles(self,comment="",author="" ,folderName="/Users/dwinter/atf", files=None,ext=None):
1.1 dwinter 1429: """import files"""
1.81 casties 1430: logging.debug("importFiles folderName=%s files=%s ext=%s"%(folderName,files,ext))
1.22 dwinter 1431: root=self.cdli_main
1.49 dwinter 1432: count=0
1.3 dwinter 1433: if not files:
1434: files=os.listdir(folderName)
1435:
1.1 dwinter 1436: for f in files:
1437: folder=f[0:3]
1438: f2=f[0:5]
1.85 dwinter 1439:
1440: #check if main folder PXX already exists
1.22 dwinter 1441: obj=self.ZopeFind(root,obj_ids=[folder])
1.81 casties 1442: logging.debug("importFiles: folder=%s f2=%s obj=%s"%(folder,f2,obj))
1.19 dwinter 1443: if ext:
1.118 dwinter 1444:
1445: if type(ext.result) is types.FileType:
1446: ext.result.write("<p>adding: %s </p>\n"%f)
1447: else:
1448: ext.result="<p>adding: %s </p>"%f+ext.result
1.81 casties 1449:
1.85 dwinter 1450:
1451: if not obj: # if not create it
1.22 dwinter 1452: manage_addCDLIFileFolder(root,folder,folder)
1453: fobj=getattr(root,folder)
1.58 dwinter 1454: #transaction.get().commit()
1.81 casties 1455:
1.1 dwinter 1456: else:
1457: fobj=obj[0][1]
1458:
1.85 dwinter 1459: #check IF PYYYYY already exist
1.1 dwinter 1460: obj2=fobj.ZopeFind(fobj,obj_ids=[f2])
1.81 casties 1461: logging.debug("importFiles: fobj=%s obj2=%s"%(fobj,obj2))
1.1 dwinter 1462:
1.85 dwinter 1463: if not obj2:# if not create it
1.1 dwinter 1464: manage_addCDLIFileFolder(fobj,f2,f2)
1465: fobj2=getattr(fobj,f2)
1466:
1467: else:
1468: fobj2=obj2[0][1]
1469:
1.85 dwinter 1470: # not add the file
1.48 dwinter 1471: file2=os.path.join(folderName,f)
1.1 dwinter 1472: id=f
1.81 casties 1473: logging.debug("importFiles: addCDLIFile fobj2=%s, f=%s file2=%s"%(fobj2,repr(f),repr(file2)))
1474: fobj2.addFile(vC='',file=file(file2),author=author,newName=f)
1.113 dwinter 1475: logging.debug("importfiles: fobj2.add")
1.66 dwinter 1476: count+=1
1.85 dwinter 1477:
1478: #now add the file to the storage
1479: ob = getattr(fobj2,f)
1.113 dwinter 1480: logging.debug("importfiles: btree_start")
1481: #self.cdliRoot.updateOrAddToFileBTree(ob)
1482: logging.debug("importfiles: btree_end")
1.81 casties 1483: if count%100==0:
1484: logging.debug("importfiles: committing")
1.66 dwinter 1485: transaction.get().commit()
1.81 casties 1486:
1.113 dwinter 1487: logging.debug("importfiles: committing")
1.81 casties 1488: transaction.get().commit()
1.113 dwinter 1489: logging.debug("importfiles: committing done")
1.3 dwinter 1490: return "ok"
1.22 dwinter 1491:
1492:
1493: manage_addCDLIRootForm=DTMLFile('dtml/rootAdd', globals())
1.1 dwinter 1494:
1495:
1.22 dwinter 1496: def manage_addCDLIRoot(self, id, title='',
1.1 dwinter 1497: createPublic=0,
1498: createUserF=0,
1499: REQUEST=None):
1500: """Add a new Folder object with id *id*.
1501:
1502: If the 'createPublic' and 'createUserF' parameters are set to any true
1503: value, an 'index_html' and a 'UserFolder' objects are created respectively
1504: in the new folder.
1505: """
1.22 dwinter 1506: ob=CDLIRoot()
1.1 dwinter 1507: ob.id=str(id)
1508: ob.title=title
1.61 dwinter 1509: try:
1.66 dwinter 1510: self._setObject(id, ob)
1.61 dwinter 1511: except:
1.66 dwinter 1512: pass
1.1 dwinter 1513: ob=self._getOb(id)
1514:
1515: checkPermission=getSecurityManager().checkPermission
1516:
1517: if createUserF:
1518: if not checkPermission('Add User Folders', ob):
1519: raise Unauthorized, (
1520: 'You are not authorized to add User Folders.'
1521: )
1522: ob.manage_addUserFolder()
1523:
1524:
1525: if REQUEST is not None:
1.22 dwinter 1526: return self.manage_main(self, REQUEST, update_menu=1)
1527:
1.105 dwinter 1528:
1529: import cdli_basket
1530:
1531:
1532: # Die folgenden Klassen sollte nicht mehr aus diesem Paket benutzt werden, sondern direkt aus
1533: # cdli_basket importiert werden.
1534: class uploadATFfinallyThread(cdli_basket.uploadATFfinallyThread):
1535: """depricates"""
1536: pass
1537:
1538: class tmpStore(cdli_basket.tmpStore):
1539: """depricated"""
1540: pass
1541:
1542: class uploadATFThread(cdli_basket.uploadATFThread):
1543: """depricated"""
1544: pass
1545:
1546: class CDLIBasketContainer(cdli_basket.CDLIBasketContainer):
1547: """depricated"""
1548: pass
1549:
1550: class CDLIBasket(cdli_basket.CDLIBasket):
1551: """depricated"""
1552: pass
1553:
1554: class CDLIBasketVersion(cdli_basket.CDLIBasketVersion):
1555: """depricated"""
1556: pass
1557:
1558: class BasketContent(cdli_basket.BasketContent):
1559: """depricated"""
1560: pass
1561:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>