File:  [Repository] / MPIWGWeb / Attic / MPIWGRoot.py
Revision 1.1.2.18: download - view: text, annotated - select for diffs - revision graph
Mon Sep 8 08:40:05 2008 UTC (15 years, 9 months ago) by casties
Branches: r2
added language switch for Feature

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

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