Annotation of cdli/cdli_files.py, revision 1.27
1.22 dwinter 1: """CDLI extensions of the filearchive"""
1.1 dwinter 2: from Products.versionedFile.versionedFile import *
3: from Products.ZCatalog.CatalogPathAwareness import CatalogAware
1.22 dwinter 4: from tempfile import mkstemp,mkdtemp
1.1 dwinter 5: import os.path
6: import os
7: from types import *
1.3 dwinter 8: import urlparse
1.4 dwinter 9: from OFS.OrderedFolder import OrderedFolder
10: from OFS.SimpleItem import SimpleItem
11: import time
1.12 dwinter 12: from OFS.Folder import manage_addFolder
13: import re
1.19 dwinter 14: from AccessControl import ClassSecurityInfo
15: from Acquisition import Implicit
16: from threading import Thread
17: from ZPublisher.HTTPRequest import HTTPRequest
18: from ZPublisher.HTTPResponse import HTTPResponse
19: from ZPublisher.BaseRequest import RequestContainer
1.20 dwinter 20: import threading
1.26 dwinter 21:
1.22 dwinter 22:
1.19 dwinter 23:
24: class uploadATFfinallyThread(Thread):
1.20 dwinter 25: """class for adding uploaded filed (temporarily stored in the staging area at /tmp"""
26:
1.19 dwinter 27: def __init__(self):
1.20 dwinter 28: """init for uploadATFfinallyThread"""
1.19 dwinter 29: self.continueVar=True
30: self.returnValue=None
31: self.end=False
32: Thread.__init__(self)
33:
34: def set(self,procedure,comment="",basketname='',unlock=None,SESSION=None,username=None,serverport="8080"):
1.20 dwinter 35: """set start values for the thread"""
1.19 dwinter 36: self.procedure=procedure
37: self.comment=comment
38: self.basketname=basketname
39: self.unlock=unlock
40: self.SESSION=SESSION
41: self.username=username
42: self.serverport=serverport
43:
44: def __call__(self):
1.20 dwinter 45: """call of the thread (equals run)"""
1.19 dwinter 46: self.run()
47: return True
48:
49: def getContext(self, app,serverport="8080"):
1.20 dwinter 50: """get the context within the ZODB"""
51:
1.19 dwinter 52: resp = HTTPResponse(stdout=None)
53: env = {
54: 'SERVER_NAME':'localhost',
55: 'SERVER_PORT':serverport,
56: 'REQUEST_METHOD':'GET'
57: }
58: req = HTTPRequest(None, env, resp)
59: return app.__of__(RequestContainer(REQUEST = req))
60:
1.26 dwinter 61:
1.19 dwinter 62: def run(self):
1.20 dwinter 63: """run"""
64:
1.19 dwinter 65: self.result=""
1.20 dwinter 66: #find context within ZODB
1.19 dwinter 67: from Zope import DB
68: conn = DB.open()
69: root = conn.root()
70: app = root['Application']
71: ctx = self.getContext(app,serverport=self.serverport)
72:
1.20 dwinter 73: #add the files
1.19 dwinter 74: self.uploadATFfinallyThread(ctx,self.procedure,comment=self.comment,basketname=self.basketname,unlock=self.unlock,SESSION=self.SESSION,username=self.username)
1.20 dwinter 75: #commit the transactions
1.19 dwinter 76: get_transaction().commit()
77: conn.close()
1.20 dwinter 78: #set flag for end of this method
1.19 dwinter 79: self.end=True
80: return True
81:
1.22 dwinter 82: def __del__(self):
83: """delete"""
84:
85:
86:
1.19 dwinter 87: def getResult(self):
1.20 dwinter 88: """method for accessing result"""
89:
1.19 dwinter 90: return self.result
91:
92: def uploadATFfinallyThread(self,ctx,procedure,comment="",basketname='',unlock=None,RESPONSE=None,SESSION=None,username=None):
93: """upload the files"""
1.20 dwinter 94: #TODO: make this configurable, at the moment, rootFolder for cdli has to be cdliRoot
1.19 dwinter 95: ctx2=ctx.cdliRoot
96:
97: self.result+="<h2>Start processing</h2>"
1.20 dwinter 98:
99: #shall I only upload the changed files?
1.19 dwinter 100: if procedure=="uploadchanged":
101:
102: uploadFns=SESSION.get('changed',[])+SESSION.get('newPs',[])
103:
1.20 dwinter 104: #or all
1.19 dwinter 105: elif procedure=="uploadAll":
106: uploadFns=[]
107: for x in os.listdir(SESSION['tmpdir']):
108: if not x in SESSION['errors']:
109: uploadFns.append(x)
1.20 dwinter 110:
111: #or maybe nothing
1.19 dwinter 112: elif procedure=="noupload":
113: return True
114: else:
115: uploadFns=[]
116:
1.20 dwinter 117: #do first the changed files
1.19 dwinter 118: for fn in uploadFns:
119: founds=ctx2.CDLICatalog.search({'title':fn})
120: if len(founds)>0:
121: SESSION['author']=str(username)
122: self.result+="<p>Changing : %s"%fn
123: founds[0].getObject().manage_addCDLIFileObject('',comment,SESSION['author'],file=file(os.path.join(SESSION['tmpdir'],fn)))
124:
125:
1.20 dwinter 126: #now add the new files
1.19 dwinter 127: newPs=SESSION['newPs']
128: if len(newPs)>0:
129: tmpDir=SESSION['tmpdir']
130: self.result+="<p>Adding files</p>"
1.20 dwinter 131: #TODO: make this configurable, at the moment base folder for the files has to be cdli_main
1.22 dwinter 132:
133: ctx2.importFiles(comment=comment,author=str(username) ,folderName=tmpDir, files=newPs,ext=self)
1.19 dwinter 134:
135:
136:
1.20 dwinter 137: #unlock locked files?
1.19 dwinter 138: if unlock:
139: self.result+="<p>Unlock files</p>"
140: unlockFns=[]
141: for x in os.listdir(SESSION['tmpdir']):
142: if not x in SESSION['errors']:
143: unlockFns.append(x)
144:
145: for fn in unlockFns:
146: founds=ctx2.CDLICatalog.search({'title':fn})
147: if len(founds)>0:
148: SESSION['author']=str(username)
149:
150: founds[0].getObject().lockedBy=""
151:
1.20 dwinter 152: #if a basketname is give, add files to the basket
1.19 dwinter 153: if not (basketname ==''):
154: self.result+="<p>Add basket</p>"
155: basketId=ctx2.basketContainer.getBasketIdfromName(basketname)
156:
157: if not basketId: # create new basket
158: ob=ctx2.basketContainer.addBasket(basketname)
159: basketId=ob.getId()
160: basket=getattr(ctx2.basketContainer,str(basketId))
161: ids=os.listdir(SESSION['tmpdir'])
162: basket.addObjects(ids,deleteOld=True,username=str(username))
163:
164: if RESPONSE is not None:
165: RESPONSE.redirect(self.aq_parent.absolute_url())
166:
167:
168:
169: return True
170:
171: class uploadATFThread(Thread):
1.20 dwinter 172: """class for checking the files befor uploading"""
1.19 dwinter 173:
174: def __init__(self):
1.20 dwinter 175: """initialise"""
176:
1.19 dwinter 177: self.continueVar=True
178: self.returnValue=None
179:
180: Thread.__init__(self)
181:
182:
183: def set(self,upload,basketId,username,serverport="8080"):
1.20 dwinter 184: """set start values for the thread"""
1.19 dwinter 185: self.result=""
186: self.upload=upload
187: self.basketId=basketId
188: self.username=username
189: self.serverport=serverport
190:
191: def __call__(self):
1.20 dwinter 192: """call method """
1.19 dwinter 193: self.run()
194: return True
195:
196: def getContext(self, app,serverport="8080"):
1.20 dwinter 197: """get the context within the ZODB"""
1.19 dwinter 198: resp = HTTPResponse(stdout=None)
199: env = {
200: 'SERVER_NAME':'localhost',
201: 'SERVER_PORT':serverport,
202: 'REQUEST_METHOD':'GET'
203: }
204: req = HTTPRequest(None, env, resp)
205: return app.__of__(RequestContainer(REQUEST = req))
206:
207: def run(self):
208:
209: self.result=""
1.20 dwinter 210: #find context within ZODB
1.19 dwinter 211: from Zope import DB
212: conn = DB.open()
213: root = conn.root()
214: app = root['Application']
215: ctx = self.getContext(app,serverport=self.serverport)
216: self.uploadATFThread(ctx,self.upload,self.basketId)
1.24 dwinter 217:
218: ctx.cdliRoot.cdli_main.tmpStore2[self.getName()[0:]]=self.returnValue
219:
1.22 dwinter 220: get_transaction().commit()
1.19 dwinter 221:
222: while self.continueVar:
223: pass
1.22 dwinter 224:
1.19 dwinter 225: conn.close()
1.22 dwinter 226:
1.19 dwinter 227:
228: def getResult(self):
1.20 dwinter 229: """method for accessing result"""
1.19 dwinter 230: return self.result
231:
232: def uploadATFThread(self,ctx,upload,basketId=0):
233: """upload an atf file"""
234: #TODO: add comments
235: #TODO: finish uploadATF
1.25 dwinter 236: self.result="<html><body><h2>I got your file, start now to split it into single atf-files!</h2><p>"
237:
1.20 dwinter 238: #make sure that id is a string and not an integer
1.19 dwinter 239: basketId=str(basketId)
240:
1.20 dwinter 241: #TODO: make this configurable, at the moment, rootFolder for cdli has to be cdliRoot
242: ctx2=ctx.cdliRoot
1.19 dwinter 243:
1.20 dwinter 244: #get temporary file for staging the downloaded and splitted files
1.19 dwinter 245: dir=mkdtemp()
1.20 dwinter 246:
247:
248: changed=[] # changed files
249: errors=[] # files with errors
250: newPs=[] # new p filed
251: psNotInCatalog=[] # files not in the catalog
252:
253: #split the uploadedd atf file
1.25 dwinter 254: basketNameFromFile, numberOfFiles=splitatf(upload,dir,ext=self)
1.19 dwinter 255:
1.20 dwinter 256: #find basketId if not set
257:
258: #get active abaket
1.19 dwinter 259: if basketId == '0':
260: basketObj=ctx2.basketContainer.getActiveBasket()
261: if basketObj:
262: basketId=basketObj.getId()
263:
1.20 dwinter 264: #if there is no active baske and no basketid given, id is empty, else get besketname and length
1.19 dwinter 265: if basketId == '0':
266: basketNameFromId=""
267: basketLen=0
268: else:
269: basketNameFromId=getattr(ctx2.basketContainer,basketId).title
270: basketLen=getattr(ctx2.basketContainer,basketId).getLastVersion().numberOfItems()
271:
272:
1.25 dwinter 273: self.result+="""<html><body><h2>I got the files</h2><
274: p>I am computing the differences to the exisiting files</p>"""
1.20 dwinter 275:
276: #start to check the files
1.19 dwinter 277: for fn in os.listdir(dir):
278:
1.25 dwinter 279: self.result+="<p>process:%s</p>"%fn
1.19 dwinter 280:
1.20 dwinter 281: # check if file is in the catalog
282: #TODO: checkCatalog is not implemented yet
1.19 dwinter 283: if ctx2.cdli_main.checkCatalog(fn):
284: psNotInCatalog.append(fn)
285:
1.20 dwinter 286: #check if p-file already at the server
1.19 dwinter 287: founds=ctx2.CDLICatalog.search({'title':fn})
288:
1.20 dwinter 289: #if not than add filename to the list of newfiles
1.19 dwinter 290: if len(founds)==0:
291: newPs.append(fn)
1.20 dwinter 292:
293: #if p file alread at the server
1.19 dwinter 294: for found in founds:
1.20 dwinter 295: #analyse the differences to the actual file
1.19 dwinter 296: obj=found.getObject()
297:
298: if (not obj.lockedBy=='') and (not obj.lockedBy==self.username):
299: errors.append(obj)
300: else:
301: data=file(os.path.join(dir,fn)).read()
302: diffs=obj.diff(data)
303: if diffs[0]>0:
304: changed.append((obj,diffs))
305: #hochladen
306:
1.20 dwinter 307: #ready, set the returnValues
1.19 dwinter 308: self.result+="<h3>Done</h3></body></html>"
309:
310: self.returnValue={}
311: self.returnValue['changed']=changed
312: self.returnValue['errors']=errors
313: self.returnValue['newPs']=newPs
314: self.returnValue['tmpdir']=dir
315: self.returnValue['basketLen']=basketLen
316: self.returnValue['numberOfFiles']=numberOfFiles
317: self.returnValue['basketNameFromId']=basketNameFromId
318: self.returnValue['basketNameFromFile']=basketNameFromFile
319: self.returnValue['basketId']=basketId
320: self.returnValue['dir']=dir
321:
322: #ctx2.cdli_main.setTemp('v_uploadATF_returnValue',True)
323:
324:
1.4 dwinter 325: class Basket_old(Folder):
326: """shopping basket - alte fassung """
1.1 dwinter 327:
328: meta_type="Basket"
329: _v_stack={}
330:
1.3 dwinter 331: def getObjUrl(self,objId):
332: """getUrl"""
1.9 dwinter 333: founds=self.CDLICatalog.search({'title':objId})
1.3 dwinter 334: if len(founds)>0:
335: return founds[0].getObject().absolute_url()
336:
1.4 dwinter 337: else: #assume version number
1.3 dwinter 338: splitted=objId.split("_")
1.9 dwinter 339: founds=self.CDLICatalog.search({'title':splitted[1]})
1.3 dwinter 340: return founds[0].getObject().absolute_url()+'/'+objId
341:
1.1 dwinter 342: def storeAllLink(self,results):
343: """erzeuge link zum speicher aller results"""
344: nr=self.REQUEST['_ZopeId']
345:
346: if results:
347: self._v_stack[nr]=[x.getObject().getId() for x in results]
348:
349: return self.absolute_url()+"/storeAll?id="+nr
350:
351: def storeAll(self,id):
352: """store all"""
353: try:
354: results=self._v_stack[id]
355: except:
356: #TODO: write expired page
357: return "expired"
358:
359: return self.storeInBasketForm(results)
360:
361: def storeInBasketForm(self,ids):
362: """ store an object form"""
363:
364: if type(ids) is not ListType:
365: ids=[ids]
366: self.REQUEST.SESSION['ids']=ids[0:]
367:
368: self.REQUEST.SESSION['BACKLINK']=self.REQUEST['HTTP_REFERER']
369:
370: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','storeBasketObject.zpt')).__of__(self)
371: return pt()
372:
373: def storeInBasket(self,username,ids=None,RESPONSE=None,REQUEST=None):
374: """store it"""
375:
376: if not ids:
377: ids=REQUEST.SESSION['ids']
378:
379: self.REQUEST.SESSION['basketUser']=username
380:
381: baskets=self.ZopeFind(self,obj_ids=[username])
382: if len(baskets)>0:
383: basket=baskets[0][1]
384: else:
385: manage_addBasketObject(self,username)
386: basket=self._getOb(username)
387:
388:
389: basket.addObjects(ids)
390: back=self.REQUEST.SESSION.get('BACKLINK', None)
391:
392: if RESPONSE:
393: RESPONSE.redirect(back)
394:
395:
396:
397: def showBasket(self,user=None,set=None,RESPONSE=None):
398: """show the basket"""
399:
400: if user:
401: self.REQUEST.SESSION['basketUser']=user
402:
403: if not user and not set:
404: user=self.REQUEST.SESSION.get('basketUser',None)
405:
406: if not user:
1.4 dwinter 407: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','orizeBasketUser.zpt')).__of__(self)
1.1 dwinter 408: return pt()
409: else:
410: baskets=self.ZopeFind(self,obj_ids=[user])
411:
412:
413: if len(baskets)>0:
414: RESPONSE.redirect(baskets[0][1].absolute_url())
415: return True
416: else:
417: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','emptyBasket.zpt')).__of__(self)
418: return pt()
419:
420:
1.4 dwinter 421: def manage_addBasket_oldForm(self):
1.1 dwinter 422: """add the basket form"""
423: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addBasket.zpt')).__of__(self)
424: return pt()
425:
1.4 dwinter 426: def manage_addBasket_old(self,id,title,RESPONSE=None):
1.1 dwinter 427: """add the basket"""
428: ob=Basket()
429:
430: ob.id=str(id)
431: ob.title=title
432: self._setObject(id, ob)
433: ob=self._getOb(id)
434:
435: if RESPONSE is not None:
436: RESPONSE.redirect('manage_main')
437:
438:
1.4 dwinter 439: class BasketObject_old(Folder):
440: """Basket Object - alte fassung"""
1.1 dwinter 441:
1.2 dwinter 442: meta_type="basketObject"
1.1 dwinter 443: def __init__(self):
1.16 dwinter 444: """init basket object"""
445: self.contents=[]
1.1 dwinter 446:
447: def numberOfItems(self):
448: """return anzahl der elemente im basket"""
449: return len(self.contents)
450:
451: def addObjects(self,ids):
452: """addObjects"""
453:
454: for id in ids:
1.9 dwinter 455: founds=self.CDLICatalog.search({'title':id})
1.1 dwinter 456: for found in founds:
457: if found.getObject() not in self.contents:
458: tm=self.contents[0:]
459: tm.append(found.getObject())
460: self.contents=tm[0:]
461:
462: return True
463:
464: def index_html(self):
1.16 dwinter 465: """view the basket"""
466: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','basketObject_index_html.zpt')).__of__(self)
467: return pt()
1.1 dwinter 468:
469: def deleteObjects(self,ids,RESPONSE=None):
470: """delete objects"""
471: list = self.contents[0:]
472: for content in list:
473:
474: if content.getId() in ids:
475: self.contents.remove(content)
476:
477:
478: if RESPONSE:
1.16 dwinter 479: RESPONSE.redirect(self.absolute_url())
1.1 dwinter 480:
481:
1.2 dwinter 482: def unlockTest(self):
483: """unlock all files of the testuser for debuggin"""
484: for object in self.contents:
485:
486: if str(object.lockedBy)=="test":
487: object.lockedBy=""
488:
489: def downloadObjectsAsOneFile(self,lock=None,procedure=None,REQUEST=None):
1.1 dwinter 490: """download all selected files in one file"""
1.2 dwinter 491:
1.1 dwinter 492: ret=""
1.2 dwinter 493: lockedObjects={}
494:
495:
496: if lock:
497:
498: if str(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
499:
500: return "please login first"
501:
502: #check if a locked object exist in the basket.
503: lockedObjects={}
504: for object in self.contents:
505:
506: if not object.lockedBy=="":
507: lockedObjects[object.title]=repr(object.lockedBy)
508:
509:
510: keys=lockedObjects.keys()
511:
512:
513: if len(keys)>0 and (not procedure):
514: self.REQUEST.SESSION['lockedObjects']=lockedObjects
515: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','lockedObjects.zpt')).__of__(self)
516: return pt()
517:
518: elif not procedure: #keine fails gesperrt dann alle donwloaden
519: procedure="downloadAll"
520:
1.16 dwinter 521:
1.1 dwinter 522: for object in self.contents:
1.2 dwinter 523:
524: if (procedure=="downloadAll") or (object.lockedBy=='') or (object.lockedBy==self.REQUEST['AUTHENTICATED_USER']):
525: ret+=object.getLastVersion().data
526:
527: if lock and object.lockedBy=='':
528: object.lockedBy=self.REQUEST['AUTHENTICATED_USER']
529:
1.1 dwinter 530:
531: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename="basket_%s.atf" """%self.getId())
532: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
1.2 dwinter 533: length=len(ret)
534: self.REQUEST.RESPONSE.setHeader("Content-Length",length)
1.1 dwinter 535: self.REQUEST.RESPONSE.write(ret)
1.2 dwinter 536:
537:
1.4 dwinter 538: def manage_addBasket_oldObjectForm(self):
1.1 dwinter 539: """add form"""
540: pass
541:
1.4 dwinter 542: def manage_addBasket_oldObject(self,id,title='',RESPONSE=None):
1.1 dwinter 543: """add"""
544:
545: ob=BasketObject()
546:
547: ob.id=str(id)
548: ob.title=title
549: self._setObject(id, ob)
550: ob=self._getOb(id)
551:
552: if RESPONSE is not None:
553: RESPONSE.redirect('manage_main')
554:
1.4 dwinter 555:
556: class CDLIBasketContainer(OrderedFolder):
557: """contains the baskets"""
558:
559:
1.9 dwinter 560: security=ClassSecurityInfo()
1.4 dwinter 561: meta_type="CDLIBasketContainer"
562:
1.12 dwinter 563: def deleteBaskets(self,ids=None):
564: """delete baskets, i.e. move them into trash folder"""
565:
566:
567: found=self.ZopeFind(self,obj_ids=['trash'])
568:
569: if len(found)<1:
570: manage_addFolder(self, 'trash')
571: trash=self._getOb('trash')
572: else:
573: trash=found[0][1]
574:
575: if type(ids) is not ListType:
576: ids=[ids]
577: cut=self.manage_cutObjects(ids)
578: trash.manage_pasteObjects(cut)
579:
580: def manageBaskets(self,ids,submit,REQUEST=None,RESPONSE=None):
581: """manage baskets, delete or copy"""
582: if submit=="delete":
583: self.deleteBaskets(ids)
584:
585:
586:
587: if RESPONSE:
588: RESPONSE.redirect(self.absolute_url())
1.5 dwinter 589: def getBasketIdfromName(self,basketname):
590: """get id from name"""
591:
592: for basket in self.ZopeFind(self,obj_metatypes=["CDLIBasket"]):
593: if basket[1].title==basketname:
594: return basket[0]
595: else:
596: None
1.9 dwinter 597:
598: security.declareProtected('manage','uploadBasket_html')
599:
1.4 dwinter 600: def uploadBasket_html(self,basketId='0'):
601: """upload an atf file, html form"""
1.9 dwinter 602:
603:
1.4 dwinter 604: basketId=str(basketId)
605: if not basketId=='0':
606: basketName=getattr(self.basketContainer,basketId).title
607: else:
608: basketName=""
609:
610: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadBasket_html.zpt')).__of__(self)
611: return pt(basketId=basketId,basketName=basketName)
612:
613:
614:
615: def index_html(self):
616: """stanadard ansicht"""
1.9 dwinter 617:
618:
619:
1.4 dwinter 620: ext=self.ZopeFind(self,obj_ids=["index.html"])
621: if ext:
622: return ext[0][1]()
623:
624: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','BasketContainerMain')).__of__(self)
625: return pt()
626:
627: def getStorageFolderRoot(self):
628: """root des storage folders"""
629: return self.cdli_main
630:
631: def __init__(self,id,title):
632: """ init basket container"""
633: self.id=id
634: self.title=title
635:
636:
637: def getBaskets(self,sortField='title'):
638: """get all baskets files"""
639:
640: def sortName(x,y):
641: return cmp(x[1].title.lower(),y[1].title.lower())
642:
643: def sortDate(x,y):
644: return cmp(y[1].getLastVersion().getTime(),x[1].getLastVersion().getTime())
645:
646:
647: def sortComment(x,y):
648:
649:
650:
651: try:
652: xc=getattr(x[1],'comment','ZZZZZZZZZZZZZ').lower()
653: except:
654: xc='ZZZZZZZZZZZZZ'.lower()
655: try:
656: yc=getattr(y[1],'comment','ZZZZZZZZZZZZZ').lower()
657: except:
658: yc='ZZZZZZZZZZZZZ'.lower()
659:
660:
661: if (xc=='') or (xc=='ZZZZZZZZZZZZZ'.lower()):
662:
663: try:
664: xc=x[1].getLastVersion().getComment().lower()
665: except:
666: xc='ZZZZZZZZZZZZZ'.lower()
667:
668: if (yc=='') or (yc=='ZZZZZZZZZZZZZ'.lower()):
669: try:
670: yc=y[1].getLastVersion().getComment().lower()
671: except:
672: yc='ZZZZZZZZZZZZZ'.lower()
673:
674:
675: return cmp(xc,yc)
676:
677: def sortAuthor(x,y):
678:
679: return cmp(x[1].getLastVersion().getUser().lower(),y[1].getLastVersion().getUser().lower())
680:
681: baskets=self.ZopeFind(self,obj_metatypes=['CDLIBasket'])
682:
683:
684: if sortField=='title':
685: baskets.sort(sortName)
686: elif sortField=='date':
687: baskets.sort(sortDate)
688: elif sortField=='author':
689: baskets.sort(sortAuthor)
690: elif sortField=='comment':
691: baskets.sort(sortComment)
692:
693: return baskets
694:
695:
696:
697: def getNewId(self):
698: """createIds"""
699: last=getattr(self,'last',0)
700: last +=1
701: while len(self.ZopeFind(self,obj_ids=[str(last)]))>0:
702: last+=1
703:
704: self.last=last
705: return last
706:
1.6 dwinter 707: def setActiveBasket(self,basketId,REQUEST=None):
1.4 dwinter 708: """store active basketId in a cookie"""
709: self.REQUEST.RESPONSE.setCookie("CDLIActiveBasket",basketId,path="/")
1.12 dwinter 710:
1.6 dwinter 711: if REQUEST:
1.12 dwinter 712: REQUEST.RESPONSE.redirect(REQUEST['URL1']+'?'+REQUEST['QUERY_STRING'])
1.6 dwinter 713:
1.4 dwinter 714: def getActiveBasket(self):
715: """get active basket from cookie"""
716:
717: id= self.REQUEST.cookies.get('CDLIActiveBasket',None)
1.6 dwinter 718: if id:
719: obj=getattr(self,str(id),None)
720: else:
721: obj=None
1.4 dwinter 722: return obj
1.6 dwinter 723:
1.4 dwinter 724: def getActualUserName(self):
725: """get name of the actualuser"""
726: return str(self.REQUEST['AUTHENTICATED_USER'])
727:
728:
729: def addBasket(self,newBasketName):
730: """add a new basket"""
731:
732: ob=manage_addCDLIBasket(self,newBasketName)
733: return ob
734:
1.6 dwinter 735: def storeInBasket(self,submit,ids=None,newBasketName=None,fromFileList=None,RESPONSE=None,REQUEST=None):
1.4 dwinter 736: """store it"""
1.6 dwinter 737: if not ids:
738: ids=self.REQUEST.SESSION['fileIds']
739:
1.4 dwinter 740: if type(ids) is not ListType:
741: ids=[ids]
742:
1.6 dwinter 743: if (submit.lower()=="store in new basket") or (submit.lower()=="new basket"):
1.4 dwinter 744: basketRet=self.addBasket(newBasketName)
745: self.setActiveBasket(basketRet.getId())
746: basket=getattr(self,basketRet.getId())
1.6 dwinter 747: elif (submit.lower()=="store in active basket") or (submit.lower()=="active basket"):
1.4 dwinter 748: basket=self.getActiveBasket()
1.6 dwinter 749:
750: added=basket.addObjects(ids)
751: back=self.REQUEST['HTTP_REFERER'].split("?")[0]+"?basketName="+basket.title+"&numberOfObjects="+str(added)
752:
753:
754: if fromFileList:
1.7 dwinter 755:
1.6 dwinter 756: return self.cdli_main.findObjectsFromList(list=self.REQUEST.SESSION['fileIds'],basketName=basket.title,numberOfObjects=added)
757:
1.4 dwinter 758: if RESPONSE:
1.6 dwinter 759:
1.4 dwinter 760: RESPONSE.redirect(back)
761:
1.6 dwinter 762: return True
763:
1.4 dwinter 764: def manage_addCDLIBasketContainerForm(self):
765: """add the CDLIBasketContainer form"""
766: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addCDLIBasketContainer.zpt')).__of__(self)
767: return pt()
768:
769: def manage_addCDLIBasketContainer(self,id,title,RESPONSE=None):
770: """add the basket"""
771: ob=CDLIBasketContainer(id,title)
772:
773: self._setObject(id, ob)
774:
775: if RESPONSE is not None:
776: RESPONSE.redirect('manage_main')
777:
1.5 dwinter 778: class CDLIBasket(Folder,CatalogAware):
1.4 dwinter 779: """basket"""
780:
781: meta_type="CDLIBasket"
1.5 dwinter 782: default_catalog="CDLIBasketCatalog"
1.4 dwinter 783:
784: def getFile(self,obj):
785: return obj[1]
786:
787: def getFileLastVersion(self,obj):
788: return obj[0]
789:
1.5 dwinter 790: def getFileNamesInLastVersion(self):
791: """get content of the last version as list"""
792:
793: return [x[1].getId() for x in self.getLastVersion().getContent()]
794:
1.4 dwinter 795: def isActual(self,obj):
796: """teste ob im basket die aktuelle version ist"""
797: actualNo=obj[1].getLastVersion().getVersionNumber()
798: storedNo=obj[0].getVersionNumber()
1.12 dwinter 799:
800: founds=self.CDLICatalog.search({'title':obj[0].getId()})
801: if len(founds)>0 and founds[0].getObject().aq_parent.getId()==".trash":
802: return False, -1
803:
1.4 dwinter 804: if actualNo==storedNo:
1.12 dwinter 805: return True , 0
1.4 dwinter 806: else:
1.12 dwinter 807: return False, actualNo
1.4 dwinter 808:
809: def history(self):
810: """history"""
811:
812: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
813: if ext:
814: return getattr(self,ext[0][1].getId())()
815:
816: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','BasketHistory')).__of__(self)
817: return pt()
818:
819: def getStorageFolderRoot(self):
820: """root des storage folders"""
821: return self.aq_parent.cdli_main
822:
823: def __init__(self,id,title,shortDescription="",comment=""):
824: """init a CDLIBasket"""
825:
826: self.id=id
827: self.title=title
828: self.shortDescription=shortDescription
829: self.comment=comment
830:
831:
832:
833: def getLastVersion(self):
834: """hole letzte version"""
835: ids=[int(x[0]) for x in self.ZopeFind(self,obj_metatypes=["CDLIBasketVersion"])]
836: ids.sort()
837: if len(ids)==0:
838: return None
839: else:
840: ob=getattr(self,str(ids[-1]))
841: return ob
842:
843: def getVersions(self):
844: """get versions"""
845: versions=self.ZopeFind(self,obj_metatypes=["CDLIBasketVersion"])
846: return versions
847:
848:
849:
1.19 dwinter 850: def addObjects(self,ids,deleteOld=None,username=None):
1.4 dwinter 851: """generate a new version of the basket with objects added"""
852:
853: lastVersion=self.getLastVersion()
854:
855: if lastVersion is None:
856: oldContent=[]
857: else:
858: oldContent=lastVersion.basketContent[0:]
859:
860: if deleteOld:
861: oldContent=[]
862:
863: newContent=[]
1.6 dwinter 864: added=0
1.4 dwinter 865: for id in ids:
866: founds=self.CDLICatalog.search({'title':id})
1.6 dwinter 867:
1.4 dwinter 868: for found in founds:
869: if found.getObject() not in oldContent:
870: #TODO: was passiert wenn, man eine Object dazufgt, das schon da ist aber eine neuere version
871: newContent.append((found.getObject().getLastVersion(),found.getObject()))
1.6 dwinter 872: added+=1
1.4 dwinter 873:
874: content=oldContent+newContent
1.19 dwinter 875: if not username:
876: user=self.getActualUserName()
877: else:
878: user = username
879:
1.4 dwinter 880: ob=manage_addCDLIBasketVersion(self,user,comment="",basketContent=content)
881:
1.6 dwinter 882: return added
1.4 dwinter 883:
1.12 dwinter 884: def deleteObjects(self,ids,RESPONSE=None,REQUEST=None):
1.4 dwinter 885: """delete objects"""
1.12 dwinter 886:
887: if type(ids) is not ListType:
888: ids=[ids]
889:
890: lastVersion=self.getLastVersion()
891: oldContent=lastVersion.basketContent[0:]
892: newContent=[]
893: for obj in oldContent:
894: if obj[1].getId() not in ids:
895: newContent.append(obj)
896:
897:
898: user=self.getActualUserName()
899:
900: ob=manage_addCDLIBasketVersion(self,user,comment="",basketContent=newContent)
901:
902: if RESPONSE:
903: obj=self._getOb(ob.getId())
904: RESPONSE.redirect(obj.absolute_url())
1.4 dwinter 905:
906: def manage_addCDLIBasketForm(self):
907: """add the CDLIBasketContainer form"""
908: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addCDLIBasket.zpt')).__of__(self)
909: return pt()
910:
911: def manage_addCDLIBasket(self,title,shortDescription="",comment="",RESPONSE=None):
912: """add the basket"""
913:
914: id=str(self.getNewId())
915:
916: ob=CDLIBasket(id,title,shortDescription,comment)
917:
918: self._setObject(id, ob)
919:
920: if RESPONSE is not None:
921: RESPONSE.redirect('manage_main')
922: else:
923: return ob
924:
925: class CDLIBasketVersion(SimpleItem):
926: """version of a basket"""
927:
928: meta_type="CDLIBasketVersion"
929:
930: def downloadObjectsAsOneFile(self,lock=None,procedure=None,REQUEST=None):
931: """download all selected files in one file"""
932:
933: ret=""
934: lockedObjects={}
935:
936:
937: if lock:
938:
939: if str(self.REQUEST['AUTHENTICATED_USER'])=='Anonymous User':
940:
941: return "please login first"
942:
943: #check if a locked object exist in the basket.
944: lockedObjects={}
945: for object in self.basketContent:
946:
947: if not object[1].lockedBy=="":
948: lockedObjects[object[1].title]=repr(object[1].lockedBy)
949:
950:
951: keys=lockedObjects.keys()
952:
953:
954: if len(keys)>0 and (not procedure):
955: self.REQUEST.SESSION['lockedObjects']=lockedObjects
956: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','lockedObjects.zpt')).__of__(self)
957: return pt()
958:
959: elif not procedure: #keine fails gesperrt dann alle donwloaden
960: procedure="downloadAll"
961:
962:
963: for object in self.basketContent:
964:
965: if (procedure=="downloadAll") or (object[1].lockedBy=='') or (object[1].lockedBy==self.REQUEST['AUTHENTICATED_USER']):
966: ret+=object[0].data
967:
968: if lock and object[1].lockedBy=='':
969: object[1].lockedBy=self.REQUEST['AUTHENTICATED_USER']
970:
971: basket_name=self.aq_parent.title+"_V"+self.getId()
972:
973: #write basketname to header of atf file
974: ret="#atf basket %s\n"%basket_name+ret
975:
976: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename="%s.atf" """%basket_name)
977: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
978: length=len(ret)
979: self.REQUEST.RESPONSE.setHeader("Content-Length",length)
980: self.REQUEST.RESPONSE.write(ret)
981:
982:
983: def numberOfItems(self):
984: """return anzahl der elemente im basket"""
985: return len(self.basketContent)
986:
987: def getTime(self):
988: """getTime"""
989: #return self.bobobase_modification_time().ISO()
990:
991: if hasattr(self,'time'):
992: return time.strftime("%Y-%m-%d %H:%M:%S",self.time)
993: elif hasattr(self,'timefixed'):
994: return self.timefixed
995: else:
996: setattr(self,'timefixed',self.bobobase_modification_time().ISO())
997: return self.bobobase_modification_time().ISO()
998:
999: def getContent(self):
1000: """get Basket Content"""
1001: return self.basketContent
1002:
1003:
1004: def __init__(self,id,user,comment="",basketContent=[]):
1005: """ init a basket version"""
1006: self.id=id
1007: self.coment=comment
1008: self.basketContent=basketContent[0:]
1009: self.user=user
1010: self.time=time.localtime()
1011:
1012: def getUser(self):
1013: """get user"""
1014: return self.user
1015:
1016: def getComment(self):
1017: """get Comment"""
1018: return self.comment
1019:
1020: def index_html(self):
1021: """view the basket"""
1022: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','BasketVersionMain.zpt')).__of__(self)
1023: return pt()
1024:
1025: def getObjUrl(self,result):
1026: """getUrl of the version of the object"""
1027: objId=result[1].getTitle()
1028: founds=self.CDLICatalog.search({'title':objId})
1029: if len(founds)>0:
1.12 dwinter 1030: return founds[0].getObject().getLastVersion().absolute_url()
1.4 dwinter 1031:
1032: else: #assume version number
1033: splitted=objId.split("_")
1.9 dwinter 1034: founds=self.CDLICatalog.search({'title':splitted[1]})
1.12 dwinter 1035: return founds[0].getObject().getLastVersion().absolute_url()+'/'+objId
1.4 dwinter 1036:
1037: def manage_addCDLIBasketVersion(self,user,comment="",basketContent=[],RESPONSE=None):
1038: """add a version"""
1039:
1040: #check for already existing versions
1041:
1042: lastVersion=self.getLastVersion()
1043: if lastVersion is None:
1044: newId=str(1)
1045: else:
1046: newId=str(int(lastVersion.getId())+1)
1047:
1048: ob=CDLIBasketVersion(newId,user,comment,basketContent)
1049:
1050: self._setObject(newId, ob)
1051:
1052: if RESPONSE is not None:
1053: RESPONSE.redirect('manage_main')
1054: else:
1055: return ob
1056:
1.25 dwinter 1057: class CDLIFileObject(versionedFileObject,CatalogAware):
1.1 dwinter 1058: """CDLI file object"""
1059:
1060: meta_type="CDLI File Object"
1.25 dwinter 1061: default_catalog='CDLIObjectsCatalog'
1.1 dwinter 1062:
1.12 dwinter 1063: security=ClassSecurityInfo()
1064:
1.26 dwinter 1065:
1066: security.declarePublic('makeThisVersionCurrent')
1067:
1068: def makeThisVersionCurrent_html(self):
1069: """form for making this version current"""
1070:
1071: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','makeThisVersionCurrent.zpt')).__of__(self)
1072: return pt()
1.27 ! dwinter 1073: def makeThisVersionCurrent(self,comment,author,RESPONSE=None):
1.26 dwinter 1074: """copy this version to current"""
1075: parent=self.aq_parent
1076:
1077:
1078: newversion=parent.manage_addCDLIFileObject('',comment,author)
1079: newversion.data=self.data[0:]
1.27 ! dwinter 1080:
! 1081: if RESPONSE is not None:
! 1082: RESPONSE.redirect(self.aq_parent.absolute_url()+'/history')
! 1083:
! 1084:
1.26 dwinter 1085: return True
1086:
1087: security.declarePublic('view')
1088:
1.1 dwinter 1089: def view(self):
1090: """view file"""
1091: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','viewCDLIFile.zpt')).__of__(self)
1092: return pt()
1093:
1.12 dwinter 1094: security.declarePublic('getDesignation')
1095: def getDesignation(self):
1096: """get the designation out of the file"""
1.16 dwinter 1097: try:
1.18 dwinter 1098: txt=re.match("&[Pp](\d*)\s*=([^\r\n]*)",self.data[0:])
1.13 dwinter 1099: except:
1.16 dwinter 1100: txt=self.data[0:]
1101:
1102: return "ERROR"
1.12 dwinter 1103: try:
1104: return txt.group(2)
1105: except:
1106: return "ERROR"
1107:
1.1 dwinter 1108: manage_addCDLIFileObjectForm=DTMLFile('dtml/fileAdd', globals(),Kind='CDLIFileObject',kind='CDLIFileObject', version='1')
1109:
1110: def manage_addCDLIFileObject(self,id,vC='',author='', file='',title='',precondition='', content_type='',
1111: REQUEST=None):
1112: """Add a new File object.
1113:
1114: Creates a new File object 'id' with the contents of 'file'"""
1115:
1116: id=str(id)
1117: title=str(title)
1118: content_type=str(content_type)
1119: precondition=str(precondition)
1120:
1121: id, title = cookId(id, title, file)
1122:
1123: self=self.this()
1124:
1125: # First, we create the file without data:
1126: self._setObject(id, CDLIFileObject(id,title,'',content_type, precondition))
1127: self._getOb(id).versionComment=str(vC)
1128: self._getOb(id).time=time.localtime()
1129:
1130: setattr(self._getOb(id),'author',author)
1131:
1132: # Now we "upload" the data. By doing this in two steps, we
1133: # can use a database trick to make the upload more efficient.
1134: if file:
1135: self._getOb(id).manage_upload(file)
1136: if content_type:
1137: self._getOb(id).content_type=content_type
1138:
1139: if REQUEST is not None:
1140: REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')
1.3 dwinter 1141:
1142: class CDLIFile(versionedFile,CatalogAware):
1143: """CDLI file"""
1144:
1145: meta_type="CDLI file"
1146: default_catalog='CDLICatalog'
1.5 dwinter 1147:
1.26 dwinter 1148: #security.declarePublic('history')
1149: def history(self):
1150: """history"""
1151:
1152: ext=self.ZopeFind(self.aq_parent,obj_ids=["history_template.html"])
1153: if ext:
1154: return getattr(self,ext[0][1].getId())()
1155:
1156: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','versionHistory')).__of__(self)
1157: return pt()
1158:
1159:
1.12 dwinter 1160:
1.8 dwinter 1161: def isContainedInBaskets(self,context=None):
1162: """check is this file is part of any basket
1163: @param context: (optional) necessessary if CDLIBasketCatalog is not an (inherited) attribute of self, context.CDLIBasketCatalog
1164: has to exist.
1165: """
1166:
1167: if not context:
1168: context=self
1.12 dwinter 1169:
1170: ret=[]
1171: for x in context.CDLIBasketCatalog.search({'getFileNamesInLastVersion':self.getId()}):
1172: #if the basket x is deleted it seemes to be that x is sometimes still in the Catalog, why?
1173: try:
1174: ret.append(x.getObject())
1175: except:
1176: pass
1177: return ret
1178: #return [x.getObject() for x in context.CDLIBasketCatalog.search({'getFileNamesInLastVersion':self.getId()})]
1.5 dwinter 1179:
1180:
1181: def addCDLIFileObjectForm(self):
1182: """add a new version"""
1183:
1184: if str(self.REQUEST['AUTHENTICATED_USER']) in ["Anonymous User"]:
1185: return "please login first"
1186: if (self.lockedBy==self.REQUEST['AUTHENTICATED_USER']) or (self.lockedBy==''):
1187: out=DTMLFile('dtml/fileAdd', globals(),Kind='CDLIFileObject',kind='CDLIFileObject',version=self.getVersion()).__of__(self)
1188: return out()
1189: else:
1190: return "Sorry file is locked by somebody else"
1191:
1.3 dwinter 1192: def manage_addCDLIFileObject(self,id,vC,author,file='',title='',precondition='', content_type='',changeName='no',newName='', RESPONSE=None):
1193: """add"""
1194: try: #TODO: der ganze vC unsinn muss ueberarbeitet werden
1195: vC=self.REQUEST['vC']
1196: except:
1197: pass
1198:
1199:
1200: if changeName=="yes":
1201: filename=file.filename
1202: self.title=filename[max(filename.rfind('/'),
1203: filename.rfind('\\'),
1204: filename.rfind(':'),
1205: )+1:]
1206:
1207:
1208: if not newName=='':
1209: self.title=newName[0:]
1210:
1211:
1212:
1213:
1214:
1215: positionVersionNum=getattr(self,'positionVersionNum','front')
1216:
1217: if positionVersionNum=='front':
1218: id="V%i"%self.getVersion()+"_"+self.title
1219: else:
1220: tmp=os.path.splitext(self.title)
1221: if len(tmp)>1:
1222: id=tmp[0]+"_V%i"%self.getVersion()+tmp[1]
1223: else:
1224: id=tmp[0]+"_V%i"%self.getVersion()
1225:
1226:
1227: manage_addCDLIFileObject(self,id,vC,author,file,id,precondition, content_type)
1228: objs=self.ZopeFind(self,obj_ids=[id])[0][1].setVersionNumber(int(self.getVersion()))
1.22 dwinter 1229: try:
1230: #FIXME: wozu ist das gut?
1231: self.REQUEST.SESSION['objID_parent']=self.getId()
1232: except:
1233: pass
1.3 dwinter 1234: if RESPONSE:
1235: obj=self.ZopeFind(self,obj_ids=[id])[0][1]
1236: if obj.getSize()==0:
1237: self.REQUEST.SESSION['objID']=obj.getId()
1238: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','errorUploadFile')).__of__(self)
1239: return pt()
1240:
1241: else:
1.12 dwinter 1242: RESPONSE.redirect(self.REQUEST['URL2']+'?uploaded=%s'%self.title)
1.3 dwinter 1243:
1244: else:
1245: return self.ZopeFind(self,obj_ids=[id])[0][1]
1246:
1247:
1248: def manage_addCDLIFileForm(self):
1249: """interface for adding the OSAS_root"""
1250: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addCDLIFile.zpt')).__of__(self)
1251: return pt()
1252:
1253: def manage_addCDLIFile(self,id,title,lockedBy, author=None, RESPONSE=None):
1254: """add the OSAS_root"""
1255: newObj=CDLIFile(id,title,lockedBy,author)
1.22 dwinter 1256:
1257: tryToggle=True
1258: tryCount=0
1259:
1260:
1261:
1262: self._setObject(id,newObj)
1263:
1264:
1.3 dwinter 1265: if RESPONSE is not None:
1266: RESPONSE.redirect('manage_main')
1267:
1268:
1.1 dwinter 1269:
1270:
1.25 dwinter 1271: def splitatf(fh,dir=None,ext=None):
1.2 dwinter 1272: """split it"""
1.4 dwinter 1273: ret=None
1.2 dwinter 1274: nf=None
1.25 dwinter 1275: i=0
1.2 dwinter 1276: for line in fh.readlines():
1.25 dwinter 1277: if ext:
1278: i+=1
1279: if (i%100)==0:
1280: ext.result+="."
1281: if i==10000:
1282: i=0
1283: ext.result+="<br>"
1.4 dwinter 1284: #check if basket name is in the first line
1285: if line.find("#atf basket")>=0:
1286: ret=line.replace('#atf basket ','')
1.5 dwinter 1287: ret=ret.split('_')[0]
1.4 dwinter 1288: else:
1289: if (len(line.lstrip())>0) and (line.lstrip()[0]=="&"): #newfile
1290: if nf:
1291: nf.close() #close last file
1292:
1293:
1294: filename=line[1:].split("=")[0].rstrip()+".atf"
1295: if dir:
1296: filename=os.path.join(dir,filename)
1297: nf=file(filename,"w")
1298: if nf:
1299: nf.write(line)
1.2 dwinter 1300:
1301: nf.close()
1302: fh.close()
1.5 dwinter 1303: return ret,len(os.listdir(dir))
1.4 dwinter 1304:
1.19 dwinter 1305:
1.1 dwinter 1306: class CDLIFileFolder(versionedFileFolder):
1.4 dwinter 1307: """CDLI File Folder"""
1.1 dwinter 1308:
1.19 dwinter 1309: security=ClassSecurityInfo()
1.1 dwinter 1310: meta_type="CDLI Folder"
1311: filesMetaType=['CDLI file']
1312: folderMetaType=['CDLI Folder']
1313: default_catalog='CDLICatalog'
1.25 dwinter 1314: defaultFileCatalog=default_catalog #wenn dieses definiert ist, wird beim hinzufgen einer neuen version eines files dieser catalog neuiniziert
1315:
1.24 dwinter 1316: tmpStore2={}
1.19 dwinter 1317: def setTemp(self,name,value):
1318: """set tmp"""
1319:
1320: setattr(self,name,value)
1321:
1322:
1.12 dwinter 1323: def delete(self,ids):
1324: """delete this file, i.e. move into a trash folder"""
1325:
1326: found=self.ZopeFind(self,obj_ids=['.trash'])
1327:
1328: if len(found)<1:
1329: manage_addCDLIFileFolder(self, '.trash',title="Trash")
1330: trash=self._getOb('.trash')
1331: else:
1332: trash=found[0][1]
1333:
1334: if type(ids) is not ListType:
1335: ids=[ids]
1336: cut=self.manage_cutObjects(ids)
1337: trash.manage_pasteObjects(cut)
1338:
1.4 dwinter 1339: def getVersionNumbersFromIds(self,ids):
1340: """get the numbers of the current versions of documents described by their ids"""
1341:
1342: ret=[]
1343: searchStr=" OR ".join(ids)
1344:
1.9 dwinter 1345: founds=self.CDLICatalog.search({'title':searchStr})
1.4 dwinter 1346:
1347: for found in founds:
1348: lastVersion=found.getObject().getLastVersion()
1349: ret.append((found.getId,lastVersion))
1350:
1351: return ret
1352:
1.14 dwinter 1353: def checkCatalog(self,fn):
1354: """check if fn is in the catalog"""
1.19 dwinter 1355: #TODO add checkCatalog
1.14 dwinter 1356:
1357:
1.19 dwinter 1358:
1.26 dwinter 1359: def findObjectsFromListWithVersion(self,list):
1360: """find objects from a list with versions
1361: @param list: list of tuples (cdliFile,version)
1362: """
1363:
1364:
1365:
1366: #self.REQUEST.SESSION['fileIds']=list#store fieldIds in session for further usage
1367: #self.REQUEST.SESSION['searchList']=self.REQUEST.SESSION['fileIds']
1368:
1369:
1370: pt=getattr(self,'filelistVersioned.html')
1371:
1372: return pt(search=list)
1373:
1374:
1375:
1.25 dwinter 1376: def findObjectsFromList(self,display=False,start=None,upload=None,list=None,basketName=None,numberOfObjects=None,RESPONSE=None):
1.1 dwinter 1377: """findObjectsFromList (, TAB oder LINE separated)"""
1.15 dwinter 1378:
1379:
1.6 dwinter 1380: if upload: # list from file upload
1381: txt=upload.read()
1382: txt=txt.replace(",","\n")
1383: txt=txt.replace("\t","\n")
1.12 dwinter 1384: txt=txt.replace("\r","\n")
1.6 dwinter 1385: idsTmp=txt.split("\n")
1386: ids=[]
1387: for id in idsTmp: # make sure that no empty lines
1388: idTmp=id.lstrip().rstrip()
1389: if len(idTmp)>0:
1390:
1391: ids.append(idTmp)
1392:
1393: #self.REQUEST.SESSION['ids']=" OR ".join(ids)
1.12 dwinter 1394:
1.6 dwinter 1395: pt=getattr(self,'filelist.html')
1.7 dwinter 1396: self.REQUEST.SESSION['searchList']=ids
1.6 dwinter 1397: return pt(search=ids)
1.7 dwinter 1398:
1.6 dwinter 1399: if basketName:
1.7 dwinter 1400: #TODO: get rid of one of these..
1401:
1.6 dwinter 1402: pt=getattr(self,'filelist.html')
1.7 dwinter 1403: return pt(basketName=basketName,numberOfObjects=numberOfObjects)
1.6 dwinter 1404:
1.15 dwinter 1405: if list is not None: # got already a list
1.6 dwinter 1406: ret=[]
1407: for fileId in list:
1408: if len(fileId.split("."))==1:
1409: fileId=fileId+".atf"
1.12 dwinter 1410:
1.6 dwinter 1411: ret+=self.CDLICatalog({'title':fileId})
1.7 dwinter 1412: #TODO: get rid of one of these..
1.25 dwinter 1413: ids=[x.getObject().getId() for x in ret]
1414: self.REQUEST.SESSION['fileIds']=ids#store fieldIds in session for further usage
1.7 dwinter 1415: self.REQUEST.SESSION['searchList']=self.REQUEST.SESSION['fileIds']
1.25 dwinter 1416:
1417: if display:
1418: pt=getattr(self,'filelist.html')
1419:
1420: return pt(search=ids)
1421: else:
1422: return ret
1423:
1424:
1.1 dwinter 1425:
1.7 dwinter 1426: if start:
1427: RESPONSE.redirect("filelist.html?start:int="+str(start))
1.15 dwinter 1428:
1.18 dwinter 1429:
1.19 dwinter 1430:
1431: security.declareProtected('Manage','createAllFilesAsSingleFile')
1.1 dwinter 1432: def createAllFilesAsSingleFile(self,RESPONSE=None):
1433: """download all files"""
1434:
1435: def sortF(x,y):
1436: return cmp(x[0],y[0])
1437:
1438: catalog=getattr(self,self.default_catalog)
1439: #tf,tfilename=mkstemp()
1440:
1441:
1442: list=[(x.getId,x) for x in catalog()]
1443: list.sort(sortF)
1444:
1445: RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%"all.atf")
1446: RESPONSE.setHeader("Content-Type","application/octet-stream")
1447:
1448: for l in list:
1449: obj=l[1].getObject()
1450:
1451: if obj.meta_type=="CDLI file":
1452:
1453: #os.write(tf,obj.getLastVersion().data)
1454: if RESPONSE:
1.13 dwinter 1455: RESPONSE.write(obj.getLastVersion().data[0:])
1.1 dwinter 1456: #os.close(tf)
1457: #RESPONSE.redirect(self.absolute_url()+"/downloadFile?fn="%tfilename)
1458: return True
1459:
1460: def downloadFile(self,fn):
1461: """download fn - not used yet"""
1462: self.REQUEST.RESPONSE.setHeader("Content-Disposition","""attachement; filename=%s"""%self.getLastVersion().getId())
1463: self.REQUEST.RESPONSE.setHeader("Content-Type","application/octet-stream")
1464: self.REQUEST.RESPONSE.write(file(fn).read())
1465:
1466:
1467:
1468: def hasParent(self):
1469: """returns true falls subfolder"""
1470:
1471: if self.aq_parent.meta_type in self.folderMetaType:
1472: return True
1473: else:
1474: return False
1475:
1476: def getFolders(self):
1477: """get all subfolders"""
1478: ret=[]
1479: folders=self.ZopeFind(self,obj_metatypes=self.folderMetaType)
1480: for folder in folders:
1481: ret.append((folder[1],
1482: len(self.ZopeFind(folder[1],obj_metatypes=self.folderMetaType)),
1483: len(self.ZopeFind(folder[1],obj_metatypes=self.filesMetaType))
1484: ))
1485: return ret
1486:
1487:
1488: def getFolders_OLD(self):
1489: """get all subfolders"""
1490: ret=[]
1491: folders=self.ZopeFind(self,obj_metatypes=self.folderMetaType)
1492: for folder in folders:
1493: ret.append((folder[1],
1494: len(self.ZopeFind(folder[1],obj_metatypes=self.folderMetaType)),
1495: len(getattr(self,self.default_catalog)({'path':folder[0]}))
1496: ))
1497: return ret
1498:
1499: def index_html(self):
1500: """main"""
1501: ext=self.ZopeFind(self,obj_ids=["index.html"])
1502: if ext:
1503: return ext[0][1]()
1504:
1505: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','CDLIFileFolderMain')).__of__(self)
1506: return pt()
1507:
1.22 dwinter 1508:
1509: manage_addCDLIFileFolderForm=DTMLFile('dtml/folderAdd', globals())
1510:
1511:
1512: def manage_addCDLIFileFolder(self, id, title='',
1513: createPublic=0,
1514: createUserF=0,
1515: REQUEST=None):
1516: """Add a new Folder object with id *id*.
1517:
1518: If the 'createPublic' and 'createUserF' parameters are set to any true
1519: value, an 'index_html' and a 'UserFolder' objects are created respectively
1520: in the new folder.
1521: """
1522: ob=CDLIFileFolder()
1523: ob.id=str(id)
1524: ob.title=title
1525: self._setObject(id, ob)
1526: ob=self._getOb(id)
1527:
1528: checkPermission=getSecurityManager().checkPermission
1529:
1530: if createUserF:
1531: if not checkPermission('Add User Folders', ob):
1532: raise Unauthorized, (
1533: 'You are not authorized to add User Folders.'
1534: )
1535: ob.manage_addUserFolder()
1536:
1537:
1538: if REQUEST is not None:
1539: return self.manage_main(self, REQUEST, update_menu=1)
1540:
1541: class CDLIRoot(Folder):
1542: """main folder for cdli"""
1543:
1544: meta_type="CDLIRoot"
1545:
1.26 dwinter 1546: def forceunlock(self):
1547: "break all locks"
1548: ret=[]
1549: for f in self.ZopeFind(self,obj_metatypes="CDLI file",search_sub=1):
1550: un=f[1].forceunlock()
1551: print un
1552: if un and un !="":
1553: ret.append((f[0],un))
1554: print ret
1555: return ret
1556:
1557: def getChangesByAuthor(self,author,n=100):
1.25 dwinter 1558: """getChangesByAuthor"""
1.26 dwinter 1559: zcat=self.CDLIObjectsCatalog
1560: res=zcat({'lastEditor':author,
1.25 dwinter 1561: 'sort_on':'getTime',
1562: 'sort_order':'descending',
1563: 'sort_limit':n})[:n ]
1.26 dwinter 1564:
1565: return res
1566:
1567: def getChangesByAuthor_html(self,author,n=100):
1568: """html output for changes by author"""
1569: tmp={}
1570: list=[]
1571: for x in self.getChangesByAuthor(author):
1572: nr=x.getObject().getVersionNumber()
1573: id=x.getObject().aq_parent.getId()
1574: #hinzufuegen, wenn Version neuer als die
1575: if tmp.get(id,(0,0))[1] < nr:
1576: tmp[id]=(x.getObject().aq_parent,nr)
1577:
1578:
1579: return self.cdli_main.findObjectsFromListWithVersion(list=tmp.values())
1580:
1.25 dwinter 1581: def getLastChanges(self,n=100):
1582: """get the last n changes"""
1583: n=int(n)
1584: zcat=self.CDLICatalog
1585: return zcat({'sort_on':'getLastChangeDate',
1586: 'sort_order':'descending',
1587: 'sort_limit':n})[:n ]
1588:
1589:
1590: def getLastChanges_html(self,n=100):
1591: """get the last n changes"""
1592: list = [x.getId for x in self.getLastChanges(n)]
1593: return self.cdli_main.findObjectsFromList(list=list,display=True)
1594:
1.24 dwinter 1595: def refreshTxt(self,txt="",threadName=None):
1.22 dwinter 1596: """txt fuer refresh"""
1597:
1.24 dwinter 1598: return """ 2;url=%s?repeat=%s """%(self.absolute_url()+txt,threadName)
1.22 dwinter 1599:
1600:
1.24 dwinter 1601: def getResult(self,threadName=None):
1.22 dwinter 1602: """result of thread"""
1603: try:
1.24 dwinter 1604: return self._v_uploadATF[threadName].getResult()
1.22 dwinter 1605: except:
1606: return "One moment, please"
1607:
1.24 dwinter 1608:
1609: def checkThreads(self):
1610: """check threads"""
1611: return threading.enumerate()
1612:
1.22 dwinter 1613: def uploadATF(self,repeat=None,upload=None,basketId=0,RESPONSE=None):
1614: """standard ausgabe"""
1615: #self._v_uploadATF.returnValue=None
1616:
1617: threadName=repeat
1618: if not threadName or threadName=="":
1619: tmpVar=False
1.24 dwinter 1620:
1.22 dwinter 1621: thread=uploadATFThread()
1.24 dwinter 1622: threadName=thread.getName()[0:]
1623: if not hasattr(self,'_v_uploadATF'):
1624: self._v_uploadATF={}
1625:
1626: self._v_uploadATF[threadName]=thread
1.22 dwinter 1627: #self._xmltrans.start()
1628: #thread=Thread(target=self._v_uploadATF)
1629:
1.24 dwinter 1630: self._v_uploadATF[threadName].set(upload,basketId,self.REQUEST['AUTHENTICATED_USER'],serverport=self.REQUEST['SERVER_PORT'])
1.22 dwinter 1631: #thread.start()
1.24 dwinter 1632: self._v_uploadATF[threadName].start()
1.22 dwinter 1633:
1634:
1.24 dwinter 1635: self.threadName=self._v_uploadATF[threadName].getName()[0:]
1.22 dwinter 1636: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1637:
1638: if wait_template:
1639: return wait_template[0][1]()
1640: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1.24 dwinter 1641: return pt(txt='/uploadATF',threadName=threadName)
1.22 dwinter 1642: #_v_xmltrans.run()
1643:
1644: else:
1645: #recover thread, if lost
1646: if not hasattr(self,'_v_uploadATF'):
1.24 dwinter 1647: self._v_uploadATF={}
1648: if not self._v_uploadATF.get(threadName,None):
1.22 dwinter 1649: for thread in threading.enumerate():
1650: if threadName == thread.getName():
1.24 dwinter 1651: self._v_uploadATF[threadName]=thread
1652:
1653: if not self._v_uploadATF[threadName].returnValue:
1.22 dwinter 1654:
1655:
1656: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1657: if wait_template:
1658: return wait_template[0][1]()
1659:
1660: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1661:
1.24 dwinter 1662: return pt(txt='/uploadATF',threadName=threadName)
1.22 dwinter 1663:
1664: else:
1665: # tmp={}
1.24 dwinter 1666: # for key in self._v_uploadATF[threadName].returnValue.keys():
1667: # t=self._v_uploadATF[threadName].returnValue[key]
1.22 dwinter 1668: # if type(t) is ListType:
1.24 dwinter 1669: # tmp[key]=self._v_uploadATF[threadName].returnValue[key][0:]
1.22 dwinter 1670: # else:
1.24 dwinter 1671: # tmp[key]=self._v_uploadATF[threadName].returnValue[key]
1672:
1673: tmp=self.cdli_main.tmpStore2[threadName]
1674: del(self.cdli_main.tmpStore2[threadName])
1675: self._v_uploadATF[threadName].continueVar=False
1.22 dwinter 1676: self.REQUEST.SESSION['changed']=[x[0].getId() for x in tmp['changed']]
1677: self.REQUEST.SESSION['errors']=[x.getId() for x in tmp['errors']]
1678: self.REQUEST.SESSION['newPs']=tmp['newPs']
1679: self.REQUEST.SESSION['tmpdir']=tmp['dir']
1680:
1681: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadCheck.zpt')).__of__(self)
1682: return pt(changed=tmp['changed'],errors=tmp['errors'],dir=tmp['dir'],newPs=tmp['newPs'],basketLen=tmp['basketLen'],numberOfFiles=tmp['numberOfFiles'],
1683: basketNameFromId=tmp['basketNameFromId'],basketNameFromFile=tmp['basketNameFromFile'],basketId=tmp['basketId'])
1684:
1685: def uploadATFfinally(self,procedure='',comment="",basketname='',unlock=None,repeat=None,RESPONSE=None):
1686: """nowupload the files"""
1687:
1688:
1689:
1690: threadName=repeat
1691: if not threadName or threadName=="":
1.24 dwinter 1692: thread=uploadATFfinallyThread()
1693: threadName=thread.getName()[0:]
1694: self._v_uploadATF[threadName]=thread
1.22 dwinter 1695:
1696:
1.24 dwinter 1697: self._v_uploadATF[threadName].set(procedure,comment=comment,basketname=basketname,unlock=unlock,SESSION=self.REQUEST.SESSION,username=self.REQUEST['AUTHENTICATED_USER'],serverport=self.REQUEST['SERVER_PORT'])
1.22 dwinter 1698:
1.24 dwinter 1699: self._v_uploadATF[threadName].start()
1.22 dwinter 1700:
1701:
1.24 dwinter 1702:
1.22 dwinter 1703: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1704:
1705: if wait_template:
1706: return wait_template[0][1]()
1707: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1708:
1.24 dwinter 1709: return pt(txt='/uploadATFfinally',threadName=threadName)
1.22 dwinter 1710: #_v_xmltrans.run()
1711:
1712: else:
1713: #recover thread, if lost
1714: if not hasattr(self,'_v_uploadATF'):
1.24 dwinter 1715: self._v_uploadATF={}
1716: if not self._v_uploadATF.get(threadName,None):
1.22 dwinter 1717: for thread in threading.enumerate():
1718: if threadName == thread.getName():
1.24 dwinter 1719: self._v_uploadATF[threadName]=thread
1.22 dwinter 1720:
1.24 dwinter 1721: if self._v_uploadATF.get(threadName,None) and (self._v_uploadATF[threadName] is not None) and (not self._v_uploadATF[threadName].end) :
1.22 dwinter 1722:
1723: wait_template=self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['wait_template'])
1724: if wait_template:
1725: return wait_template[0][1]()
1726:
1727: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','uploadATFWait.zpt')).__of__(self)
1.24 dwinter 1728: return pt(txt='/uploadATFfinally',threadName=threadName)
1.22 dwinter 1729: else:
1730:
1731: if RESPONSE is not None:
1732: RESPONSE.redirect(self.absolute_url())
1733:
1.19 dwinter 1734: def importFiles(self,comment="",author="" ,folderName="/Users/dwinter/Documents/workspace/cdli/atf", files=None,ext=None):
1.1 dwinter 1735: """import files"""
1.22 dwinter 1736: root=self.cdli_main
1.1 dwinter 1737:
1.3 dwinter 1738: if not files:
1739: files=os.listdir(folderName)
1740:
1.1 dwinter 1741: for f in files:
1742: folder=f[0:3]
1743: f2=f[0:5]
1.22 dwinter 1744: obj=self.ZopeFind(root,obj_ids=[folder])
1.19 dwinter 1745: if ext:
1746:
1747: ext.result+="<p>Adding: %s </p>"%f
1.1 dwinter 1748: if not obj:
1.22 dwinter 1749: manage_addCDLIFileFolder(root,folder,folder)
1750: fobj=getattr(root,folder)
1751: #get_transaction().commit()
1.1 dwinter 1752: else:
1753: fobj=obj[0][1]
1754:
1755: obj2=fobj.ZopeFind(fobj,obj_ids=[f2])
1756:
1757: if not obj2:
1758: manage_addCDLIFileFolder(fobj,f2,f2)
1759: fobj2=getattr(fobj,f2)
1760:
1761: else:
1762: fobj2=obj2[0][1]
1763:
1764: file2=file(os.path.join(folderName,f))
1765: id=f
1766: manage_addCDLIFile(fobj2,f,'','')
1767: id=f
1768: ob=fobj2._getOb(f)
1769: ob.title=id
1770:
1771: manage_addCDLIFileObject(ob,id,comment,author,file2,content_type='')
1.3 dwinter 1772: self.CDLICatalog.catalog_object(ob)
1773: #self.CDLICatalog.manage_catalogFoundItems(obj_ids=[id],search_sub=1)
1774: #self.CDLICatalog.manage_catalogObject(self.REQUEST, self.REQUEST.RESPONSE, 'CDLICatalog', urlparse.urlparse(ob.absolute_url())[1])
1775:
1776: return "ok"
1.22 dwinter 1777:
1778:
1779: manage_addCDLIRootForm=DTMLFile('dtml/rootAdd', globals())
1.1 dwinter 1780:
1781:
1.22 dwinter 1782: def manage_addCDLIRoot(self, id, title='',
1.1 dwinter 1783: createPublic=0,
1784: createUserF=0,
1785: REQUEST=None):
1786: """Add a new Folder object with id *id*.
1787:
1788: If the 'createPublic' and 'createUserF' parameters are set to any true
1789: value, an 'index_html' and a 'UserFolder' objects are created respectively
1790: in the new folder.
1791: """
1.22 dwinter 1792: ob=CDLIRoot()
1.1 dwinter 1793: ob.id=str(id)
1794: ob.title=title
1795: self._setObject(id, ob)
1796: ob=self._getOb(id)
1797:
1798: checkPermission=getSecurityManager().checkPermission
1799:
1800: if createUserF:
1801: if not checkPermission('Add User Folders', ob):
1802: raise Unauthorized, (
1803: 'You are not authorized to add User Folders.'
1804: )
1805: ob.manage_addUserFolder()
1806:
1807:
1808: if REQUEST is not None:
1.22 dwinter 1809: return self.manage_main(self, REQUEST, update_menu=1)
1810:
1.1 dwinter 1811:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>