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

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