1: """CDLI extensions of the filearchive"""
2: from Products.versionedFile.extVersionedFile import *
3: from Products.ZCatalog.CatalogPathAwareness import CatalogAware
4: from tempfile import mkstemp,mkdtemp
5: import os.path
6: import os
7: from types import *
8: import urlparse
9: import urllib
10: import cgi
11: from OFS.OrderedFolder import OrderedFolder
12: from OFS.SimpleItem import SimpleItem
13: import time
14: from OFS.Folder import manage_addFolder
15: import re
16: from AccessControl import ClassSecurityInfo
17: from Acquisition import Implicit
18: from Globals import Persistent
19: from threading import Thread
20: from ZPublisher.HTTPRequest import HTTPRequest
21: from ZPublisher.HTTPResponse import HTTPResponse
22: from ZPublisher.BaseRequest import RequestContainer
23: import threading
24: from BTrees.OOBTree import OOBTree, OOTreeSet
25: import logging
26: import transaction
27: import copy
28: import codecs
29: import sys
30: from BTrees.IOBTree import IOBTree
31: import cdliSplitter
32: from sets import Set
33: import md5
34: from DownloadBasket import DownloadBasketFinallyThread
35:
36: def makelist(mySet):
37: x = list(mySet)
38: x.sort()
39: return x
40:
41: def unicodify(s):
42: """decode str (utf-8 or latin-1 representation) into unicode object"""
43: if not s:
44: return u""
45: if isinstance(s, str):
46: try:
47: return s.decode('utf-8')
48: except:
49: return s.decode('latin-1')
50: else:
51: return s
52:
53: def utf8ify(s):
54: """encode unicode object or string into byte string in utf-8 representation.
55: assumes string objects to be utf-8"""
56: if not s:
57: return ""
58: if isinstance(s, str):
59: return s
60: else:
61: return s.encode('utf-8')
62:
63: def formatAtfHtml(l):
64: """escape special ATF characters for HTML"""
65: if not l:
66: return ""
67:
68: # replace &
69: l = l.replace('&','&')
70: # replace angular brackets
71: l = l.replace('<','<')
72: l = l.replace('>','>')
73: return l
74:
75: def formatAtfLineHtml(l, nolemma=True):
76: """format ATF line for HTML"""
77: if not l:
78: return ""
79:
80: if nolemma:
81: # ignore lemma lines
82: if l.lstrip().startswith('#lem:'):
83: return ""
84:
85: return formatAtfHtml(l)
86:
87:
88:
89: def formatAtfFullLineNum(txt, nolemma=True):
90: """format full line numbers in ATF text"""
91: # surface codes
92: surfaces = {'@obverse':'obv',
93: '@reverse':'rev',
94: '@surface':'surface',
95: '@edge':'edge',
96: '@left':'left',
97: '@right':'right',
98: '@top':'top',
99: '@bottom':'bottom',
100: '@face':'face',
101: '@seal':'seal'}
102:
103: if not txt:
104: return ""
105:
106: ret = []
107: surf = ""
108: col = ""
109: for line in txt.splitlines():
110: line = unicodify(line)
111: if line and line[0] == '@':
112: # surface or column
113: words = line.split(' ')
114: if words[0] in surfaces:
115: surf = line.replace(words[0],surfaces[words[0]]).strip()
116:
117: elif words[0] == '@column':
118: col = ' '.join(words[1:])
119:
120: elif line and line[0] in '123456789':
121: # ordinary line -> add line number
122: line = "%s:%s:%s"%(surf,col,line)
123:
124: ret.append(line)
125:
126: return '\n'.join(ret)
127:
128:
129: def generateXMLReturn(hash):
130: """erzeugt das xml file als returnwert fuer uploadATFRPC"""
131:
132: ret="<return>"
133:
134: ret+="<errors>"
135: for error in hash['errors']:
136: ret+="""<error atf="%s">%s</error>"""%error
137:
138: ret+="</errors>"
139:
140: ret+="<changes>"
141: for changed in hash['changed']:
142: ret+="""<change atf="%s">%s</change>"""%changed
143: ret+="</changes>"
144:
145: ret+="<newPs>"
146: for new in hash['newPs']:
147: ret+="""<new atf="%s"/>"""%new
148: ret+="</newPs>"
149:
150: ret+="</return>"
151: return ret
152:
153:
154: def unique(s):
155: """Return a list of the elements in s, but without duplicates.
156:
157: For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
158: unique("abcabc") some permutation of ["a", "b", "c"], and
159: unique(([1, 2], [2, 3], [1, 2])) some permutation of
160: [[2, 3], [1, 2]].
161:
162: For best speed, all sequence elements should be hashable. Then
163: unique() will usually work in linear time.
164:
165: If not possible, the sequence elements should enjoy a total
166: ordering, and if list(s).sort() doesn't raise TypeError it's
167: assumed that they do enjoy a total ordering. Then unique() will
168: usually work in O(N*log2(N)) time.
169:
170: If that's not possible either, the sequence elements must support
171: equality-testing. Then unique() will usually work in quadratic
172: time.
173: (from the python cookbook)
174: """
175:
176: n = len(s)
177: if n == 0:
178: return []
179:
180: # Try using a dict first, as that's the fastest and will usually
181: # work. If it doesn't work, it will usually fail quickly, so it
182: # usually doesn't cost much to *try* it. It requires that all the
183: # sequence elements be hashable, and support equality comparison.
184: u = {}
185: try:
186: for x in s:
187: u[x] = 1
188: except TypeError:
189: del u # move on to the next method
190: else:
191: return u.keys()
192:
193: # We can't hash all the elements. Second fastest is to sort,
194: # which brings the equal elements together; then duplicates are
195: # easy to weed out in a single pass.
196: # NOTE: Python's list.sort() was designed to be efficient in the
197: # presence of many duplicate elements. This isn't true of all
198: # sort functions in all languages or libraries, so this approach
199: # is more effective in Python than it may be elsewhere.
200: try:
201: t = list(s)
202: t.sort()
203: except TypeError:
204: del t # move on to the next method
205: else:
206: assert n > 0
207: last = t[0]
208: lasti = i = 1
209: while i < n:
210: if t[i] != last:
211: t[lasti] = last = t[i]
212: lasti += 1
213: i += 1
214: return t[:lasti]
215:
216: # Brute force is all that's left.
217: u = []
218: for x in s:
219: if x not in u:
220: u.append(x)
221: return u
222:
223:
224: class BasketContent(SimpleItem):
225: """classe fuer den Inhalt eines Baskets"""
226:
227: def __init__(self,content=[]):
228: """content"""
229: self.contentList=content[0:]
230:
231: def getContent(self):
232: """get content"""
233:
234: return self.contentList
235:
236: def setContent(self,content):
237: self.contentList=content[0:]
238:
239: def numberOfItems(self):
240: """number"""
241:
242: return len(self.getContent())
243:
244:
245: class uploadATFfinallyThread(Thread):
246: """class for adding uploaded filed (temporarily stored in the staging area at /tmp"""
247:
248: def __init__(self):
249: """init for uploadATFfinallyThread"""
250: self.continueVar=True
251: self.returnValue=None
252: self.end=False
253: Thread.__init__(self)
254:
255: def set(self,procedure,comment="",basketname='',unlock=None,SESSION=None,username=None,serverport="8080"):
256: """set start values for the thread"""
257: self.procedure=procedure
258: self.comment=comment
259: self.basketname=basketname
260: self.unlock=unlock
261: self.SESSION=SESSION
262: self.username=username
263: self.serverport=serverport
264:
265:
266: def __call__(self):
267: """call of the thread (equals run)"""
268: self.run()
269: return True
270:
271: def getContext(self, app,serverport="8080"):
272: """get the context within the ZODB"""
273:
274: resp = HTTPResponse(stdout=None)
275: env = {
276: 'SERVER_NAME':'localhost',
277: 'SERVER_PORT':serverport,
278: 'REQUEST_METHOD':'GET'
279: }
280: req = HTTPRequest(None, env, resp)
281: return app.__of__(RequestContainer(REQUEST = req))
282:
283:
284: def run(self):
285: """run"""
286:
287: self.result=""
288: #find context within ZODB
289: from Zope import DB
290: conn = DB.open()
291: root = conn.root()
292: app = root['Application']
293: ctx = self.getContext(app,serverport=self.serverport)
294:
295: #add the files
296: self.uploadATFfinallyThread(ctx,self.procedure,comment=self.comment,basketname=self.basketname,unlock=self.unlock,SESSION=self.SESSION,username=self.username)
297: #commit the transactions
298: transaction.get().commit()
299: conn.close()
300: #set flag for end of this method
301: self.end=True
302: logging.info("ended")
303: return True
304:
305: def __del__(self):
306: """delete"""
307:
308:
309:
310: def getResult(self):
311: """method for accessing result"""
312:
313: return self.result
314:
315: def uploadATFfinallyThread(self,ctx,procedure,comment="",basketname='',unlock=None,RESPONSE=None,SESSION=None,username=None):
316: """upload the files"""
317: #TODO: make this configurable, at the moment, rootFolder for cdli has to be cdliRoot
318: ctx2=ctx.cdliRoot
319:
320: self.result+="<h2>Start processing</h2>"
321:
322: #shall I only upload the changed files?
323: logging.debug("uploadATFfinally procedure: %s"%procedure)
324: if procedure=="uploadchanged":
325: changed=[x[0] for x in SESSION.get('changed',[])]
326: uploadFns=changed+SESSION.get('newPs',[])
327:
328: #or all
329: elif procedure=="uploadAll":
330: uploadFns=[]
331: for x in os.listdir(SESSION['tmpdir']):
332: if not x in SESSION['lockerrors']:
333: uploadFns.append(x)
334:
335: #or maybe nothing
336: elif procedure=="noupload":
337: return True
338: else:
339: uploadFns=[]
340:
341: #do first the changed files
342: i=0
343: for fn in uploadFns:
344: logging.debug("uploadATFfinally uploadFn=%s"%fn)
345: i+=1
346: founds=ctx2.CDLICatalog.search({'title':fn})
347: if len(founds)>0:
348: SESSION['author']=str(username)
349: self.result="<p>Changing : %s"%fn+self.result
350: logging.debug("uploadatffinallythread changing:%s"%fn+self.result)
351: founds[0].getObject().manage_addCDLIFileObject('',comment,SESSION['author'],file=os.path.join(SESSION['tmpdir'],fn),from_tmp=True)
352: if i%200==0:
353: transaction.get().commit()
354: logging.debug("uploadatffinallythread changing: do commit")
355:
356: transaction.get().commit()
357: logging.debug("uploadatffinallythread changing: last commit")
358:
359: #now add the new files
360: newPs=SESSION['newPs']
361: if len(newPs)>0:
362: tmpDir=SESSION['tmpdir']
363: logging.debug("uploadatffinallythread adding start")
364: self.result="<p>Adding files</p>"+self.result
365: #TODO: make this configurable, at the moment base folder for the files has to be cdli_main
366: ctx2.importFiles(comment=comment,author=str(username) ,folderName=tmpDir, files=newPs,ext=self)
367: logging.debug("uploadatffinallythread adding finished")
368:
369: #unlock locked files?
370: if unlock:
371: logging.debug("uploadatffinallythread unlocking start")
372: self.result="<p>Unlock files</p>"+self.result
373: unlockFns=[]
374: for x in os.listdir(SESSION['tmpdir']):
375: if not x in SESSION['errors']:
376: unlockFns.append(x)
377:
378: logging.debug("unlocking have now what to unlock")
379:
380: for fn in unlockFns:
381: #logging.info("will unlock: %s"%fn)
382: founds=ctx2.CDLICatalog.search({'title':fn})
383: #logging.info("found it: %s"%repr(founds))
384: if len(founds)>0:
385: #logging.info("unlock: %s"%founds[0].getObject().getId())
386: SESSION['author']=str(username)
387: founds[0].getObject().lockedBy=""
388:
389: logging.debug("uploadatffinallythread unlocking done")
390:
391: #if a basketname is given, add files to the basket
392: if not (basketname ==''):
393: logging.debug("uploadatffinallythread add to basket %s"%basketname)
394: self.result="<p>Add to basket</p>"+self.result
395: basketId=ctx2.basketContainer.getBasketIdfromName(basketname)
396:
397: if not basketId: # create new basket
398: logging.debug("uploadatffinallythread create basket %s"%basketname)
399: self.result="<p>Create a new basket</p>"+self.result
400: ob=ctx2.basketContainer.addBasket(basketname)
401: basketId=ob.getId()
402: basket=getattr(ctx2.basketContainer,str(basketId))
403: ids=os.listdir(SESSION['tmpdir'])
404: #logging.debug("should add:"+repr(ids))
405: basket.addObjects(ids,deleteOld=True,username=str(username))
406:
407: logging.debug("uploadatffinallythread uploadfinally done")
408:
409: if RESPONSE is not None:
410: RESPONSE.redirect(self.aq_parent.absolute_url())
411:
412: return True
413:
414: class tmpStore(SimpleItem):
415: """simple item"""
416: meta_type="cdli_upload"
417:
418: def __init__(self,id):
419: """init tmp"""
420: self.id=id
421:
422: class uploadATFThread(Thread):
423: """class for checking the files befor uploading"""
424:
425: def __init__(self):
426: """initialise"""
427:
428: self.continueVar=True
429: self.returnValue=None
430:
431: Thread.__init__(self)
432:
433:
434: def set(self,upload,basketId,username,idTmp,serverport="8080"):
435: """set start values for the thread"""
436: self.result=""
437: self.upload=upload
438: self.basketId=basketId
439: self.username=username
440: self.serverport=serverport
441: self.idTmp=idTmp
442:
443: def __call__(self):
444: """call method """
445: self.run()
446: return True
447:
448: def getContext(self, app,serverport="8080"):
449: """get the context within the ZODB"""
450: resp = HTTPResponse(stdout=None)
451: env = {
452: 'SERVER_NAME':'localhost',
453: 'SERVER_PORT':serverport,
454: 'REQUEST_METHOD':'GET'
455: }
456: req = HTTPRequest(None, env, resp)
457: return app.__of__(RequestContainer(REQUEST = req))
458:
459: def run(self):
460: idTmp=self.idTmp
461: self.result=""
462: #find context within ZODB
463: from Zope import DB
464: conn = DB.open()
465: root = conn.root()
466: app = root['Application']
467: ctx = self.getContext(app,serverport=self.serverport)
468: logging.info("run intern")
469: try:
470: logging.info("created: %s"%idTmp)
471: ctx.temp_folder._setObject(idTmp,tmpStore(idTmp))
472: except:
473: logging.error("thread upload: %s %s"%sys.exc_info()[0:2])
474:
475: logging.info("call thread intern")
476: self.uploadATFThread(ctx,self.upload,idTmp,self.basketId)
477:
478: #ctx.cdliRoot.cdli_main.tmpStore2[self.getName()[0:]]=self.returnValue
479:
480:
481: transaction.get().commit()
482:
483: conn.close()
484:
485: return getattr(ctx.temp_folder,idTmp)
486:
487: def getResult(self):
488: """method for accessing result"""
489: return self.result
490:
491: def uploadATFThread(self,ctx,upload,idTmp,basketId=0):
492: """upload an atf file"""
493: #TODO: add comments
494: #TODO: finish uploadATF
495:
496: stObj=getattr(ctx.temp_folder,idTmp)
497: logging.info("start, upload thread")
498: self.result="<html><body><h2>I got your file, start now to split it into single atf-files!</h2><p>"
499:
500: #make sure that id is a string and not an integer
501: basketId=str(basketId)
502:
503: #TODO: make this configurable, at the moment, rootFolder for cdli has to be cdliRoot
504: ctx2=ctx.cdliRoot
505:
506: #get temporary file for staging the downloaded and splitted files
507: dir=mkdtemp()
508:
509:
510: changed=[] # changed files
511: errors=[] # files with errors
512: lockerrors=[] # files with errors
513:
514: newPs=[] # new p filed
515: psNotInCatalog=[] # files not in the catalog
516:
517: #split the uploadedd atf file
518: basketNameFromFile, numberOfFiles=splitatf(upload,dir,ext=self)
519:
520: #find basketId if not set
521:
522: #get active abaket
523: if basketId == '0':
524: basketObj=ctx2.basketContainer.getActiveBasket()
525: if basketObj:
526: basketId=basketObj.getId()
527:
528: #if there is no active basket and no basketid given, id is empty, else get besketname and length
529: if basketId == '0':
530: basketNameFromId=""
531: basketLen=0
532: else:
533: basketNameFromId=getattr(ctx2.basketContainer,basketId).title
534: basketLen=getattr(ctx2.basketContainer,basketId).getLastVersion().numberOfItems()
535:
536: logging.info("got the file, upload thread")
537: self.result+="""<html><body><h2>I got the files</h2><
538: p>I am computing the differences to the exisiting files</p>"""
539:
540: #start to check the files
541: for fn in os.listdir(dir):
542:
543: self.result="<p>process:%s</p>"%fn+self.result
544:
545: # check if file is in the catalog
546: #TODO: checkCatalog is not implemented yet
547: if ctx2.cdli_main.checkCatalog(fn):
548: psNotInCatalog.append(fn)
549:
550: #check if p-file already at the server
551: founds=ctx2.CDLICatalog.search({'title':fn})
552:
553: #if not than add filename to the list of newfiles
554:
555: data=file(os.path.join(dir,fn)).read()
556: status,msg=checkFile(fn,data,dir)
557: #status=True
558:
559:
560: if not status: # error
561: errors.append((fn,msg))
562:
563: else:
564: if len(founds)==0:
565: newPs.append(fn)
566:
567: #if p file alread at the server
568: for found in founds:
569: #analyse the differences to the actual file
570: obj=found.getObject()
571:
572: if (not (str(obj.lockedBy))=='') and (not (str(obj.lockedBy)==str(self.username))):
573: lockerrors.append((fn,str(obj.lockedBy)))
574: else:
575:
576: diffs=obj.diff(data)
577: if diffs[0]>0:
578: changed.append((obj,diffs)) #hochladen
579:
580: #ready, set the returnValues
581: self.result+="<h3>Done</h3></body></html>"
582:
583: stObj.returnValue={}
584:
585: stObj.returnValue['errors']=errors
586:
587: stObj.returnValue['newPs']=newPs
588: stObj.returnValue['tmpdir']=dir
589: stObj.returnValue['basketLen']=basketLen
590: stObj.returnValue['numberOfFiles']=numberOfFiles
591: stObj.returnValue['basketNameFromId']=basketNameFromId
592: stObj.returnValue['basketNameFromFile']=basketNameFromFile
593: stObj.returnValue['basketId']=basketId
594: stObj.returnValue['dir']=dir
595: #stObj.returnValue['changed']=copy.copy(changed)
596: stObj.returnValue['changed']=[(x[0].getId(),x[1][0]) for x in changed]
597: #stObj.returnValue['lockerrors']=[x[0].getId() for x in lockerrors]
598: stObj.returnValue['lockerrors']=[x for x in lockerrors]
599: self.returnValue=True
600: #ctx2.cdli_main.setTemp('v_uploadATF_returnValue',True)
601:
602:
603: class CDLIBasketContainer(OrderedFolder):
604: """contains the baskets"""
605:
606:
607: security=ClassSecurityInfo()
608: meta_type="CDLIBasketContainer"
609:
610: def getPNumbersOfBasket(self,basketName):
611: """get all pnumbers of a basket as a list, returns an empty list if basket not found
612: @param basketName: name of the basket
613: """
614: ret=[]
615: basketId=self.getBasketIdfromName(basketName)
616: if not basketId:
617: return []
618:
619: ob=getattr(self,basketId).getContent()
620:
621: ret=[x[0].split(".")[0] for x in ob]
622:
623: return ret
624:
625: security.declareProtected('manage','getBasketAsOneFile')
626: def getBasketAsOneFile(self,basketName,current="no"):
627: """returns all files of the basket combined in one file
628: @param basketName: Name of the basket
629: @param current: (optional) if current is set to "yes" then the most current version of
630: all files are downloaded and not the versions of the files as stored in the basket
631: """
632: ret=""
633: basketId=self.getBasketIdfromName(basketName)
634: if not basketId:
635: return ""
636:
637: ob=getattr(self,basketId).getLastVersion()
638: for object in ob.getContent():
639: if current=="no": #version as they are in the basket
640: ret+=str(object[0].getData())+"\n"
641: elif current=="yes":
642: #search current object
643: #logging.debug("current: %s"%object[1].getId().split(".")[0])
644: founds=self.CDLICatalog.search({'title':object[1].getId().split(".")[0]})
645: if len(founds)>0:
646: ret+=str(founds[0].getObject().getLastVersion().getData())+"\n"
647: return ret
648:
649: security.declareProtected('manage','upDateBaskets')
650: def upDateBaskets(self):
651: """update content in to objects"""
652:
653: founds=self.ZopeFind(self,obj_metatypes=['CDLIBasketVersion'],search_sub=1)
654:
655: for found in founds:
656: found[1].updateBasket()
657:
658: security.declareProtected('manage','deleteBaskets')
659: def deleteBaskets(self,ids=None):
660: """delete baskets, i.e. move them into trash folder"""
661:
662:
663: found=self.ZopeFind(self,obj_ids=['trash'])
664:
665: if len(found)<1:
666: manage_addFolder(self, 'trash')
667: trash=self._getOb('trash')
668: else:
669: trash=found[0][1]
670:
671: if type(ids) is not ListType:
672: ids=[ids]
673: cut=self.manage_cutObjects(ids)
674: trash.manage_pasteObjects(cut)
675:
676: security.declareProtected('manage','manageBaskets')
677: def manageBaskets(self,submit,ids=None,basket1="",basket2="",joinBasket="",subtractBasket="",REQUEST=None,RESPONSE=None):
678: """manage baskets, delete or copy"""
679: if submit=="delete":
680: self.deleteBaskets(ids)
681:
682: elif submit=="join":
683: flag,msg=self.joinBasket(joinBasket, ids)
684: logging.info("joining %s %s"%(flag,msg))
685:
686: elif submit=="subtract":
687: logging.info("BBBb %s %s"%(basket1,basket2))
688: flag,msg=self.subtractBasket(subtractBasket, basket1,basket2)
689: logging.info("subtract %s %s"%(flag,msg))
690:
691: if RESPONSE:
692: RESPONSE.redirect(self.absolute_url())
693:
694: security.declareProtected('View','getBasketIdfromName')
695: def getBasketIdfromName(self,basketname):
696: """get id from name"""
697:
698: for basket in self.ZopeFind(self,obj_metatypes=["CDLIBasket"]):
699: if basket[1].title==basketname:
700: return basket[0]
701: else:
702: None
703:
704: security.declareProtected('manage','uploadBasket_html')
705:
706: def uploadBasket_html(self,basketId='0'):
707: """upload an atf file, html form"""
708:
709:
710: basketId=str(basketId)
711: if not basketId=='0':
712: basketName=getattr(self.basketContainer,basketId).title
713: else:
714: basketName=""
715:
716: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadBasket_html.zpt')).__of__(self)
717: return pt(basketId=basketId,basketName=basketName)
718:
719:
720: security.declareProtected('manage','index_html')
721: def index_html(self):
722: """stanadard ansicht"""
723:
724:
725:
726: ext=self.ZopeFind(self,obj_ids=["index.html"])
727: if ext:
728: return ext[0][1]()
729:
730: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','BasketContainerMain')).__of__(self)
731: return pt()
732:
733: def getStorageFolderRoot(self):
734: """root des storage folders"""
735: return self.cdli_main
736:
737: def __init__(self,id,title):
738: """ init basket container"""
739: self.id=id
740: self.title=title
741:
742:
743: def getBasketsId(self):
744: """get all baskets als klartext"""
745:
746: ret=""
747: baskets=self.ZopeFind(self,obj_metatypes=['CDLIBasket'])
748: for basket in baskets:
749: com,user,time,values = basket[1].getContentIds()
750: ret+= "BASKET:"+com+"\t"+user+"\t"+time+"\n"
751: for x in values:
752: ret+= x[0]+"\t"+x[1]+"\n"
753: return ret
754:
755: def getBaskets(self,sortField='title'):
756: """get all baskets files"""
757:
758: def sortName(x,y):
759: return cmp(x[1].title.lower(),y[1].title.lower())
760:
761: def sortDate(x,y):
762: return cmp(y[1].getLastVersion().getTime(),x[1].getLastVersion().getTime())
763:
764:
765: def sortComment(x,y):
766:
767:
768:
769: try:
770: xc=getattr(x[1],'comment','ZZZZZZZZZZZZZ').lower()
771: except:
772: xc='ZZZZZZZZZZZZZ'.lower()
773: try:
774: yc=getattr(y[1],'comment','ZZZZZZZZZZZZZ').lower()
775: except:
776: yc='ZZZZZZZZZZZZZ'.lower()
777:
778:
779: if (xc=='') or (xc=='ZZZZZZZZZZZZZ'.lower()):
780:
781: try:
782: xc=x[1].getLastVersion().getComment().lower()
783: except:
784: xc='ZZZZZZZZZZZZZ'.lower()
785:
786: if (yc=='') or (yc=='ZZZZZZZZZZZZZ'.lower()):
787: try:
788: yc=y[1].getLastVersion().getComment().lower()
789: except:
790: yc='ZZZZZZZZZZZZZ'.lower()
791:
792:
793: return cmp(xc,yc)
794:
795: def sortAuthor(x,y):
796:
797: return cmp(x[1].getLastVersion().getUser().lower(),y[1].getLastVersion().getUser().lower())
798:
799: baskets=self.ZopeFind(self,obj_metatypes=['CDLIBasket'])
800:
801:
802: if sortField=='title':
803: baskets.sort(sortName)
804: elif sortField=='date':
805: baskets.sort(sortDate)
806: elif sortField=='author':
807: baskets.sort(sortAuthor)
808: elif sortField=='comment':
809: baskets.sort(sortComment)
810:
811: return baskets
812:
813:
814: def subtractBasket(self,newBasket,basket1,basket2):
815: """subtract basket2 from basket1
816: (i.e. newbasket will contain alle elements of basket1 which are not in basket2),
817: if basket2 contains files which are not in basket1, then theses files fill be ignored
818:
819: @param newbasket: name of the new basket
820: @param basket1: basket where basket2 will be subtracted from
821: @param basket2: see above
822:
823: """
824: logging.info("CCCCC %s %s"%(basket1,basket2))
825:
826: try:
827: newB=self.addBasket(newBasket)
828: except:
829: return False, "cannot create the new basket"
830:
831:
832:
833:
834:
835: bas2= getattr(self,basket2)
836: bas2content=bas2.getContent()
837: bas2ids=[x[0] for x in bas2content]
838:
839:
840:
841: bas1= getattr(self,basket1)
842: bas1content=bas1.getContent()
843:
844:
845: newBasketContent={}
846:
847: for id,version in bas1content:
848: if not (id in bas2ids):
849: newBasketContent[id]=version
850:
851: username=self.getActualUserName()
852:
853: logging.info("sbc %s"%newBasketContent)
854: newB.addObjectsWithVersion(newBasketContent,username=username,catalog=self.CDLICatalog)
855:
856: return True, ""
857:
858:
859: def joinBasket(self,newBasket,oldBaskets):
860: """join two baskets
861: @param newbasket: name of the new basket
862: @param oldbaskets: list of baskets to be joined
863: """
864: try:
865: newB=self.addBasket(newBasket)
866: except:
867: return False, "cannot create the new basket"
868:
869: newBasketContent={}
870: for ob in oldBaskets:
871: x= getattr(self,ob,None)
872: if x is None:
873: return False, "cannot find basket: %s"%ob
874:
875: ids=x.getContent() # hole den Inhalt
876:
877: for id,version in ids:
878: if newBasketContent.has_key(id): # p number gibt's schon
879: newBasketContent[id]=max(newBasketContent[id],version) # speichere die groessere Versionsnumber
880: else:
881: newBasketContent[id]=version
882: username=self.getActualUserName()
883:
884: logging.info("nbc %s"%newBasketContent)
885: newB.addObjectsWithVersion(newBasketContent,username=username,catalog=self.CDLICatalog)
886:
887: return True, ""
888:
889: def getNewId(self):
890: """createIds"""
891: last=getattr(self,'last',0)
892: last +=1
893: while len(self.ZopeFind(self,obj_ids=[str(last)]))>0:
894: last+=1
895:
896: self.last=last
897: return last
898:
899: def setActiveBasket(self,basketId,REQUEST=None):
900: """store active basketId in a cookie"""
901: self.REQUEST.RESPONSE.setCookie("CDLIActiveBasket",basketId,path="/")
902: try:
903: qs=cgi.parse_qs(REQUEST['QUERY_STRING'])
904: del(qs['basketId'])
905: except:
906: qs={}
907: if REQUEST:
908: REQUEST.RESPONSE.redirect(REQUEST['URL1']+'?'+urllib.urlencode(qs))
909:
910: def getActiveBasket(self):
911: """get active basket from cookie"""
912:
913: id= self.REQUEST.cookies.get('CDLIActiveBasket',None)
914: if id:
915: obj=getattr(self,str(id),None)
916: else:
917: obj=None
918: return obj
919:
920: def getActualUserName(self):
921: """get name of the actualuser"""
922: return str(self.REQUEST['AUTHENTICATED_USER'])
923:
924: security.declareProtected('manage','addBasket')
925: def addBasket(self,newBasketName):
926: """add a new basket"""
927:
928: ob=manage_addCDLIBasket(self,newBasketName)
929: return ob
930:
931: def storeInBasket(self,submit,ids=None,newBasketName=None,fromFileList=None,RESPONSE=None,REQUEST=None):
932: """store it"""
933: if not ids:
934: ids=self.REQUEST.SESSION['fileIds']
935:
936: if (type(ids) is not ListType) and (not isinstance(ids,Set)):
937: ids=[ids]
938:
939: if isinstance(ids,Set):
940: ids=list(ids)
941:
942: if (submit.lower()=="store in new basket") or (submit.lower()=="new basket"):
943: basketRet=self.addBasket(newBasketName)
944: self.setActiveBasket(basketRet.getId())
945: basket=getattr(self,basketRet.getId())
946: elif (submit.lower()=="store in active basket") or (submit.lower()=="active basket"):
947: basket=self.getActiveBasket()
948:
949: added=basket.addObjects(ids)
950: back=self.REQUEST['HTTP_REFERER'].split("?")[0]+"?basketName="+basket.title+"&numberOfObjects="+str(added)
951:
952:
953: if fromFileList:
954:
955: return self.cdli_main.findObjectsFromList(list=ids,basketName=basket.title,numberOfObjects=added)
956:
957: if RESPONSE:
958:
959: RESPONSE.redirect(back)
960:
961: return True
962:
963: def manage_addCDLIBasketContainerForm(self):
964: """add the CDLIBasketContainer form"""
965: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addCDLIBasketContainer.zpt')).__of__(self)
966: return pt()
967:
968: def manage_addCDLIBasketContainer(self,id,title,RESPONSE=None):
969: """add the basket"""
970: ob=CDLIBasketContainer(id,title)
971:
972: self._setObject(id, ob)
973:
974: if RESPONSE is not None:
975: RESPONSE.redirect('manage_main')
976:
977: class CDLIBasket(Folder,CatalogAware):
978: """basket"""
979:
980: meta_type="CDLIBasket"
981: default_catalog="CDLIBasketCatalog"
982:
983: def searchInBasket(self,indexName,searchStr,regExp=False):
984: """searchInBasket"""
985:
986: lst=self.searchInLineIndexDocs(indexName,searchStr,uniq=True,regExp=regExp) #TODO: fix this
987: ret={}
988:
989: lv=self.getLastVersion()
990:
991:
992: for obj in lv.content.getContent():
993: id=obj[1].getId().split(".")[0]
994: if id in lst:
995:
996: ret[id]=self.showWordInFile(id,searchStr,lineList=self.getLinesFromIndex(indexName,searchStr,id,regExp=regExp),regExp=regExp,indexName=indexName)
997:
998:
999: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','searchResultsInBasket')).__of__(self)
1000: return pt(result=ret,indexName=indexName,regExp=regExp,word=searchStr)
1001:
1002:
1003:
1004:
1005: def searchInBasket_v1(self,searchStr):
1006: """search occurences of searchStr in files im basket"""
1007: ret=[]
1008: lv=self.getLastVersion()
1009: logging.info("searching")
1010: for obj in lv.content.getContent():
1011: txt=obj[0].getData()
1012: for x in txt.split("\n"):
1013: logging.info("search %s"%x)
1014: if re.match(searchStr,x):
1015: ret.append(x)
1016:
1017: return "\n".join(ret)
1018:
1019:
1020: def getFile(self,obj):
1021: return obj[1]
1022:
1023: def getFileLastVersion(self,obj):
1024: return obj[0]
1025:
1026: def getFileNamesInLastVersion(self):
1027: """get content of the last version as list"""
1028:
1029: return [x[1].getId() for x in self.getLastVersion().getContent()]
1030:
1031:
1032: def isActual(self,obj):
1033: """teste ob im basket die aktuelle version ist"""
1034: try:
1035: #logging.debug("isActual:"+repr(obj))
1036: actualNo=obj[1].getLastVersion().getVersionNumber()
1037: storedNo=obj[0].getVersionNumber()
1038:
1039:
1040: #actualNo=self.getFileObjectLastVersion(obj.getId()).getVersionNumber()
1041:
1042: #if len(founds)>0 and founds[0].getObject().aq_parent.getId()==".trash":
1043: # return False, -1
1044:
1045: if actualNo==storedNo:
1046: return True , 0
1047: else:
1048: return False, actualNo
1049: except:
1050: logging.error( """is actual: %s (%s %s)"""%(repr(obj),sys.exc_info()[0],sys.exc_info()[1]))
1051:
1052: return False, -1
1053:
1054: def history(self):
1055: """history"""
1056:
1057: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
1058: if ext:
1059: return getattr(self,ext[0][1].getId())()
1060:
1061: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','BasketHistory')).__of__(self)
1062: return pt()
1063:
1064: def getStorageFolderRoot(self):
1065: """root des storage folders"""
1066: return self.aq_parent.cdli_main
1067:
1068: def __init__(self,id,title,shortDescription="",comment=""):
1069: """init a CDLIBasket"""
1070:
1071: self.id=id
1072: self.title=title
1073: self.shortDescription=shortDescription
1074: self.comment=comment
1075:
1076: def getActualUserName(self):
1077: """get name of the actualuser"""
1078:
1079: return str(self.REQUEST['AUTHENTICATED_USER'])
1080:
1081:
1082: def getLastVersion(self):
1083: """hole letzte version"""
1084:
1085: ids=[]
1086: idsTmp= self.objectIds()
1087: for x in idsTmp:
1088: try:
1089: ids.append(int(x))
1090: except:
1091: pass
1092: ids.sort()
1093:
1094: if len(ids)==0:
1095: return None
1096: else:
1097: ob=getattr(self,str(ids[-1]))
1098:
1099:
1100: return ob
1101:
1102: def getVersions(self):
1103: """get versions"""
1104: versions=self.ZopeFind(self,obj_metatypes=["CDLIBasketVersion"])
1105: return versions
1106:
1107:
1108: def updateObjects(self,ids,RESPONSE=None,REQUEST=None):
1109: """update ids, ids not in the basket the add"""
1110: if type(ids) is not ListType:
1111: ids=[ids]
1112:
1113: lastVersion=self.getLastVersion()
1114: oldContent=lastVersion.content.getContent()
1115: newContent=[]
1116:
1117: #first copy the old
1118: for obj in oldContent:
1119: if obj[1].getId() not in ids:
1120: newContent.append(obj)
1121: #now add the new
1122:
1123: for id in ids:
1124: founds=self.CDLICatalog.search({'title':id})
1125:
1126: for found in founds:
1127: if found.getObject() not in oldContent:
1128: #TODO: was passiert wenn, man eine Object dazufŸgt, das schon da ist aber eine neuere version
1129: newContent.append((found.getObject().getLastVersion(),found.getObject()))
1130:
1131:
1132: content=newContent
1133: user=self.getActualUserName()
1134:
1135: ob=manage_addCDLIBasketVersion(self,user,comment="",basketContent=newContent)
1136:
1137: obj=self._getOb(ob.getId())
1138: if RESPONSE:
1139:
1140: RESPONSE.redirect(obj.absolute_url())
1141:
1142: return obj
1143:
1144: def addObjectsWithVersion(self,ids,deleteOld=None,username=None,catalog=None):
1145: """generate a new version of the basket with objects added,
1146: hier wird jedoch nicht die letzte Version jedes Files hinzugefuegt, s
1147: ondern ids is ein Tupel mit der Id (d.h. der p-number) und der Versionsnummer.
1148: """
1149: logging.info("add to basket (%s)"%(self.getId()))
1150: lastVersion=self.getLastVersion()
1151:
1152: if not catalog:
1153: catalog=self.CDLICatalog
1154:
1155: if lastVersion is None:
1156: oldContent=[]
1157: else:
1158: oldContent=lastVersion.content.getContent()
1159:
1160: if deleteOld:
1161: oldContent=[]
1162:
1163: newContent=[]
1164: added=0
1165:
1166: for id,version in ids.iteritems():
1167: logging.info("adding %s %s"%(id,version))
1168: id=id.split(".")[0] # title nur die pnumber ohne atf
1169:
1170: try:
1171: founds=catalog.search({'title':id})
1172: except:
1173: founds=[]
1174: logging.info(" found %s "%(founds))
1175: for found in founds:
1176: if found.getObject() not in oldContent:
1177:
1178: #TODO: was passiert wenn, man eine Object dazufŸgt, das schon da ist aber eine neuere version
1179: newContent.append((found.getObject().getVersions()[version-1][1],found.getObject()))
1180: added+=1
1181:
1182: content=oldContent+newContent
1183: if not username:
1184: logging.error("XXXXXXXXXXX %s"%repr(self))
1185: user=self.getActualUserName()
1186: else:
1187: user = username
1188:
1189: ob=manage_addCDLIBasketVersion(self,user,comment="",basketContent=content)
1190: logging.info("add to basket (%s) done"%(self.getId()))
1191: return added
1192:
1193:
1194: def addObjects(self,ids,deleteOld=None,username=None):
1195: """generate a new version of the basket with objects added"""
1196:
1197: def swap(x):
1198: return (x[1],x[0])
1199:
1200: logging.info("add to basket (%s)"%(self.getId()))
1201: lastVersion=self.getLastVersion()
1202:
1203: if lastVersion is None:
1204: oldContent=[]
1205: else:
1206: oldContent=lastVersion.content.getContent()
1207:
1208: if deleteOld:
1209: oldContent=[]
1210:
1211: added=0
1212: # for id in ids:
1213: # logging.debug("adding:"+id)
1214: # try:
1215: # founds=self.CDLICatalog.search({'title':id})
1216: # except:
1217: # founds=[]
1218: #
1219: # for found in founds:
1220: # if found.getObject() not in oldContent:
1221: # #TODO: was passiert wenn, man eine Object dazufŸgt, das schon da ist aber eine neuere version
1222: # newContent.append((found.getObject().getLastVersion(),found.getObject()))
1223: # added+=1
1224:
1225: hash = md5.new(repr(makelist(ids))).hexdigest() # erzeuge hash als identification
1226: #logging.debug("JJJJJJJ:"+repr(self.makelist(ids)))
1227:
1228:
1229: if hasattr(self.cdliRoot,'v_tmpStore') and self.cdliRoot.v_tmpStore.has_key("hash"): #TODO: muss eigentlich self.cdliRoot.v_tmpStore.has_key(hash): heissen (ohne "), erstmal so gesetzt damit der hash hier nie benutzt wird
1230: logging.debug("from store!")
1231: newContent=Set(map(swap,self.cdliRoot.v_tmpStore[hash]))
1232:
1233: else:
1234: logging.debug("not from store!")
1235: newContent=Set([(self.getFileObjectLastVersion(x),self.getFileObject(x)) for x in ids])
1236:
1237:
1238: content=Set(oldContent).union(newContent)
1239: added = len(content)-len(oldContent)
1240: if not username:
1241: user=self.getActualUserName()
1242: else:
1243: user = username
1244:
1245: #logging.debug("content:"+repr(list(content)))
1246: ob=manage_addCDLIBasketVersion(self,user,comment="",basketContent=list(content))
1247: logging.info("add to basket (%s) done"%(self.getId()))
1248: return added
1249:
1250:
1251:
1252: def getContent(self):
1253: """print content"""
1254: ret=[]
1255:
1256: lv=self.getLastVersion()
1257: for obj in lv.content.getContent():
1258: #logging.info("XXXXXXXXXX %s"%repr(obj))
1259: ret.append((obj[1].getId(),obj[0].versionNumber))
1260:
1261: return ret
1262:
1263: def getContentIds(self):
1264: """print basket content"""
1265: ret=[]
1266: lv=self.getLastVersion()
1267: for obj in lv.content.getContent():
1268: ret.append((obj[0].getId(),obj[1].getId()))
1269:
1270:
1271: return lv.getComment(),lv.getUser(),lv.getTime(),ret
1272:
1273: def changeBasket(self,ids,submit,RESPONSE=None,REQUEST=None):
1274: """change a basket"""
1275: if submit=="update":
1276: return self.updateObjects(ids,RESPONSE=RESPONSE,REQUEST=REQUEST)
1277: elif submit=="delete":
1278: return self.deleteObjects(ids,RESPONSE=RESPONSE,REQUEST=REQUEST)
1279:
1280: def deleteObjects(self,ids,RESPONSE=None,REQUEST=None):
1281: """delete objects"""
1282:
1283: if type(ids) is not ListType:
1284: ids=[ids]
1285:
1286: lastVersion=self.getLastVersion()
1287: oldContent=lastVersion.content.getContent()
1288: newContent=[]
1289: for obj in oldContent:
1290: if obj[1].getId() not in ids:
1291: newContent.append(obj)
1292:
1293:
1294: user=self.getActualUserName()
1295:
1296: ob=manage_addCDLIBasketVersion(self,user,comment="",basketContent=newContent)
1297:
1298: if RESPONSE:
1299: obj=self._getOb(ob.getId())
1300: RESPONSE.redirect(obj.absolute_url())
1301:
1302: def manage_addCDLIBasketForm(self):
1303: """add the CDLIBasketContainer form"""
1304: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addCDLIBasket.zpt')).__of__(self)
1305: return pt()
1306:
1307: def manage_addCDLIBasket(self,title,shortDescription="",comment="",RESPONSE=None):
1308: """add the basket"""
1309:
1310: id=str(self.getNewId())
1311:
1312: ob=CDLIBasket(id,title,shortDescription,comment)
1313:
1314: self._setObject(id, ob)
1315:
1316: if RESPONSE is not None:
1317: RESPONSE.redirect('manage_main')
1318: else:
1319: return ob
1320:
1321: class CDLIBasketVersion(Implicit,Persistent,Folder):
1322: """version of a basket"""
1323:
1324: meta_type="CDLIBasketVersion"
1325: security=ClassSecurityInfo()
1326:
1327: def updateBasket(self):
1328: """update"""
1329: try:
1330: self._setObject('content',BasketContent(self.basketContent))
1331: except:
1332: try:
1333: if len(self.basketContent)>0:
1334: self.content.setContent(self.basketContent)
1335: except:
1336: print "error",self.getId(),self.aq_parent.getId()
1337: self.basketContent=[]
1338:
1339:
1340: def containsNonActualFiles(self):
1341: """returns True if basket contains one or more non current files"""
1342:
1343: objs=self.getContent()
1344: for obj in objs:
1345: if not self.isActual(obj)[0]:
1346: return True
1347: return False
1348:
1349: def downloadListOfPnumbers(self):
1350: """download pnumbers of the basket as list"""
1351:
1352: basket_name=self.aq_parent.title
1353:
1354: ids=self.getContent() # get the list of objects
1355: logging.error(ids)
1356: ret="\n".join([x[1].getId().split(".")[0] for x in ids])
1357:
1358: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename="%s.txt" """%basket_name)
1359: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
1360: length=len(ret)
1361: self.REQUEST.RESPONSE.setHeader("Content-Length",length)
1362: self.REQUEST.RESPONSE.write(ret)
1363:
1364: security.declareProtected('manage','downloadObjectsAsOneFile')
1365: def downloadObjectsAsOneFile(self,lock=None,procedure=None,REQUEST=None,check="yes",current="no"):
1366: """download all selected files in one file"""
1367:
1368: if self.temp_folder.downloadCounterBaskets > 10000:
1369: return """I am sorry, currently the server has to many requests for downloads, please come back later!"""
1370:
1371:
1372: if (check=="yes") and self.containsNonActualFiles():
1373: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','downloadObjectAsOneFile_check.zpt')).__of__(self)
1374:
1375: return pt(lock=lock)
1376:
1377: else:
1378:
1379: return self.downloadObjectsAsOneFileFinally(lock=lock,procedure=procedure,REQUEST=REQUEST,current="no")
1380:
1381: def downloadObjectsAsOneFileFinally(self,lock=None,procedure=None,REQUEST=None,current="no",repeat=None):
1382: """print do the download"""
1383:
1384:
1385: ret=""
1386: lockedObjects={}
1387:
1388:
1389:
1390: if lock:
1391: logging.debug("------lock:"+repr(lock))
1392: if str(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
1393:
1394: return "please login first"
1395:
1396: #check if a locked object exist in the basket.
1397: lockedObjects={}
1398: for object in self.content.getContent():
1399:
1400: if (not str(object[1].lockedBy)=="") and (not (str(object[1].lockedBy)==str(self.REQUEST['AUTHENTICATED_USER']))):
1401: lockedObjects[object[1].title]=repr(object[1].lockedBy)
1402:
1403:
1404: keys=lockedObjects.keys()
1405:
1406:
1407: if len(keys)>0 and (not procedure):
1408: self.REQUEST.SESSION['lockedObjects']=lockedObjects
1409: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','lockedObjects.zpt')).__of__(self)
1410:
1411:
1412: return pt()
1413:
1414: elif not procedure: #keine fails gesperrt dann alle donwloaden
1415: procedure="downloadAll"
1416:
1417:
1418:
1419:
1420: threadName=repeat
1421: if not threadName or threadName=="":
1422: thread=DownloadBasketFinallyThread()
1423: threadName=thread.getName()[0:]
1424:
1425: if (not hasattr(self,'_v_downloadBasket')):
1426: self._v_downloadBasket={}
1427:
1428:
1429: self._v_downloadBasket[threadName]=thread
1430: logging.debug("dwonloadfinally:"+repr(self))
1431: basketID=self.aq_parent.aq_parent.getId()
1432: versionNumber=self.aq_parent.getId()
1433:
1434: if lock:
1435: logging.debug("-----start locking")
1436: for object in self.content.getContent():
1437: if object[1].lockedBy =='':
1438: object[1].lockedBy=self.REQUEST['AUTHENTICATED_USER']
1439: logging.debug("-----finished locking")
1440:
1441: #obj.lockedBy=user
1442: self._v_downloadBasket[threadName].set(lock,procedure,self.REQUEST['AUTHENTICATED_USER'],current,basketID,versionNumber)
1443:
1444: self._v_downloadBasket[threadName].start()
1445:
1446:
1447:
1448: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1449:
1450: if wait_template:
1451: return wait_template[0][1]()
1452: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','downloadBasketWait.zpt')).__of__(self)
1453:
1454: return pt(txt=self.absolute_url()+'/downloadObjectsAsOneFileFinally',threadName=threadName,
1455: counter=self._v_downloadBasket[threadName].getCounter(),
1456: number=self._v_downloadBasket[threadName].getNumberOfFiles())
1457: #_v_xmltrans.run()
1458:
1459: else:
1460: #recover thread, if lost
1461: if not hasattr(self,'_v_downloadBasket'):
1462: self._v_downloadBasket={}
1463: if not self._v_downloadBasket.get(threadName,None):
1464: for thread in threading.enumerate():
1465: if threadName == thread.getName():
1466: self._v_downloadBasket[threadName]=thread
1467:
1468: if self._v_downloadBasket.get(threadName,None) and (self._v_downloadBasket[threadName] is not None) and (not self._v_downloadBasket[threadName].end) :
1469:
1470: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1471: if wait_template:
1472: return wait_template[0][1]()
1473:
1474: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','downloadBasketWait.zpt')).__of__(self)
1475: return pt(txt=self.absolute_url()+'/downloadObjectsAsOneFileFinally',threadName=threadName,
1476: counter=self._v_downloadBasket[threadName].getCounter(),
1477: number=self._v_downloadBasket[threadName].getNumberOfFiles())
1478: else:
1479:
1480:
1481: logging.debug("FINISHED")
1482: if not self._v_downloadBasket.get(threadName,None):
1483: for thread in threading.enumerate():
1484: if threadName == thread.getName():
1485: self._v_downloadBasket[threadName]=thread
1486:
1487: #files = self._v_downloadBasket[threadName].result
1488: files=self.basketContainer.resultHash[threadName]
1489: lockedFiles=self.basketContainer.resultLockedHash[threadName]
1490:
1491: # fh=file("/var/tmp/test")
1492: #ret =fh.read()
1493:
1494: if (not isinstance(self.aq_parent,CDLIBasket)):
1495: basket_name=self.aq_parent.aq_parent.title+"_V"+self.getId()
1496: else:
1497: basket_name=self.aq_parent.title+"_V"+self.getId()
1498:
1499:
1500:
1501: #write basketname to header of atf file
1502:
1503:
1504: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename="%s.atf" """%basket_name)
1505: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
1506: #length=len(ret)
1507: #self.REQUEST.RESPONSE.setHeader("Content-Length",length)
1508:
1509: ret="#basket: %s\n"%basket_name
1510: self.REQUEST.RESPONSE.write(ret)
1511:
1512: for fileName in files:
1513: try:
1514: self.REQUEST.RESPONSE.write(file(fileName).read())
1515: except:
1516: logging.error("downloadasonefile: cannot read %s"%fileName)
1517:
1518:
1519: self.REQUEST.RESPONSE.write("\n# locked files\n")
1520: for fileName in lockedFiles:
1521: self.REQUEST.RESPONSE.write("# %s by %s\n"%fileName)
1522:
1523: self.REQUEST.RESPONSE.write("# locked files end\n")
1524:
1525: del self.basketContainer.resultHash[threadName]
1526: del self.basketContainer.resultLockedHash[threadName]
1527:
1528: def numberOfItems(self):
1529: """return anzahl der elemente im basket"""
1530: return self.content.numberOfItems()
1531:
1532: def getTime(self):
1533: """getTime"""
1534: #return self.bobobase_modification_time().ISO()
1535:
1536: if hasattr(self,'time'):
1537: return time.strftime("%Y-%m-%d %H:%M:%S",self.time)
1538: elif hasattr(self,'timefixed'):
1539: return self.timefixed
1540: else:
1541: setattr(self,'timefixed',self.bobobase_modification_time().ISO())
1542: return self.bobobase_modification_time().ISO()
1543:
1544: def getContent(self):
1545: """get Basket Content"""
1546: return self.content.getContent()
1547:
1548:
1549: def __init__(self,id,user,comment="",basketContent=[]):
1550: """ init a basket version"""
1551: self.id=id
1552: self.comment=comment
1553: self._setObject('content',BasketContent(basketContent))
1554: #self.basketContent=basketContent[0:]a
1555: self.user=user
1556: self.time=time.localtime()
1557:
1558: def getUser(self):
1559: """get user"""
1560: return self.user
1561:
1562: def getComment(self):
1563: """get Comment"""
1564: return self.comment
1565:
1566: security.declareProtected('manage','index_html')
1567: def index_html(self):
1568: """view the basket"""
1569:
1570: if self.REQUEST.get('change',False):
1571: ob=self.aq_parent.updateObjects(self.REQUEST['change'])
1572:
1573: self.REQUEST.RESPONSE.redirect(ob.absolute_url())#go to new basket, because changing generates a new basket
1574:
1575: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','BasketVersionMain.zpt')).__of__(self)
1576: return pt()
1577:
1578: def getObjUrl(self,result):
1579: """getUrl of the version of the object"""
1580: objId=result[1].getTitle()
1581: founds=self.CDLICatalog.search({'title':objId})
1582: if len(founds)>0:
1583: return founds[0].getObject().getLastVersion().absolute_url()
1584:
1585: else: #assume version number
1586: splitted=objId.split("_")
1587: founds=self.CDLICatalog.search({'title':splitted[1]})
1588: return founds[0].getObject().getLastVersion().absolute_url()+'/'+objId
1589:
1590: def manage_addCDLIBasketVersion(self,user,comment="",basketContent=[],RESPONSE=None):
1591: """add a version"""
1592:
1593: #check for already existing versions
1594:
1595: lastVersion=self.getLastVersion()
1596: if lastVersion is None:
1597: newId=str(1)
1598: else:
1599: newId=str(int(lastVersion.getId())+1)
1600:
1601: ob=CDLIBasketVersion(newId,user,comment,basketContent)
1602:
1603: self._setObject(newId, ob)
1604:
1605: if RESPONSE is not None:
1606: RESPONSE.redirect('manage_main')
1607: else:
1608: return ob
1609:
1610: class CDLIFileObject(CatalogAware,extVersionedFileObject):
1611: """CDLI file object"""
1612:
1613: meta_type="CDLI File Object"
1614: default_catalog='CDLIObjectsCatalog'
1615:
1616: security=ClassSecurityInfo()
1617:
1618: security.declareProtected('manage','index_html')
1619:
1620: security.declarePublic('view')
1621: view = PageTemplateFile('zpt/viewCDLIFile.zpt', globals())
1622:
1623: security.declarePublic('editATF')
1624: editATF = PageTemplateFile('zpt/editATFFile.zpt', globals())
1625:
1626: def PrincipiaSearchSource(self):
1627: """Return cataloguable key for ourselves."""
1628: return str(self)
1629:
1630: def setAuthor(self, author):
1631: """change the author"""
1632: self.author = author
1633:
1634: def makeThisVersionCurrent_html(self):
1635: """form for mthis version current"""
1636:
1637: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','makeThisVersionCurrent.zpt')).__of__(self)
1638: return pt()
1639:
1640: security.declarePublic('makeThisVersionCurrent')
1641: def makeThisVersionCurrent(self,comment,author,RESPONSE=None):
1642: """copy this version to current"""
1643: parent=self.aq_parent
1644: parent.manage_addVersionedFileObject(id=None,vC=comment,author=author,file=self.getData(),RESPONSE=RESPONSE)
1645: #newversion=parent.manage_addCDLIFileObject('',comment,author)
1646: #newversion.manage_upload(self.getData())
1647:
1648: #if RESPONSE is not None:
1649: # RESPONSE.redirect(self.aq_parent.absolute_url()+'/history')
1650:
1651: return True
1652:
1653: def getFormattedData(self):
1654: """fromat text"""
1655: data=self.getData()
1656: # return re.sub("\s\#lem"," #lem",data) #remove return vor #lem
1657: return re.sub("#lem"," #lem",data) #remove return vor #lem
1658:
1659:
1660: security.declarePublic('getPNumber')
1661: def getPNumber(self):
1662: """get the pnumber"""
1663: try:
1664: txt=re.match("&[Pp](\d*)\s*=([^\r\n]*)",self.getData()[0:])
1665: except:
1666: txt=self.getData()[0:]
1667:
1668: return "ERROR"
1669: try:
1670: return "P"+txt.group(1)
1671: except:
1672: return "ERROR"
1673:
1674: security.declarePublic('getDesignation')
1675: def getDesignation(self):
1676: """get the designation out of the file"""
1677: try:
1678: txt=re.match("&[Pp](\d*)\s*=([^\r\n]*)",self.getData()[0:])
1679: except:
1680: txt=self.getData()[0:]
1681:
1682: return "ERROR"
1683: try:
1684: return txt.group(2)
1685: except:
1686: return "ERROR"
1687:
1688:
1689: manage_addCDLIFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='CDLIFileObject',kind='CDLIFileObject', version='1')
1690:
1691: def manage_addCDLIFileObject(self,id,vC='',author='', file='',title='',versionNumber=0,
1692: precondition='', content_type='',
1693: from_tmp=False,REQUEST=None):
1694: """Add a new File object.
1695: Creates a new File object 'id' with the contents of 'file'"""
1696:
1697: id=str(id)
1698: title=str(title)
1699: content_type=str(content_type)
1700: precondition=str(precondition)
1701:
1702: id, title = cookId(id, title, file)
1703:
1704: self=self.this()
1705:
1706: # First, we create the file without data:
1707: self._setObject(id, CDLIFileObject(id,title,versionNumber=versionNumber,versionComment=vC,time=time.localtime(),author=author))
1708: fob = self._getOb(id)
1709:
1710: # Now we "upload" the data. By doing this in two steps, we
1711: # can use a database trick to make the upload more efficient.
1712:
1713: if file and not from_tmp:
1714: fob.manage_upload(file)
1715: elif file and from_tmp:
1716: fob.manage_file_upload(file) # manage_upload_from_tmp doesn't exist in ExtFile2
1717: # fob.manage_upload_from_tmp(file) # manage_upload_from_tmp doesn't exist in ExtFile2
1718: if content_type:
1719: fob.content_type=content_type
1720:
1721: #logging.debug("manage_add: lastversion=%s"%self.getData())
1722: logging.debug("reindex1: %s in %s"%(repr(self),repr(self.default_catalog)))
1723: self.reindex_object()
1724: #logging.debug("manage_add: fob_data=%s"%fob.getData())
1725: logging.debug("reindex2: %s in %s"%(repr(fob), repr(fob.default_catalog)))
1726: fob.index_object()
1727:
1728: self.CDLIRoot.updateOrAddToFileBTree(ob)
1729: if REQUEST is not None:
1730: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
1731:
1732:
1733: class CDLIFile(extVersionedFile,CatalogAware):
1734: """CDLI file"""
1735:
1736: security=ClassSecurityInfo()
1737: meta_type="CDLI file"
1738: content_meta_type = ["CDLI File Object"]
1739:
1740: default_catalog='CDLICatalog'
1741:
1742: security.declareProtected('manage','index_html')
1743:
1744: def getLastVersionData(self):
1745: """get last version data"""
1746: return self.getData()
1747:
1748: def getLastVersionFormattedData(self):
1749: """get last version data"""
1750: return self.getContentObject().getFormattedData()
1751:
1752: def getTextId(self):
1753: """returns P-number of text"""
1754: # assuming that its the beginning of the title
1755: return self.title[:7]
1756:
1757: #security.declarePublic('history')
1758: def history(self):
1759: """history"""
1760:
1761: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
1762: if ext:
1763: return getattr(self,ext[0][1].getId())()
1764:
1765: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionHistory')).__of__(self)
1766: return pt()
1767:
1768:
1769: def getBasketFromId(self,basketid, context=None):
1770: """get basket from id"""
1771:
1772: if not context:
1773: context=self
1774:
1775: for basket in self.ZopeFind(context,obj_metatypes=["CDLIBasket"]):
1776: if basket[0]==basketid:
1777: return basket[1]
1778: else:
1779: None
1780:
1781:
1782: def isContainedInBaskets(self,context=None):
1783: """check is this file is part of any basket
1784: @param context: (optional) necessessary if CDLIBasketCatalog is not an (inherited) attribute of self, context.CDLIBasketCatalog
1785: has to exist.
1786: """
1787:
1788: if not context:
1789: context=self
1790:
1791: ret=[]
1792: for x in context.CDLIBasketCatalog.search({'getFileNamesInLastVersion':self.getId()}):
1793: #if the basket x is deleted it seemes to be that x is sometimes still in the Catalog, why?
1794: try:
1795: ret.append(x.getObject())
1796: except:
1797: pass
1798: return ret
1799: #return [x.getObject() for x in context.CDLIBasketCatalog.search({'getFileNamesInLastVersion':self.getId()})]
1800:
1801:
1802: def _newContentObject(self, id, title='', versionNumber=0, versionComment=None, time=None, author=None):
1803: """factory for content objects. to be overridden in derived classes."""
1804: logging.debug("_newContentObject(CDLI)")
1805: return CDLIFileObject(id,title,versionNumber=versionNumber,versionComment=versionComment,time=time,author=author)
1806:
1807:
1808: def addCDLIFileObjectForm(self):
1809: """add a new version"""
1810:
1811: if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
1812: return "please login first"
1813: if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
1814: out=DTMLFile('dtml/fileAdd', globals(),Kind='CDLIFileObject',kind='CDLIFileObject',version=self.getVersion()).__of__(self)
1815: return out()
1816: else:
1817: return "Sorry file is locked by somebody else"
1818:
1819: def manage_addCDLIFileObject(self,id,vC,author,
1820: file='',title='',
1821: precondition='',
1822: content_type='',
1823: changeName='no',newName='',
1824: come_from=None,
1825: from_tmp=False,RESPONSE=None):
1826: """add"""
1827:
1828: try: #TODO: der ganze vC unsinn muss ueberarbeitet werden
1829: vC=self.REQUEST['vC']
1830: except:
1831: pass
1832:
1833: ob = self.addContentObject(id, vC, author, file, title, changeName=changeName, newName=newName, from_tmp=from_tmp,
1834: precondition=precondition, content_type=content_type)
1835:
1836: try:
1837: #FIXME: wozu ist das gut?
1838: self.REQUEST.SESSION['objID_parent']=self.getId()
1839: except:
1840: pass
1841:
1842: #self.cdliRoot.updateOrAddToFileBTree(self)# now update the object in the cache
1843:
1844:
1845: if RESPONSE:
1846: if ob.getSize()==0:
1847: self.REQUEST.SESSION['objID']=ob.getId()
1848: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
1849: return pt()
1850: else:
1851: if come_from and (come_from!=""):
1852: RESPONSE.redirect(come_from+"?change="+self.getId())
1853: else:
1854: RESPONSE.redirect(self.REQUEST['URL2']+'?uploaded=%s'%self.title)
1855: else:
1856: return ob
1857:
1858:
1859: def manage_addCDLIFileForm(self):
1860: """interface for adding the OSAS_root"""
1861: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addCDLIFile.zpt')).__of__(self)
1862: return pt()
1863:
1864: def manage_addCDLIFile(self,id,title,lockedBy, author=None, RESPONSE=None):
1865: """add the OSAS_root"""
1866: newObj=CDLIFile(id,title,lockedBy,author)
1867:
1868: tryToggle=True
1869: tryCount=0
1870:
1871: self._setObject(id,newObj)
1872: getattr(self,id).reindex_object()
1873:
1874: if RESPONSE is not None:
1875: RESPONSE.redirect('manage_main')
1876:
1877:
1878: def checkUTF8(data):
1879: """check utf 8"""
1880: try:
1881: data.encode('utf-8')
1882: return True
1883: except:
1884: return False
1885:
1886:
1887: def checkFile(filename,data,folder):
1888: """check the files"""
1889: # first check the file name
1890: fn=filename.split(".") # no extension
1891:
1892: if not fn[0][0]=="P":
1893: return False,"P missing in the filename"
1894: elif len(fn[0])!=7:
1895: return False,"P number has not the right length 6"
1896: elif not checkUTF8(data):
1897: return False,"not utf-8"
1898: else:
1899: return True,""
1900:
1901:
1902: def splitatf(fh,dir=None,ext=None):
1903: """split it"""
1904: ret=None
1905: nf=None
1906: i=0
1907:
1908: #ROC: why split \n first and then \r???
1909: if (type(fh) is StringType) or (type(fh) is UnicodeType):
1910: iter=fh.split("\n")
1911: else:
1912: iter=fh.readlines()
1913:
1914: for lineTmp in iter:
1915: lineTmp=lineTmp.replace(codecs.BOM_UTF8,'') # make sure that all BOM are removed..
1916: for line in lineTmp.split("\r"):
1917: #logging.log("Deal with: %s"%line)
1918: if ext:
1919: i+=1
1920: if (i%100)==0:
1921: ext.result+="."
1922: if i==10000:
1923: i=0
1924: ext.result+="<br>"
1925: #check if basket name is in the first line
1926: if line.find("#atf basket")>=0: #old convention
1927: ret=line.replace('#atf basket ','')
1928: ret=ret.split('_')[0]
1929: elif line.find("#basket:")>=0: #new convention
1930: ret=line.replace('#basket: ','')
1931: ret=ret.split('_')[0]
1932:
1933: else:
1934: if (len(line.lstrip())>0) and (line.lstrip()[0]=="&"): #newfile
1935: if nf:
1936: nf.close() #close last file
1937:
1938:
1939: filename=line[1:].split("=")[0].rstrip()+".atf"
1940: if dir:
1941: filename=os.path.join(dir,filename)
1942: nf=file(filename,"w")
1943: logging.info("open %s"%filename)
1944: if nf:
1945: nf.write(line.replace("\n","")+"\n")
1946:
1947: try:
1948: nf.close()
1949: except:
1950: pass
1951:
1952: if not((type(fh) is StringType) or (type(fh) is UnicodeType)):
1953: fh.close()
1954: return ret,len(os.listdir(dir))
1955:
1956:
1957: class CDLIFileFolder(extVersionedFileFolder):
1958: """CDLI File Folder"""
1959:
1960: security=ClassSecurityInfo()
1961: meta_type="CDLI Folder"
1962: file_meta_type=['CDLI file']
1963: folder_meta_type=['CDLI Folder']
1964:
1965: file_catalog='CDLICatalog'
1966:
1967: #downloadCounter=0 # counts how many download for all files currently run, be mehr als 5 wird verweigert.
1968: tmpStore2={}
1969:
1970: def _newVersionedFile(self, id, title='', lockedBy=None, author=None):
1971: """factory for versioned files. to be overridden in derived classes."""
1972: logging.debug("_newVersionedFile(CDLI)")
1973: return CDLIFile(id, title, lockedBy=lockedBy, author=author)
1974:
1975: def setTemp(self,name,value):
1976: """set tmp"""
1977:
1978: setattr(self,name,value)
1979:
1980: deleteFileForm = PageTemplateFile("zpt/doDeleteFile", globals())
1981:
1982: def delete(self,ids,REQUEST=None):
1983: """delete these files"""
1984: if type(ids) is not ListType:
1985: ids=[ids]
1986:
1987: self.manage_delObjects(ids)
1988:
1989: if REQUEST is not None:
1990: return self.index_html()
1991:
1992:
1993: def getVersionNumbersFromIds(self,ids):
1994: """get the numbers of the current versions of documents described by their ids"""
1995:
1996: ret=[]
1997: searchStr=" OR ".join(ids)
1998:
1999: founds=self.CDLICatalog.search({'title':searchStr})
2000:
2001: for found in founds:
2002: lastVersion=found.getObject().getContentObject()
2003: ret.append((found.getId,lastVersion))
2004:
2005: return ret
2006:
2007: def getFile(self,fn):
2008: """get the content of the file fn"""
2009: logging.debug("getFile: %s"%repr(fn))
2010: if not self.hasObject(fn):
2011: # search deeper
2012: founds=getattr(self, self.file_catalog).search({'textid':fn})
2013: if founds:
2014: obj=founds[0].getObject().getContentObject()
2015: else:
2016: return ""
2017: else:
2018: obj = self[fn].getContentObject()
2019:
2020: return obj.getData()[0:]
2021:
2022:
2023: def checkCatalog(self,fn):
2024: """check if fn is in the catalog"""
2025: #TODO add checkCatalog
2026:
2027:
2028: def findObjectsFromListWithVersion(self,list,author=None):
2029: """find objects from a list with versions
2030: @param list: list of tuples (cdliFile,version)
2031: """
2032: #self.REQUEST.SESSION['fileIds']=list#store fieldIds in session for further usage
2033: #self.REQUEST.SESSION['searchList']=self.REQUEST.SESSION['fileIds']
2034:
2035: pt=getattr(self,'filelistVersioned.html')
2036:
2037: return pt(search=list,author=author)
2038:
2039:
2040: def getAllPNumbers(self):
2041: """get a list of all files (resp their p-numbers) stored"""
2042:
2043: ret=[x.getId for x in self.CDLICatalog()]
2044:
2045: return ret
2046:
2047: def expandFile(self,fileId,fileTree):
2048: """wildcard in fileID suche alle Treffer"""
2049: founds=self.CDLICatalog({'title':fileId})
2050: for found in founds:
2051: fileTree.add(found.getId)
2052: logging.debug("ADDD:"+found.getId)
2053:
2054: 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):
2055: """findObjectsFromList (, TAB oder LINE separated)"""
2056:
2057: logging.debug("start: findObjectsFromList")
2058: #logging.debug("start: findObjectsFromList"+repr(list))
2059:
2060:
2061: if upload: # list from file upload
2062: txt=upload.read()
2063:
2064: if enterList:
2065: txt=enterList
2066:
2067: if upload or enterList:
2068: txt=txt.replace(",","\n")
2069: txt=txt.replace("\t","\n")
2070: txt=txt.replace("\r","\n")
2071: idsTmp=txt.split("\n")
2072: ids=[]
2073: for id in idsTmp: # make sure that no empty lines
2074: idTmp=id.lstrip().rstrip()
2075: if len(idTmp)>0:
2076:
2077: ids.append(idTmp)
2078:
2079: #self.REQUEST.SESSION['ids']=" OR ".join(ids)
2080:
2081: pt=getattr(self,'filelist.html')
2082: self.REQUEST.SESSION['searchList']=ids
2083: return pt(search=ids)
2084:
2085: if basketName:
2086: #TODO: get rid of one of these..
2087:
2088: pt=getattr(self,'filelist.html')
2089: return pt(basketName=basketName,numberOfObjects=numberOfObjects)
2090:
2091: if hash is not None and hasattr(self.cdliRoot,'v_tmpStore') and self.cdliRoot.v_tmpStore.has_key(hash):
2092:
2093: logging.debug("asking for storage2")
2094: result =self.cdliRoot.v_tmpStore[hash]
2095: if result:
2096: logging.debug("give result from storage2")
2097: return hash,self.cdliRoot.v_tmpStore[hash]
2098:
2099: if list is not None: # got already a list
2100:
2101: logging.debug(" ----List version")
2102: ret=[]
2103: fileTree=Set()
2104:
2105: for fileId in list:
2106:
2107: if fileId.find("*")>-1: #check for wildcards
2108: self.expandFile(fileId,fileTree)
2109:
2110: elif len(fileId.split("."))==1:
2111: fileId=fileId+".atf"
2112: fileTree.add(fileId)
2113: #logging.debug(" -----:"+fileId)
2114: #ret+=self.CDLICatalog({'title':fileId})
2115: #x =self.getFileObject(fileId)
2116: #if x is not None:
2117: # ret.append(x)
2118:
2119:
2120:
2121: ids = fileTree & self.v_file_ids
2122: #self.REQUEST.SESSION['fileIds']=ids#store fieldIds in session for further usage
2123: l=makelist(fileTree)[0:]
2124: #logging.debug("l-list:"+repr(l))
2125: self.REQUEST.SESSION['fileIds']=l#store fieldIds in session for further usage
2126: self.REQUEST.SESSION['searchList']=l
2127: #self.REQUEST.SESSION['searchList']=['P000001.atf']
2128:
2129:
2130: hash = md5.new(repr(makelist(fileTree))).hexdigest() # erzeuge hash als identification
2131: self.REQUEST.SESSION['hash']=hash
2132: #TODO: do I need garbage collection for v_tmpStore ?
2133:
2134: #logging.debug("Hash:"+repr(hash))
2135: #
2136: # if hasattr(self.cdliRoot,'v_tmpStore') and self.cdliRoot.v_tmpStore.has_key(hash):
2137: # logging.debug("asking for storage")
2138: # res=self.cdliRoot.v_tmpStore[hash]
2139: # if res:
2140: # if returnHash == True:
2141: # return hash,res
2142: # return res
2143:
2144: #TODO: get rid of one of these..
2145: #ids=[x.getObject().getId() for x in ret]
2146: ret=[(self.getFileObject(x),self.getFileObjectLastVersion(x)) for x in ids]
2147:
2148: #self.REQUEST.SESSION['fileIds']=ids#store fieldIds in session for further usage
2149: #self.REQUEST.SESSION['searchList']=self.REQUEST.SESSION['fileIds']
2150:
2151: if display:
2152: pt=getattr(self,'filelist.html')
2153:
2154: return pt(search=ids)
2155: else:
2156: #self.REQUEST.SESSION['hash'] = ret # store in session
2157: if not hasattr(self,'v_tmpStore'):
2158: self.cdliRoot.v_tmpStore={}
2159: #logging.debug("HHHHHHNEU:"+repr(self.makelist(ids)))
2160: #logging.debug("HHHHHHNEU:"+repr(hash))
2161: self.cdliRoot.v_tmpStore[hash] = ret # store in session
2162: if returnHash == True:
2163: return hash,ret
2164: return ret
2165:
2166:
2167:
2168: if start:
2169: RESPONSE.redirect("filelist.html?start:int="+str(start))
2170:
2171: security.declareProtected('Manage','createAllFilesAsSingleFile')
2172: def createAllFilesAsSingleFile(self,RESPONSE=None):
2173: """download all files"""
2174:
2175: def sortF(x,y):
2176: return cmp(x[0],y[0])
2177:
2178: catalog=getattr(self,self.file_catalog)
2179: #tf,tfilename=mkstemp()
2180: if not hasattr(self.temp_folder,'downloadCounter'):
2181: self.temp_folder.downloadCounter=0
2182:
2183: if getattr(self.temp_folder,'downloadCounter',0) > 5:
2184: return """I am sorry, currently the server has to many requests for downloads, please come back later!"""
2185:
2186: self.temp_folder.downloadCounter+=1
2187: self._p_changed=1
2188: transaction.get().commit()
2189:
2190: list=[(x.getId,x) for x in catalog()]
2191: list.sort(sortF)
2192:
2193:
2194:
2195: RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%"all.atf")
2196: RESPONSE.setHeader("Content-Type","application/octet-stream")
2197: tmp=""
2198: for l in list:
2199: obj=l[1].getObject()
2200:
2201: if obj.meta_type=="CDLI file":
2202:
2203: #os.write(tf,obj.getLastVersion().data)
2204: if RESPONSE:
2205: RESPONSE.write(obj.getData()[0:])
2206: RESPONSE.write("\n")
2207: self.temp_folder.downloadCounter-=1
2208: self._p_changed=1
2209: transaction.get().commit()
2210: #os.close(tf)
2211: #RESPONSE.redirect(self.absolute_url()+"/downloadFile?fn="%tfilename)
2212: return True
2213:
2214: def downloadFile(self,fn):
2215: """download fn - not used yet"""
2216: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getLastVersion().getId())
2217: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
2218: self.REQUEST.RESPONSE.write(file(fn).read())
2219:
2220:
2221:
2222: def hasParent(self):
2223: """returns true falls subfolder"""
2224:
2225: if self.aq_parent.meta_type in self.folder_meta_type:
2226: return True
2227: else:
2228: return False
2229:
2230: def getFolders(self):
2231: """get all subfolders"""
2232: ret=[]
2233: folders=self.ZopeFind(self,obj_metatypes=self.folder_meta_type)
2234: for folder in folders:
2235: ret.append((folder[1],
2236: len(self.ZopeFind(folder[1],obj_metatypes=self.folder_meta_type)),
2237: len(self.ZopeFind(folder[1],obj_metatypes=self.file_meta_type))
2238: ))
2239: return ret
2240:
2241:
2242: security.declareProtected('manage','index_html')
2243: def index_html(self):
2244: """main"""
2245: ext=self.ZopeFind(self,obj_ids=["index.html"])
2246: if ext:
2247: return ext[0][1]()
2248:
2249: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','CDLIFileFolderMain')).__of__(self)
2250: return pt()
2251:
2252:
2253: manage_addCDLIFileFolderForm=DTMLFile('dtml/folderAdd', globals())
2254:
2255:
2256: def manage_addCDLIFileFolder(self, id, title='',
2257: createPublic=0,
2258: createUserF=0,
2259: REQUEST=None):
2260: """Add a new Folder object with id *id*.
2261:
2262: If the 'createPublic' and 'createUserF' parameters are set to any true
2263: value, an 'index_html' and a 'UserFolder' objects are created respectively
2264: in the new folder.
2265: """
2266: ob=CDLIFileFolder()
2267: ob.id=str(id)
2268: ob.title=title
2269: self._setObject(id, ob)
2270: ob=self._getOb(id)
2271:
2272: checkPermission=getSecurityManager().checkPermission
2273:
2274: if createUserF:
2275: if not checkPermission('Add User Folders', ob):
2276: raise Unauthorized, (
2277: 'You are not authorized to add User Folders.'
2278: )
2279: ob.manage_addUserFolder()
2280:
2281:
2282: if REQUEST is not None:
2283: return self.manage_main(self, REQUEST, update_menu=1)
2284:
2285: class CDLIRoot(Folder):
2286: """main folder for cdli"""
2287:
2288: meta_type="CDLIRoot"
2289: downloadCounterBaskets=0 # counts the current basket downloads if counter > 10 no downloads are possible
2290:
2291: file_catalog = 'CDLICatalog'
2292:
2293: # word splitter for search
2294: splitter = {'words':cdliSplitter.wordSplitter(),
2295: 'graphemes':cdliSplitter.graphemeSplitter()}
2296:
2297:
2298: def viewATF(self,id,RESPONSE):
2299: """view an Object"""
2300: ob = self.CDLICatalog({'title':id})
2301: logging.debug(ob[0].getObject().getLastVersion().absolute_url()+"/view")
2302: if len(ob)>0:
2303: RESPONSE.redirect(ob[0].getObject().getLastVersion().absolute_url()+"/view")
2304: return "not found"
2305:
2306: def history(self,id,RESPONSE):
2307: """view an Object"""
2308: ob = self.CDLICatalog({'title':id})
2309: if len(ob)>0:
2310: RESPONSE.redirect(ob[0].absolute_url+"/history")
2311: return "not found"
2312:
2313:
2314: def downloadLocked(self,id,RESPONSE):
2315: """view an Object"""
2316: ob = self.CDLICatalog({'title':id})
2317: if len(ob)>0:
2318: RESPONSE.redirect(ob[0].absolute_url+"/downloadLocked")
2319: return "not found"
2320:
2321: def download(self,id,RESPONSE):
2322: """view an Object"""
2323: ob = self.CDLICatalog({'title':id})
2324: if len(ob)>0:
2325: RESPONSE.redirect(ob[0].getLastVersion().absolute_url())
2326: return "not found"
2327: def addCDLIFileObjectForm(self,id,RESPONSE):
2328: """view an Object"""
2329: ob = self.CDLICatalog({'title':id})
2330: if len(ob)>0:
2331: RESPONSE.redirect(ob[0].absolute_url+"/addCDLIFileObjectForm")
2332: return "not found"
2333:
2334: def addVersionedFileObjectForm(self,id,RESPONSE):
2335: """view an Object"""
2336: ob = self.CDLICatalog({'title':id})
2337: if len(ob)>0:
2338: RESPONSE.redirect(ob[0].absolute_url+"/addVersionedFileObjectForm")
2339: return "not found"
2340:
2341: def unlock(self,id,RESPONSE):
2342: """view an Object"""
2343: ob = self.CDLICatalog({'title':id})
2344: if len(ob)>0:
2345: RESPONSE.redirect(ob[0].absolute_url+"/unlock")
2346: return "not found"
2347:
2348: def getFileObject(self,fileId):
2349: """get an object"""
2350: x=self.v_files.get(fileId)
2351: #logging.debug(x)
2352: return x
2353:
2354: def getFileObjectLastVersion(self,fileId):
2355: """get an object"""
2356: x=self.v_files_lastVersion.get(fileId)
2357: l#ogging.debug("lastVersion: "+repr(x))
2358: return x
2359:
2360: def showFileIds(self):
2361: """showIds"""
2362: return self.v_file_ids
2363:
2364: def generateFileBTree(self):
2365: """erzeuge einen Btree aus allen Files"""
2366: self.v_files = OOBTree()
2367: self.v_files_lastVersion = OOBTree()
2368: self.v_file_ids = Set()
2369:
2370: for x in self.CDLICatalog.searchResults():
2371:
2372: self.v_files.update({x.getId:x.getObject()})
2373: self.v_files_lastVersion.update({x.getId:x.getObject().getLastVersion()})
2374: self.v_file_ids.add(x.getId)
2375: logging.debug("add:"+x.getId+"XXX"+repr(x.getObject()))
2376:
2377: return True
2378:
2379:
2380: def updateOrAddToFileBTree(self,obj):
2381: """update a BTree"""
2382: self.v_files.update({obj.getId():obj})
2383: self.v_files_lastVersion.update({obj.getId():obj.getLastVersion()})
2384:
2385: self.v_file_ids.add(obj.getId())
2386: logging.debug("update:"+obj.getId()+"XXX"+repr(obj))
2387:
2388: def deleteFromBTree(self,objId):
2389: """delete an obj"""
2390: self.v_files.pop(objId)
2391: self.v_files_lastVersion.pop(objId)
2392: self.v_file_ids.remove(objId)
2393:
2394:
2395:
2396: def deleteFiles(self,ids):
2397: """delete files"""
2398: for id in ids:
2399: founds=self.CDLICatalog.search({'title':id.split(".")[0]})
2400: if founds:
2401: logging.debug("deleting %s"%founds)
2402: folder=founds[0].getObject().aq_parent #get the parent folder of the object
2403: logging.debug("deleting from %s"%folder)
2404: cut=folder.delete([founds[0].getId]) #cut it out
2405:
2406:
2407:
2408: def searchText(self, query, index='graphemes'):
2409: """searches query in the fulltext index and returns a list of file ids/P-numbers"""
2410: # see also: http://www.plope.com/Books/2_7Edition/SearchingZCatalog.stx#2-13
2411: logging.debug("searchtext for '%s' in index %s"%(query,index))
2412: #import Products.ZCTextIndex.QueryParser
2413: #qp = QueryParser.QueryParser()
2414: #logging.debug()
2415: idxQuery = {index:{'query':query}}
2416: idx = getattr(self, self.file_catalog)
2417: # do search
2418: resultset = idx.search(query_request=idxQuery,sort_index='textid')
2419: # put only the P-Number in the result
2420: results = [res.getId[:7] for res in resultset]
2421: logging.debug("searchtext: found %d texts"%len(results))
2422: return results
2423:
2424:
2425: def getFile(self, pnum):
2426: """get the translit file with the given pnum"""
2427: f = getattr(self, self.file_catalog).search({'textid':pnum})
2428: if not f:
2429: return ""
2430:
2431: return f[0].getObject().getData()
2432:
2433:
2434: def showFile(self,fileId,wholePage=False):
2435: """show a file
2436: @param fileId: P-Number of the document to be displayed
2437: """
2438: f=getattr(self, self.file_catalog).search({'textid':fileId})
2439: if not f:
2440: return ""
2441:
2442: if wholePage:
2443: logging.debug("show whole page")
2444: return f[0].getObject().getContentObject().view()
2445: else:
2446: return f[0].getObject().getLastVersionFormattedData()
2447:
2448:
2449: def showWordInFile(self,fileId,word,indexName='graphemes',regExp=False,):
2450: """get lines with word from FileId"""
2451: logging.debug("showwordinfile word='%s' index=%s file=%s"%(word,indexName,fileId))
2452:
2453: file = formatAtfFullLineNum(self.getFile(fileId))
2454: ret=[]
2455:
2456: # add whitespace before and whitespace and line-end to splitter bounds expressions
2457: bounds = self.splitter[indexName].bounds
2458: splitexp = "(%s|\s)(%%s)(%s|\s|\Z)"%(bounds,bounds)
2459: # clean word expression
2460: # TODO: this should use QueryParser itself
2461: # take out double quotes
2462: word = word.replace('"','')
2463: # take out ignorable signs
2464: ignorable = self.splitter[indexName].ignorex
2465: word = ignorable.sub('', word)
2466: # compile into regexp objects and escape parens
2467: wordlist = [re.compile(splitexp%re.escape(w)) for w in word.split(' ')]
2468:
2469: for line in file.splitlines():
2470: for word in wordlist:
2471: #logging.debug("showwordinfile: searching for %s in %s"%(word.pattern,ignoreable.sub('',line)))
2472: if word.search(ignorable.sub('',line)):
2473: line = formatAtfLineHtml(line)
2474: ret.append(line)
2475: break
2476:
2477: return ret
2478:
2479:
2480: def showWordInFiles(self,fileIds,word,indexName='graphemes',regExp=False):
2481: """
2482: get lines with word from all ids in list FileIds.
2483: returns dict with id:lines pairs.
2484: """
2485: logging.debug("showwordinfiles word='%s' index=%s file=%s"%(word,indexName,fileIds))
2486:
2487: return dict([(id,self.showWordInFile(id, word, indexName, regExp)) for id in fileIds])
2488:
2489:
2490: def tagWordInFile(self,fileId,word,indexName='graphemes',regExp=False):
2491: """get text with word highlighted from FileId"""
2492: logging.debug("tagwordinfile word='%s' index=%s file=%s"%(word,indexName,fileId))
2493:
2494: file=self.getFile(fileId)
2495: tagStart=u'<span class="found">'
2496: tagEnd=u'</span>'
2497: tagStr=tagStart + u'%%s' + tagEnd
2498: ret=[]
2499:
2500: # add whitespace to splitter bounds expressions and compile into regexp object
2501: bounds = self.splitter[indexName].bounds
2502: wordsplit = re.compile("(%s|\s)"%bounds)
2503: # clean word expression
2504: # TODO: this should use QueryParser itself
2505: word = word.replace('"','') # take out double quotes
2506: # take out ignoreable signs
2507: ignorable = self.splitter[indexName].ignorex
2508: word = ignorable.sub('', word)
2509: # split search terms by blanks
2510: words = word.split(' ')
2511: # split search terms again (for grapheme search with words)
2512: splitwords = dict(((w,self.splitter[indexName].process([w])) for w in words))
2513:
2514: for line in file.splitlines():
2515: line = unicodify(line)
2516: # ignore lemma and other lines
2517: if line.lstrip().startswith('#lem:'):
2518: continue
2519: # ignore p-num line
2520: if line.startswith('&P'):
2521: continue
2522: # ignore version lines
2523: if line.startswith('#version'):
2524: continue
2525: # ignore atf type lines
2526: if line.startswith('#atf:'):
2527: continue
2528:
2529: # first scan
2530: hitwords = []
2531: for w in words:
2532: if ignorable.sub('',line).find(w) > -1:
2533: # word is in line
2534: # append split word for grapheme search with words
2535: hitwords.extend(splitwords[w])
2536: #hitwords.extend(wordsplit.split(w))
2537:
2538: # examine hits closer
2539: if hitwords:
2540: # split line into words
2541: parts = wordsplit.split(line)
2542: line = ""
2543: for p in parts:
2544: #logging.debug("tagwordinfile: searching for %s in %s"%(p,hitwords))
2545: # reassemble line
2546: if ignorable.sub('', p) in hitwords:
2547: #logging.debug("tagwordinfile: found %s in %s"%(p,hitwords))
2548: # this part was found
2549: line += tagStart + formatAtfHtml(p) + tagEnd
2550: else:
2551: line += formatAtfHtml(p)
2552:
2553: else:
2554: # no hits
2555: line = formatAtfHtml(line)
2556:
2557: ret.append(line)
2558:
2559: return u'<br>\n'.join(ret)
2560:
2561:
2562:
2563: def tagWordInFiles(self,fileIds,word,indexName='graphemes',regExp=False):
2564: """
2565: get texts with highlighted word from all ids in list FileIds.
2566: returns dict with id:text pairs.
2567: """
2568: logging.debug("tagwordinfiles word='%s' index=%s file=%s"%(word,indexName,fileIds))
2569: return dict([(id,self.tagWordInFile(id, word, indexName, regExp)) for id in fileIds])
2570:
2571:
2572: def getFileVersionList(self, pnum):
2573: """get the version history as a list for the translit file with the given pnum"""
2574: f = getattr(self, self.file_catalog).search({'textid':pnum})
2575: if not f:
2576: return []
2577:
2578: return f[0].getObject().getVersionList()
2579:
2580:
2581: def URLquote(self,str):
2582: """quote url"""
2583: return urllib.quote(str)
2584:
2585: def URLunquote(self,str):
2586: """unquote url"""
2587: return urllib.unquote(str)
2588:
2589: def URLquote_plus(self,str):
2590: """quote url"""
2591: return urllib.quote_plus(str)
2592:
2593: def URLunquote_plus(self,str):
2594: """unquote url"""
2595: return urllib.unquote_plus(str)
2596:
2597:
2598: def forceunlock(self):
2599: "break all locks"
2600: ret=[]
2601: for f in self.ZopeFind(self,obj_metatypes="CDLI file",search_sub=1):
2602: un=f[1].forceunlock()
2603:
2604: if un and un !="":
2605: ret.append((f[0],un))
2606:
2607: return ret
2608:
2609:
2610: def getChangesByAuthor(self,author,n=100):
2611: """getChangesByAuthor"""
2612: zcat=self.CDLIObjectsCatalog
2613: res=zcat({'lastEditor':author,
2614: 'sort_on':'getTime',
2615: 'sort_order':'descending',
2616: 'sort_limit':n})[:n ]
2617:
2618: return res
2619:
2620: def getChangesByAuthor_html(self,author,n=100):
2621: """html output for changes by author"""
2622: tmp={}
2623: list=[]
2624: for x in self.getChangesByAuthor(author):
2625: nr=x.getObject().getVersionNumber()
2626: id=x.getObject().aq_parent.getId()
2627: #hinzufuegen, wenn Version neuer als die
2628: if tmp.get(id,(0,0))[1] < nr:
2629: tmp[id]=(x.getObject().aq_parent,nr)
2630:
2631:
2632: return self.cdli_main.findObjectsFromListWithVersion(list=tmp.values(),author=author)
2633:
2634: def getLastChanges(self,n=100):
2635: """get the last n changes"""
2636: n=int(n)
2637: zcat=self.CDLICatalog
2638: return zcat({'sort_on':'getLastChangeDate',
2639: 'sort_order':'descending',
2640: 'sort_limit':n})[:n ]
2641:
2642:
2643: def getLastChanges_html(self,n=100):
2644: """get the last n changes"""
2645: list = [x.getId for x in self.getLastChanges(n)]
2646: return self.cdli_main.findObjectsFromList(list=list,display=True)
2647:
2648: def refreshTxt(self,txt="",threadName=None):
2649: """txt fuer refresh"""
2650:
2651: return """ 2;url=%s?repeat=%s """%(self.absolute_url()+txt,threadName)
2652:
2653: def refreshTxtBasket(self,txt="",threadName=None):
2654: """txt fuer refresh"""
2655:
2656: return """ 2;url=%s?repeat=%s """%(txt,threadName)
2657:
2658:
2659: def getResult(self,threadName=None):
2660: """result of thread"""
2661: try:
2662: return self._v_uploadATF[threadName].getResult()
2663: except:
2664: return "One moment, please"
2665:
2666:
2667: def checkThreads(self):
2668: """check threads"""
2669: ret="<html><body>"
2670: for thread in threading.enumerate():
2671: ret+="<p>%s (%s): %s</p>"%(repr(thread),thread.getName(),thread.isAlive())
2672:
2673: return ret
2674:
2675:
2676: def uploadATFRPC(self,data,username):
2677: """upload an atffile via xml-rpc"""
2678: uploader=uploadATFThread()
2679:
2680: #generate an random id for the upload object
2681: from random import randint
2682: if (not self.REQUEST.SESSION.get('idTmp',None)):
2683:
2684: idTmp=str(randint(0,1000000000))
2685: self.REQUEST.SESSION['idTmp']=idTmp
2686: else:
2687: idTmp=self.REQUEST.SESSION.get('idTmp',None)
2688:
2689:
2690: uploader.set(data,0,username,idTmp)
2691:
2692: stObj=uploader.run()
2693:
2694: processor=uploadATFfinallyThread()
2695:
2696: basketname=stObj.returnValue['basketNameFromFile']
2697:
2698: processor.set("uploadchanged",basketname=basketname,SESSION=stObj.returnValue,username=username,serverport=self.REQUEST['SERVER_PORT'])
2699:
2700: processor.run()
2701:
2702:
2703: return generateXMLReturn(stObj.returnValue)
2704:
2705: def uploadATF(self,repeat=None,upload=None,basketId=0,RESPONSE=None):
2706: """upload an atf file / basket file"""
2707: #self._v_uploadATF.returnValue=None
2708:
2709: #generate an random id for the upload thread
2710: from random import randint
2711: if (not self.REQUEST.SESSION.get('idTmp',None)):
2712:
2713: idTmp=str(randint(0,1000000000))
2714: self.REQUEST.SESSION['idTmp']=idTmp
2715: else:
2716: idTmp=self.REQUEST.SESSION.get('idTmp',None)
2717:
2718:
2719: threadName=repeat
2720: if not threadName or threadName=="":
2721: #new thread not called from the waiting page
2722: tmpVar=False
2723:
2724: thread=uploadATFThread()
2725: threadName=thread.getName()[0:]
2726: if (not hasattr(self,'_v_uploadATF')):
2727: self._v_uploadATF={}
2728:
2729: self._v_uploadATF[threadName]=thread
2730: #self._xmltrans.start()
2731: #thread=Thread(target=self._v_uploadATF)
2732: logging.info("set thread. extern")
2733: self._v_uploadATF[threadName].set(upload,basketId,self.REQUEST['AUTHENTICATED_USER'],idTmp,serverport=self.REQUEST['SERVER_PORT'])
2734: #thread.start()
2735: logging.info("start thread. extern")
2736: self._v_uploadATF[threadName].start()
2737:
2738:
2739: self.threadName=self._v_uploadATF[threadName].getName()[0:]
2740: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
2741:
2742: if wait_template:
2743: return wait_template[0][1]()
2744: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
2745: return pt(txt='/uploadATF',threadName=threadName)
2746: #_v_xmltrans.run()
2747:
2748: else:
2749: #recover thread, if lost
2750: if (not hasattr(self,'_v_uploadATF')):
2751: self._v_uploadATF={}
2752: if not self._v_uploadATF.get(threadName,None):
2753: for thread in threading.enumerate():
2754: if threadName == thread.getName():
2755: self._v_uploadATF[threadName]=thread
2756:
2757: if self._v_uploadATF.get(threadName,None) and (not self._v_uploadATF[threadName].returnValue):
2758:
2759:
2760: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
2761: if wait_template:
2762: return wait_template[0][1]()
2763:
2764: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
2765:
2766: return pt(txt='/uploadATF',threadName=threadName)
2767:
2768: else:
2769: tmp=getattr(self.temp_folder,idTmp).returnValue
2770:
2771: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadCheck.zpt')).__of__(self)
2772:
2773: return pt(changed=tmp['changed'],lockerrors=tmp['lockerrors'],errors=tmp['errors'],dir=tmp['dir'],newPs=tmp['newPs'],basketLen=tmp['basketLen'],numberOfFiles=tmp['numberOfFiles'],
2774: basketNameFromId=tmp['basketNameFromId'],basketNameFromFile=tmp['basketNameFromFile'],basketId=tmp['basketId'])
2775:
2776: def redoUpload(self,threadName):
2777: """redo the upload"""
2778: tmp=self.cdli_main.tmpStore2[threadName]
2779: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadCheck.zpt')).__of__(self)
2780: return pt(changed=tmp['changed'],lockerrors=tmp['lockerrors'],errors=tmp['errors'],dir=tmp['dir'],newPs=tmp['newPs'],basketLen=tmp['basketLen'],numberOfFiles=tmp['numberOfFiles'],
2781: basketNameFromId=tmp['basketNameFromId'],basketNameFromFile=tmp['basketNameFromFile'],basketId=tmp['basketId'])
2782:
2783: def uploadATFfinally(self,procedure='',comment="",basketname='',unlock=None,repeat=None,RESPONSE=None):
2784: """nowupload the files"""
2785:
2786:
2787:
2788: threadName=repeat
2789: if not threadName or threadName=="":
2790: thread=uploadATFfinallyThread()
2791: threadName=thread.getName()[0:]
2792:
2793: if (not hasattr(self,'_v_uploadATF')):
2794: self._v_uploadATF={}
2795:
2796:
2797: self._v_uploadATF[threadName]=thread
2798:
2799: idTmp=self.REQUEST.SESSION['idTmp']
2800: stObj=getattr(self.temp_folder,idTmp)
2801: 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'])
2802:
2803: self._v_uploadATF[threadName].start()
2804:
2805:
2806:
2807: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
2808:
2809: if wait_template:
2810: return wait_template[0][1]()
2811: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
2812:
2813: return pt(txt='/uploadATFfinally',threadName=threadName)
2814: #_v_xmltrans.run()
2815:
2816: else:
2817: #recover thread, if lost
2818: if not hasattr(self,'_v_uploadATF'):
2819: self._v_uploadATF={}
2820: if not self._v_uploadATF.get(threadName,None):
2821: for thread in threading.enumerate():
2822: if threadName == thread.getName():
2823: self._v_uploadATF[threadName]=thread
2824:
2825: if self._v_uploadATF.get(threadName,None) and (self._v_uploadATF[threadName] is not None) and (not self._v_uploadATF[threadName].end) :
2826:
2827: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
2828: if wait_template:
2829: return wait_template[0][1]()
2830:
2831: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
2832: return pt(txt='/uploadATFfinally',threadName=threadName)
2833: else:
2834:
2835:
2836: idTmp=self.REQUEST.SESSION['idTmp']
2837: stObj=getattr(self.temp_folder,idTmp)
2838: self.REQUEST.SESSION['idTmp']=None
2839:
2840: #update changed
2841: logging.debug("dir:"+repr(stObj.returnValue['changed']))
2842: for x in stObj.returnValue['changed']:
2843: ob=self.CDLICatalog.search({'title':x[0]})
2844:
2845: self.cdliRoot.updateOrAddToFileBTree(ob[0].getObject())
2846: if RESPONSE is not None:
2847: RESPONSE.redirect(self.absolute_url())
2848:
2849: def importFiles(self,comment="",author="" ,folderName="/Users/dwinter/atf", files=None,ext=None):
2850: """import files"""
2851: logging.debug("importFiles folderName=%s files=%s ext=%s"%(folderName,files,ext))
2852: root=self.cdli_main
2853: count=0
2854: if not files:
2855: files=os.listdir(folderName)
2856:
2857: for f in files:
2858: folder=f[0:3]
2859: f2=f[0:5]
2860:
2861: #check if main folder PXX already exists
2862: obj=self.ZopeFind(root,obj_ids=[folder])
2863: logging.debug("importFiles: folder=%s f2=%s obj=%s"%(folder,f2,obj))
2864: if ext:
2865: ext.result="<p>adding: %s </p>"%f+ext.result
2866:
2867:
2868: if not obj: # if not create it
2869: manage_addCDLIFileFolder(root,folder,folder)
2870: fobj=getattr(root,folder)
2871: #transaction.get().commit()
2872:
2873: else:
2874: fobj=obj[0][1]
2875:
2876: #check IF PYYYYY already exist
2877: obj2=fobj.ZopeFind(fobj,obj_ids=[f2])
2878: logging.debug("importFiles: fobj=%s obj2=%s"%(fobj,obj2))
2879:
2880: if not obj2:# if not create it
2881: manage_addCDLIFileFolder(fobj,f2,f2)
2882: fobj2=getattr(fobj,f2)
2883:
2884: else:
2885: fobj2=obj2[0][1]
2886:
2887: # not add the file
2888: file2=os.path.join(folderName,f)
2889: id=f
2890: logging.debug("importFiles: addCDLIFile fobj2=%s, f=%s file2=%s"%(fobj2,repr(f),repr(file2)))
2891: fobj2.addFile(vC='',file=file(file2),author=author,newName=f)
2892: count+=1
2893:
2894: #now add the file to the storage
2895: ob = getattr(fobj2,f)
2896: self.cdliRoot.updateOrAddToFileBTree(ob)
2897:
2898: if count%100==0:
2899: logging.debug("importfiles: committing")
2900: transaction.get().commit()
2901:
2902: transaction.get().commit()
2903: return "ok"
2904:
2905:
2906: manage_addCDLIRootForm=DTMLFile('dtml/rootAdd', globals())
2907:
2908:
2909: def manage_addCDLIRoot(self, id, title='',
2910: createPublic=0,
2911: createUserF=0,
2912: REQUEST=None):
2913: """Add a new Folder object with id *id*.
2914:
2915: If the 'createPublic' and 'createUserF' parameters are set to any true
2916: value, an 'index_html' and a 'UserFolder' objects are created respectively
2917: in the new folder.
2918: """
2919: ob=CDLIRoot()
2920: ob.id=str(id)
2921: ob.title=title
2922: try:
2923: self._setObject(id, ob)
2924: except:
2925: pass
2926: ob=self._getOb(id)
2927:
2928: checkPermission=getSecurityManager().checkPermission
2929:
2930: if createUserF:
2931: if not checkPermission('Add User Folders', ob):
2932: raise Unauthorized, (
2933: 'You are not authorized to add User Folders.'
2934: )
2935: ob.manage_addUserFolder()
2936:
2937:
2938: if REQUEST is not None:
2939: return self.manage_main(self, REQUEST, update_menu=1)
2940:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>