Annotation of MPIWGWeb/MPIWGRoot.py, revision 1.1.2.11

1.1.2.1   dwinter     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: 
1.1.2.6   casties    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: 
1.1.2.1   dwinter    40: class MPIWGRoot(ZSQLExtendFolder):
                     41:     """Stammordner fuer den Web-Server"""
                     42: 
1.1.2.6   casties    43:     fieldLabels={'WEB_title':'WEB_Title',
                     44:                  'xdata_01':'Responsible Scientists',
                     45:                  'xdata_02':'Department',
                     46:                  'xdata_03':'Historical Persons',
                     47:                  'xdata_04':'Time period',
                     48:                  'xdata_05':'Sorting number',
                     49:                  'xdata_06':'Keywords',
                     50:                  'xdata_07':'Short title',
                     51:                  'xdata_08':'Other involved scholars' ,
                     52:                  'xdata_09':'Disciplines',
                     53:                  'xdata_10':'Themes',
                     54:                  'xdata_11':'Object Digitallibrary',
                     55:                  'xdata_12':'Cooperation partners',
                     56:                  'xdata_13':'Funding institutions',
                     57:                  'WEB_project_header':'WEB_project_header',
                     58:                  'WEB_project_description':'WEB_project_description',
                     59:                  'WEB_related_pub':'WEB_related_pub'}
1.1.2.1   dwinter    60:     
                     61:     folders=['MPIWGProject','Folder','ECHO_Navigation']
                     62:     meta_type='MPIWGRoot'
                     63: 
1.1.2.11! dwinter    64:     def getGetNeighbourhood(self,obj, wordStr, length=100,tagging=True):
        !            65:         """finde umgebung um die worte in wordStr, zurueckgegeben wird eine Array mit den Umgebungen von Fundstellen der Worte
        !            66:         alle Tags werden entfernt, die Fundstellen werden mit <span class="found">XX</span> getaggt, die Umgebungen werden 
        !            67:         case insensitive gesucht
        !            68:         @param wordStr: string mit Worten getrennt durch Leerzeichen, Phrasen sind mit " gekennzeichnet
        !            69:                         "eine phrase", "*"  bezeichnet wildcards und wird ignoriert"
        !            70:         @param length: optional, default wert 100, 2*length ist die groesse der Umgebung
        !            71:         @param tagging: optional default wert true, kein span tag wird erzweugt falls tag=false
        !            72:         """
        !            73:         
        !            74:         ret=[] # nimmt das Array auf, dass spaeter zurueckgegeben wird
        !            75:         ranges=[] #Array mit tupeln x,y wobei x die Position des Anfang und y des Endes der i-ten Umgebung angiebt
        !            76:         
        !            77:         def isInRanges(nr,length):
        !            78:             """test ob eine gegeben Position nr schon irgendwo in einer Umgebung ist, gibt den Index des ersten Wertes aus ranges zurueck, 
        !            79:             -1, wenn kein Treffer
        !            80:             
        !            81:             @param nr: Position die geprueft werden soll
        !            82:             @param length: Laenge des Wortes das geprueft werden soll
        !            83:             """
        !            84:             for x in ranges:
        !            85:                 if (x[0]<=nr) and (nr < (x[1]-length)):
        !            86:                     return ranges.index(x)
        !            87:             return -1
        !            88:                 
        !            89:         # deal with phrases, in Phrasen werden die Leerzeichen durch "_" ersetzt.
        !            90:         def rep_empty(str):
        !            91:             x= re.sub(" ","_",str.group(0))
        !            92:             return re.sub("\"","",x)
        !            93:             
        !            94:         wordStr=re.sub("\".*?\"", rep_empty,wordStr)#ersetze leerzeichen in " " durch "_" und loesche "
        !            95:         
        !            96:         #deal with wildcards, for our purposes it is enough to delete the wildcard 
        !            97:         wordStr=wordStr.replace("*","")
        !            98:         
        !            99:         words=wordStr.split(" ")
        !           100:         #if not words is ListType:
        !           101:         #   words=[words]
        !           102:             
        !           103:         txt=obj.harvest_page()
        !           104:         if not txt:
        !           105:             return ret
        !           106:         txt=re.sub("<.*?>", "", txt) # loesche alle Tags
        !           107:         for word in words:
        !           108:             word=re.sub("_"," ",word) # ersetze zurueck "_" durch " "
        !           109:             pos=0
        !           110:             
        !           111:             n=txt.lower().count(word.lower()) # wie oft tritt das Wort auf
        !           112: 
        !           113:             for i in range(n):
        !           114:                 pos=txt.lower().find(word.lower(),pos)
        !           115: 
        !           116:                 if pos > 0:
        !           117:                     x=max(0,pos-length)
        !           118:                     y=min(len(txt),pos+length)
        !           119:                   
        !           120:                     
        !           121:                     #is word already in one of the results
        !           122:                     nr=isInRanges(pos,len(word))
        !           123:                     if nr >=0:# word ist in einer schon gefunden Umgebung, dann vergroessere diese
        !           124:                         x=min(ranges[nr][0],x)
        !           125:                         y=max(ranges[nr][1],y)
        !           126:               
        !           127:                     str=txt[x:y]
        !           128:                 
        !           129:                     if nr >=0: # word ist in einer schon gefunden Umgebung
        !           130:                         ranges[nr]=(x,y) # neue Position der Umgebung
        !           131: 
        !           132:                         ret[nr]=str # neue Umgebung
        !           133:                     else: # andernfalls neue Umgebung hinzufuegen
        !           134:                         ranges.append((x,y))
        !           135: 
        !           136:                         ret.append(str)
        !           137:                     
        !           138:                     pos=pos+len(word)
        !           139:                 else:
        !           140:                     break;
        !           141:                 
        !           142:         # now highlight everything        
        !           143:         if tagging:
        !           144:             for x in range(len(ret)):
        !           145:                 for word in words:
        !           146:                     repl=re.compile(word,re.IGNORECASE)
        !           147:                     ret[x]=repl.sub(""" <span class="found">%s</span>"""%word.upper(),ret[x])
        !           148: 
        !           149:         return ret
