File:  [Repository] / MPIWGWeb / Attic / MPIWGRoot.py
Revision 1.1.2.20: download - view: text, annotated - select for diffs - revision graph
Fri Sep 12 15:54:49 2008 UTC (15 years, 9 months ago) by casties
Branches: r2
fixed bug with DB connection in MPIWGStaff when root is not called "de"

    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 sub-navigation elements i.e. below sections"""
  347:         # get section -> parent should be MPIWGRoot
  348:         p = obj
  349:         sec = None
  350:         # descend parents to the root (and remember the last id)
  351:         while p is not None and p.meta_type != 'MPIWGRoot':
  352:             sec = p
  353:             p = p.aq_parent
  354:     
  355:         subsecs = sec.objectItems(self.nav_meta_types)
  356:         subsecs = [s for s in subsecs if s[1].title != ""]
  357:         subsecs.sort(sortWeight)
  358:         return subsecs
  359:                 
  360:     def isType(self,object,meta_type):
  361:         """teste ob ein object vom meta_type ist."""
  362:         return (object.meta_type==meta_type)
  363:     
  364:     def isActive(self,name):
  365:         """teste ob subnavigation aktiv"""
  366:         for part in self.REQUEST['URL'].split("/"):
  367:             if part==name:
  368:                 return True
  369:         return False
  370:         
  371:     
  372:     def getSections(self):
  373:         """returns a list of all sections i.e. top-level MPIWGFolders"""
  374:         secs = self.objectItems(['MPIWGFolder'])
  375:         secs.sort(sortWeight)
  376:         #logging.debug("root: %s secs: %s"%(repr(self.absolute_url()), repr(secs)))
  377:         # return pure list of objects
  378:         return [s[1] for s in secs]
  379: 
  380:     def getSectionStyle(self, name, style=""):
  381:         """returns a string with the given style + '-sel' if the current section == name"""
  382:         if self.getSection() == name:
  383:             return style + '-sel'
  384:         else:
  385:             return style    
  386: 
  387:     def getFeatures(self):
  388:         """returns a list of all Features"""
  389:         dir = getattr(self, 'features')
  390:         features = dir.objectItems(['MPIWGFeature'])
  391:         features.sort(sortWeight)
  392:         # return pure list of objects
  393:         return [f[1] for f in features]
  394: 
  395: 
  396:     def getMPIWGRoot(self):
  397:         """returns the MPIWG root"""
  398:         return self
  399: 
  400:     def MPIWGrootURL(self):
  401:         """returns the URL to the root"""
  402:         return self.absolute_url()
  403:         
  404:     def upDateSQL(self,fileName):
  405:         """updates SQL databases using fm.jar"""
  406:         fmJarPath=os.path.join(package_home(globals()), 'updateSQL/fm.jar')
  407:         xmlPath=os.path.join(package_home(globals()), "updateSQL/%s"%fileName)
  408:         logger("MPIWG Web",logging.INFO,"java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath))
  409:         ret=os.popen("java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath),"r").read()
  410:         logger("MPIWG Web",logging.INFO,"result convert: %s"%ret)
  411:         return 1
  412:     
  413:     def patchProjects(self,RESPONSE):
  414:         """patch"""
  415:         projects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'])
  416:         for project in projects:
  417:                 tmp=project[1].WEB_project_description[0].replace("/CD/projects/","")[0:]
  418:                 setattr(project[1],'WEB_project_description',[tmp[0:]])
  419:                 RESPONSE.write("<p>%s</p>\n"%project[0])
  420:             
  421:     def replaceNotEmpty(self,format,field):
  422:         """replace not empty"""
  423:         if field and (not field.lstrip()==''):
  424:             return self.decode(format%field)
  425:         else:
  426:             return ""
  427:         
  428: 
  429:     def isActiveMember(self,key):
  430:         """tested ob Mitarbeiter key ist aktiv"""
  431:         key=utf8ify(key)
  432:         ret=self.getat(self.ZSQLInlineSearch(_table='personal_www',
  433:                                             _op_key='eq',key=key,
  434:                                             _op_publish_the_data='eq',
  435:                                             publish_the_data='yes'))
  436:         
  437:         logging.info("ACTIVE_MEMBER  %s"%ret)
  438:         if ret:
  439:             return True
  440:         else:
  441:             return False
  442:         
  443:     def isActual(self,project):
  444:         """checke if project is actual"""
  445:         actualTime=time.localtime()
  446:         
  447:         if hasattr(project,'getObject'): #obj ist aus einer catalogTrefferList
  448:             obj=project.getObject()
  449:         else:
  450:             obj=project
  451:             
  452:         if getattr(obj,'archiveTime',actualTime)< actualTime:
  453:             return False
  454:         else:
  455:             return True
  456:         
  457:     def redirectIndex_html(self,request):
  458:         #return request['URL1']+'/index_html'
  459:         
  460:         return urllib.urlopen(request['URL1']+'/index_html').read()
  461: 
  462:     
  463:     def formatBibliography(self,here,found):
  464:         """format"""
  465:         return formatBibliography(here,found)
  466:     
  467:     def getValue(self,fieldStr):
  468:         """Inhalt des Feldes"""
  469:         
  470:         if type(fieldStr)==StringType:
  471:             field=fieldStr
  472:         else:
  473:             field=fieldStr[0]
  474:         try:
  475:             if field[len(field)-1]==";":
  476:                 field=field[0:len(field)-1]
  477:         except:
  478: 
  479:             """nothing"""
  480:         field=re.sub(r';([^\s])','; \g<1>',field)
  481:         return field.encode('utf-8')
  482: 
  483: 
  484:     
  485:     def sortedNames(self,list):
  486:         """sort names"""
  487: 
  488:         def sortLastName(x_c,y_c):
  489:             try:
  490:                 x=urllib.unquote(x_c).encode('utf-8','ignore')
  491:             except:
  492:                 x=urllib.unquote(x_c)
  493: 
  494:             try:
  495:                 y=urllib.unquote(y_c).encode('utf-8','ignore')
  496:             except:
  497:                 x=urllib.unquote(y_c)
  498:                 
  499: 
  500:             
  501:             try:
  502:                 last_x=x.split()[len(x.split())-1]
  503:                 last_y=y.split()[len(y.split())-1]
  504: 
  505:             except:
  506: 
  507:                 last_x=""
  508:                 last_y=""
  509:             
  510:             
  511:             
  512:             if last_x<last_y:
  513:                 return 1
  514:             elif last_x>last_y:
  515:                 return -1
  516:             else:
  517:                 return 0
  518:             
  519:         list.sort(sortLastName)
  520:         list.reverse()
  521:         
  522:         return list
  523:     
  524:     def __init__(self, id, title):
  525:         """init"""
  526:         self.id=id
  527:         self.title=title
  528: 
  529:     def removeStopWords(self,xo):
  530:         """remove stop words from xo"""
  531:         if not hasattr(self,'_v_stopWords'):
  532:             self._v_stopWords=self.stopwords_en.data.split("\n")
  533:     
  534:         x=str(xo)
  535:     
  536:         strx=x.split(" ")
  537:   
  538:         for tmp in strx:
  539:      
  540:             if tmp.lower() in self._v_stopWords:
  541:                 del strx[strx.index(tmp)]
  542: 
  543:         return " ".join(strx)
  544:     
  545:     def urlQuote(self,str):
  546:         """quote"""
  547:         return urllib.quote(str)
  548: 
  549:     def urlUnQuote(self,str):
  550:         """quote"""
  551:         return urllib.unquote(str)
  552:     
  553:         
  554: 
  555:     def getProjectsByFieldContent(self,fieldName,fieldContentsEntry, date=None):
  556:         """gib alle Projekte aus mit Value von field mit fieldName enthaelt ein Element der Liste fieldContents"""
  557:         def sort(x,y):
  558:                 return cmp(x.WEB_title[0],y.WEB_title[0])
  559: 
  560:         if type(fieldContentsEntry) is StringType:
  561:             fieldContentsTmp=[fieldContentsEntry]
  562:         else:
  563:             fieldContentsTmp=fieldContentsEntry
  564: 
  565:         fieldContents=[]
  566:         for x in fieldContentsTmp:
  567:             fieldContents.append(" AND ".join(x.split()))
  568:         projects=self.ProjectCatalog({fieldName:string.join(fieldContents,' AND')})
  569:         #print projects
  570:         #ret=[x for x in projects]
  571:         ret=[]
  572:         for x in projects:
  573:             obj=x.getObject()
  574:             obj=obj.getActualVersion(date)
  575:             if obj and (not getattr(obj,'invisible',None)):
  576:                 #if not (x in ret):
  577:                     ret.append(x)
  578: 
  579:         ret.sort(sort)
  580:         return ret
  581: 
  582:     def changeMPIWGRootForm(self):
  583:         """edit"""
  584:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeMPIWGRootForm')).__of__(self)
  585:         return pt()
  586: 
  587:     def changeMPIWGRoot(self,title,disciplineList,themesList,connection_id,lang=None,RESPONSE=None):
  588:         """change"""
  589:         self.title=title
  590:         self.connection_id=connection_id
  591:         self.disciplineList=disciplineList
  592:         self.themesList=themesList
  593:         if lang is not None:
  594:             self.lang = lang
  595: 
  596:         if RESPONSE is not None:
  597:             RESPONSE.redirect('manage_main')
  598: 
  599: 
  600:     def getContexts(self,childs=None,parents=None,depth=None,date=None,onlyActive=True):
  601:         """childs alle childs, alle parents"""
  602:         ret=[]
  603:         
  604:         if parents:
  605:             pnums=parents.split(".")
  606:             while len(pnums) > 1:
  607:                 pnums.pop()
  608:                 parentId=string.join(pnums,".")
  609:         
  610:                 for project in self.getProjectFields('xdata_05',sort='int',date=date):
  611:                     if project[1]==parentId:
  612:                         ret.append(project)
  613:                 
  614:                 if (depth is not None) and (len(ret) >= depth):
  615:                     break
  616: 
  617:         if childs:
  618:             for project in self.getProjectFields('xdata_05',sort='int',date=date):
  619:                 searchStr=childs+"(\..*)"
  620:                
  621:                 if (onlyActive and project[0].isActiveProject()) or (not onlyActive):
  622:                     if re.match(searchStr,project[1]):
  623:                         
  624:                         if depth:
  625:     
  626:                             if int(depth)>=len(project[1].split("."))-len(childs.split(".")):
  627:                         
  628:                                 ret.append(project)
  629:                         else:
  630:                             ret.append(project)
  631:         
  632:         #logging.debug("getContexts: childs=%s parents=%s depth=%s => %s"%(childs,parents,depth,repr(ret)))
  633:         return ret
  634: 
  635:     
  636:     def getProjectFields(self,fieldName,date=None,folder=None,sort=None):
  637:         """getListofFieldNames"""
  638:         ret=[]
  639:     
  640:         objects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'],search_sub=0)
  641: 
  642:                 
  643:         for object in objects:
  644:             obj=object[1]
  645:             obj=obj.getActualVersion(date)
  646:             if obj and (not getattr(obj,'invisible',None)):
  647:                 if fieldName=="WEB_title_or_short":
  648: 
  649:                     if len(obj.getContent('xdata_07'))<3: # hack weil z.Z. manchmal noch ein Trennzeichen ; oder , im Feld statt leer
  650:                         fieldNameTmp="WEB_title"
  651:                     else:
  652:                         fieldNameTmp="xdata_07"
  653:                 else:
  654:                     fieldNameTmp=fieldName
  655: 
  656:                 ret.append((obj,obj.getContent(fieldNameTmp)))
  657: 
  658:         
  659:         if sort=="int":
  660:             ret.sort(sortI)
  661:         elif sort=="stopWords":
  662:  
  663:             ret.sort(sortStopWords(self))
  664:             
  665:         else:
  666:             ret.sort(sortF)
  667:         
  668:         return ret
  669: 
  670:     def showNewProjects(self):
  671:         projects=[]
  672:         for objs in self.getProjectFields('WEB_title_or_short'): # Get all Projets
  673:             if objs[0].xdata_05 and (objs[0].xdata_05[0] == ""):
  674:                 
  675:                 projects.append(objs)
  676:                 
  677:         return projects
  678:     
  679:         
  680:     manage_options = Folder.manage_options+(
  681:         {'label':'Update personal homepages','action':'updatePersonalwww_html'},
  682:         {'label':'Reindex catalogs','action':'reindexCatalogs'},
  683:         {'label':'Main config','action':'changeMPIWGRootForm'},
  684:         {'label':'add e-mails','action':'showNewDBEntries'},
  685:         {'label':'update the institutsbibliography','action':'updateInstitutsbiliography'},
  686:         #{'label':'Edit Historical Persons','action':'editHistoricalPersonsForm'},
  687:         #{'label':'Store Historical Persons','action':'storeHistoricalPersons'},
  688:         )
  689:     
  690: 
  691:     def updatePublicationDB(self,personId=None):
  692:         """updates the publication db, i.e. copy year and type into the main table"""
  693:         
  694:         if personId:
  695:             founds = self.ZSQLInlineSearch(_table="publications",key_main=personId)
  696:         else:
  697:             founds = self.ZSQLInlineSearch(_table="publications")
  698:             
  699:         for found in founds:
  700:                         
  701:             if found.id_institutsbibliographie and (not found.id_institutsbibliographie =="") and (not found.id_institutsbibliographie =="0"):
  702:                 
  703:                 entries = self.ZSQLInlineSearch(_table="institutsbiblio",id=found.id_institutsbibliographie)
  704:                 for entry in entries:
  705:                     self.ZSQLChange(_table='publications',_identify='oid=%s' % found.oid,year=entry.year,referencetype=entry.reference_type)
  706:                     
  707:             if found.id_gen_bib and (not found.id_gen_bib ==""):
  708:                 entries = self.ZSQLInlineSearch(_table="bibliography",id=found.id_gen_bib)
  709:                 for entry in entries:
  710:                     self.ZSQLChange(_table='publications',_identify='oid=%s' % found.oid,year=entry.year,referencetype=entry.reference_type)
  711:                     
  712:         return True        
  713:     
  714:     def showNewDBEntries(self):
  715:         """zeige neue Eintraege in der Datenbank ohne e-mail adressen bzw. fuer die noch kein Object angelegt wurde"""
  716:         
  717:         qstr="select * from personal_www where web_object_created='no' and not key=''"
  718:         res=self.ZSQLQuery(qstr)
  719:         
  720:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','showNewDBEntries.zpt')).__of__(self)
  721:         return pt(newEntries=res)
  722:    
  723:     def createNewStaffObjects(self,RESPONSE):
  724:         """create new staff object"""
  725:         
  726:         memberFolder=getattr(self,'members')
  727:         args=self.REQUEST.form
  728:         arg_k=args.keys()
  729:         arg_k.remove("submit")
  730:         ret=""
  731:         for key in arg_k:
  732:             k=self.urlUnQuote(key)
  733:           
  734:             qstr="select * from personal_www where key=%s"%self.ZSQLQuote(k)
  735:             res=self.ZSQLQuery(qstr)[0]
  736:             if args[key]!="": #email-adresse wurde eingetragen
  737:                 #create the object
  738:                 e_mail=args[key]
  739:                 try:
  740:                     newObj=MPIWGStaff.MPIWGStaff(e_mail,res.last_name,res.first_name,k)
  741:                     memberFolder._setObject(e_mail,newObj)
  742:                     obj=getattr(memberFolder,e_mail)
  743:                     obj.reindex_object()
  744:                     ret+="Created %s \n"%e_mail
  745:                     created=True
  746:                 except:
  747:                     msg="Cannot create new user %s (%s %s)"%(e_mail,sys.exc_info()[0],sys.exc_info()[1])
  748:                     logging.error(msg)
  749:                     ret+=msg+"\n"
  750:                     created=False
  751:                 
  752:                 if created:
  753:                     qstr="update personal_www set web_object_created='yes',e_mail='%s@mpiwg-berlin.mpg.de' where key=%s"%(e_mail,self.ZSQLQuote(k))
  754:                     self.ZSQLQuery(qstr)
  755:         
  756:         return ret
  757:                    
  758:         
  759:     def generateNewPersonEntry(self,data):
  760:         """generate a new person entry for data, neue personen werden zunaechst nur in der datenbank angelegt """
  761:         
  762:         #memberFolder=getattr(self,'members')
  763:         #create the object
  764:         
  765: #        try:
  766: #            newObj=MPIWGStaff.MPIWGStaff(urllib.quote(data['key']),data['last_name'].encode('utf-8'),data['first_name'].encode('utf-8')) 
  767: #            memberFolder._setObject(urllib.quote(data['key']),newObj)
  768: #        except:
  769: #            return False, "Cannot create new user %s (%s %s)"%(data['key'],sys.exc_info()[0],sys.exc_info()[1])
  770: #        
  771:         
  772:         #create the new entry in the database
  773:         
  774:         
  775:         result,msg=MPIWGStaff.createNewDBEntry(self,data['publish_the_data'],data['key'],data['last_name'],
  776:                                   data['first_name'],data['title'],data['status'],"",
  777:                                   "",data['date_from'],data['date_to'],
  778:                                   data['department'],data['home_inst'],data['funded_by'],
  779:                                   data['e_mail2'],data['current_work'],"yes",data['date_stay_at_mpiwg'],data['group'],"no",data['current_work'])
  780:         
  781:         return result,msg
  782:  
  783:     def updatePersonEntry(self,data,ignoreEntries=[]):
  784:         """update an person entry from data. but ignore all fields in ignore Entries"""
  785:         
  786:         ignoreEntries.append('current_work') # TODO:updatecurrent work
  787:         
  788:         if data['date_to']=="": # wenn date_to leer
  789:              data['date_to']="date_none"
  790:         
  791:         if data['date_from']=="": # wenn date_fromleer
  792:              data['date_from']="date_none"
  793:         msg=""
  794:    
  795:         
  796:         #eintragen
  797:          
  798:         columns=data.keys()
  799:         for x in ignoreEntries:
  800:             logging.info("ign rem: %s"%x)
  801:             try: #falls in ignore entries felder sind, die nicht in columns sind, fange den fehler ab
  802:              columns.remove(x)
  803:             except:
  804:                 pass
  805: 
  806:         
  807:         insert=[]
  808:         for key in columns:
  809:             if data[key]=="date_none": # date_none eintrag wird zu null uebersetzt
  810:                 insert.append('%s=null'%key)
  811:             else:
  812:                 insert.append(""" "%s"=%s"""%(key,self.ZSQLQuote(data[key])))
  813:             
  814:         insertStr=",".join(insert)
  815:         queryStr="update personal_www SET %s where key='%s'"%(insertStr,data['key'])
  816:         self.ZSQLQuery("SET DATESTYLE TO 'German'")
  817:         self.ZSQLQuery(queryStr)
  818:        
  819:         #currentwork
  820:         #if not (txt==""):
  821:         #    queryStr="INSERT INTO current_work (id_main,current,publish) VALUES ('%s','%s','%s')"%(id,txt,txt_p)
  822:         #
  823:         #    self.ZSQLQuery(queryStr)
  824:         
  825:         return True,msg
  826: 
  827: 
  828:     def updatePersonalwww_doIt(self):
  829:         """do the update"""
  830:         args=self.REQUEST.form
  831:         resultSet=self.REQUEST.SESSION['personal_www']['resultSet']
  832:         news=self.REQUEST.SESSION['personal_www']['news']
  833:         conflicts=self.REQUEST.SESSION['personal_www']['conflicts']
  834:         ret="<html><body>"
  835:         # generate the new entry
  836:       
  837:         if news and (len(news)>0):
  838:             ret+="<h2>Hinzugef&uuml;gt</h2>"
  839:             ret+="<p>Neueintr&auml;ge erscheinen erst auf der Homepage, wenn ihnen eine e-mail Adresse zugeordnet wurde.</p>"
  840:             ret+="<ul>"
  841:         for new in news:
  842:       
  843:             if args.has_key(self.urlQuote(new.encode('utf-8'))): # entry was selected
  844:                 result,msg=self.generateNewPersonEntry(resultSet[new])
  845:                 if not result:
  846:                     logging.error("Error (generateNewPersonEntry) %s"%msg)
  847:                     ret+="<li>ERROR: %s %s"%(new.encode('utf-8'),msg)
  848:                 else:
  849:                     ret+="<li>OK: %s"%(new.encode('utf-8'))
  850:         if news and (len(news)>0):
  851:             ret+="<p>Neueintr&auml;ge erscheinen erst auf der Homepage, wenn ihnen eine e-mail Adresse zugeordnet wurde.</p>"
  852:             ret+="</ul>"     
  853:         
  854:         # update
  855: 
  856:         if len(conflicts.keys())>0:
  857:             ret+="<h2>&Auml;nderung des Benutzers &uuml;bernehmen</h2>"
  858:             ret+="<p>Wenn n&ouml;tig in Filemaker-db &auml;ndern:</p>"
  859:             
  860:         # konflicte   
  861:         for conflict in conflicts.keys():
  862:             ignoreEntries=[]
  863:             displayIgnored=[]
  864:             for cf in conflicts[conflict]:
  865:                 if args[conflict.encode('utf-8')+'_'+cf[0]]=="stored": #use the stored one
  866:                     ignoreEntries.append(cf[0])  #so ignore field cf[0]       
  867:                     displayIgnored.append(cf)
  868:             if len(displayIgnored)>0:
  869:                 ret+="<h3>%s</h3>"%conflict.encode('utf-8')
  870:                 
  871:                 ret+="<table border='1'>"
  872:                 for iE in displayIgnored:
  873:                     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'))
  874:                 ret+="</tabel>"
  875:                 
  876:             self.updatePersonEntry(resultSet[conflict],ignoreEntries=ignoreEntries)
  877:          
  878:          # rest
  879:         cl=list(conflicts.keys())
  880:         
  881:         for key in resultSet.keys():
  882:              if key not in cl:
  883:                  self.updatePersonEntry(resultSet[key])
  884:         return ret+"</body></html>"
  885:                      
  886: 
  887:     def updateInstitutsbiliography(self):
  888:         """update the Institutsbibliogrpahy"""
  889:         self.upDateSQL('personalwww.xml')
  890:         return "<html><body>DONE</body></html>"
  891: 
  892: 
  893:     
  894: 
  895:     def updatePersonalwww_html(self):
  896:         """update form for the homepages web form"""
  897:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','updatePersonalwww.zpt')).__of__(self)
  898:         return pt()
  899: 
  900:     
  901:     def updatePersonalwww(self,uploadfile):
  902:         """update personalwww
  903:         @param uploadfile: file handle auf das file
  904:         """
  905:         dsn=self.getConnectionObj().connection_string
  906:         #dsn="dbname=personalwww"
  907:         resultSet=updatePersonalWWW.importFMPXML(uploadfile)
  908:         news,conflicts=updatePersonalWWW.checkImport(dsn, resultSet)
  909: 
  910:         self.REQUEST.SESSION['personal_www']={}
  911:         self.REQUEST.SESSION['personal_www']['resultSet']=resultSet
  912:         self.REQUEST.SESSION['personal_www']['news']=news
  913:         self.REQUEST.SESSION['personal_www']['conflicts']=conflicts
  914:         
  915:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','updatePersonalwww_check.zpt')).__of__(self)
  916:         return pt()
  917:     
  918: 
  919:      
  920:     def reindexCatalogs(self,RESPONSE=None):
  921:         """reindex members and project catalog"""
  922:         
  923:         
  924:         try:
  925:             
  926:             self.ProjectCatalog.manage_catalogReindex(self.REQUEST,RESPONSE,self.REQUEST['URL1'])
  927:         except:
  928:             logger("MPIWG Root (updatehomepage)",logging.WARNING," %s %s"%sys.exc_info()[:2])
  929:             
  930:         
  931:     
  932:         
  933:            
  934:         if RESPONSE:
  935:             RESPONSE.redirect('manage_main')
  936: 
  937:         
  938:         
  939: 
  940:     def getAllMembers(self):
  941:         #ret=[]
  942:         
  943:         def sorter(x,y):
  944:             return cmp(x[0],y[0])
  945:                     
  946:         results=self.MembersCatalog({'isPublished':True})
  947:        
  948:         ret=[(", ".join([proj.lastName, proj.firstName]).decode('utf-8'),proj.getKey) for proj in results]
  949:         
  950:         ret.sort(sorter)
  951:         return ret
  952:     
  953:     
  954:     def printAllMembers(self):
  955:         """print"""
  956:         members=self.getAllMembers()
  957:         ret=""
  958:         for x in members:
  959:             ret+="<p>%s</p>"%x
  960:         return ret
  961:     
  962:         
  963:     def makeList(self,entry):
  964:         """makes a list out of one entry or repeat a list"""
  965:         if type(entry) is StringType:
  966:             return [entry]
  967:         else:
  968:             return entry
  969: 
  970:     def getTreeRSS(self,dep=None,date=None,onlyActive=1,onlyArchived=0):
  971:         """generateTree"""
  972:         rss="""<?xml version="1.0" encoding="utf-8"?>
  973:                  <rss version="2.0">
  974:                    <channel>"""
  975:         
  976:         for obj in self.getTree(dep, date, onlyActive, onlyArchived):
  977:             linkStr="""<link>http://www.mpiwg-berlin.mpg.de/en/research/projects/%s</link>"""
  978:             rss+="""<item>"""
  979:             rss+=linkStr%obj[3].getId()
  980:             rss+="""</item>"""
  981:             if hasattr(obj[3],'publicationList'):
  982: 	        rss+="""<item>"""
  983:                 rss+=linkStr%(obj[3].getId()+"/publicationList");
  984:                 rss+="""</item>"""
  985:         rss+="""</channel>
  986:         </rss>"""
  987: 
  988:         
  989:         return rss
  990: 
  991:     def getTree(self,dep=None,date=None,onlyActive=0,onlyArchived=0):
  992:         """generate Tree from project list
  993:         als Liste, jeder Eintrag ist ein Tupel ,(Tiefe, ProjektNummer,ProjektObject
  994:         onlyActive = 0  : alle Projekte
  995:         onlyActive = 1 : nur active Projekte
  996:         onlyActive = 2: nur inactive Projekte
  997:         
  998:         onlyArchived=0: alle Projekte
  999:         onlyArchived= 1 : nur aktuelle Projekte
 1000:         onlyArchived = 2: nur archivierte Projekte
 1001:         """
 1002: 
 1003:         returnListTmp=[]
 1004:         returnList=[]
 1005:         
 1006:         for project in self.getProjectFields('xdata_05',sort="int",date=date): # get Projects sorted by xdata_05
 1007: 
 1008:             for idNr in project[1].split(";"): # more than one number
 1009:                 if not idNr=="":
 1010:                     splittedId=idNr.split(".")
 1011:                     depth=len(splittedId)
 1012:                     nr=idNr
 1013:                     #title=project[0].WEB_title
 1014:                     title=[project[0].getContent('WEB_title')]
 1015:                     #print title
 1016:                     
 1017:                     if idNr[0]=="x": # kompatibilitaet mit alter Konvention, x vor der Nummer macht project inactive
 1018:                         project[0].setActiveFlag(False)
 1019:                    
 1020:                     if (not dep) or (idNr[0]==dep): #falls dep gesetzt ist nur dieses hinzufuegen.
 1021:                         
 1022:                         if (onlyActive==0):
 1023:                             returnListTmp.append((depth,nr,title,project[0]))
 1024:                         elif (onlyActive==1) and project[0].isActiveProject(): #nur active projekte
 1025:                             returnListTmp.append((depth,nr,title,project[0]))
 1026:                         elif (onlyActive==2) and (not project[0].isActiveProject()): #nur active projekte
 1027:                             returnListTmp.append((depth,nr,title,project[0]))
 1028:                    
 1029:                    
 1030:         #filter jetzt die Liste nach Archived oder nicht
 1031:         for entry in returnListTmp:
 1032:                     if (onlyArchived==0):
 1033:                             returnList.append(entry)
 1034:                     elif (onlyArchived==1) and (not entry[3].isArchivedProject()): #nur active projekte
 1035:                             returnList.append(entry)
 1036:                     elif (onlyArchived==2) and (entry[3].isArchivedProject()): #nur active projekte
 1037:                             returnList.append(entry)
 1038:                    
 1039:         
 1040:         return returnList
 1041: 
 1042: 
 1043:         
 1044:     def changePosition(self,treeId,select,RESPONSE=None):
 1045:         """Change Postion Entry"""
 1046:         numbers=[]
 1047: 
 1048:         # Suche hoechste bisherige nummer
 1049:         projects=self.getProjectFields('xdata_05') # get Projects sorted by xdata_05
 1050:         #print "pj",projects
 1051:         for project in projects: #suche alle subtrees der treeId
 1052:             #print treeId
 1053:             
 1054:             founds=re.match(treeId+"\.(.*)",project[1].split(";")[0])
 1055:             if founds:
 1056:                 #print "x",founds.group(0),len(founds.group(0).split("."))
 1057:                 if len(founds.group(0).split("."))==len(treeId.split("."))+1: # nur ein punkt mehr, d.h. untere ebene
 1058:                     try:
 1059:                         numbers.append(int(founds.group(0).split(".")[len(founds.group(0).split("."))-1]))
 1060:                     except:
 1061:                         numbers.append(int(0))
 1062: 
 1063:         try:
 1064:             highest=max(numbers)
 1065:         except:
 1066:             highest=0
 1067:         projects=self.showNewProjects()
 1068:         for i in self.makeList(select):
 1069:             highest+=10
 1070:             projects[int(i)][0].xdata_05=treeId+"."+str(highest)
 1071: 
 1072: 
 1073:         if RESPONSE is not None:
 1074:             RESPONSE.redirect('showTree')
 1075:         
 1076:     def changeTree(self,RESPONSE=None):
 1077:         """change the complete tree"""
 1078:         form=self.REQUEST.form
 1079:         hashList={}
 1080:         onlyArchived=int(form.get("onlyArchived",0))
 1081:         onlyActive=int(form.get("onlyActive",0))
 1082:         
 1083:         
 1084:         fields=self.getTree(onlyArchived=onlyArchived,onlyActive=onlyActive)
 1085:         
 1086:         logging.info("GOT TREE!----------------------------------------------------")
 1087:         for field in form.keys():
 1088:             
 1089:             splitted=field.split('_')
 1090:             if (len(splitted)>1) and (splitted[1]=="runningNumber"): #feld hat die Form Nummer_name und runnignNumber
 1091:             
 1092:                 
 1093:                 nr=int(splitted[0]) # nummer des Datensatzes
 1094:                 currentEntry = fields[nr]
 1095:             
 1096:                 if form.has_key(str(nr)+'_active'): # active flag is set
 1097:                     fields[nr][3].setActiveFlag(True)
 1098:                 else:
 1099:                     fields[nr][3].setActiveFlag(False)
 1100:                     
 1101:                 #nummer hat sich geŠndert
 1102:                 
 1103:                 entryChanged = False;
 1104:                 
 1105:                 
 1106:                 if not (fields[nr][3].xdata_05==form[str(nr)+'_number']):
 1107:                     logging.info("Changed!Number+++++++++++++++++++++++++++++++++")
 1108:                     fields[nr][3].xdata_05=form[str(nr)+'_number']
 1109:                     entryChanged = True
 1110:                     
 1111:                 #completed har sich geaendert
 1112:                             
 1113:                 if not (fields[nr][3].getCompletedAt()==fields[nr][3].transformDate(form[str(nr)+'_completed'])):
 1114:                     fields[nr][3].setCompletedAt(form[str(nr)+'_completed'])
 1115:                     logging.info("Changed!Completed+++++++++++++++++++++++++++++++++")
 1116:                     entryChanged = True
 1117:                 
 1118:                 if not (fields[nr][3].getStartedAt()==fields[nr][3].transformDate(form[str(nr)+'_started'])):
 1119:                     fields[nr][3].setStartedAt(form[str(nr)+'_started'])
 1120:                     logging.info("Changed!Started+++++++++++++++++++++++++++++++++")
 1121:                     entryChanged = True
 1122:                 
 1123:                 
 1124:                 if entryChanged:
 1125:                     logging.info("Changed!+++++++++++++++++++++++++++++++++")
 1126:                     fields[nr][3].copyObjectToArchive()
 1127:                 
 1128:                     
 1129:         if RESPONSE is not None:
 1130:             RESPONSE.redirect('showTree')
 1131: 
 1132:     def getProjectWithId(self,id):
 1133:         fields=self.getProjectFields('xdata_05')
 1134:         for field in fields:
 1135:             if field[1]==id:
 1136:                 return field[0]
 1137: 
 1138:         return None
 1139:             
 1140:         
 1141:             
 1142:         
 1143:     def getRelativeUrlFromPerson(self,list):
 1144:         """get urls to person list"""
 1145:         ret=[]
 1146:         persons=list.split(";")
 1147:         for person in persons:
 1148:             
 1149:             if len(person)>1: #nicht nur Trennzeichen
 1150:                 splitted=person.split(",")
 1151:                 if len(splitted)==1:
 1152:                     splitted=person.split(" ")
 1153:                 splittedNew=[re.sub(r'\s(.*)','$1',split) for split in splitted]
 1154:                 if splittedNew[0]=='':
 1155:                     del splittedNew[0]
 1156:                 search=string.join(splittedNew,' AND ')
 1157:                 
 1158:                 if not search=='':
 1159: 
 1160:                     try:
 1161:                         proj=self.MembersCatalog({'title':search})
 1162:                     except:
 1163:                         proj=None
 1164: 
 1165:                 if proj:
 1166:                     #ret.append("<a href=%s >%s</a>"%(proj[0].absolute_url,person.encode('utf-8')))
 1167:                     ret.append("<a href=%s >%s</a>"%('members/'+proj[0].id+'/index.html',person))
 1168:                 else:
 1169:                     #ret.append("%s"%person.encode('utf-8'))
 1170:                     ret.append("%s"%person)
 1171:         return string.join(ret,";")
 1172:         
 1173:     def getMemberIdFromKey(self,key):
 1174:         """gibt die ensprechende id  im members Ordner zum key"""
 1175:         
 1176:         if key=="":
 1177:             return ""
 1178:         try:
 1179:             key=utf8ify(key)
 1180:             catalogged=self.MembersCatalog({'getKey':key})
 1181:             if len(catalogged)==0:
 1182:                 return ""
 1183:             else:
 1184:                 return catalogged[0].getObject().getId()
 1185:         
 1186:         except:
 1187:             return ""
 1188: 
 1189:             
 1190: 
 1191:     def getProjectsOfMembers(self,date=None):
 1192:         """give tuple member /projects"""
 1193:         ret=[]
 1194:         members=self.getAllMembers()
 1195:         logging.error("X %s"%repr(members))
 1196:         #return str(members)
 1197:         for x in members:
 1198:             logging.error("X %s"%repr(x))
 1199:             projects=self.getProjectsOfMember(key=x[1],date=date)
 1200:             if len(projects)>0:
 1201:                 ret.append((x[0],projects))
 1202:             
 1203:         return ret
 1204: 
 1205:     def getProjectsOfMember(self,key=None,date=None,onlyArchived=1,onlyActive=1):
 1206:         """get projects of a member
 1207:     
 1208:         @param key: (optional) Key zur Idenfikation des Benutzer
 1209:         @param date: (optional) Version die zum Zeitpunkt date gueltig war
 1210:         @param onlyArchived: 
 1211:         onlyArchived=0: alle Projekte
 1212:         onlyArchived= 1 : nur aktuelle Projekte
 1213:         onlyArchived = 2: nur archivierte Projekte
 1214:         """
 1215:         # TODO: Die ganze Loesung
 1216:         def sortP(x,y):
 1217:             """sort by sorting number"""
 1218:             return cmp(x.WEB_title,y.WEB_title)
 1219:         
 1220:         ret=[]  
 1221:         if key:     
 1222:             proj=self.ProjectCatalog({'getPersonKeyList':utf8ify(key)})
 1223:         else:
 1224:             return ret # key muss definiert sein
 1225:         
 1226:      
 1227:         if proj:
 1228:             proj2=[]
 1229:             for x in proj:
 1230:                 #logging.error("proj:%s"%repr(x.getPath()))
 1231:                 if (not getattr(x.getObject(),'invisible',None)) and (getattr(x.getObject(),'archiveTime','')==''):   
 1232:                       proj2.append(x)
 1233: 
 1234:         else:
 1235:             proj2=[]
 1236:             
 1237:        
 1238:        
 1239:         proj2.sort(sortP)
 1240: 
 1241:         projectListe=[]
 1242:         #logging.error("getprojectsofmember proj2: %s"%repr(proj2))
 1243:         for proj in proj2:   
 1244:             obj=proj.getObject()
 1245:             add=False
 1246:             if onlyArchived==1: #nur aktuell projecte
 1247:                 if not obj.isArchivedProject():
 1248:                     add=True
 1249:             elif onlyArchived==2: #nur archivierte
 1250:                 if obj.isArchivedProject():
 1251:                     add=True
 1252:             else: #alle
 1253:                add=True 
 1254:                
 1255:             if onlyActive==1: #nur active projecte
 1256:                 if obj.isActiveProject():
 1257:                     add=add & True
 1258:                 else:
 1259:                     add=add & False
 1260:                 
 1261:             elif onlyArchived==2: #nur nicht aktvive
 1262:                 if not obj.isActiveProject():
 1263:                     add=add & True
 1264:             else: #alle
 1265:                add=add & True
 1266:                     
 1267:             if add:
 1268:                 projectListe.append(obj)
 1269:                 
 1270:         #logging.error("getprojectsofmember projectliste: %s"%repr(projectListe))
 1271:         return projectListe
 1272:      
 1273:     def givePersonList(self,name):
 1274:         """check if person is in personfolder and return list of person objects"""
 1275:         
 1276:         splitted=name.split(",")
 1277:         if len(splitted)==1:
 1278:             splitted=name.lstrip().rstrip().split(" ")
 1279:         splittedNew=[split.lstrip() for split in splitted]
 1280:         
 1281:         if splittedNew[0]=='':
 1282:             del splittedNew[0]
 1283:         search=string.join(splittedNew,' AND ')
 1284:         
 1285:         if not search=='':
 1286:             proj=self.MembersCatalog({'title':search})
 1287: 
 1288:         if proj:
 1289:             return [[x.lastName,x.firstName] for x in proj]
 1290:         else:
 1291:             return []
 1292:             
 1293: ##         splitted=name.split(",") # version nachname, vorname...
 1294: ##         if len(splitted)>1:
 1295: ##             lastName=splitted[0] 
 1296: ##             firstName=splitted[1]
 1297: ##         else: 
 1298: ##             splitted=name.split(" ") #version vorname irgenwas nachnamae
 1299:         
 1300: ##             lastName=splitted[len(splitted)-1]
 1301: ##             firstName=string.join(splitted[0:len(splitted)-1])
 1302: 
 1303: ##         objs=[]
 1304: 
 1305:         #print  self.members 
 1306:       ##   for x in self.members.__dict__:
 1307: ##             obj=getattr(self.members,x)
 1308: ##             if hasattr(obj,'lastName') and hasattr(obj,'firstName'):
 1309:                 
 1310: ##                 if (re.match(".*"+obj.lastName+".*",lastName) or re.match(".*"+lastName+".*",obj.lastName)) and (re.match(".*"+obj.firstName+".*",firstName) or re.match(".*"+firstName+".*",obj.firstName)):
 1311:                     
 1312: ##                     objs.append((obj,lastName+", "+firstName))
 1313: 
 1314:         
 1315: ##        return objs
 1316: 
 1317: 
 1318:     def personCheck(self,names):
 1319:         """all persons for list"""
 1320:         #print "names",names
 1321:         splitted=names.split(";")
 1322:         ret={}
 1323:         for name in splitted:
 1324: 
 1325:             if not (name==""):
 1326:                 try:
 1327:                     ret[name]=self.givePersonList(name)
 1328:                 except:
 1329:                     """NOTHIHN"""
 1330:         #print "RET",ret
 1331:         return ret
 1332: 
 1333:     def giveCheckList(self,person,fieldname):
 1334:         """return checklist"""
 1335:         #print "GCL",fieldname
 1336:         if fieldname=='xdata_01':
 1337:             x=self.personCheck(person.getContent(fieldname))
 1338:             #print "GCLBACKX",x
 1339:             return x
 1340:         
 1341: 
 1342:     def isCheckField(self,fieldname):
 1343:         """return chechfield"""
 1344:         
 1345:         return (fieldname in checkFields)
 1346: 
 1347:     
 1348:     def generateNameIndex(self):
 1349:         """erzeuge einen index verwendeter personen"""
 1350:         import psycopg
 1351:         o = psycopg.connect('dbname=authorities user=dwinter password=3333',serialize=0) 
 1352:         results={}
 1353:         print self.fulltext.historicalNames.items()
 1354:         for nameItem in self.fulltext.historicalNames.items(): #gehe durch alle namen des lexikons
 1355:             
 1356:             c = o.cursor() 
 1357:             name=nameItem[0]
 1358:             print "check",name
 1359:             c.execute("select lastname,firstname from persons where lower(lastname) = '%s'"%quote(name))
 1360:             tmpres=c.fetchall()
 1361:             firstnames=[result[1] for result in tmpres] # find all firstnames
 1362:             if tmpres:
 1363:                 lastname=tmpres[0][0]
 1364:                 
 1365:             for found in self.fulltext({'names':name}):
 1366:                 if found.getObject().isActual():
 1367:                     for nh in found.getObject().getGetNeighbourhood(name, length=50,tagging=False): #hole umgebung
 1368:                         #schaue nun ob der vorname hinter oder vor dem name ist
 1369:                         position=nh.find(lastname)
 1370:                         # vorher
 1371:                         #print "NH",nh
 1372:                         bevorS=nh[0:position].split()
 1373:                         #print "BV",bevorS
 1374:                         if len(bevorS)>1:
 1375:                             try:
 1376:                                 bevor=[bevorS[-1],bevorS[-2]]
 1377:                             except:
 1378:                                 bevor=[bevorS[0]]
 1379:                         else:
 1380:                             bevor=[]
 1381:                         #nachher
 1382:                         behindS= re.split("[,|;| ]",nh[position:]) 
 1383:                         #print "BH",behindS
 1384:                         if len(behindS)>2:
 1385:                             try:
 1386:                                 behind=behindS[1:3]
 1387:                             except:
 1388:                                 behind=[bevorS[1]]
 1389:                         else:
 1390:                             behind=[]
 1391:                         for firstname in firstnames:
 1392:                             if firstname in bevor+behind: #Namen wie mit Adelspraedikaten werden so erstmal nich gefunden
 1393:                                 id="%s,%s"%(lastname,firstname)
 1394:                                 if not results.has_key(id):
 1395:                                     results[id]=[]
 1396:                                 objId=found.getObject().getId()
 1397:                                 if not (objId in results[id]):
 1398:                                     print "d %s for %s"%(id,objId)    
 1399:                                     results[id].append(objId)    
 1400:             self.nameIndex=results
 1401:         return results
 1402:                     
 1403:     def editNameIndexHTML(self):
 1404:         """edit the name index"""
 1405:         if not hasattr(self,'nameIndexEdited'): # falls editierter index noch nicht existiert, kopiere automatisch erstellten
 1406:             self.nameIndexEdited=copy.copy(self.nameIndex)
 1407:             print "huh"
 1408:         #self.nameIndexEdited=copy.copy(self.nameIndex)
 1409:         #print self.nameIndexEdited
 1410:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','editHistoricalNames.zpt')).__of__(self)
 1411:         return pt()
 1412:     
 1413:     def getNamesInProject(self,projectId):
 1414:         """get all names ofnameIndexEdited which are references in projec with projectId"""
 1415:         
 1416:         ret=[]
 1417:         for name in self.nameIndexEdited.keys():
 1418:             if projectId in self.nameIndexEdited[name]:
 1419:                 ret.append(name)
 1420:         
 1421:         return ret
 1422:     
 1423:     def editNameIndex(self,RESPONSE=None,name=None,occurrances=None,submit=None):
 1424:         """edit the index"""
 1425:         nI=self.nameIndexEdited # mI introduced to make sure that changes to nameIndexEdited are know to ZODB
 1426:         if submit=="delete":
 1427:            
 1428: 
 1429:             dh=getattr(self,'deletedHistoricalNames',{})
 1430:             
 1431:             if type(dh) is ListType:
 1432:                 dh={}
 1433:             if not dh.has_key(name):
 1434:                 dh[name]=occurrances.split("\n")
 1435:             else:
 1436:                 dh[name]+=occurrances.split("\n")
 1437:             
 1438:             self.deletedHistoricalNames=dh
 1439:             
 1440:             del self.nameIndexEdited[name]
 1441:             
 1442:         
 1443:         elif (submit=="change"):
 1444:             
 1445:             nI[name]=occurrances.split("\n")[0:]
 1446:             
 1447:         elif (submit=="add"):
 1448:             if not nI.has_key(name):
 1449:                 nI[name]=occurrances.split("\n")
 1450:             else:
 1451:                 nI[name]+=occurrances.split("\n")
 1452:     
 1453:         self.nameIndexEdited=nI
 1454:    
 1455:       
 1456:         if RESPONSE is not None:
 1457:             RESPONSE.redirect('editNameIndexHTML')
 1458:         
 1459:     
 1460:     
 1461:     def restoreIndex(self):
 1462:         """restore"""
 1463:         self.nameIndexEdited=self.nameIndex
 1464:         return "done"
 1465:     
 1466: 
 1467:             
 1468: def manage_addMPIWGRootForm(self):
 1469:     """form for adding the root"""
 1470:     pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addMPIWGRootForm.zpt')).__of__(self)
 1471:     return pt()
 1472: 
 1473: def manage_addMPIWGRoot(self,id,title,connection_id="",RESPONSE=None):
 1474:     """add a root folder"""
 1475:     newObj=MPIWGRoot(id,title)
 1476:     self._setObject(id,newObj)
 1477:     ob=getattr(self,id)
 1478:     setattr(ob,'connection_id',connection_id)
 1479:     if RESPONSE is not None:
 1480:         RESPONSE.redirect('manage_main')
 1481:         

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