File:  [Repository] / cdli / cdli_files.py
Revision 1.100: download - view: text, annotated - select for diffs - revision graph
Wed Oct 15 09:54:54 2008 UTC (15 years, 8 months ago) by dwinter
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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