1.1.2.9   dwinter   150:     def copyAllImagesToMargin(self):
                    151:         """tranformiere alle Bilder in die Margins"""
                    152:         projects=self.getTree()
                    153:         ret=""
                    154:         for project in projects:
                    155:             proj=project[3]
                    156:             try:
                    157:                 persons=proj.copyImageToMargin();
                    158:             except:
                    159:                 logging.error("Cannnot do: %s"%repr(project))
                    160:                 
1.1.2.1   dwinter   161:     def transformProjectsToId(self):
                    162:         """trnasformiere zu ID, Hilfsfunktion die die alten Templates analysiert und mit der neuen Liste
                    163:         verantwortlicher Personen versieht"""
                    164:         projects=self.getTree()
                    165:         ret=""
                    166:         for project in projects:
1.1.2.11! dwinter   167:             
1.1.2.1   dwinter   168:             proj=project[3]
                    169:             persons=proj.identifyNames(proj.getContent('xdata_01'))
                    170:             if not hasattr(proj,'responsibleScientistsList'):
                    171:                         proj.responsibleScientistsList=[]
                    172:                         
                    173:             for person in persons.items():
1.1.2.2   dwinter   174:               
1.1.2.1   dwinter   175:                 if len(person[1]) >1: #nicht eindeutig
                    176:                     ret+="nicht eindeutig ---  %s:  %s\n"%(proj.getId(),person[0])
                    177:                     
                    178:                 elif len(person[1]) ==0: #kein eintrage
                    179:                     ret+="kein eintrag---  %s:  %s\n"%(proj.getId(),person[0])
                    180:                     proj.responsibleScientistsList.append((person[0],""))
                    181:                 else:           
                    182:                     proj.responsibleScientistsList.append((person[0],person[1][0].getObject().getKey()))
                    183:         
                    184:         return ret
