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