File:  [Repository] / MPIWGWeb / Attic / MPIWGRoot.py
Revision 1.1.2.38: download - view: text, annotated - select for diffs - revision graph
Wed Feb 29 19:01:19 2012 UTC (12 years, 4 months ago) by dwinter
Branches: r2
*** empty log message ***

    1: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
    2: from Products.PageTemplates.PageTemplate import PageTemplate
    3: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
    4: from Products.ZSQLExtend.ZSQLExtend import ZSQLExtendFolder
    5: from Products.ZCatalog.CatalogPathAwareness import CatalogAware
    6: from OFS.Image import Image
    7: from Globals import package_home
    8: import urllib
    9: import MPIWGStaff
   10: import string
   11: import re
   12: import os
   13: from types import *
   14: import logging
   15: import xmlhelper # Methoden zur Verwaltung der projekt xml
   16: from OFS.SimpleItem import SimpleItem
   17: from OFS.Folder import Folder
   18: from Products.ZSQLMethods.SQL import SQLConnectionIDs
   19: from AccessControl import ClassSecurityInfo
   20: from bibliography import *
   21: import time
   22: import xml.dom.minidom
   23: import sys
   24: import transaction
   25: 
   26: #from Ft.Xml.XPath import Evaluate
   27: #from Ft.Xml.XPath.Context import Context
   28: #from Ft.Xml.Domlette import NonvalidatingReader,PrettyPrint, Print
   29: #from Ft.Xml import EMPTY_NAMESPACE
   30: import copy
   31: import updatePersonalWWW
   32: import MPIWGStaff
   33: from MPIWGHelper import *
   34: from BeautifulSoup import BeautifulSoup, Comment
   35: from ZODB import FileStorage, DB
   36: from ZEO import ClientStorage
   37: 
   38: def sortWeight(x,y):
   39:     x1=int(getattr(x[1],'weight','0'))
   40:     y1=int(getattr(y[1],'weight','0'))
   41:     return cmp(x1,y1)
   42: 
   43: 
   44: class MPIWGRoot(ZSQLExtendFolder):
   45:     """Stammordner fuer den Web-Server"""
   46: 
   47:     _v_harvestCache=None
   48:     meta_type='MPIWGRoot'
   49: 
   50:     fieldLabels={'WEB_title':'WEB_Title',
   51:                  'xdata_01':'Responsible Scientists',
   52:                  'xdata_02':'Department',
   53:                  'xdata_03':'Historical Persons',
   54:                  'xdata_04':'Time period',
   55:                  'xdata_05':'Sorting number',
   56:                  'xdata_06':'Keywords',
   57:                  'xdata_07':'Short title',
   58:                  'xdata_08':'Other involved scholars' ,
   59:                  'xdata_09':'Disciplines',
   60:                  'xdata_10':'Themes',
   61:                  'xdata_11':'Object Digitallibrary',
   62:                  'xdata_12':'Cooperation partners',
   63:                  'xdata_13':'Funding institutions',
   64:                  'WEB_project_header':'WEB_project_header',
   65:                  'WEB_project_description':'WEB_project_description',
   66:                  'WEB_related_pub':'WEB_related_pub'}
   67:     
   68:     # (is this used?)
   69:     folders=['MPIWGProject','Folder','ECHO_Navigation']
   70:     # language of this instance
   71:     lang = 'en'
   72:     # types of objects that show up in navigation
   73:     nav_meta_types = ['MPIWGTemplate','MPIWGLink','MPIWGFolder']
   74: 
   75:     manage_options = Folder.manage_options+(
   76:         {'label':'Update personal homepages','action':'updatePersonalwww_html'},
   77:         {'label':'Reindex catalogs','action':'reindexCatalogs'},
   78:         {'label':'Main config','action':'changeMPIWGRootForm'},
   79:         {'label':'add e-mails','action':'showNewDBEntries'},
   80:         #{'label':'update the institutsbibliography','action':'updateInstitutsbiliography'},
   81:         #{'label':'Edit Historical Persons','action':'editHistoricalPersonsForm'},
   82:         #{'label':'Store Historical Persons','action':'storeHistoricalPersons'},
   83:         )
   84:     
   85: 
   86:     def getHarvestCachePort(self):
   87:         return getattr(self,"harvestPort",29999)
   88:     
   89:     def getHarvestCacheServer(self):
   90:         return getattr(self,"harvestServer","localhost")
   91:    
   92:     
   93:     def getHarvestCache(self):
   94:         logging.debug("CACHE:"+repr(self._v_harvestCache))
   95:         if self._v_harvestCache==None:
   96:              #storage = FileStorage.FileStorage('/tmp/'+self.getId()+'test-filestorage.fs')
   97:              addr = self.getHarvestCacheServer(), self.getHarvestCachePort()
   98:              storage = ClientStorage.ClientStorage(addr)
   99:              db = DB(storage)
  100:              self._v_harvestDV=db
  101:              self._v_harvestDV=db
  102:              conn = db.open()
  103:              dbroot = conn.root()
  104:              if not dbroot.has_key('templates'):
  105:                  from BTrees.OOBTree import OOBTree
  106:                  dbroot['templates'] = OOBTree()
  107:                  
  108:              self._v_harvestCache = dbroot['templates']
  109:         logging.debug("CACHE2:"+repr(self._v_harvestCache))            
  110:         return self._v_harvestCache
  111:     
  112:     
  113:     
  114:     def __del__(self):
  115:          if self._v_harvestCache!=None:
  116:              self._v_harvestDV.close();
  117:              
  118:     def getGetNeighbourhood(self,obj, wordStr, length=100,tagging=True):
  119:         """finde umgebung um die worte in wordStr, zurueckgegeben wird eine Array mit den Umgebungen von Fundstellen der Worte
  120:         alle Tags werden entfernt, die Fundstellen werden mit <span class="found">XX</span> getaggt, die Umgebungen werden 
  121:         case insensitive gesucht
  122:         @param wordStr: string mit Worten getrennt durch Leerzeichen, Phrasen sind mit " gekennzeichnet
  123:                         "eine phrase", "*"  bezeichnet wildcards und wird ignoriert"
  124:         @param length: optional, default wert 100, 2*length ist die groesse der Umgebung
  125:         @param tagging: optional default wert true, kein span tag wird erzweugt falls tag=false
  126:         """
  127:         
  128:         ret=[] # nimmt das Array auf, dass spaeter zurueckgegeben wird
  129:         ranges=[] #Array mit tupeln x,y wobei x die Position des Anfang und y des Endes der i-ten Umgebung angiebt
  130:         
  131:         wordStr=wordStr.lstrip().rstrip()
  132:         
  133:         def isInRanges(nr,length):
  134:             """test ob eine gegeben Position nr schon irgendwo in einer Umgebung ist, gibt den Index des ersten Wertes aus ranges zurueck, 
  135:             -1, wenn kein Treffer
  136:             
  137:             @param nr: Position die geprueft werden soll
  138:             @param length: Laenge des Wortes das geprueft werden soll
  139:             """
  140:             for x in ranges:
  141:                 if (x[0]<=nr) and (nr < (x[1]-length)):
  142:                     return ranges.index(x)
  143:             return -1
  144:                 
  145:         # deal with phrases, in Phrasen werden die Leerzeichen durch "_" ersetzt.
  146:         def rep_empty(str):
  147:             x= re.sub(" ","_",str.group(0))
  148:             return re.sub("\"","",x)
  149:             
  150:         wordStr=re.sub("\".*?\"", rep_empty,wordStr)#ersetze leerzeichen in " " durch "_" und loesche "
  151:         
  152:         #deal with wildcards, for our purposes it is enough to delete the wildcard 
  153:         wordStr=wordStr.replace("*","")
  154:         
  155:         words=wordStr.split(" ")
  156:         #if not words is ListType:
  157:         #   words=[words]
  158:         
  159:         
  160:         txtCache = self.en.getHarvestCache();
  161:         txt=  txtCache.get(obj.absolute_url(),None)
  162:        
  163:         if txt==None:
  164:             
  165:             logging.debug("NO CACHE for: "+obj.absolute_url())
  166:             txt=obj.harvest_page(mode="slim")
  167:         
  168:         
  169:         if not txt:
  170:             return ret
  171:         
  172:         soup = BeautifulSoup(txt)
  173:         
  174:         comments = soup.findAll(text=lambda text:isinstance(text, Comment))
  175:         [comment.extract() for comment in comments]
  176:         
  177:         txt = ''.join(soup.findAll(text=True))
  178:         
  179:         
  180:         #txt=re.sub("<.*?>", "", txt) # loesche alle Tags
  181:         for word in words:
  182:             word=re.sub("_"," ",word) # ersetze zurueck "_" durch " "
  183:             pos=0
  184:             
  185:             n=txt.lower().count(word.lower()) # wie oft tritt das Wort auf
  186: 
  187:             for i in range(n):
  188:                 pos=txt.lower().find(word.lower(),pos)
  189: 
  190:                 if pos > 0:
  191:                     x=max(0,pos-length)
  192:                     y=min(len(txt),pos+length)
  193:                   
  194:                     
  195:                     #is word already in one of the results
  196:                     nr=isInRanges(pos,len(word))
  197:                     if nr >=0:# word ist in einer schon gefunden Umgebung, dann vergroessere diese
  198:                         x=min(ranges[nr][0],x)
  199:                         y=max(ranges[nr][1],y)
  200:               
  201:                     str=txt[x:y]
  202:                     if x!=0: #add dots if in the middle of text
  203:                         str="..."+str
  204:                     
  205:                     if y!=len(txt): #add dots if in the middle of text
  206:                         str=str+"..."
  207:                         
  208:                         
  209:                 
  210:                     if nr >=0: # word ist in einer schon gefunden Umgebung
  211:                         ranges[nr]=(x,y) # neue Position der Umgebung
  212: 
  213:                         ret[nr]=str # neue Umgebung
  214:                     else: # andernfalls neue Umgebung hinzufuegen
  215:                         ranges.append((x,y))
  216: 
  217:                         ret.append(str)
  218:                     
  219:                     pos=pos+len(word)
  220:                 else:
  221:                     break;
  222:                 
  223:         # now highlight everything        
  224:         if tagging:
  225:             for x in range(len(ret)):
  226:                 for word in words:
  227:                     repl=re.compile(word,re.IGNORECASE)
  228:                     ret[x]=repl.sub(""" <span class="found">%s</span>"""%word.upper(),ret[x])
  229: 
  230:         return ret
  231:     def copyAllImagesToMargin(self):
  232:         """tranformiere alle Bilder in die Margins"""
  233:         projects=self.getTree()
  234:         ret=""
  235:         for project in projects:
  236:             proj=project[3]
  237:             try:
  238:                 persons=proj.copyImageToMargin();
  239:             except:
  240:                 logging.error("Cannnot do: %s"%repr(project))
  241:                 
  242:     def transformProjectsToId(self):
  243:         """trnasformiere zu ID, Hilfsfunktion die die alten Templates analysiert und mit der neuen Liste
  244:         verantwortlicher Personen versieht"""
  245:         projects=self.getTree()
  246:         ret=""
  247:         for project in projects:
  248:             
  249:             proj=project[3]
  250:             persons=proj.identifyNames(proj.getContent('xdata_01'))
  251:             if not hasattr(proj,'responsibleScientistsList'):
  252:                         proj.responsibleScientistsList=[]
  253:                         
  254:             for person in persons.items():
  255:               
  256:                 if len(person[1]) >1: #nicht eindeutig
  257:                     ret+="nicht eindeutig ---  %s:  %s\n"%(proj.getId(),person[0])
  258:                     
  259:                 elif len(person[1]) ==0: #kein eintrage
  260:                     ret+="kein eintrag---  %s:  %s\n"%(proj.getId(),person[0])
  261:                     proj.responsibleScientistsList.append((person[0],""))
  262:                 else:           
  263:                     proj.responsibleScientistsList.append((person[0],person[1][0].getObject().getKey()))
  264:         
  265:         return ret
  266:           
  267:                 
  268:     def harvestProjects(self):
  269:         """harvest"""
  270:         folder="/tmp"
  271:         try:
  272:             os.mkdir("/tmp/harvest_MPIWG")
  273:         except:
  274:             pass
  275:         founds=self.ZopeFind(self.aq_parent.projects,obj_metatypes=['MPIWGProject'],search_sub=1)
  276:         for found in founds:
  277:             txt=found[1].harvest_page()
  278:         
  279:             if txt and (txt != ""):
  280:                 name=found[0].replace("/","_")
  281:                 fh=file("/tmp/harvest_MPIWG/"+name,"w")
  282:                 fh.write(txt)
  283:                 fh.close()
  284:                 
  285:     def decode(self,str):
  286:         """decoder"""
  287: 
  288:         if not str:
  289:             return ""
  290:         if type(str) is StringType:
  291:             try:            
  292:                 return str.decode('utf-8')
  293:             except:
  294:                 return str.decode('latin-1')
  295:         else:
  296:             return str
  297: 
  298: 
  299:     def getat(self,array,idx=0,default=None):
  300:         """return array element idx or default (but no exception)"""
  301:         if len(array) <= idx:
  302:             return default
  303:         else:
  304:             return array[idx]
  305:         
  306:     def getLang(self):
  307:         """returns the default language"""
  308:         return self.lang
  309: 
  310:     def browserCheck(self):
  311:         """check the browsers request to find out the browser type"""
  312:         bt = {}
  313:         ua = self.REQUEST.get_header("HTTP_USER_AGENT")
  314:         bt['ua'] = ua
  315:         bt['isIE'] = False
  316:         bt['isN4'] = False
  317:         if string.find(ua, 'MSIE') > -1:
  318:             bt['isIE'] = True
  319:         else:
  320:             bt['isN4'] = (string.find(ua, 'Mozilla/4.') > -1)
  321: 
  322:         try:
  323:             nav = ua[string.find(ua, '('):]
  324:             ie = string.split(nav, "; ")[1]
  325:             if string.find(ie, "MSIE") > -1:
  326:                 bt['versIE'] = string.split(ie, " ")[1]
  327:         except: pass
  328: 
  329:         bt['isMac'] = string.find(ua, 'Macintosh') > -1
  330:         bt['isWin'] = string.find(ua, 'Windows') > -1
  331:         bt['isIEWin'] = bt['isIE'] and bt['isWin']
  332:         bt['isIEMac'] = bt['isIE'] and bt['isMac']
  333:         bt['staticHTML'] = False
  334: 
  335:         return bt
  336: 
  337: 
  338:     def versionHeaderEN(self):
  339:         """version header text"""
  340:         
  341:         date= self.REQUEST.get('date',None)
  342:         if date:
  343:             txt="""<h2>This pages shows the project which existed at %s</h2>"""%str(date)
  344:             return txt
  345:         return ""
  346: 
  347:     def versionHeaderDE(self):
  348:         """version header text"""
  349:         date= self.REQUEST.get('date',None)
  350:         if date:
  351:             txt="""<h2>Auf dieser Seite finden Sie die Projekte mit Stand vom %s</h2>"""%str(date)
  352:         return ""
  353:     
  354:         
  355:     def createOrUpdateId_raw(self):
  356:         """create sequence to create ids for bibliography"""
  357:         debug=None
  358:         #suche groesste existierende id
  359:         founds=self.ZSQLQuery("select id from bibliography")
  360:         
  361:         if founds:
  362:             ids=[int(x.id[1:]) for x in founds]
  363:             maximum=max(ids)
  364:             
  365:             id_raw=self.ZSQLQuery("select nextval('id_raw')",debug=debug)
  366:             
  367:             if id_raw:
  368:                 self.ZSQLQuery("drop sequence id_raw",debug=debug)
  369:             
  370:             self.ZSQLQuery("create sequence id_raw start %i"%(maximum+1),debug=debug)
  371:         
  372:     
  373:     def queryLink(self,link):
  374:         """append querystring to the link"""
  375:         return "%s?%s"%(link,self.REQUEST.get('QUERY_STRING',''))
  376: 
  377:     def getKategory(self,url):
  378:         """kategorie"""
  379:         splitted=url.split("/")
  380:         return splitted[4]
  381: 
  382:     def generateUrlProject(self,url,project=None):
  383:         """erzeuge aus absoluter url, relative des Projektes"""
  384:         if project:
  385:             splitted=url.split("/")
  386:             length=len(splitted)
  387:             short=splitted[length-2:length]
  388:             
  389:             base=self.REQUEST['URL3']+"/"+"/".join(short)
  390: 
  391:         else:
  392:             findPart=url.find("/projects/")
  393:             base=self.REQUEST['URL1']+"/"+url[findPart:]
  394: 
  395:                 
  396:         return base
  397:     
  398:     def isNewCapital(self,text=None,reset=None):
  399:         if reset:
  400:             self.REQUEST['capital']="A"
  401:             return True
  402:         else:
  403:             if len(text)>0 and not (text[0]==self.REQUEST['capital']):
  404:                 self.REQUEST['capital']=text[0]
  405:                 return True
  406:             else:
  407:                 return False
  408:     
  409:     def subNavStatic(self,obj):
  410:         """subnav" von self"""
  411:         subs=self.ZopeFind(obj,obj_metatypes=['MPIWGTemplate','MPIWGLink'])
  412:         subret=[]
  413: 
  414:         for x in subs:
  415:             if not(x[1].title==""):
  416:                 subret.append(x)
  417:         subret.sort(sortWeight)
  418:         return subret
  419:     
  420:     def subNav(self,obj):
  421:         """return sub-navigation elements i.e. below sections"""
  422:         # get section -> parent should be MPIWGRoot
  423:         p = obj
  424:         sec = None
  425:         # descend parents to the root (and remember the last id)
  426:         while p is not None and p.meta_type != 'MPIWGRoot':
  427:             sec = p
  428:             p = p.aq_parent
  429:     
  430:         subsecs = sec.objectItems(self.nav_meta_types)
  431:         subsecs = [s for s in subsecs if s[1].title != ""]
  432:         subsecs.sort(sortWeight)
  433:         return subsecs
  434:                 
  435:     def isType(self,object,meta_type):
  436:         """teste ob ein object vom meta_type ist."""
  437:         return (object.meta_type==meta_type)
  438:     
  439:     def isActive(self,name):
  440:         """teste ob subnavigation aktiv"""
  441:         for part in self.REQUEST['URL'].split("/"):
  442:             if part==name:
  443:                 return True
  444:         return False
  445:         
  446:     
  447:     def getSections(self):
  448:         """returns a list of all sections i.e. top-level MPIWGFolders"""
  449:         secs = self.objectItems(['MPIWGFolder'])
  450:         secs.sort(sortWeight)
  451:         #logging.debug("root: %s secs: %s"%(repr(self.absolute_url()), repr(secs)))
  452:         # return pure list of objects
  453:         return [s[1] for s in secs]
  454: 
  455:     def getSectionStyle(self, name, style=""):
  456:         """returns a string with the given style + '-sel' if the current section == name"""
  457:         if self.getSection() == name:
  458:             return style + '-sel'
  459:         else:
  460:             return style    
  461: 
  462:     def getFeatures(self, num=None):
  463:         """returns a list of the last num Features"""
  464:         dir = getattr(self, 'features')
  465:         features = dir.objectItems(['MPIWGFeature'])
  466:         features.sort(sortWeight)
  467:         if num is not None:
  468:             # take only the last num elements
  469:             features = features[-num:]
  470:         # return pure list of objects
  471:         return [f[1] for f in features]
  472: 
  473: 
  474:     def getMPIWGRoot(self):
  475:         """returns the MPIWG root"""
  476:         return self
  477: 
  478:     def MPIWGrootURL(self):
  479:         """returns the URL to the root"""
  480:         return self.absolute_url()
  481:         
  482:     def upDateSQL(self,fileName):
  483:         """updates SQL databases using fm.jar"""
  484:         fmJarPath=os.path.join(package_home(globals()), 'updateSQL/fm.jar')
  485:         xmlPath=os.path.join(package_home(globals()), "updateSQL/%s"%fileName)
  486:         logger("MPIWG Web",logging.INFO,"java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath))
  487:         ret=os.popen("java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath),"r").read()
  488:         logger("MPIWG Web",logging.INFO,"result convert: %s"%ret)
  489:         return 1
  490:     
  491:     def patchProjects(self,RESPONSE):
  492:         """patch"""
  493:         projects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'])
  494:         for project in projects:
  495:                 tmp=project[1].WEB_project_description[0].replace("/CD/projects/","")[0:]
  496:                 setattr(project[1],'WEB_project_description',[tmp[0:]])
  497:                 RESPONSE.write("<p>%s</p>\n"%project[0])
  498:             
  499:     def replaceNotEmpty(self,format,field):
  500:         """replace not empty"""
  501:         if field and (not field.lstrip()==''):
  502:             return self.decode(format%field)
  503:         else:
  504:             return ""
  505:         
  506: 
  507:     def isActiveMember(self,key):
  508:         """tested ob Mitarbeiter key ist aktiv"""
  509:         key=utf8ify(key)
  510:         ret=self.getat(self.ZSQLInlineSearch(_table='personal_www',
  511:                                             _op_key='eq',key=key,
  512:                                             _op_publish_the_data='eq',
  513:                                             publish_the_data='yes'))
  514:         
  515:         logging.info("ACTIVE_MEMBER  %s"%ret)
  516:         if ret:
  517:             return True
  518:         else:
  519:             return False
  520:         
  521:     def isActual(self,project):
  522:         """checke if project is actual"""
  523:         actualTime=time.localtime()
  524:         
  525:         if hasattr(project,'getObject'): #obj ist aus einer catalogTrefferList
  526:             obj=project.getObject()
  527:         else:
  528:             obj=project
  529:             
  530:         if getattr(obj,'archiveTime',actualTime)< actualTime:
  531:             return False
  532:         else:
  533:             return True
  534:         
  535:     def redirectIndex_html(self,request):
  536:         #return request['URL1']+'/index_html'
  537:         
  538:         return urllib.urlopen(request['URL1']+'/index_html').read()
  539: 
  540:     
  541:     def formatBibliography(self,here,found):
  542:         """format"""
  543:         return formatBibliography(here,found)
  544:     
  545:     def getValue(self,fieldStr):
  546:         """Inhalt des Feldes"""
  547:         
  548:         if type(fieldStr)==StringType:
  549:             field=fieldStr
  550:         else:
  551:             field=fieldStr[0]
  552:         try:
  553:             if field[len(field)-1]==";":
  554:                 field=field[0:len(field)-1]
  555:         except:
  556: 
  557:             """nothing"""
  558:         field=re.sub(r';([^\s])','; \g<1>',field)
  559:         return field.encode('utf-8')
  560: 
  561: 
  562:     
  563:     def sortedNames(self,list):
  564:         """sort names"""
  565: 
  566:         def sortLastName(x_c,y_c):
  567:             try:
  568:                 x=urllib.unquote(x_c).encode('utf-8','ignore')
  569:             except:
  570:                 x=urllib.unquote(x_c)
  571: 
  572:             try:
  573:                 y=urllib.unquote(y_c).encode('utf-8','ignore')
  574:             except:
  575:                 x=urllib.unquote(y_c)
  576:                 
  577: 
  578:             
  579:             try:
  580:                 last_x=x.split()[len(x.split())-1]
  581:                 last_y=y.split()[len(y.split())-1]
  582: 
  583:             except:
  584: 
  585:                 last_x=""
  586:                 last_y=""
  587:             
  588:             
  589:             
  590:             if last_x<last_y:
  591:                 return 1
  592:             elif last_x>last_y:
  593:                 return -1
  594:             else:
  595:                 return 0
  596:             
  597:         list.sort(sortLastName)
  598:         list.reverse()
  599:         
  600:         return list
  601:     
  602:     def __init__(self, id, title):
  603:         """init"""
  604:         self.id=id
  605:         self.title=title
  606: 
  607:     def removeStopWords(self,xo):
  608:         """remove stop words from xo"""
  609:         if not hasattr(self,'_v_stopWords'):
  610:             self._v_stopWords=self.stopwords_en.data.split("\n")
  611:     
  612:         x=str(xo)
  613:     
  614:         strx=x.split(" ")
  615:   
  616:         for tmp in strx:
  617:      
  618:             if tmp.lower() in self._v_stopWords:
  619:                 del strx[strx.index(tmp)]
  620: 
  621:         return " ".join(strx)
  622:     
  623:     def urlQuote(self,str):
  624:         """quote"""
  625:         return urllib.quote(str)
  626: 
  627:     def urlUnQuote(self,str):
  628:         """quote"""
  629:         return urllib.unquote(str)
  630:     
  631:         
  632: 
  633:     def getProjectsByFieldContent(self,fieldName,fieldContentsEntry, date=None):
  634:         """gib alle Projekte aus mit Value von field mit fieldName enthaelt ein Element der Liste fieldContents"""
  635:         def sort(x,y):
  636:                 return cmp(x.WEB_title[0],y.WEB_title[0])
  637: 
  638:         if type(fieldContentsEntry) is StringType:
  639:             fieldContentsTmp=[fieldContentsEntry]
  640:         else:
  641:             fieldContentsTmp=fieldContentsEntry
  642: 
  643:         fieldContents=[]
  644:         for x in fieldContentsTmp:
  645:             fieldContents.append(" AND ".join(x.split()))
  646:         projects=self.ProjectCatalog({fieldName:string.join(fieldContents,' AND')})
  647:         #print projects
  648:         #ret=[x for x in projects]
  649:         ret=[]
  650:         for x in projects:
  651:             obj=x.getObject()
  652:             obj=obj.getActualVersion(date)
  653:             if obj and (not getattr(obj,'invisible',None)):
  654:                 #if not (x in ret):
  655:                     ret.append(x)
  656: 
  657:         ret.sort(sort)
  658:         return ret
  659: 
  660:     def changeMPIWGRootForm(self):
  661:         """edit"""
  662:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeMPIWGRootForm')).__of__(self)
  663:         return pt()
  664: 
  665:     def changeMPIWGRoot(self,title,connection_id,coneServiceURL,harvestPort,harvestServer,lang=None,autocommit=None,RESPONSE=None):
  666:         """change"""
  667:         self.title=title
  668:         self.connection_id=connection_id
  669:         #self.disciplineList=disciplineList
  670:         #self.themesList=themesList
  671:         self.coneServiceURL=coneServiceURL
  672:         self.harvestServer=harvestServer
  673:         try:
  674:             self.harvestPort=int(harvestPort)
  675:         except:
  676:             logging.error("couldn't change port!: no number:"+harvestPort)
  677:         
  678:         if lang is not None:
  679:             self.lang = lang
  680: 
  681:         self.autocommit = (autocommit == "on")
  682:         if RESPONSE is not None:
  683:             RESPONSE.redirect('manage_main')
  684: 
  685: 
  686:     def getContexts(self,childs=None,parents=None,depth=None,date=None,onlyActive=True):
  687:         """childs alle childs, alle parents"""
  688:         ret=[]
  689:     
  690:         if parents:
  691:             pnums=parents.split(".")
  692:             while len(pnums) > 1:
  693:                 pnums.pop()
  694:                 parentId=string.join(pnums,".")
  695:         
  696:                 for project in self.getProjectFields('xdata_05',sort='int',date=date):
  697:                     if project[1]==parentId:
  698:                         ret.append(project)
  699:                 
  700:                 if (depth is not None) and (len(ret) >= depth):
  701:                     break
  702: 
  703:         if childs:
  704:             for project in self.getProjectFields('xdata_05',sort='int',date=date):
  705:                 searchStr=childs+"(\..*)"
  706:                
  707:                 if (onlyActive and project[0].isActiveProject()) or (not onlyActive):
  708:                     if re.match(searchStr,project[1]):
  709:                         
  710:                         if depth:
  711:     
  712:                             if int(depth)>=len(project[1].split("."))-len(childs.split(".")):
  713:                         
  714:                                 ret.append(project)
  715:                         else:
  716:                             ret.append(project)
  717:         
  718:         #logging.debug("getContexts: childs=%s parents=%s depth=%s => %s"%(childs,parents,depth,repr(ret)))
  719:      
  720:         return ret
  721: 
  722:     def getAllProjectsAndTagsAsCSV(self,archived=1):
  723:         """alle projekte auch die nicht getaggten"""
  724:         retList=[]
  725:         for project in self.getProjectFields('WEB_title_or_short'):
  726:             proj = project[0]
  727:             p_name = project[1]
  728:             retProj=[]
  729:             if (not proj.isArchivedProject() and archived==1) or (proj.isArchivedProject() and archived==2):
  730:                 retProj.append(self.utf8ify(p_name))  
  731:                 retProj.append(self.utf8ify(proj.getContent('xdata_01')))   
  732:                 retProj.append(self.utf8ify(getattr(proj,'creationTime','20050101000000')))  
  733:                 retProj.append("|".join([person[1] for person in self.thesaurus.getPersonsFromProject(proj.getId())]))
  734:                 retProj.append("|".join([person[1] for person in self.thesaurus.getHistoricalPlacesFromProject(proj.getId())]))
  735:                 retProj.append("|".join([person[1] for person in self.thesaurus.getObjectsFromProject(proj.getId())]))
  736:                 retProj.append("|".join(self.thesaurus.getTags(proj.getId())))
  737:                 retList.append("\t".join(retProj))
  738: 
  739:         return "\n".join(retList);
  740:     
  741:     def getProjectFields(self,fieldName,date=None,folder=None,sort=None):
  742:         """getListofFieldNames"""
  743:         ret=[]
  744:     
  745:         objects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'],search_sub=0)
  746: 
  747:                 
  748:         for object in objects:
  749:             obj=object[1]
  750:             obj=obj.getActualVersion(date)
  751:             if obj and (not getattr(obj,'invisible',None)):
  752:                 if fieldName=="WEB_title_or_short":
  753: 
  754:                     if len(obj.getContent('xdata_07'))<3: # hack weil z.Z. manchmal noch ein Trennzeichen ; oder , im Feld statt leer
  755:                         fieldNameTmp="WEB_title"
  756:                     else:
  757:                         fieldNameTmp="xdata_07"
  758:                 else:
  759:                     fieldNameTmp=fieldName
  760: 
  761:                 ret.append((obj,obj.getContent(fieldNameTmp)))
  762: 
  763:         
  764:         if sort=="int":
  765:             ret.sort(sortI)
  766:         elif sort=="stopWords":
  767:  
  768:             ret.sort(sortStopWords(self))
  769:             
  770:         else:
  771:             ret.sort(sortF)
  772:         
  773:         return ret
  774: 
  775:     def showNewProjects(self):
  776:         projects=[]
  777:         for objs in self.getProjectFields('WEB_title_or_short'): # Get all Projets
  778:             if objs[0].xdata_05 and (objs[0].xdata_05[0] == ""):
  779:                 
  780:                 projects.append(objs)
  781:                 
  782:         return projects
  783:     
  784:         
  785:     def updatePublicationDB(self,personId=None):
  786:         """updates the publication db, i.e. copy year and type into the main table"""
  787:         
  788:         if personId:
  789:             founds = self.ZSQLInlineSearch(_table="publications",key_main=personId)
  790:         else:
  791:             founds = self.ZSQLInlineSearch(_table="publications")
  792:             
  793:         for found in founds:
  794:                         
  795:             if found.id_institutsbibliographie and (not found.id_institutsbibliographie =="") and (not found.id_institutsbibliographie =="0"):
  796:                 
  797:                 entries = self.ZSQLInlineSearch(_table="institutsbiblio",id=found.id_institutsbibliographie)
  798:                 for entry in entries:
  799:                     self.ZSQLChange(_table='publications',_identify='oid=%s' % found.oid,year=entry.year,referencetype=entry.reference_type)
  800:                     
  801:             if found.id_gen_bib and (not found.id_gen_bib ==""):
  802:                 entries = self.ZSQLInlineSearch(_table="bibliography",id=found.id_gen_bib)
  803:                 for entry in entries:
  804:                     self.ZSQLChange(_table='publications',_identify='oid=%s' % found.oid,year=entry.year,referencetype=entry.reference_type)
  805:                     
  806:         return True        
  807:     
  808:     def showNewDBEntries(self):
  809:         """zeige neue Eintraege in der Datenbank ohne e-mail adressen bzw. fuer die noch kein Object angelegt wurde"""
  810:         
  811:         qstr="select * from personal_www where web_object_created='no' and not key=''"
  812:         res=self.ZSQLQuery(qstr)
  813:         
  814:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','showNewDBEntries.zpt')).__of__(self)
  815:         return pt(newEntries=res)
  816:    
  817:     def createNewStaffObjects(self,RESPONSE):
  818:         """create new staff object"""
  819:         
  820:         memberFolder=getattr(self,'members')
  821:         args=self.REQUEST.form
  822:         arg_k=args.keys()
  823:         arg_k.remove("submit")
  824:         ret=""
  825:         for key in arg_k:
  826:             k=self.urlUnQuote(key)
  827:           
  828:             qstr="select * from personal_www where key=%s"%self.ZSQLQuote(k)
  829:             res=self.ZSQLQuery(qstr)[0]
  830:             if args[key]!="": #email-adresse wurde eingetragen
  831:                 #create the object
  832:                 e_mail=args[key]
  833:                 try:
  834:                     newObj=MPIWGStaff.MPIWGStaff(e_mail,res.last_name,res.first_name,k)
  835:                     memberFolder._setObject(e_mail,newObj)
  836:                     obj=getattr(memberFolder,e_mail)
  837:                     obj.reindex_object()
  838:                     ret+="Created %s \n"%e_mail
  839:                     created=True
  840:                 except:
  841:                     msg="Cannot create new user %s (%s %s)"%(e_mail,sys.exc_info()[0],sys.exc_info()[1])
  842:                     logging.error(msg)
  843:                     ret+=msg+"\n"
  844:                     created=False
  845:                 
  846:                 if created:
  847:                     qstr="update personal_www set web_object_created='yes',e_mail='%s@mpiwg-berlin.mpg.de' where key=%s"%(e_mail,self.ZSQLQuote(k))
  848:                     self.ZSQLQuery(qstr)
  849:         
  850:         return ret
  851:                    
  852:         
  853:     def generateNewPersonEntry(self,data):
  854:         """generate a new person entry for data, neue personen werden zunaechst nur in der datenbank angelegt """
  855:         
  856:         #memberFolder=getattr(self,'members')
  857:         #create the object
  858:         
  859: #        try:
  860: #            newObj=MPIWGStaff.MPIWGStaff(urllib.quote(data['key']),data['last_name'].encode('utf-8'),data['first_name'].encode('utf-8')) 
  861: #            memberFolder._setObject(urllib.quote(data['key']),newObj)
  862: #        except:
  863: #            return False, "Cannot create new user %s (%s %s)"%(data['key'],sys.exc_info()[0],sys.exc_info()[1])
  864: #        
  865:         
  866:         #create the new entry in the database
  867:         
  868:         
  869:         result,msg=MPIWGStaff.createNewDBEntry(self,data['publish_the_data'],data['key'],data['last_name'],
  870:                                   data['first_name'],data['titles_new'],data['status'],"",
  871:                                   "",data['date_from'],data['date_to'],
  872:                                   data['department'],'',data['funded_by'],
  873:                                   data['e_mail2'],data['current_work'],"yes",data['date_stay_at_mpiwg'],data['group'],"no",data['current_work'])
  874:         
  875:         return result,msg
  876:  
  877:     def updatePersonEntry(self,data,ignoreEntries=None):
  878:         """update an person entry from data. but ignore all fields in ignore Entries"""
  879:         if ignoreEntries is None:
  880:             ignoreEntries = []
  881:             
  882:         #ignoreEntries.append('current_work') # TODO:updatecurrent work
  883:         logging.debug("updatePersonEntry: data=%s ignoreEntries=%s"%(repr(data),repr(ignoreEntries)))
  884:         
  885:         if data['date_to']=="": # wenn date_to leer
  886:              data['date_to']="date_none"
  887:         
  888:         if data['date_from']=="": # wenn date_fromleer
  889:              data['date_from']="date_none"
  890:         msg=""
  891:    
  892:         
  893:         #eintragen
  894:          
  895:         columns=data.keys()
  896:         for x in ignoreEntries:
  897:             logging.debug("updatePersonEntry: ignoring %s"%x)
  898:             try: #falls in ignore entries felder sind, die nicht in columns sind, fange den fehler ab
  899:                 columns.remove(x)
  900:             except:
  901:                 pass
  902: 
  903:         
  904:         insert=[]
  905:         for key in columns:
  906:             if data[key]=="date_none": # date_none eintrag wird zu null uebersetzt
  907:                 insert.append('%s=null'%key)
  908:             else:
  909:                 insert.append(""" "%s"=%s"""%(key,self.ZSQLQuote(data[key])))
  910:             
  911:         insertStr=",".join(insert)
  912:         queryStr="update personal_www SET %s where key='%s'"%(insertStr,data['key'])
  913:         self.ZSQLQuery("SET DATESTYLE TO 'German'")
  914:         self.ZSQLQuery(queryStr)
  915:        
  916:         #currentwork
  917:         #if not (txt==""):
  918:         #    queryStr="INSERT INTO current_work (id_main,current,publish) VALUES ('%s','%s','%s')"%(id,txt,txt_p)
  919:         #
  920:         #    self.ZSQLQuery(queryStr)
  921:         
  922:         return True,msg
  923: 
  924: 
  925:     def updatePersonalwww_doIt(self):
  926:         """do the update"""
  927:         args=self.REQUEST.form
  928:         resultSet=self.REQUEST.SESSION['personal_www']['resultSet']
  929:         news=self.REQUEST.SESSION['personal_www']['news']
  930:         conflicts=self.REQUEST.SESSION['personal_www']['conflicts']
  931:         logging.debug("updatePersonalwww_doIt: args=%s\n  resultSet=%s\n  news=%s\n  conflicts=%s"%(args,resultSet,news,conflicts))
  932:         
  933:         ret="<html><body>"
  934:         # generate the new entry
  935:       
  936:         if news and (len(news)>0):
  937:             ret+="<h2>Hinzugef&uuml;gt</h2>"
  938:             ret+="<p>Neueintr&auml;ge erscheinen erst auf der Homepage, wenn ihnen eine e-mail Adresse zugeordnet wurde.</p>"
  939:             ret+="<ul>"
  940:             
  941:         for new in news:
  942:             if args.has_key(self.urlQuote(new.encode('utf-8'))): # entry was selected
  943:                 result,msg=self.generateNewPersonEntry(resultSet[new])
  944:                 if not result:
  945:                     logging.error("Error (generateNewPersonEntry) %s"%msg)
  946:                     ret+="<li>ERROR: %s %s"%(new.encode('utf-8'),msg)
  947:                 else:
  948:                     ret+="<li>OK: %s"%(new.encode('utf-8'))
  949:                     
  950:         if news and (len(news)>0):
  951:             ret+="<p>Neueintr&auml;ge erscheinen erst auf der Homepage, wenn ihnen eine e-mail Adresse zugeordnet wurde.</p>"
  952:             ret+="</ul>"     
  953:         
  954:         # update
  955: 
  956:         if len(conflicts.keys())>0:
  957:             ret+="<h2>&Auml;nderung des Benutzers &uuml;bernehmen</h2>"
  958:             ret+="<p>Wenn n&ouml;tig in Filemaker-db &auml;ndern:</p>"
  959:             
  960:         # konflicte   
  961:         for conflict in conflicts.keys():
  962:             ignoreEntries=[]
  963:             displayIgnored=[]
  964:             for cf in conflicts[conflict]:
  965:                 if args[conflict.encode('utf-8')+'_'+cf[0]]=="stored": #use the stored one
  966:                     ignoreEntries.append(cf[0])  #so ignore field cf[0]       
  967:                     displayIgnored.append(cf)
  968:                     
  969:             if len(displayIgnored)>0:
  970:                 ret+="<h3>%s</h3>"%conflict.encode('utf-8')
  971:                 ret+="<table border='1'>"
  972:                 for iE in displayIgnored:
  973:                     ret+="<tr><td>%s</td><td>%s</td><td>%s</td>"%(iE[0].encode('utf-8'),iE[1].encode('utf-8'),iE[2].encode('utf-8'))
  974:                 ret+="</table>"
  975:                 
  976:             self.updatePersonEntry(resultSet[conflict],ignoreEntries=ignoreEntries)
  977:          
  978:          # rest
  979:         cl=list(conflicts.keys())
  980:         
  981:         for key in resultSet.keys():
  982:              if key not in cl:
  983:                  self.updatePersonEntry(resultSet[key])
  984:         return ret+"</body></html>"
  985:                      
  986: 
  987:     def updateInstitutsbiliography(self):
  988:         """update the Institutsbibliogrpahy"""
  989:         self.upDateSQL('personalwww.xml')
  990:         return "<html><body>DONE</body></html>"
  991: 
  992: 
  993:     
  994: 
  995:     def updatePersonalwww_html(self):
  996:         """update form for the homepages web form"""
  997:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','updatePersonalwww.zpt')).__of__(self)
  998:         return pt()
  999: 
 1000:     
 1001:     def updatePersonalwww(self,uploadfile):
 1002:         """update personalwww
 1003:         @param uploadfile: file handle auf das file
 1004:         """
 1005:         dsn=self.getConnectionObj().connection_string
 1006:         #dsn="dbname=personalwww"
 1007:         resultSet=updatePersonalWWW.importFMPXML(uploadfile)
 1008:         news,conflicts=updatePersonalWWW.checkImport(dsn, resultSet)
 1009: 
 1010:         self.REQUEST.SESSION['personal_www']={}
 1011:         self.REQUEST.SESSION['personal_www']['resultSet']=resultSet
 1012:         self.REQUEST.SESSION['personal_www']['news']=news
 1013:         self.REQUEST.SESSION['personal_www']['conflicts']=conflicts
 1014:         
 1015:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','updatePersonalwww_check.zpt')).__of__(self)
 1016:         return pt()
 1017:     
 1018: 
 1019:      
 1020:     def reindexCatalogs(self,RESPONSE=None):
 1021:         """reindex members and project catalog"""
 1022:         
 1023:         
 1024:         try:
 1025:             
 1026:             self.ProjectCatalog.manage_catalogReindex(self.REQUEST,RESPONSE,self.REQUEST['URL1'])
 1027:             logger("MPIWG Root (reindexCatalog: projects)",logging.INFO,"DONE")
 1028:         except:
 1029:             logger("MPIWG Root (reindexCatalog: projects)",logging.WARNING," %s %s"%sys.exc_info()[:2])
 1030:         
 1031:         try:
 1032:             
 1033:             self.MembersCatalog.manage_catalogReindex(self.REQUEST,RESPONSE,self.REQUEST['URL1'])
 1034:             logger("MPIWG Root (reindexCatalog: members)",logging.INFO,"DONE")
 1035:         except:
 1036:             logger("MPIWG Root (reindexCatalog: members)",logging.WARNING," %s %s"%sys.exc_info()[:2])
 1037:         
 1038:         try:
 1039:             
 1040:             self.fulltextProjectsMembers.manage_catalogReindex(self.REQUEST,RESPONSE,self.REQUEST['URL1'])
 1041:             logger("MPIWG Root (reindexCatalog: fulltextProjectsMembers)",logging.INFO,"DONE")
 1042:         except:
 1043:             logger("MPIWG Root (reindexCatalog: fulltextProjectsMembers)",logging.WARNING," %s %s"%sys.exc_info()[:2])
 1044:             
 1045:         
 1046:         
 1047:         
 1048:         
 1049:         
 1050:         if RESPONSE:
 1051:             RESPONSE.redirect('manage_main')
 1052: 
 1053:         
 1054:         
 1055: 
 1056:     def getAllMembers(self):
 1057:         #ret=[]
 1058:         
 1059:         def sorter(x,y):
 1060:             return cmp(x[0],y[0])
 1061:                     
 1062:         results=self.MembersCatalog({'isPublished':True})
 1063:        
 1064:         ret=[(unicodify(", ".join([proj.lastName, proj.firstName])), proj.getKey) for proj in results]
 1065:         
 1066:         ret.sort(sorter)
 1067:         return ret
 1068:     
 1069:     
 1070:     def printAllMembers(self):
 1071:         """print"""
 1072:         members=self.getAllMembers()
 1073:         ret=""
 1074:         for x in members:
 1075:             ret+="<p>%s</p>"%x
 1076:         return ret
 1077:     
 1078:         
 1079:     def makeList(self,entry):
 1080:         """makes a list out of one entry or repeat a list"""
 1081:         if type(entry) is StringType:
 1082:             return [entry]
 1083:         else:
 1084:             return entry
 1085: 
 1086:     def getTreeRSS(self,dep=None,date=None,onlyActive=1,onlyArchived=0):
 1087:         """generateTree"""
 1088:         rss="""<?xml version="1.0" encoding="utf-8"?>
 1089:                  <rss version="2.0">
 1090:                    <channel>"""
 1091:         
 1092:         for obj in self.getTree(dep, date, onlyActive, onlyArchived):
 1093:             linkStr="""<link>http://www.mpiwg-berlin.mpg.de/en/research/projects/%s</link>"""
 1094:             rss+="""<item>"""
 1095:             rss+=linkStr%obj[3].getId()
 1096:             rss+="""</item>"""
 1097:             if hasattr(obj[3],'publicationList'):
 1098: 	        rss+="""<item>"""
 1099:                 rss+=linkStr%(obj[3].getId()+"/publicationList");
 1100:                 rss+="""</item>"""
 1101:         rss+="""</channel>
 1102:         </rss>"""
 1103: 
 1104:         
 1105:         return rss
 1106: 
 1107:     def getTree(self,dep=None,date=None,onlyActive=0,onlyArchived=0):
 1108:         """generate Tree from project list
 1109:         als Liste, jeder Eintrag ist ein Tupel ,(Tiefe, ProjektNummer,ProjektObject
 1110:         onlyActive = 0  : alle Projekte
 1111:         onlyActive = 1 : nur active Projekte
 1112:         onlyActive = 2: nur inactive Projekte
 1113:         
 1114:         onlyArchived=0: alle Projekte
 1115:         onlyArchived= 1 : nur aktuelle Projekte
 1116:         onlyArchived = 2: nur archivierte Projekte
 1117:         
 1118:         department fuer das Tree geholt werden soll
 1119:         """
 1120: 
 1121:         returnListTmp=[]
 1122:         returnList=[]
 1123:         
 1124:         for project in self.getProjectFields('xdata_05',sort="int",date=date): # get Projects sorted by xdata_05
 1125: 
 1126:             for idNr in project[1].split(";"): # more than one number
 1127:                 if not idNr=="":
 1128:                     splittedId=idNr.split(".")
 1129:                     depth=len(splittedId)
 1130:                     nr=idNr
 1131:                     #title=project[0].WEB_title
 1132:                     title=[project[0].getContent('WEB_title')]
 1133:                     #print title
 1134:                     
 1135:                     if idNr[0]=="x": # kompatibilitaet mit alter Konvention, x vor der Nummer macht project inactive
 1136:                         project[0].setActiveFlag(False)
 1137:                    
 1138:                     if (not dep) or (splittedId[0]==dep): #falls dep gesetzt ist nur dieses hinzufuegen.
 1139:                         
 1140:                         if (onlyActive==0):
 1141:                             returnListTmp.append((depth,nr,title,project[0]))
 1142:                         elif (onlyActive==1) and project[0].isActiveProject(): #nur active projekte
 1143:                             returnListTmp.append((depth,nr,title,project[0]))
 1144:                         elif (onlyActive==2) and (not project[0].isActiveProject()): #nur active projekte
 1145:                             returnListTmp.append((depth,nr,title,project[0]))
 1146:                    
 1147:                    
 1148:         #filter jetzt die Liste nach Archived oder nicht
 1149:         for entry in returnListTmp:
 1150:                     if (onlyArchived==0):
 1151:                             returnList.append(entry)
 1152:                     elif (onlyArchived==1) and (not entry[3].isArchivedProject()): #nur active projekte
 1153:                             returnList.append(entry)
 1154:                     elif (onlyArchived==2) and (entry[3].isArchivedProject()): #nur active projekte
 1155:                             returnList.append(entry)
 1156:                    
 1157:         
 1158:         return returnList
 1159: 
 1160: 
 1161:         
 1162:     def changePosition(self,treeId,select,RESPONSE=None):
 1163:         """Change Postion Entry"""
 1164:         numbers=[]
 1165: 
 1166:         # Suche hoechste bisherige nummer
 1167:         projects=self.getProjectFields('xdata_05') # get Projects sorted by xdata_05
 1168:         #print "pj",projects
 1169:         for project in projects: #suche alle subtrees der treeId
 1170:             #print treeId
 1171:             
 1172:             founds=re.match(treeId+"\.(.*)",project[1].split(";")[0])
 1173:             if founds:
 1174:                 #print "x",founds.group(0),len(founds.group(0).split("."))
 1175:                 if len(founds.group(0).split("."))==len(treeId.split("."))+1: # nur ein punkt mehr, d.h. untere ebene
 1176:                     try:
 1177:                         numbers.append(int(founds.group(0).split(".")[len(founds.group(0).split("."))-1]))
 1178:                     except:
 1179:                         numbers.append(int(0))
 1180: 
 1181:         try:
 1182:             highest=max(numbers)
 1183:         except:
 1184:             highest=0
 1185:         projects=self.showNewProjects()
 1186:         for i in self.makeList(select):
 1187:             highest+=10
 1188:             projects[int(i)][0].xdata_05=treeId+"."+str(highest)
 1189: 
 1190: 
 1191:         if RESPONSE is not None:
 1192:             RESPONSE.redirect('showTree')
 1193:         
 1194:     def changeTree(self,RESPONSE=None):
 1195:         """change the complete tree"""
 1196:         form=self.REQUEST.form
 1197:         hashList={}
 1198:         onlyArchived=int(form.get("onlyArchived",0))
 1199:         onlyActive=int(form.get("onlyActive",0))
 1200:         dep=form.get("dep",None)
 1201:         
 1202:         fields=self.getTree(dep=dep,onlyArchived=onlyArchived,onlyActive=onlyActive)
 1203:         
 1204:         logging.info("GOT TREE!----------------------------------------------------")
 1205:         for field in form.keys():
 1206:             
 1207:             splitted=field.split('_')
 1208:             if (len(splitted)>1) and (splitted[1]=="runningNumber"): #feld hat die Form Nummer_name und runnignNumber
 1209:             
 1210:                 
 1211:                 nr=int(splitted[0]) # nummer des Datensatzes
 1212:                 currentEntry = fields[nr]
 1213:             
 1214:                 if form.has_key(str(nr)+'_active'): # active flag is set
 1215:                     fields[nr][3].setActiveFlag(True)
 1216:                 else:
 1217:                     fields[nr][3].setActiveFlag(False)
 1218:                     
 1219:                 #nummer hat sich geaendert
 1220:                 
 1221:                 entryChanged = False;
 1222:                 
 1223:                 if isinstance(fields[nr][3].xdata_05,list): #for some reasons somtimes the content of the field is a list with one entry.
 1224:                     fields[nr][3].xdata_05=fields[nr][3].xdata_05[0]
 1225:                     
 1226:                 if not (fields[nr][3].xdata_05==form[str(nr)+'_number']):
 1227:                     logging.info("Changed!Number+++++++++++++++++++++++++++++++++")
 1228:                     logging.info(repr(fields[nr][3].xdata_05)+" ---> "+ repr(form[str(nr)+'_number']))
 1229:                     fields[nr][3].xdata_05=form[str(nr)+'_number']
 1230:                     entryChanged = True
 1231:                     
 1232:                 #completed har sich geaendert
 1233:                           
 1234:                 td = fields[nr][3].transformDate # hole die funktion zum transformieren des datums
 1235:                   
 1236:                 if not (td(fields[nr][3].getCompletedAt())==td(form[str(nr)+'_completed'])):
 1237:                     fields[nr][3].setCompletedAt(form[str(nr)+'_completed'])
 1238:                     logging.info(repr(td(fields[nr][3].getCompletedAt()))+" ---> "+ repr(td(form[str(nr)+'_completed'])))
 1239:                     logging.info("Changed!Completed+++++++++++++++++++++++++++++++++")
 1240:                     entryChanged = True
 1241:                 
 1242:                 if not (td(fields[nr][3].getStartedAt())==td(form[str(nr)+'_started'])):
 1243:                     fields[nr][3].setStartedAt(form[str(nr)+'_started'])
 1244:             
 1245:                     logging.info(repr(td(fields[nr][3].getStartedAt()))+" ---> "+ repr(td(form[str(nr)+'_started'])))
 1246:                     logging.info("Changed!Started+++++++++++++++++++++++++++++++++")
 1247:                     entryChanged = True
 1248:                 
 1249:                 
 1250:                 if entryChanged:
 1251:                     logging.info("Changed!+++++++++++++++++++++++++++++++++")
 1252:                     fields[nr][3].copyObjectToArchive()
 1253:                 
 1254:                     
 1255:         if RESPONSE is not None:
 1256:             RESPONSE.redirect('showTree')
 1257: 
 1258:     def getProjectWithId(self,id):
 1259:         fields=self.getProjectFields('xdata_05')
 1260:         for field in fields:
 1261:             if field[1]==id:
 1262:                 return field[0]
 1263: 
 1264:         return None
 1265:             
 1266:         
 1267:             
 1268:         
 1269:     def getRelativeUrlFromPerson(self,list):
 1270:         """get urls to person list"""
 1271:         ret=[]
 1272:         persons=list.split(";")
 1273:         for person in persons:
 1274:             
 1275:             if len(person)>1: #nicht nur Trennzeichen
 1276:                 splitted=person.split(",")
 1277:                 if len(splitted)==1:
 1278:                     splitted=person.split(" ")
 1279:                 splittedNew=[re.sub(r'\s(.*)','$1',split) for split in splitted]
 1280:                 if splittedNew[0]=='':
 1281:                     del splittedNew[0]
 1282:                 search=string.join(splittedNew,' AND ')
 1283:                 
 1284:                 if not search=='':
 1285: 
 1286:                     try:
 1287:                         proj=self.MembersCatalog({'title':search})
 1288:                     except:
 1289:                         proj=None
 1290: 
 1291:                 if proj:
 1292:                     #ret.append("<a href=%s >%s</a>"%(proj[0].absolute_url,person.encode('utf-8')))
 1293:                     ret.append("<a href=%s >%s</a>"%('members/'+proj[0].id+'/index.html',person))
 1294:                 else:
 1295:                     #ret.append("%s"%person.encode('utf-8'))
 1296:                     ret.append("%s"%person)
 1297:         return string.join(ret,";")
 1298:         
 1299:     def getMemberIdFromKey(self,key):
 1300:         """gibt die ensprechende id  im members Ordner zum key"""
 1301:         
 1302:         if key=="":
 1303:             return ""
 1304:         try:
 1305:             key=utf8ify(key)
 1306:             catalogged=self.MembersCatalog({'getKey':key})
 1307:             if len(catalogged)==0:
 1308:                 return ""
 1309:             else:
 1310:                 return catalogged[0].getObject().getId()
 1311:         
 1312:         except:
 1313:             return ""
 1314: 
 1315:             
 1316: 
 1317:     def getProjectsOfMembers(self,date=None):
 1318:         """give tuple member /projects"""
 1319:         ret=[]
 1320:         members=self.getAllMembers()
 1321:         logging.debug("X %s"%repr(members))
 1322:         #return str(members)
 1323:         for x in members:
 1324:             #logging.debug("X %s"%repr(x))
 1325:             projects=self.getProjectsOfMember(key=x[1],date=date)
 1326:             if len(projects)>0:
 1327:                 ret.append((x[0],projects))
 1328:             
 1329:         return ret
 1330: 
 1331:     def getProjectsOfMember(self,key=None,date=None,onlyArchived=1,onlyActive=1):
 1332:         """get projects of a member
 1333:     
 1334:         @param key: (optional) Key zur Idenfikation des Benutzer
 1335:         @param date: (optional) Version die zum Zeitpunkt date gueltig war
 1336:         @param onlyArchived: 
 1337:         onlyArchived=0: alle Projekte
 1338:         onlyArchived= 1 : nur aktuelle Projekte
 1339:         onlyArchived = 2: nur archivierte Projekte
 1340:         """
 1341:         # TODO: Die ganze Loesung
 1342:         def sortP(x,y):
 1343:             """sort by sorting number"""
 1344:             return cmp(x.WEB_title,y.WEB_title)
 1345:         
 1346:         ret=[]  
 1347:         if key:     
 1348:             logging.debug("MPIWGROOT (getProjectsOfMember):"+key)
 1349:             proj=self.ProjectCatalog({'getPersonKeyList':utf8ify(key)})
 1350:         else:
 1351:             return ret # key muss definiert sein
 1352:         
 1353:         #logging.debug("MPIWGROOT (getProjectsOfMember):"+repr(proj))
 1354:         if proj:
 1355:             proj2=[]
 1356:             for x in proj:
 1357:                 #logging.error("proj:%s"%repr(x.getPath()))
 1358:                 if (not getattr(x.getObject(),'invisible',None)) and (getattr(x.getObject(),'archiveTime','')==''):   
 1359:                       proj2.append(x)
 1360: 
 1361:         else:
 1362:             proj2=[]
 1363:             
 1364:        
 1365:        
 1366:         proj2.sort(sortP)
 1367: 
 1368:         projectListe=[]
 1369:         #logging.error("getprojectsofmember proj2: %s"%repr(proj2))
 1370:         for proj in proj2:   
 1371:             obj=proj.getObject()
 1372:             add=False
 1373:             if onlyArchived==1: #nur aktuell projecte
 1374:                 if not obj.isArchivedProject():
 1375:                     add=True
 1376:             elif onlyArchived==2: #nur archivierte
 1377:                 if obj.isArchivedProject():
 1378:                     add=True
 1379:             else: #alle
 1380:                add=True 
 1381:                
 1382:             if onlyActive==1: #nur active projecte
 1383:                 if obj.isActiveProject():
 1384:                     add=add & True
 1385:                 else:
 1386:                     add=add & False
 1387:                 
 1388:             elif onlyArchived==2: #nur nicht aktvive
 1389:                 if not obj.isActiveProject():
 1390:                     add=add & True
 1391:             else: #alle
 1392:                add=add & True
 1393:                     
 1394:             if add:
 1395:                 projectListe.append(obj)
 1396:                 
 1397:         #logging.error("getprojectsofmember projectliste: %s"%repr(projectListe))
 1398:         return projectListe
 1399:      
 1400:     def givePersonList(self,name):
 1401:         """check if person is in personfolder and return list of person objects"""
 1402:         
 1403:         splitted=name.split(",")
 1404:         if len(splitted)==1:
 1405:             splitted=name.lstrip().rstrip().split(" ")
 1406:         splittedNew=[split.lstrip() for split in splitted]
 1407:         
 1408:         if splittedNew[0]=='':
 1409:             del splittedNew[0]
 1410:         search=string.join(splittedNew,' AND ')
 1411:         
 1412:         if not search=='':
 1413:             proj=self.MembersCatalog({'title':search})
 1414: 
 1415:         if proj:
 1416:             return [[x.lastName,x.firstName] for x in proj]
 1417:         else:
 1418:             return []
 1419:             
 1420: ##         splitted=name.split(",") # version nachname, vorname...
 1421: ##         if len(splitted)>1:
 1422: ##             lastName=splitted[0] 
 1423: ##             firstName=splitted[1]
 1424: ##         else: 
 1425: ##             splitted=name.split(" ") #version vorname irgenwas nachnamae
 1426:         
 1427: ##             lastName=splitted[len(splitted)-1]
 1428: ##             firstName=string.join(splitted[0:len(splitted)-1])
 1429: 
 1430: ##         objs=[]
 1431: 
 1432:         #print  self.members 
 1433:       ##   for x in self.members.__dict__:
 1434: ##             obj=getattr(self.members,x)
 1435: ##             if hasattr(obj,'lastName') and hasattr(obj,'firstName'):
 1436:                 
 1437: ##                 if (re.match(".*"+obj.lastName+".*",lastName) or re.match(".*"+lastName+".*",obj.lastName)) and (re.match(".*"+obj.firstName+".*",firstName) or re.match(".*"+firstName+".*",obj.firstName)):
 1438:                     
 1439: ##                     objs.append((obj,lastName+", "+firstName))
 1440: 
 1441:         
 1442: ##        return objs
 1443: 
 1444: 
 1445:     def personCheck(self,names):
 1446:         """all persons for list"""
 1447:         #print "names",names
 1448:         splitted=names.split(";")
 1449:         ret={}
 1450:         for name in splitted:
 1451: 
 1452:             if not (name==""):
 1453:                 try:
 1454:                     ret[name]=self.givePersonList(name)
 1455:                 except:
 1456:                     """NOTHIHN"""
 1457:         #print "RET",ret
 1458:         return ret
 1459: 
 1460:     def giveCheckList(self,person,fieldname):
 1461:         """return checklist"""
 1462:         #print "GCL",fieldname
 1463:         if fieldname=='xdata_01':
 1464:             x=self.personCheck(person.getContent(fieldname))
 1465:             #print "GCLBACKX",x
 1466:             return x
 1467:         
 1468: 
 1469:     def isCheckField(self,fieldname):
 1470:         """return chechfield"""
 1471:         
 1472:         return (fieldname in checkFields)
 1473: 
 1474:     
 1475:     def generateNameIndex(self):
 1476:         """erzeuge einen index verwendeter personen"""
 1477:         import psycopg
 1478:         o = psycopg.connect('dbname=authorities user=dwinter password=3333',serialize=0) 
 1479:         results={}
 1480:         print self.fulltext.historicalNames.items()
 1481:         for nameItem in self.fulltext.historicalNames.items(): #gehe durch alle namen des lexikons
 1482:             
 1483:             c = o.cursor() 
 1484:             name=nameItem[0]
 1485:             print "check",name
 1486:             c.execute("select lastname,firstname from persons where lower(lastname) = '%s'"%quote(name))
 1487:             tmpres=c.fetchall()
 1488:             firstnames=[result[1] for result in tmpres] # find all firstnames
 1489:             if tmpres:
 1490:                 lastname=tmpres[0][0]
 1491:                 
 1492:             for found in self.fulltext({'names':name}):
 1493:                 if found.getObject().isActual():
 1494:                     for nh in found.getObject().getGetNeighbourhood(name, length=50,tagging=False): #hole umgebung
 1495:                         #schaue nun ob der vorname hinter oder vor dem name ist
 1496:                         position=nh.find(lastname)
 1497:                         # vorher
 1498:                         #print "NH",nh
 1499:                         bevorS=nh[0:position].split()
 1500:                         #print "BV",bevorS
 1501:                         if len(bevorS)>1:
 1502:                             try:
 1503:                                 bevor=[bevorS[-1],bevorS[-2]]
 1504:                             except:
 1505:                                 bevor=[bevorS[0]]
 1506:                         else:
 1507:                             bevor=[]
 1508:                         #nachher
 1509:                         behindS= re.split("[,|;| ]",nh[position:]) 
 1510:                         #print "BH",behindS
 1511:                         if len(behindS)>2:
 1512:                             try:
 1513:                                 behind=behindS[1:3]
 1514:                             except:
 1515:                                 behind=[bevorS[1]]
 1516:                         else:
 1517:                             behind=[]
 1518:                         for firstname in firstnames:
 1519:                             if firstname in bevor+behind: #Namen wie mit Adelspraedikaten werden so erstmal nich gefunden
 1520:                                 id="%s,%s"%(lastname,firstname)
 1521:                                 if not results.has_key(id):
 1522:                                     results[id]=[]
 1523:                                 objId=found.getObject().getId()
 1524:                                 if not (objId in results[id]):
 1525:                                     print "d %s for %s"%(id,objId)    
 1526:                                     results[id].append(objId)    
 1527:             self.nameIndex=results
 1528:         return results
 1529:                     
 1530:     def editNameIndexHTML(self):
 1531:         """edit the name index"""
 1532:         if not hasattr(self,'nameIndexEdited'): # falls editierter index noch nicht existiert, kopiere automatisch erstellten
 1533:             self.nameIndexEdited=copy.copy(self.nameIndex)
 1534:             print "huh"
 1535:         #self.nameIndexEdited=copy.copy(self.nameIndex)
 1536:         #print self.nameIndexEdited
 1537:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','editHistoricalNames.zpt')).__of__(self)
 1538:         return pt()
 1539:     
 1540:     def getNamesInProject(self,projectId):
 1541:         """get all names ofnameIndexEdited which are references in projec with projectId"""
 1542:         
 1543:         ret=[]
 1544:         for name in self.nameIndexEdited.keys():
 1545:             if projectId in self.nameIndexEdited[name]:
 1546:                 ret.append(name)
 1547:         
 1548:         return ret
 1549:     
 1550:     def editNameIndex(self,RESPONSE=None,name=None,occurrances=None,submit=None):
 1551:         """edit the index"""
 1552:         nI=self.nameIndexEdited # mI introduced to make sure that changes to nameIndexEdited are know to ZODB
 1553:         if submit=="delete":
 1554:            
 1555: 
 1556:             dh=getattr(self,'deletedHistoricalNames',{})
 1557:             
 1558:             if type(dh) is ListType:
 1559:                 dh={}
 1560:             if not dh.has_key(name):
 1561:                 dh[name]=occurrances.split("\n")
 1562:             else:
 1563:                 dh[name]+=occurrances.split("\n")
 1564:             
 1565:             self.deletedHistoricalNames=dh
 1566:             
 1567:             del self.nameIndexEdited[name]
 1568:             
 1569:         
 1570:         elif (submit=="change"):
 1571:             
 1572:             nI[name]=occurrances.split("\n")[0:]
 1573:             
 1574:         elif (submit=="add"):
 1575:             if not nI.has_key(name):
 1576:                 nI[name]=occurrances.split("\n")
 1577:             else:
 1578:                 nI[name]+=occurrances.split("\n")
 1579:     
 1580:         self.nameIndexEdited=nI
 1581:    
 1582:       
 1583:         if RESPONSE is not None:
 1584:             RESPONSE.redirect('editNameIndexHTML')
 1585:         
 1586:     
 1587:     
 1588:     def restoreIndex(self):
 1589:         """restore"""
 1590:         self.nameIndexEdited=self.nameIndex
 1591:         return "done"
 1592:     
 1593: 
 1594:     def sortResults(self,results):
 1595:         """search the catalog and give results back sorted by meta_type"""
 1596:         ret = {}
 1597:         logging.debug(results())
 1598:         for result in results():
 1599:             metaType = result.meta_type
 1600:             resultList= ret.get(metaType,[])
 1601:             resultList.append(result)
 1602:             ret[metaType]=resultList
 1603:         
 1604:         logging.debug(ret)
 1605:         return ret
 1606:         
 1607:             
 1608: def manage_addMPIWGRootForm(self):
 1609:     """form for adding the root"""
 1610:     pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addMPIWGRootForm.zpt')).__of__(self)
 1611:     return pt()
 1612: 
 1613: def manage_addMPIWGRoot(self,id,title,connection_id="",RESPONSE=None):
 1614:     """add a root folder"""
 1615:     newObj=MPIWGRoot(id,title)
 1616:     self._setObject(id,newObj)
 1617:     ob=getattr(self,id)
 1618:     setattr(ob,'connection_id',connection_id)
 1619:     if RESPONSE is not None:
 1620:         RESPONSE.redirect('manage_main')
 1621:         

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