1.1.2.9   dwinter   185:           
1.1.2.1   dwinter   186:                 
                    187:     def harvestProjects(self):
                    188:         """harvest"""
                    189:         folder="/tmp"
                    190:         try:
                    191:             os.mkdir("/tmp/harvest_MPIWG")
                    192:         except:
                    193:             pass
                    194:         founds=self.ZopeFind(self.aq_parent.projects,obj_metatypes=['MPIWGProject'],search_sub=1)
                    195:         for found in founds:
                    196:             txt=found[1].harvest_page()
                    197:         
                    198:             if txt and (txt != ""):
                    199:                 name=found[0].replace("/","_")
                    200:                 fh=file("/tmp/harvest_MPIWG/"+name,"w")
                    201:                 fh.write(txt)
                    202:                 fh.close()
                    203:                 
                    204:     def decode(self,str):
                    205:         """decoder"""
1.1.2.3   dwinter   206: 
1.1.2.1   dwinter   207:         if not str:
                    208:             return ""
                    209:         if type(str) is StringType:
                    210:             try:            
                    211:                 return str.decode('utf-8')
                    212:             except:
                    213:                 return str.decode('latin-1')
                    214:         else:
                    215:             return str
                    216: 
                    217: 
                    218:     def getat(self,array,idx=0,default=None):
                    219:         """return array element idx or default (but no exception)"""
                    220:         if len(array) <= idx:
                    221:             return default
                    222:         else:
                    223:             return array[idx]
                    224:         
                    225: 
                    226:     def browserCheck(self):
                    227:         """check the browsers request to find out the browser type"""
                    228:         bt = {}
                    229:         ua = self.REQUEST.get_header("HTTP_USER_AGENT")
                    230:         bt['ua'] = ua
                    231:         bt['isIE'] = False
                    232:         bt['isN4'] = False
                    233:         if string.find(ua, 'MSIE') > -1:
                    234:             bt['isIE'] = True
                    235:         else:
                    236:             bt['isN4'] = (string.find(ua, 'Mozilla/4.') > -1)
                    237: 
                    238:         try:
                    239:             nav = ua[string.find(ua, '('):]
                    240:             ie = string.split(nav, "; ")[1]
                    241:             if string.find(ie, "MSIE") > -1:
                    242:                 bt['versIE'] = string.split(ie, " ")[1]
                    243:         except: pass
                    244: 
                    245:         bt['isMac'] = string.find(ua, 'Macintosh') > -1
                    246:         bt['isWin'] = string.find(ua, 'Windows') > -1
                    247:         bt['isIEWin'] = bt['isIE'] and bt['isWin']
                    248:         bt['isIEMac'] = bt['isIE'] and bt['isMac']
                    249:         bt['staticHTML'] = False
                    250: 
                    251:         return bt
                    252: 
                    253: 
                    254:     def versionHeaderEN(self):
                    255:         """version header text"""
                    256:         
                    257:         date= self.REQUEST.get('date',None)
                    258:         if date:
                    259:             txt="""<h2>This pages shows the project which existed at %s</h2>"""%str(date)
                    260:             return txt
                    261:         return ""
                    262: 
                    263:     def versionHeaderDE(self):
                    264:         """version header text"""
                    265:         date= self.REQUEST.get('date',None)
                    266:         if date:
                    267:             txt="""<h2>Auf dieser Seite finden Sie die Projekte mit Stand vom %s</h2>"""%str(date)
                    268:         return ""
                    269:     
                    270:         
                    271:     def createOrUpdateId_raw(self):
                    272:         """create sequence to create ids for bibliography"""
                    273:         debug=None
                    274:         #suche groesste existierende id
                    275:         founds=self.ZSQLQuery("select id from bibliography")
                    276:         
                    277:         if founds:
                    278:             ids=[int(x.id[1:]) for x in founds]
                    279:             maximum=max(ids)
                    280:             
                    281:             id_raw=self.ZSQLQuery("select nextval('id_raw')",debug=debug)
                    282:             
                    283:             if id_raw:
                    284:                 self.ZSQLQuery("drop sequence id_raw",debug=debug)
                    285:             
                    286:             self.ZSQLQuery("create sequence id_raw start %i"%(maximum+1),debug=debug)
                    287:         
                    288:     
                    289:     def queryLink(self,link):
                    290:         """append querystring to the link"""
                    291:         return "%s?%s"%(link,self.REQUEST.get('QUERY_STRING',''))
                    292: 
                    293:     def getKategory(self,url):
                    294:         """kategorie"""
                    295:         splitted=url.split("/")
                    296:         return splitted[4]
                    297: 
                    298:     def generateUrlProject(self,url,project=None):
                    299:         """erzeuge aus absoluter url, relative des Projektes"""
                    300:         if project:
                    301:             splitted=url.split("/")
                    302:             length=len(splitted)
                    303:             short=splitted[length-2:length]
                    304:             
                    305:             base=self.REQUEST['URL3']+"/"+"/".join(short)
                    306: 
                    307:         else:
                    308:             findPart=url.find("/projects/")
                    309:             base=self.REQUEST['URL1']+"/"+url[findPart:]
                    310: 
                    311:                 
                    312:         return base
                    313:     
                    314:     def isNewCapital(self,text=None,reset=None):
                    315:         if reset:
                    316:             self.REQUEST['capital']="A"
                    317:             return True
                    318:         else:
                    319:             if len(text)>0 and not (text[0]==self.REQUEST['capital']):
                    320:                 self.REQUEST['capital']=text[0]
                    321:                 return True
                    322:             else:
                    323:                 return False
                    324:     
                    325:     def subNavStatic(self,obj):
                    326:         """subnav" von self"""
                    327:         def sortWeight(x,y):
                    328:             x1=int(getattr(x[1],'weight','0'))
                    329:             y1=int(getattr(y[1],'weight','0'))
                    330:             return cmp(x1,y1)
                    331:       
                    332:         subs=self.ZopeFind(obj,obj_metatypes=['MPIWGTemplate','MPIWGLink'])
                    333:         subret=[]
                    334: 
                    335:         for x in subs:
                    336:             if not(x[1].title==""):
                    337:                 subret.append(x)
                    338:         subret.sort(sortWeight)
                    339:         return subret
                    340:     
                    341:     def subNav(self,obj):
                    342:         """return subnav elemente"""
                    343:         def sortWeight(x,y):
                    344:             x1=int(getattr(x[1],'weight','0'))
                    345:             y1=int(getattr(y[1],'weight','0'))
                    346:             return cmp(x1,y1)
                    347:         #if obj.meta_type in ['MPIWGTemplate','MPIWGLink']:
                    348:         #    id=obj.aq_parent.getId()
                    349:         #else:
                    350: 
                    351:         #id=obj.getId()
                    352: 
                    353:         
                    354:         #suche die zweite ebene
                    355:         
                    356:         if not obj.aq_parent.getId() in ['de','en']:
                    357:             obj=obj.aq_parent
                    358:         
                    359:         while not self.ZopeFind(self,obj_ids=[obj.getId()]):
                    360:             obj=obj.aq_parent
                    361:         
                    362:       
                    363:         if hasattr(self,obj.getId()):
                    364:             
                    365:             subs=self.ZopeFind(getattr(self,obj.getId()),obj_metatypes=['MPIWGTemplate','MPIWGLink'])
                    366:             subret=[]
                    367: 
                    368:             for x in subs:
                    369:                 if not(x[1].title==""):
                    370:                     subret.append(x)
                    371:             subret.sort(sortWeight)
                    372:             return subret
                    373:         else:
                    374:             return None
                    375: 
