Annotation of cdli/cdli_files.py, revision 1.111
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.49 dwinter 93: txt=re.match("&[Pp](\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.46 dwinter 107: txt=re.match("&[Pp](\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"""
309: try:
310: data.encode('utf-8')
311: return True
312: except:
313: return False
314:
1.1 dwinter 315:
1.45 dwinter 316: def checkFile(filename,data,folder):
317: """check the files"""
318: # first check the file name
319: fn=filename.split(".") # no extension
1.48 dwinter 320:
1.45 dwinter 321: if not fn[0][0]=="P":
1.46 dwinter 322: return False,"P missing in the filename"
1.45 dwinter 323: elif len(fn[0])!=7:
1.46 dwinter 324: return False,"P number has not the right length 6"
1.69 dwinter 325: elif not checkUTF8(data):
326: return False,"not utf-8"
1.45 dwinter 327: else:
1.69 dwinter 328: return True,""
329:
1.45 dwinter 330:
1.25 dwinter 331: def splitatf(fh,dir=None,ext=None):
1.2 dwinter 332: """split it"""
1.4 dwinter 333: ret=None
1.2 dwinter 334: nf=None
1.25 dwinter 335: i=0
1.49 dwinter 336:
1.81 casties 337: #ROC: why split \n first and then \r???
1.73 dwinter 338: if (type(fh) is StringType) or (type(fh) is UnicodeType):
339: iter=fh.split("\n")
340: else:
341: iter=fh.readlines()
342:
343: for lineTmp in iter:
1.66 dwinter 344: lineTmp=lineTmp.replace(codecs.BOM_UTF8,'') # make sure that all BOM are removed..
345: for line in lineTmp.split("\r"):
1.111 ! dwinter 346: #logging.info("Deal with: %s"%line)
1.66 dwinter 347: if ext:
348: i+=1
349: if (i%100)==0:
350: ext.result+="."
351: if i==10000:
352: i=0
353: ext.result+="<br>"
354: #check if basket name is in the first line
355: if line.find("#atf basket")>=0: #old convention
356: ret=line.replace('#atf basket ','')
357: ret=ret.split('_')[0]
358: elif line.find("#basket:")>=0: #new convention
359: ret=line.replace('#basket: ','')
360: ret=ret.split('_')[0]
361:
362: else:
363: if (len(line.lstrip())>0) and (line.lstrip()[0]=="&"): #newfile
364: if nf:
365: nf.close() #close last file
366:
1.49 dwinter 367:
1.66 dwinter 368: filename=line[1:].split("=")[0].rstrip()+".atf"
369: if dir:
370: filename=os.path.join(dir,filename)
371: nf=file(filename,"w")
372: logging.info("open %s"%filename)
373: if nf:
374: nf.write(line.replace("\n","")+"\n")
375:
376: try:
377: nf.close()
1.61 dwinter 378: except:
1.66 dwinter 379: pass
1.73 dwinter 380:
381: if not((type(fh) is StringType) or (type(fh) is UnicodeType)):
382: fh.close()
1.5 dwinter 383: return ret,len(os.listdir(dir))
1.4 dwinter 384:
1.19 dwinter 385:
1.46 dwinter 386: class CDLIFileFolder(extVersionedFileFolder):
1.4 dwinter 387: """CDLI File Folder"""
1.1 dwinter 388:
1.19 dwinter 389: security=ClassSecurityInfo()
1.1 dwinter 390: meta_type="CDLI Folder"
1.81 casties 391: file_meta_type=['CDLI file']
392: folder_meta_type=['CDLI Folder']
393:
394: file_catalog='CDLICatalog'
395:
1.45 dwinter 396: #downloadCounter=0 # counts how many download for all files currently run, be mehr als 5 wird verweigert.
1.24 dwinter 397: tmpStore2={}
1.81 casties 398:
399: def _newVersionedFile(self, id, title='', lockedBy=None, author=None):
400: """factory for versioned files. to be overridden in derived classes."""
401: logging.debug("_newVersionedFile(CDLI)")
402: return CDLIFile(id, title, lockedBy=lockedBy, author=author)
403:
1.19 dwinter 404: def setTemp(self,name,value):
405: """set tmp"""
406:
407: setattr(self,name,value)
408:
1.81 casties 409: deleteFileForm = PageTemplateFile("zpt/doDeleteFile", globals())
1.19 dwinter 410:
1.81 casties 411: def delete(self,ids,REQUEST=None):
412: """delete these files"""
1.12 dwinter 413: if type(ids) is not ListType:
414: ids=[ids]
1.81 casties 415:
416: self.manage_delObjects(ids)
1.12 dwinter 417:
1.81 casties 418: if REQUEST is not None:
419: return self.index_html()
420:
421:
1.4 dwinter 422: def getVersionNumbersFromIds(self,ids):
423: """get the numbers of the current versions of documents described by their ids"""
424:
425: ret=[]
426: searchStr=" OR ".join(ids)
427:
1.9 dwinter 428: founds=self.CDLICatalog.search({'title':searchStr})
1.4 dwinter 429:
430: for found in founds:
1.81 casties 431: lastVersion=found.getObject().getContentObject()
1.4 dwinter 432: ret.append((found.getId,lastVersion))
433:
434: return ret
435:
1.67 dwinter 436: def getFile(self,fn):
437: """get the content of the file fn"""
1.81 casties 438: logging.debug("getFile: %s"%repr(fn))
439: if not self.hasObject(fn):
440: # search deeper
441: founds=getattr(self, self.file_catalog).search({'textid':fn})
442: if founds:
443: obj=founds[0].getObject().getContentObject()
444: else:
445: return ""
1.67 dwinter 446: else:
1.81 casties 447: obj = self[fn].getContentObject()
1.68 dwinter 448:
1.81 casties 449: return obj.getData()[0:]
450:
1.67 dwinter 451:
1.14 dwinter 452: def checkCatalog(self,fn):
453: """check if fn is in the catalog"""
1.19 dwinter 454: #TODO add checkCatalog
1.14 dwinter 455:
1.19 dwinter 456:
1.45 dwinter 457: def findObjectsFromListWithVersion(self,list,author=None):
1.26 dwinter 458: """find objects from a list with versions
459: @param list: list of tuples (cdliFile,version)
460: """
461: #self.REQUEST.SESSION['fileIds']=list#store fieldIds in session for further usage
462: #self.REQUEST.SESSION['searchList']=self.REQUEST.SESSION['fileIds']
463:
464: pt=getattr(self,'filelistVersioned.html')
465:
1.45 dwinter 466: return pt(search=list,author=author)
1.26 dwinter 467:
468:
1.67 dwinter 469: def getAllPNumbers(self):
470: """get a list of all files (resp their p-numbers) stored"""
471:
472: ret=[x.getId for x in self.CDLICatalog()]
473:
474: return ret
475:
1.83 dwinter 476: def expandFile(self,fileId,fileTree):
477: """wildcard in fileID suche alle Treffer"""
478: founds=self.CDLICatalog({'title':fileId})
479: for found in founds:
480: fileTree.add(found.getId)
481: logging.debug("ADDD:"+found.getId)
482:
1.85 dwinter 483: 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 484: """findObjectsFromList (, TAB oder LINE separated)"""
1.15 dwinter 485:
1.83 dwinter 486: logging.debug("start: findObjectsFromList")
1.85 dwinter 487: #logging.debug("start: findObjectsFromList"+repr(list))
488:
489:
1.6 dwinter 490: if upload: # list from file upload
491: txt=upload.read()
1.35 dwinter 492:
493: if enterList:
494: txt=enterList
495:
496: if upload or enterList:
1.6 dwinter 497: txt=txt.replace(",","\n")
498: txt=txt.replace("\t","\n")
1.12 dwinter 499: txt=txt.replace("\r","\n")
1.6 dwinter 500: idsTmp=txt.split("\n")
501: ids=[]
502: for id in idsTmp: # make sure that no empty lines
503: idTmp=id.lstrip().rstrip()
504: if len(idTmp)>0:
505:
506: ids.append(idTmp)
507:
508: #self.REQUEST.SESSION['ids']=" OR ".join(ids)
1.12 dwinter 509:
1.6 dwinter 510: pt=getattr(self,'filelist.html')
1.7 dwinter 511: self.REQUEST.SESSION['searchList']=ids
1.6 dwinter 512: return pt(search=ids)
1.7 dwinter 513:
1.6 dwinter 514: if basketName:
1.7 dwinter 515: #TODO: get rid of one of these..
516:
1.6 dwinter 517: pt=getattr(self,'filelist.html')
1.7 dwinter 518: return pt(basketName=basketName,numberOfObjects=numberOfObjects)
1.6 dwinter 519:
1.102 dwinter 520:
521: result =self.CDLICache.retrieve(hash)
522: if result:
523: logging.debug("give result from storage2")
524: return hash,result
525:
1.15 dwinter 526: if list is not None: # got already a list
1.83 dwinter 527:
528: logging.debug(" ----List version")
1.6 dwinter 529: ret=[]
1.83 dwinter 530: fileTree=Set()
531:
1.6 dwinter 532: for fileId in list:
1.83 dwinter 533:
534: if fileId.find("*")>-1: #check for wildcards
535: self.expandFile(fileId,fileTree)
536:
1.35 dwinter 537: elif len(fileId.split("."))==1:
1.6 dwinter 538: fileId=fileId+".atf"
1.83 dwinter 539: fileTree.add(fileId)
540: #logging.debug(" -----:"+fileId)
541: #ret+=self.CDLICatalog({'title':fileId})
542: #x =self.getFileObject(fileId)
543: #if x is not None:
544: # ret.append(x)
1.35 dwinter 545:
1.83 dwinter 546:
547:
548: ids = fileTree & self.v_file_ids
1.85 dwinter 549: #self.REQUEST.SESSION['fileIds']=ids#store fieldIds in session for further usage
550: l=makelist(fileTree)[0:]
1.93 dwinter 551: #logging.debug("l-list:"+repr(l))
1.85 dwinter 552: self.REQUEST.SESSION['fileIds']=l#store fieldIds in session for further usage
553: self.REQUEST.SESSION['searchList']=l
554: #self.REQUEST.SESSION['searchList']=['P000001.atf']
555:
1.83 dwinter 556:
1.85 dwinter 557: hash = md5.new(repr(makelist(fileTree))).hexdigest() # erzeuge hash als identification
558: self.REQUEST.SESSION['hash']=hash
559: #TODO: do I need garbage collection for v_tmpStore ?
1.83 dwinter 560:
1.84 dwinter 561: #logging.debug("Hash:"+repr(hash))
1.85 dwinter 562: #
563: # if hasattr(self.cdliRoot,'v_tmpStore') and self.cdliRoot.v_tmpStore.has_key(hash):
564: # logging.debug("asking for storage")
565: # res=self.cdliRoot.v_tmpStore[hash]
566: # if res:
567: # if returnHash == True:
568: # return hash,res
569: # return res
1.83 dwinter 570:
1.7 dwinter 571: #TODO: get rid of one of these..
1.83 dwinter 572: #ids=[x.getObject().getId() for x in ret]
573: ret=[(self.getFileObject(x),self.getFileObjectLastVersion(x)) for x in ids]
1.84 dwinter 574:
575: #self.REQUEST.SESSION['fileIds']=ids#store fieldIds in session for further usage
576: #self.REQUEST.SESSION['searchList']=self.REQUEST.SESSION['fileIds']
1.85 dwinter 577:
1.25 dwinter 578: if display:
579: pt=getattr(self,'filelist.html')
580:
581: return pt(search=ids)
1.83 dwinter 582: else:
583: #self.REQUEST.SESSION['hash'] = ret # store in session
1.102 dwinter 584:
1.83 dwinter 585: #logging.debug("HHHHHHNEU:"+repr(self.makelist(ids)))
1.84 dwinter 586: #logging.debug("HHHHHHNEU:"+repr(hash))
1.102 dwinter 587: self.CDLICache.store(hash,ret)
588:
1.85 dwinter 589: if returnHash == True:
590: return hash,ret
1.25 dwinter 591: return ret
592:
593:
1.1 dwinter 594:
1.7 dwinter 595: if start:
596: RESPONSE.redirect("filelist.html?start:int="+str(start))
1.85 dwinter 597:
1.19 dwinter 598: security.declareProtected('Manage','createAllFilesAsSingleFile')
1.1 dwinter 599: def createAllFilesAsSingleFile(self,RESPONSE=None):
600: """download all files"""
601:
602: def sortF(x,y):
603: return cmp(x[0],y[0])
604:
1.81 casties 605: catalog=getattr(self,self.file_catalog)
1.1 dwinter 606: #tf,tfilename=mkstemp()
1.66 dwinter 607: if not hasattr(self.temp_folder,'downloadCounter'):
608: self.temp_folder.downloadCounter=0
1.49 dwinter 609:
610: if getattr(self.temp_folder,'downloadCounter',0) > 5:
1.46 dwinter 611: return """I am sorry, currently the server has to many requests for downloads, please come back later!"""
1.45 dwinter 612:
1.46 dwinter 613: self.temp_folder.downloadCounter+=1
614: self._p_changed=1
1.58 dwinter 615: transaction.get().commit()
1.45 dwinter 616:
1.1 dwinter 617: list=[(x.getId,x) for x in catalog()]
618: list.sort(sortF)
1.46 dwinter 619:
1.45 dwinter 620:
1.1 dwinter 621:
622: RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%"all.atf")
623: RESPONSE.setHeader("Content-Type","application/octet-stream")
1.46 dwinter 624: tmp=""
1.1 dwinter 625: for l in list:
626: obj=l[1].getObject()
627:
628: if obj.meta_type=="CDLI file":
629:
630: #os.write(tf,obj.getLastVersion().data)
631: if RESPONSE:
1.81 casties 632: RESPONSE.write(obj.getData()[0:])
1.71 dwinter 633: RESPONSE.write("\n")
1.46 dwinter 634: self.temp_folder.downloadCounter-=1
635: self._p_changed=1
1.58 dwinter 636: transaction.get().commit()
1.1 dwinter 637: #os.close(tf)
638: #RESPONSE.redirect(self.absolute_url()+"/downloadFile?fn="%tfilename)
639: return True
640:
641: def downloadFile(self,fn):
642: """download fn - not used yet"""
643: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getLastVersion().getId())
644: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
645: self.REQUEST.RESPONSE.write(file(fn).read())
646:
647:
648:
649: def hasParent(self):
650: """returns true falls subfolder"""
651:
1.81 casties 652: if self.aq_parent.meta_type in self.folder_meta_type:
1.1 dwinter 653: return True
654: else:
655: return False
656:
657: def getFolders(self):
658: """get all subfolders"""
659: ret=[]
1.81 casties 660: folders=self.ZopeFind(self,obj_metatypes=self.folder_meta_type)
1.1 dwinter 661: for folder in folders:
662: ret.append((folder[1],
1.81 casties 663: len(self.ZopeFind(folder[1],obj_metatypes=self.folder_meta_type)),
664: len(self.ZopeFind(folder[1],obj_metatypes=self.file_meta_type))
1.1 dwinter 665: ))
666: return ret
667:
668:
1.77 dwinter 669: security.declareProtected('manage','index_html')
1.1 dwinter 670: def index_html(self):
671: """main"""
672: ext=self.ZopeFind(self,obj_ids=["index.html"])
673: if ext:
674: return ext[0][1]()
675:
676: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','CDLIFileFolderMain')).__of__(self)
677: return pt()
678:
1.22 dwinter 679:
680: manage_addCDLIFileFolderForm=DTMLFile('dtml/folderAdd', globals())
681:
682:
683: def manage_addCDLIFileFolder(self, id, title='',
684: createPublic=0,
685: createUserF=0,
686: REQUEST=None):
687: """Add a new Folder object with id *id*.
688:
689: If the 'createPublic' and 'createUserF' parameters are set to any true
690: value, an 'index_html' and a 'UserFolder' objects are created respectively
691: in the new folder.
692: """
693: ob=CDLIFileFolder()
694: ob.id=str(id)
695: ob.title=title
696: self._setObject(id, ob)
697: ob=self._getOb(id)
698:
699: checkPermission=getSecurityManager().checkPermission
700:
701: if createUserF:
702: if not checkPermission('Add User Folders', ob):
703: raise Unauthorized, (
704: 'You are not authorized to add User Folders.'
705: )
706: ob.manage_addUserFolder()
707:
708:
709: if REQUEST is not None:
710: return self.manage_main(self, REQUEST, update_menu=1)
711:
712: class CDLIRoot(Folder):
713: """main folder for cdli"""
714:
715: meta_type="CDLIRoot"
1.81 casties 716: downloadCounterBaskets=0 # counts the current basket downloads if counter > 10 no downloads are possible
717:
718: file_catalog = 'CDLICatalog'
719:
720: # word splitter for search
721: splitter = {'words':cdliSplitter.wordSplitter(),
722: 'graphemes':cdliSplitter.graphemeSplitter()}
723:
1.110 dwinter 724: def redirect(self,RESPONSE,url):
725: """mache ein redirect mit einem angehaengten time stamp um ein reload zu erzwingen"""
726:
727: timeStamp=time.time()
728:
729: if url.find("?")>-1: #giebt es schon parameter
730: addStr="&time=%s"
731: else:
732: addStr="?time=%s"
733:
734: RESPONSE.setHeader('Last-Modified',email.Utils.formatdate().split("-")[0]+'GMT')
735: logging.error(email.Utils.formatdate()+' GMT')
736: RESPONSE.redirect(url+addStr%timeStamp)
1.51 dwinter 737:
1.102 dwinter 738: def unicodify(self,txt):
739: return unicodify(txt)
740: def invalidateOldCacheVersion(self):
741: """loescht die alte Version des Cache"""
742: del self.v_tmpStore
743: return "done"
744:
1.86 dwinter 745: def viewATF(self,id,RESPONSE):
746: """view an Object"""
747: ob = self.CDLICatalog({'title':id})
748: logging.debug(ob[0].getObject().getLastVersion().absolute_url()+"/view")
749: if len(ob)>0:
750: RESPONSE.redirect(ob[0].getObject().getLastVersion().absolute_url()+"/view")
751: return "not found"
752:
753: def history(self,id,RESPONSE):
754: """view an Object"""
755: ob = self.CDLICatalog({'title':id})
756: if len(ob)>0:
757: RESPONSE.redirect(ob[0].absolute_url+"/history")
758: return "not found"
759:
760:
761: def downloadLocked(self,id,RESPONSE):
762: """view an Object"""
763: ob = self.CDLICatalog({'title':id})
764: if len(ob)>0:
765: RESPONSE.redirect(ob[0].absolute_url+"/downloadLocked")
766: return "not found"
767:
768: def download(self,id,RESPONSE):
769: """view an Object"""
770: ob = self.CDLICatalog({'title':id})
771: if len(ob)>0:
1.109 dwinter 772: logging.info("objekt:"+repr(ob[0]))
773: #RESPONSE.redirect(ob[0].getLastVersion().absolute_url())
774: RESPONSE.redirect(ob[0].absolute_url+"/download")
1.86 dwinter 775: return "not found"
776: def addCDLIFileObjectForm(self,id,RESPONSE):
777: """view an Object"""
778: ob = self.CDLICatalog({'title':id})
779: if len(ob)>0:
780: RESPONSE.redirect(ob[0].absolute_url+"/addCDLIFileObjectForm")
781: return "not found"
782:
783: def addVersionedFileObjectForm(self,id,RESPONSE):
784: """view an Object"""
785: ob = self.CDLICatalog({'title':id})
786: if len(ob)>0:
787: RESPONSE.redirect(ob[0].absolute_url+"/addVersionedFileObjectForm")
788: return "not found"
789:
790: def unlock(self,id,RESPONSE):
791: """view an Object"""
792: ob = self.CDLICatalog({'title':id})
793: if len(ob)>0:
794: RESPONSE.redirect(ob[0].absolute_url+"/unlock")
795: return "not found"
796:
1.83 dwinter 797: def getFileObject(self,fileId):
1.85 dwinter 798: """get an object"""
1.108 dwinter 799: if isinstance(fileId,CDLIFileObject): # support for old baskets
800: return fileId
1.83 dwinter 801: x=self.v_files.get(fileId)
1.108 dwinter 802: #logging.debug("getFileObj:"+repr(fileId))
1.83 dwinter 803: return x
804:
805: def getFileObjectLastVersion(self,fileId):
1.85 dwinter 806: """get an object"""
1.83 dwinter 807: x=self.v_files_lastVersion.get(fileId)
1.95 dwinter 808: #logging.debug("lastVersion: "+repr(x))
1.83 dwinter 809: return x
810:
1.85 dwinter 811: def showFileIds(self):
812: """showIds"""
813: return self.v_file_ids
814:
1.83 dwinter 815: def generateFileBTree(self):
816: """erzeuge einen Btree aus allen Files"""
817: self.v_files = OOBTree()
818: self.v_files_lastVersion = OOBTree()
819: self.v_file_ids = Set()
820:
821: for x in self.CDLICatalog.searchResults():
822:
823: self.v_files.update({x.getId:x.getObject()})
824: self.v_files_lastVersion.update({x.getId:x.getObject().getLastVersion()})
825: self.v_file_ids.add(x.getId)
826: logging.debug("add:"+x.getId+"XXX"+repr(x.getObject()))
827:
1.85 dwinter 828: return True
829:
830:
831: def updateOrAddToFileBTree(self,obj):
832: """update a BTree"""
833: self.v_files.update({obj.getId():obj})
834: self.v_files_lastVersion.update({obj.getId():obj.getLastVersion()})
835:
836: self.v_file_ids.add(obj.getId())
837: logging.debug("update:"+obj.getId()+"XXX"+repr(obj))
838:
839: def deleteFromBTree(self,objId):
840: """delete an obj"""
841: self.v_files.pop(objId)
842: self.v_files_lastVersion.pop(objId)
843: self.v_file_ids.remove(objId)
844:
845:
846:
1.73 dwinter 847: def deleteFiles(self,ids):
1.81 casties 848: """delete files"""
1.73 dwinter 849: for id in ids:
850: founds=self.CDLICatalog.search({'title':id.split(".")[0]})
851: if founds:
1.81 casties 852: logging.debug("deleting %s"%founds)
1.73 dwinter 853: folder=founds[0].getObject().aq_parent #get the parent folder of the object
1.81 casties 854: logging.debug("deleting from %s"%folder)
855: cut=folder.delete([founds[0].getId]) #cut it out
856:
1.73 dwinter 857:
858:
1.81 casties 859: def searchText(self, query, index='graphemes'):
860: """searches query in the fulltext index and returns a list of file ids/P-numbers"""
861: # see also: http://www.plope.com/Books/2_7Edition/SearchingZCatalog.stx#2-13
862: logging.debug("searchtext for '%s' in index %s"%(query,index))
863: #import Products.ZCTextIndex.QueryParser
864: #qp = QueryParser.QueryParser()
865: #logging.debug()
866: idxQuery = {index:{'query':query}}
867: idx = getattr(self, self.file_catalog)
868: # do search
869: resultset = idx.search(query_request=idxQuery,sort_index='textid')
870: # put only the P-Number in the result
871: results = [res.getId[:7] for res in resultset]
872: logging.debug("searchtext: found %d texts"%len(results))
873: return results
874:
875:
876: def getFile(self, pnum):
877: """get the translit file with the given pnum"""
878: f = getattr(self, self.file_catalog).search({'textid':pnum})
879: if not f:
880: return ""
1.71 dwinter 881:
1.81 casties 882: return f[0].getObject().getData()
883:
1.57 dwinter 884:
1.74 dwinter 885: def showFile(self,fileId,wholePage=False):
1.71 dwinter 886: """show a file
887: @param fileId: P-Number of the document to be displayed
888: """
1.81 casties 889: f=getattr(self, self.file_catalog).search({'textid':fileId})
1.51 dwinter 890: if not f:
891: return ""
892:
1.74 dwinter 893: if wholePage:
1.81 casties 894: logging.debug("show whole page")
895: return f[0].getObject().getContentObject().view()
1.74 dwinter 896: else:
897: return f[0].getObject().getLastVersionFormattedData()
1.55 dwinter 898:
1.56 dwinter 899:
1.81 casties 900: def showWordInFile(self,fileId,word,indexName='graphemes',regExp=False,):
901: """get lines with word from FileId"""
902: logging.debug("showwordinfile word='%s' index=%s file=%s"%(word,indexName,fileId))
1.56 dwinter 903:
1.81 casties 904: file = formatAtfFullLineNum(self.getFile(fileId))
1.66 dwinter 905: ret=[]
1.71 dwinter 906:
1.81 casties 907: # add whitespace before and whitespace and line-end to splitter bounds expressions
908: bounds = self.splitter[indexName].bounds
909: splitexp = "(%s|\s)(%%s)(%s|\s|\Z)"%(bounds,bounds)
910: # clean word expression
911: # TODO: this should use QueryParser itself
912: # take out double quotes
913: word = word.replace('"','')
914: # take out ignorable signs
915: ignorable = self.splitter[indexName].ignorex
916: word = ignorable.sub('', word)
917: # compile into regexp objects and escape parens
918: wordlist = [re.compile(splitexp%re.escape(w)) for w in word.split(' ')]
919:
920: for line in file.splitlines():
1.71 dwinter 921: for word in wordlist:
1.81 casties 922: #logging.debug("showwordinfile: searching for %s in %s"%(word.pattern,ignoreable.sub('',line)))
923: if word.search(ignorable.sub('',line)):
924: line = formatAtfLineHtml(line)
925: ret.append(line)
926: break
927:
1.66 dwinter 928: return ret
1.56 dwinter 929:
1.81 casties 930:
931: def showWordInFiles(self,fileIds,word,indexName='graphemes',regExp=False):
932: """
933: get lines with word from all ids in list FileIds.
934: returns dict with id:lines pairs.
935: """
936: logging.debug("showwordinfiles word='%s' index=%s file=%s"%(word,indexName,fileIds))
1.51 dwinter 937:
1.81 casties 938: return dict([(id,self.showWordInFile(id, word, indexName, regExp)) for id in fileIds])
939:
940:
941: def tagWordInFile(self,fileId,word,indexName='graphemes',regExp=False):
942: """get text with word highlighted from FileId"""
943: logging.debug("tagwordinfile word='%s' index=%s file=%s"%(word,indexName,fileId))
944:
945: file=self.getFile(fileId)
946: tagStart=u'<span class="found">'
947: tagEnd=u'</span>'
948: tagStr=tagStart + u'%%s' + tagEnd
1.66 dwinter 949: ret=[]
1.71 dwinter 950:
1.81 casties 951: # add whitespace to splitter bounds expressions and compile into regexp object
952: bounds = self.splitter[indexName].bounds
953: wordsplit = re.compile("(%s|\s)"%bounds)
954: # clean word expression
955: # TODO: this should use QueryParser itself
956: word = word.replace('"','') # take out double quotes
957: # take out ignoreable signs
958: ignorable = self.splitter[indexName].ignorex
959: word = ignorable.sub('', word)
960: # split search terms by blanks
961: words = word.split(' ')
962: # split search terms again (for grapheme search with words)
963: splitwords = dict(((w,self.splitter[indexName].process([w])) for w in words))
1.71 dwinter 964:
1.81 casties 965: for line in file.splitlines():
1.79 casties 966: line = unicodify(line)
1.81 casties 967: # ignore lemma and other lines
968: if line.lstrip().startswith('#lem:'):
969: continue
970: # ignore p-num line
971: if line.startswith('&P'):
972: continue
973: # ignore version lines
974: if line.startswith('#version'):
975: continue
976: # ignore atf type lines
977: if line.startswith('#atf:'):
978: continue
979:
980: # first scan
981: hitwords = []
982: for w in words:
983: if ignorable.sub('',line).find(w) > -1:
984: # word is in line
985: # append split word for grapheme search with words
986: hitwords.extend(splitwords[w])
987: #hitwords.extend(wordsplit.split(w))
988:
989: # examine hits closer
990: if hitwords:
991: # split line into words
992: parts = wordsplit.split(line)
993: line = ""
994: for p in parts:
995: #logging.debug("tagwordinfile: searching for %s in %s"%(p,hitwords))
996: # reassemble line
997: if ignorable.sub('', p) in hitwords:
998: #logging.debug("tagwordinfile: found %s in %s"%(p,hitwords))
999: # this part was found
1000: line += tagStart + formatAtfHtml(p) + tagEnd
1001: else:
1002: line += formatAtfHtml(p)
1003:
1004: else:
1005: # no hits
1006: line = formatAtfHtml(line)
1007:
1008: ret.append(line)
1009:
1010: return u'<br>\n'.join(ret)
1011:
1.66 dwinter 1012:
1013:
1.81 casties 1014: def tagWordInFiles(self,fileIds,word,indexName='graphemes',regExp=False):
1015: """
1016: get texts with highlighted word from all ids in list FileIds.
1017: returns dict with id:text pairs.
1018: """
1019: logging.debug("tagwordinfiles word='%s' index=%s file=%s"%(word,indexName,fileIds))
1020: return dict([(id,self.tagWordInFile(id, word, indexName, regExp)) for id in fileIds])
1021:
1.56 dwinter 1022:
1.82 casties 1023: def getFileVersionList(self, pnum):
1024: """get the version history as a list for the translit file with the given pnum"""
1025: f = getattr(self, self.file_catalog).search({'textid':pnum})
1026: if not f:
1027: return []
1028:
1029: return f[0].getObject().getVersionList()
1030:
1031:
1.37 dwinter 1032: def URLquote(self,str):
1033: """quote url"""
1034: return urllib.quote(str)
1035:
1036: def URLunquote(self,str):
1037: """unquote url"""
1038: return urllib.unquote(str)
1039:
1.58 dwinter 1040: def URLquote_plus(self,str):
1041: """quote url"""
1042: return urllib.quote_plus(str)
1043:
1044: def URLunquote_plus(self,str):
1045: """unquote url"""
1046: return urllib.unquote_plus(str)
1047:
1.106 dwinter 1048: def changeUserForPObjectFromFile(self,user,fname):
1049: """aendere user fuer alle p in fiele"""
1.107 dwinter 1050: pns = file(os.path.join(package_home(globals()),'inputs',fname),"r")
1051: for p in pns.readlines():
1052: p=p.lstrip().rstrip()
1053: logging.info(str(p+".atf"))
1054: pObj=self.getFileObject(p+".atf")
1055: if pObj is not None:
1056: logging.info(pObj)
1057: lv=pObj.getContentObject()
1058: logging.info("author:"+lv.author)
1059: lv.author=user
1060: lv.versionComment="XXXXXXX"
1.37 dwinter 1061:
1.106 dwinter 1062:
1063:
1.109 dwinter 1064: gen
1.105 dwinter 1065: def forceunlock(self,REQUEST=None,user=None):
1.26 dwinter 1066: "break all locks"
1067: ret=[]
1.105 dwinter 1068:
1.26 dwinter 1069: for f in self.ZopeFind(self,obj_metatypes="CDLI file",search_sub=1):
1.105 dwinter 1070: un=f[1].forceunlock(user=user)
1071: logging.info("check:"+f[0])
1.26 dwinter 1072: if un and un !="":
1073: ret.append((f[0],un))
1.46 dwinter 1074:
1.105 dwinter 1075: if REQUEST is not None:
1076: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','breakLockResponse.zpt')).__of__(self)
1077:
1078: return pt(ret=ret)
1079:
1.61 dwinter 1080: return ret
1.71 dwinter 1081:
1.61 dwinter 1082:
1.105 dwinter 1083: def getLockedFiles(self,REQUEST=None,user=None):
1084: """hole alle gesperrten files"""
1085: ret={}
1086:
1087: for f in self.ZopeFind(self,obj_metatypes="CDLI file",search_sub=1):
1088: lb = f[1].lockedBy
1089: add=False
1090: if (lb is not None) and (lb!=""):
1091:
1092: if user is None:
1093: add=True
1094: else:
1095: if str(lb)==user:
1096: add=True
1097: if add==True:
1098: if not ret.has_key(lb):
1099: ret[lb]=[]
1100: ret[lb].append(f[0])
1101:
1102:
1103: if REQUEST is not None:
1104: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','showlockResponse.zpt')).__of__(self)
1105:
1106: return pt(ret=ret)
1107:
1108: return ret
1109:
1.26 dwinter 1110: def getChangesByAuthor(self,author,n=100):
1.25 dwinter 1111: """getChangesByAuthor"""
1.26 dwinter 1112: zcat=self.CDLIObjectsCatalog
1113: res=zcat({'lastEditor':author,
1.25 dwinter 1114: 'sort_on':'getTime',
1115: 'sort_order':'descending',
1116: 'sort_limit':n})[:n ]
1.26 dwinter 1117:
1118: return res
1119:
1120: def getChangesByAuthor_html(self,author,n=100):
1121: """html output for changes by author"""
1122: tmp={}
1123: list=[]
1124: for x in self.getChangesByAuthor(author):
1125: nr=x.getObject().getVersionNumber()
1126: id=x.getObject().aq_parent.getId()
1127: #hinzufuegen, wenn Version neuer als die
1128: if tmp.get(id,(0,0))[1] < nr:
1129: tmp[id]=(x.getObject().aq_parent,nr)
1130:
1131:
1.45 dwinter 1132: return self.cdli_main.findObjectsFromListWithVersion(list=tmp.values(),author=author)
1.26 dwinter 1133:
1.25 dwinter 1134: def getLastChanges(self,n=100):
1135: """get the last n changes"""
1136: n=int(n)
1137: zcat=self.CDLICatalog
1138: return zcat({'sort_on':'getLastChangeDate',
1139: 'sort_order':'descending',
1140: 'sort_limit':n})[:n ]
1141:
1142:
1143: def getLastChanges_html(self,n=100):
1144: """get the last n changes"""
1145: list = [x.getId for x in self.getLastChanges(n)]
1146: return self.cdli_main.findObjectsFromList(list=list,display=True)
1147:
1.24 dwinter 1148: def refreshTxt(self,txt="",threadName=None):
1.22 dwinter 1149: """txt fuer refresh"""
1150:
1.24 dwinter 1151: return """ 2;url=%s?repeat=%s """%(self.absolute_url()+txt,threadName)
1.22 dwinter 1152:
1.87 dwinter 1153: def refreshTxtBasket(self,txt="",threadName=None):
1154: """txt fuer refresh"""
1155:
1156: return """ 2;url=%s?repeat=%s """%(txt,threadName)
1157:
1.22 dwinter 1158:
1.24 dwinter 1159: def getResult(self,threadName=None):
1.22 dwinter 1160: """result of thread"""
1161: try:
1.24 dwinter 1162: return self._v_uploadATF[threadName].getResult()
1.22 dwinter 1163: except:
1164: return "One moment, please"
1165:
1.24 dwinter 1166:
1167: def checkThreads(self):
1168: """check threads"""
1.42 dwinter 1169: ret="<html><body>"
1170: for thread in threading.enumerate():
1.45 dwinter 1171: ret+="<p>%s (%s): %s</p>"%(repr(thread),thread.getName(),thread.isAlive())
1.42 dwinter 1172:
1173: return ret
1174:
1175:
1.73 dwinter 1176: def uploadATFRPC(self,data,username):
1177: """upload an atffile via xml-rpc"""
1178: uploader=uploadATFThread()
1179:
1180: #generate an random id for the upload object
1181: from random import randint
1182: if (not self.REQUEST.SESSION.get('idTmp',None)):
1183:
1184: idTmp=str(randint(0,1000000000))
1185: self.REQUEST.SESSION['idTmp']=idTmp
1186: else:
1187: idTmp=self.REQUEST.SESSION.get('idTmp',None)
1188:
1189:
1190: uploader.set(data,0,username,idTmp)
1191:
1192: stObj=uploader.run()
1193:
1194: processor=uploadATFfinallyThread()
1195:
1196: basketname=stObj.returnValue['basketNameFromFile']
1197:
1198: processor.set("uploadchanged",basketname=basketname,SESSION=stObj.returnValue,username=username,serverport=self.REQUEST['SERVER_PORT'])
1199:
1200: processor.run()
1201:
1202:
1203: return generateXMLReturn(stObj.returnValue)
1204:
1.22 dwinter 1205: def uploadATF(self,repeat=None,upload=None,basketId=0,RESPONSE=None):
1.69 dwinter 1206: """upload an atf file / basket file"""
1.22 dwinter 1207: #self._v_uploadATF.returnValue=None
1.71 dwinter 1208:
1209: #generate an random id for the upload thread
1.60 dwinter 1210: from random import randint
1.61 dwinter 1211: if (not self.REQUEST.SESSION.get('idTmp',None)):
1.22 dwinter 1212:
1.60 dwinter 1213: idTmp=str(randint(0,1000000000))
1214: self.REQUEST.SESSION['idTmp']=idTmp
1215: else:
1216: idTmp=self.REQUEST.SESSION.get('idTmp',None)
1217:
1.71 dwinter 1218:
1.22 dwinter 1219: threadName=repeat
1220: if not threadName or threadName=="":
1.71 dwinter 1221: #new thread not called from the waiting page
1.22 dwinter 1222: tmpVar=False
1.24 dwinter 1223:
1.22 dwinter 1224: thread=uploadATFThread()
1.24 dwinter 1225: threadName=thread.getName()[0:]
1.36 dwinter 1226: if (not hasattr(self,'_v_uploadATF')):
1.24 dwinter 1227: self._v_uploadATF={}
1228:
1229: self._v_uploadATF[threadName]=thread
1.22 dwinter 1230: #self._xmltrans.start()
1231: #thread=Thread(target=self._v_uploadATF)
1.60 dwinter 1232: logging.info("set thread. extern")
1233: self._v_uploadATF[threadName].set(upload,basketId,self.REQUEST['AUTHENTICATED_USER'],idTmp,serverport=self.REQUEST['SERVER_PORT'])
1.22 dwinter 1234: #thread.start()
1.60 dwinter 1235: logging.info("start thread. extern")
1.24 dwinter 1236: self._v_uploadATF[threadName].start()
1.22 dwinter 1237:
1238:
1.24 dwinter 1239: self.threadName=self._v_uploadATF[threadName].getName()[0:]
1.22 dwinter 1240: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1241:
1242: if wait_template:
1243: return wait_template[0][1]()
1244: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1.24 dwinter 1245: return pt(txt='/uploadATF',threadName=threadName)
1.22 dwinter 1246: #_v_xmltrans.run()
1247:
1248: else:
1249: #recover thread, if lost
1.36 dwinter 1250: if (not hasattr(self,'_v_uploadATF')):
1.24 dwinter 1251: self._v_uploadATF={}
1252: if not self._v_uploadATF.get(threadName,None):
1.22 dwinter 1253: for thread in threading.enumerate():
1254: if threadName == thread.getName():
1.24 dwinter 1255: self._v_uploadATF[threadName]=thread
1256:
1.60 dwinter 1257: if self._v_uploadATF.get(threadName,None) and (not self._v_uploadATF[threadName].returnValue):
1.22 dwinter 1258:
1259:
1260: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1261: if wait_template:
1262: return wait_template[0][1]()
1263:
1264: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1265:
1.24 dwinter 1266: return pt(txt='/uploadATF',threadName=threadName)
1.22 dwinter 1267:
1268: else:
1.60 dwinter 1269: tmp=getattr(self.temp_folder,idTmp).returnValue
1.71 dwinter 1270:
1.22 dwinter 1271: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadCheck.zpt')).__of__(self)
1.39 dwinter 1272:
1.47 dwinter 1273: 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 1274: basketNameFromId=tmp['basketNameFromId'],basketNameFromFile=tmp['basketNameFromFile'],basketId=tmp['basketId'])
1.30 dwinter 1275:
1276: def redoUpload(self,threadName):
1277: """redo the upload"""
1278: tmp=self.cdli_main.tmpStore2[threadName]
1279: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadCheck.zpt')).__of__(self)
1.45 dwinter 1280: 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 1281: basketNameFromId=tmp['basketNameFromId'],basketNameFromFile=tmp['basketNameFromFile'],basketId=tmp['basketId'])
1282:
1.22 dwinter 1283: def uploadATFfinally(self,procedure='',comment="",basketname='',unlock=None,repeat=None,RESPONSE=None):
1284: """nowupload the files"""
1285:
1286:
1287:
1288: threadName=repeat
1289: if not threadName or threadName=="":
1.24 dwinter 1290: thread=uploadATFfinallyThread()
1291: threadName=thread.getName()[0:]
1.36 dwinter 1292:
1.35 dwinter 1293: if (not hasattr(self,'_v_uploadATF')):
1.46 dwinter 1294: self._v_uploadATF={}
1.36 dwinter 1295:
1.43 dwinter 1296:
1.24 dwinter 1297: self._v_uploadATF[threadName]=thread
1.22 dwinter 1298:
1.60 dwinter 1299: idTmp=self.REQUEST.SESSION['idTmp']
1300: stObj=getattr(self.temp_folder,idTmp)
1301: 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 1302:
1.24 dwinter 1303: self._v_uploadATF[threadName].start()
1.22 dwinter 1304:
1305:
1.24 dwinter 1306:
1.22 dwinter 1307: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1308:
1309: if wait_template:
1310: return wait_template[0][1]()
1311: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1312:
1.24 dwinter 1313: return pt(txt='/uploadATFfinally',threadName=threadName)
1.22 dwinter 1314: #_v_xmltrans.run()
1315:
1316: else:
1317: #recover thread, if lost
1318: if not hasattr(self,'_v_uploadATF'):
1.24 dwinter 1319: self._v_uploadATF={}
1320: if not self._v_uploadATF.get(threadName,None):
1.22 dwinter 1321: for thread in threading.enumerate():
1322: if threadName == thread.getName():
1.24 dwinter 1323: self._v_uploadATF[threadName]=thread
1.22 dwinter 1324:
1.24 dwinter 1325: 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 1326:
1327: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1328: if wait_template:
1329: return wait_template[0][1]()
1330:
1331: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1.24 dwinter 1332: return pt(txt='/uploadATFfinally',threadName=threadName)
1.22 dwinter 1333: else:
1.85 dwinter 1334:
1335:
1336: idTmp=self.REQUEST.SESSION['idTmp']
1337: stObj=getattr(self.temp_folder,idTmp)
1.60 dwinter 1338: self.REQUEST.SESSION['idTmp']=None
1.85 dwinter 1339:
1340: #update changed
1341: logging.debug("dir:"+repr(stObj.returnValue['changed']))
1342: for x in stObj.returnValue['changed']:
1343: ob=self.CDLICatalog.search({'title':x[0]})
1.104 dwinter 1344: try:
1345: self.cdliRoot.updateOrAddToFileBTree(ob[0].getObject())
1346: except:
1347: logging.error("uploadATFfinally - cannot update Object %s Error: %s %s"%(ob[1],sys.exc_info()[0],sys.exc_info()[1]))
1.22 dwinter 1348: if RESPONSE is not None:
1349: RESPONSE.redirect(self.absolute_url())
1350:
1.49 dwinter 1351: def importFiles(self,comment="",author="" ,folderName="/Users/dwinter/atf", files=None,ext=None):
1.1 dwinter 1352: """import files"""
1.81 casties 1353: logging.debug("importFiles folderName=%s files=%s ext=%s"%(folderName,files,ext))
1.22 dwinter 1354: root=self.cdli_main
1.49 dwinter 1355: count=0
1.3 dwinter 1356: if not files:
1357: files=os.listdir(folderName)
1358:
1.1 dwinter 1359: for f in files:
1360: folder=f[0:3]
1361: f2=f[0:5]
1.85 dwinter 1362:
1363: #check if main folder PXX already exists
1.22 dwinter 1364: obj=self.ZopeFind(root,obj_ids=[folder])
1.81 casties 1365: logging.debug("importFiles: folder=%s f2=%s obj=%s"%(folder,f2,obj))
1.19 dwinter 1366: if ext:
1.65 dwinter 1367: ext.result="<p>adding: %s </p>"%f+ext.result
1.81 casties 1368:
1.85 dwinter 1369:
1370: if not obj: # if not create it
1.22 dwinter 1371: manage_addCDLIFileFolder(root,folder,folder)
1372: fobj=getattr(root,folder)
1.58 dwinter 1373: #transaction.get().commit()
1.81 casties 1374:
1.1 dwinter 1375: else:
1376: fobj=obj[0][1]
1377:
1.85 dwinter 1378: #check IF PYYYYY already exist
1.1 dwinter 1379: obj2=fobj.ZopeFind(fobj,obj_ids=[f2])
1.81 casties 1380: logging.debug("importFiles: fobj=%s obj2=%s"%(fobj,obj2))
1.1 dwinter 1381:
1.85 dwinter 1382: if not obj2:# if not create it
1.1 dwinter 1383: manage_addCDLIFileFolder(fobj,f2,f2)
1384: fobj2=getattr(fobj,f2)
1385:
1386: else:
1387: fobj2=obj2[0][1]
1388:
1.85 dwinter 1389: # not add the file
1.48 dwinter 1390: file2=os.path.join(folderName,f)
1.1 dwinter 1391: id=f
1.81 casties 1392: logging.debug("importFiles: addCDLIFile fobj2=%s, f=%s file2=%s"%(fobj2,repr(f),repr(file2)))
1393: fobj2.addFile(vC='',file=file(file2),author=author,newName=f)
1.66 dwinter 1394: count+=1
1.85 dwinter 1395:
1396: #now add the file to the storage
1397: ob = getattr(fobj2,f)
1398: self.cdliRoot.updateOrAddToFileBTree(ob)
1399:
1.81 casties 1400: if count%100==0:
1401: logging.debug("importfiles: committing")
1.66 dwinter 1402: transaction.get().commit()
1.81 casties 1403:
1404: transaction.get().commit()
1.3 dwinter 1405: return "ok"
1.22 dwinter 1406:
1407:
1408: manage_addCDLIRootForm=DTMLFile('dtml/rootAdd', globals())
1.1 dwinter 1409:
1410:
1.22 dwinter 1411: def manage_addCDLIRoot(self, id, title='',
1.1 dwinter 1412: createPublic=0,
1413: createUserF=0,
1414: REQUEST=None):
1415: """Add a new Folder object with id *id*.
1416:
1417: If the 'createPublic' and 'createUserF' parameters are set to any true
1418: value, an 'index_html' and a 'UserFolder' objects are created respectively
1419: in the new folder.
1420: """
1.22 dwinter 1421: ob=CDLIRoot()
1.1 dwinter 1422: ob.id=str(id)
1423: ob.title=title
1.61 dwinter 1424: try:
1.66 dwinter 1425: self._setObject(id, ob)
1.61 dwinter 1426: except:
1.66 dwinter 1427: pass
1.1 dwinter 1428: ob=self._getOb(id)
1429:
1430: checkPermission=getSecurityManager().checkPermission
1431:
1432: if createUserF:
1433: if not checkPermission('Add User Folders', ob):
1434: raise Unauthorized, (
1435: 'You are not authorized to add User Folders.'
1436: )
1437: ob.manage_addUserFolder()
1438:
1439:
1440: if REQUEST is not None:
1.22 dwinter 1441: return self.manage_main(self, REQUEST, update_menu=1)
1442:
1.105 dwinter 1443:
1444: import cdli_basket
1445:
1446:
1447: # Die folgenden Klassen sollte nicht mehr aus diesem Paket benutzt werden, sondern direkt aus
1448: # cdli_basket importiert werden.
1449: class uploadATFfinallyThread(cdli_basket.uploadATFfinallyThread):
1450: """depricates"""
1451: pass
1452:
1453: class tmpStore(cdli_basket.tmpStore):
1454: """depricated"""
1455: pass
1456:
1457: class uploadATFThread(cdli_basket.uploadATFThread):
1458: """depricated"""
1459: pass
1460:
1461: class CDLIBasketContainer(cdli_basket.CDLIBasketContainer):
1462: """depricated"""
1463: pass
1464:
1465: class CDLIBasket(cdli_basket.CDLIBasket):
1466: """depricated"""
1467: pass
1468:
1469: class CDLIBasketVersion(cdli_basket.CDLIBasketVersion):
1470: """depricated"""
1471: pass
1472:
1473: class BasketContent(cdli_basket.BasketContent):
1474: """depricated"""
1475: pass
1476:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>