File:  [Repository] / cdli / cdli_files.py
Revision 1.80.2.13: download - view: text, annotated - select for diffs - revision graph
Fri Jan 4 17:27:39 2008 UTC (16 years, 5 months ago) by casties
Branches: zcat_only_1
Diff to: branchpoint 1.80: preferred, unified
small changes

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

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