1.1.2.11! dwinter   376:     def isType(self,object,meta_type):
        !           377:         """teste ob ein object vom meta_type ist."""
        !           378:         return (object.meta_type==meta_type)
        !           379:     
1.1.2.1   dwinter   380:     def isActive(self,name):
                    381:         """teste ob subnavigation aktiv"""
                    382:         for part in self.REQUEST['URL'].split("/"):
                    383:             if part==name:
                    384:                 return True
                    385:         return False
                    386:         
1.1.2.6   casties   387:     
                    388:     def getSections(self):
                    389:         """returns a list of all sections i.e. top-level MPIWGFolders"""
                    390:         secs = self.objectItems(['MPIWGFolder'])
                    391:         secs.sort(sortWeight)
                    392:         #logging.debug("root: %s secs: %s"%(repr(self.absolute_url()), repr(secs)))
                    393:         return secs
1.1.2.1   dwinter   394: 
                    395:     def getSectionStyle(self, name, style=""):
                    396:         """returns a string with the given style + '-sel' if the current section == name"""
                    397:         if self.getSection() == name:
                    398:             return style + '-sel'
                    399:         else:
                    400:             return style    
                    401: 
                    402:     def MPIWGrootURL(self):
                    403:         """returns the URL to the root"""
                    404:         return self.absolute_url()
                    405:         
                    406:     def upDateSQL(self,fileName):
                    407:         """updates SQL databases using fm.jar"""
                    408:         fmJarPath=os.path.join(package_home(globals()), 'updateSQL/fm.jar')
                    409:         xmlPath=os.path.join(package_home(globals()), "updateSQL/%s"%fileName)
                    410:         logger("MPIWG Web",logging.INFO,"java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath))
                    411:         ret=os.popen("java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath),"r").read()
                    412:         logger("MPIWG Web",logging.INFO,"result convert: %s"%ret)
                    413:         return 1
                    414:     
                    415:     def patchProjects(self,RESPONSE):
                    416:         """patch"""
                    417:         projects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'])
                    418:         for project in projects:
                    419:                 tmp=project[1].WEB_project_description[0].replace("/CD/projects/","")[0:]
                    420:                 setattr(project[1],'WEB_project_description',[tmp[0:]])
                    421:                 RESPONSE.write("<p>%s</p>\n"%project[0])
                    422:             
                    423:     def replaceNotEmpty(self,format,field):
                    424:         """replace not empty"""
                    425:         if field and (not field.lstrip()==''):
1.1.2.3   dwinter   426:             return self.decode(format%field)
1.1.2.1   dwinter   427:         else:
                    428:             return ""
                    429:         
                    430: 
                    431:     def isActiveMember(self,key):
                    432:         """tested ob Mitarbeiter key ist aktiv"""
1.1.2.10  dwinter   433:         key=utf8ify(key)
1.1.2.1   dwinter   434:         ret=self.getat(self.ZSQLInlineSearch(_table='personal_www',
                    435:                                             _op_key='eq',key=key,
                    436:                                             _op_publish_the_data='eq',
                    437:                                             publish_the_data='yes'))
                    438:         
                    439:         logging.info("ACTIVE_MEMBER  %s"%ret)
                    440:         if ret:
                    441:             return True
                    442:         else:
                    443:             return False
                    444:         
                    445:     def isActual(self,project):
                    446:         """checke if project is actual"""
                    447:         actualTime=time.localtime()
                    448:         
                    449:         if hasattr(project,'getObject'): #obj ist aus einer catalogTrefferList
                    450:             obj=project.getObject()
                    451:         else:
                    452:             obj=project
                    453:             
                    454:         if getattr(obj,'archiveTime',actualTime)< actualTime:
                    455:             return False
                    456:         else:
                    457:             return True
                    458:         
                    459:     def redirectIndex_html(self,request):
                    460:         #return request['URL1']+'/index_html'
                    461:         
                    462:         return urllib.urlopen(request['URL1']+'/index_html').read()
                    463: 
                    464:     
                    465:     def formatBibliography(self,here,found):
                    466:         """format"""
                    467:         return formatBibliography(here,found)
                    468:     
                    469:     def getValue(self,fieldStr):
                    470:         """Inhalt des Feldes"""
                    471:         
                    472:         if type(fieldStr)==StringType:
                    473:             field=fieldStr
                    474:         else:
                    475:             field=fieldStr[0]
                    476:         try:
                    477:             if field[len(field)-1]==";":
                    478:                 field=field[0:len(field)-1]
                    479:         except:
                    480: 
                    481:             """nothing"""
                    482:         field=re.sub(r';([^\s])','; \g<1>',field)
                    483:         return field.encode('utf-8')
                    484: 
                    485: 
                    486:     
                    487:     def sortedNames(self,list):
                    488:         """sort names"""
                    489: 
                    490:         def sortLastName(x_c,y_c):
                    491:             try:
                    492:                 x=urllib.unquote(x_c).encode('utf-8','ignore')
                    493:             except:
                    494:                 x=urllib.unquote(x_c)
                    495: 
                    496:             try:
                    497:                 y=urllib.unquote(y_c).encode('utf-8','ignore')
                    498:             except:
                    499:                 x=urllib.unquote(y_c)
                    500:                 
                    501: 
                    502:             
                    503:             try:
                    504:                 last_x=x.split()[len(x.split())-1]
                    505:                 last_y=y.split()[len(y.split())-1]
                    506: 
                    507:             except:
                    508: 
                    509:                 last_x=""
                    510:                 last_y=""
                    511:             
                    512:             
                    513:             
                    514:             if last_x<last_y:
                    515:                 return 1
                    516:             elif last_x>last_y:
                    517:                 return -1
                    518:             else:
                    519:                 return 0
                    520:             
                    521:         list.sort(sortLastName)
                    522:         list.reverse()
                    523:         
                    524:         return list
                    525:     
                    526:     def __init__(self, id, title):
                    527:         """init"""
                    528:         self.id=id
                    529:         self.title=title
                    530: 
                    531:     def removeStopWords(self,xo):
                    532:         """remove stop words from xo"""
                    533:         if not hasattr(self,'_v_stopWords'):
                    534:             self._v_stopWords=self.stopwords_en.data.split("\n")
                    535:     
                    536:         x=str(xo)
                    537:     
                    538:         strx=x.split(" ")
                    539:   
                    540:         for tmp in strx:
                    541:      
                    542:             if tmp.lower() in self._v_stopWords:
                    543:                 del strx[strx.index(tmp)]
                    544: 
                    545:         return " ".join(strx)
                    546:     
                    547:     def urlQuote(self,str):
                    548:         """quote"""
                    549:         return urllib.quote(str)
                    550: 
                    551:     def urlUnQuote(self,str):
                    552:         """quote"""
                    553:         return urllib.unquote(str)
                    554:     
                    555:         
                    556: 
                    557:     def getProjectsByFieldContent(self,fieldName,fieldContentsEntry, date=None):
                    558:         """gib alle Projekte aus mit Value von field mit fieldName enthaelt ein Element der Liste fieldContents"""
                    559:         def sort(x,y):
                    560:                 return cmp(x.WEB_title[0],y.WEB_title[0])
                    561: 
                    562:         if type(fieldContentsEntry) is StringType:
                    563:             fieldContentsTmp=[fieldContentsEntry]
                    564:         else:
                    565:             fieldContentsTmp=fieldContentsEntry
                    566: 
                    567:         fieldContents=[]
                    568:         for x in fieldContentsTmp:
                    569:             fieldContents.append(" AND ".join(x.split()))
                    570:         projects=self.ProjectCatalog({fieldName:string.join(fieldContents,' AND')})
                    571:         #print projects
                    572:         #ret=[x for x in projects]
                    573:         ret=[]
                    574:         for x in projects:
                    575:             obj=x.getObject()
                    576:             obj=obj.getActualVersion(date)
                    577:             if obj and (not getattr(obj,'invisible',None)):
                    578:                 #if not (x in ret):
                    579:                     ret.append(x)
                    580: 
                    581:         ret.sort(sort)
                    582:         return ret
                    583: 
                    584:     def changeMPIWGRootForm(self):
                    585:         """edit"""
                    586:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeMPIWGRootForm')).__of__(self)
                    587:         return pt()
                    588: 
                    589:     def changeMPIWGRoot(self,title,disciplineList,themesList,connection_id,RESPONSE=None):
                    590:         """change"""
                    591:         self.title=title
                    592:         self.connection_id=connection_id
                    593:         self.disciplineList=disciplineList
                    594:         self.themesList=themesList
                    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:
1.1.2.6   casties   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
1.1.2.1   dwinter   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)
1.1.2.6   casties   631:         
1.1.2.10  dwinter   632:         #logging.debug("getContexts: childs=%s parents=%s depth=%s => %s"%(childs,parents,depth,repr(ret)))
1.1.2.1   dwinter   633:         return ret
1.1.2.6   casties   634: 
1.1.2.1   dwinter   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: 
1.1.2.11! dwinter   893:     
        !           894: 
1.1.2.1   dwinter   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: 
1.1.2.7   dwinter   970:     def getTreeRSS(self,dep=None,date=None,onlyActive=1,onlyArchived=0):
1.1.2.5   dwinter   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):
1.1.2.7   dwinter   977:             linkStr="""<link>http://wwwneu.mpiwg-berlin.mpg.de/en/research/projects/%s</link>"""
1.1.2.5   dwinter   978:             rss+="""<item>"""
1.1.2.7   dwinter   979:             rss+=linkStr%obj[3].getId()
1.1.2.5   dwinter   980:             rss+="""</item>"""
1.1.2.8   dwinter   981:             if hasattr(obj[3],'publicationList'):
                    982:            rss+="""<item>"""
                    983:                 rss+=linkStr%(obj[3].getId()+"/publicationList");
                    984:                 rss+="""</item>"""
1.1.2.5   dwinter   985:         rss+="""</channel>
                    986:         </rss>"""
                    987: 
                    988:         
                    989:         return rss
1.1.2.1   dwinter   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:                 
1.1.2.4   dwinter  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:                 
1.1.2.1   dwinter  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 ""
1.1.2.10  dwinter  1178:         key=utf8ify(key)
1.1.2.1   dwinter  1179:         catalogged=self.MembersCatalog({'getKey':key})
                   1180:         if len(catalogged)==0:
                   1181:             return ""
                   1182:         else:
                   1183:             return catalogged[0].getObject().getId()
                   1184:         
                   1185: 
                   1186:             
1.1.2.2   dwinter  1187: 
1.1.2.1   dwinter  1188:     def getProjectsOfMembers(self,date=None):
                   1189:         """give tuple member /projects"""
                   1190:         ret=[]
                   1191:         members=self.getAllMembers()
                   1192:        
                   1193:         #return str(members)
                   1194:         for x in members:
                   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':key})
                   1219:         else:
                   1220:             return ret # key muss definiert sein
                   1221:         
                   1222:      
                   1223:         if proj:
                   1224:             proj2=[]
                   1225:             for x in proj:
1.1.2.10  dwinter  1226:                 #logging.error("proj:%s"%repr(x.getPath()))
1.1.2.1   dwinter  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=[]
1.1.2.10  dwinter  1238:         #logging.error("getprojectsofmember proj2: %s"%repr(proj2))
1.1.2.1   dwinter  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
1.1.2.10  dwinter  1249:                add=True 
1.1.2.1   dwinter  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:                 
1.1.2.10  dwinter  1266:         #logging.error("getprojectsofmember projectliste: %s"%repr(projectListe))
1.1.2.1   dwinter  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>