Annotation of MPIWGWeb/MPIWGProjects.py, revision 1.47.2.83
1.9 dwinter 1: """This contains the class MPIWG Projects
1.42 dwinter 2: for organizing and maintaining the different project pages
1.6 dwinter 3:
4: """
1.47.2.64 dwinter 5: #TODO: mechanismus fur links to personen ueberarbeiten, da jetzt alle e_mails als members auftauchen unabhaenig vom status publish_the_data
1.47.2.29 dwinter 6: #TODO: was passiert wenn aenderungen von jochen im filemaker nicht mit den aenderungen im sql uebereinstimmen
1.47.2.34 dwinter 7: #TODO: in einzelnen projecte steht als pfad auf die bilder noch wwwneu statt www
1.47.2.28 dwinter 8:
1.1 dwinter 9: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
10: from Products.PageTemplates.PageTemplate import PageTemplate
11: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
1.11 dwinter 12: from Products.ZSQLExtend.ZSQLExtend import ZSQLExtendFolder
1.45 dwinter 13: from Products.ZCatalog.CatalogPathAwareness import CatalogAware
1.47.2.22 dwinter 14: from OFS.Image import Image
1.34 dwinter 15: from Globals import package_home
1.12 dwinter 16: import urllib
1.1 dwinter 17: import MPIWGStaff
18: import string
19: import re
1.34 dwinter 20: import os
1.5 dwinter 21: from types import *
1.47.2.71 dwinter 22: import logging
1.47.2.23 dwinter 23: import xmlhelper # Methoden zur Verwaltung der projekt xml
1.1 dwinter 24: from OFS.SimpleItem import SimpleItem
25: from OFS.Folder import Folder
1.45 dwinter 26: from Products.ZSQLMethods.SQL import SQLConnectionIDs
1.47.2.21 dwinter 27: from AccessControl import ClassSecurityInfo
1.11 dwinter 28: from bibliography import *
1.42 dwinter 29: import time
1.47.2.28 dwinter 30: import xml.dom.minidom
31: import sys
1.47.2.29 dwinter 32: from Ft.Xml.XPath import Evaluate
33: from Ft.Xml.XPath.Context import Context
34: from Ft.Xml.Domlette import NonvalidatingReader,PrettyPrint, Print
35: from Ft.Xml import EMPTY_NAMESPACE
1.47.2.64 dwinter 36: import copy
1.47.2.71 dwinter 37: import updatePersonalWWW
38: import MPIWGStaff
1.11 dwinter 39:
1.1 dwinter 40: definedFields=['WEB_title','xdata_01','xdata_02','xdata_03','xdata_04','xdata_05','xdata_06','xdata_07','xdata_08','xdata_09','xdata_10','xdata_11','xdata_12','xdata_13','WEB_project_header','WEB_project_description','WEB_related_pub']
41:
42: checkFields = ['xdata_01']
43:
1.47.2.71 dwinter 44: #ersetzt logging
45: def logger(txt,method,txt2):
46: """logging"""
47: logging.info(txt+ txt2)
48:
1.47.2.28 dwinter 49: def getTextFromNode(nodename):
50: nodelist=nodename.childNodes
51: rc = ""
52: for node in nodelist:
53: if node.nodeType == node.TEXT_NODE:
54: rc = rc + node.data
55: return rc
1.9 dwinter 56:
1.47.2.57 dwinter 57:
58: def sortStopWordsF(self,xo,yo):
59: if not hasattr(self,'_v_stopWords'):
60: self._v_stopWords=self.stopwords_en.data.split("\n")
61:
62: x=str(xo[1])
63: y=str(yo[1])
64:
65: strx=x.split(" ")
66: stry=y.split(" ")
67:
68: for tmp in strx:
69: if tmp.lower() in self._v_stopWords:
70: del strx[strx.index(tmp)]
71:
72: for tmp in stry:
73: if tmp.lower() in self._v_stopWords:
74: del stry[stry.index(tmp)]
75:
76: return cmp(" ".join(strx)," ".join(stry))
77:
78: def sortStopWords(self):
79: return lambda x,y : sortStopWordsF(self,x,y)
80:
1.1 dwinter 81: def sortF(x,y):
1.9 dwinter 82: try:
83: return cmp(x[1],y[1])
84: except:
1.18 dwinter 85: try:
86: return cmp(str(x[1]),str(y[1]))
87: except:
1.46 dwinter 88:
1.18 dwinter 89: return 0
1.5 dwinter 90:
91: def sortI(x,y):
92: xsplit=x[1].split(".")
93: ysplit=y[1].split(".")
94: xret=""
95: yret=""
96: try:
97: for i in range(5):
98: try:
99: yret=yret+"%04i"%int(xsplit[i])
100: except:
101: yret=yret+"%04i"%0
102:
103: try:
104: xret=xret+"%04i"%int(ysplit[i])
105: except:
106: xret=xret+"%04i"%0
107:
108:
109: return cmp(int(yret),int(xret))
110: except:
111: return cmp(x[1],y[1])
1.1 dwinter 112:
1.47.2.79 casties 113:
114: def unicodify(str):
115: """decode str (utf-8 or latin-1 representation) into unicode object"""
116: if not str:
117: return ""
118: if type(str) is StringType:
119: try:
120: return str.decode('utf-8')
121: except:
122: return str.decode('latin-1')
123: else:
124: return str
125:
126: def utf8ify(str):
127: """encode unicode object or string into byte string in utf-8 representation"""
128: if not str:
129: return ""
130: if type(str) is StringType:
131: return str
132: else:
133: return str.encode('utf-8')
134:
135:
1.47.2.14 dwinter 136: class MPIWGLink(SimpleItem):
137: """create a symbolic link to another page"""
138:
139: meta_type="MPIWGLink"
140:
1.47.2.16 dwinter 141: def isActiveItem(self):
142: """teste ob ausgewaehlt"""
1.47.2.17 dwinter 143: #url1 beim link anstelle von url1, da link jeweils index_html als url hat.
144: if self.absolute_url()==self.REQUEST['URL1']:
1.47.2.16 dwinter 145: return "aktiv"
146: else:
147: return ""
1.47.2.15 dwinter 148:
1.47.2.14 dwinter 149: def __init__(self,id,link,title='',weight=''):
150: """init mpiwglink"""
151: self.id=id
152: self.link=link
153: self.title=title
154: self.weight=weight
155:
156: def getObj(self):
157: """bekomme original"""
158: ## objpath=self.link.replace("/",".")
159: ## if objpath[0]!=".":
160: ## objpath="."+objpath
161:
162: ## print objpath
163: ## return eval("self"+objpath)
164:
165:
1.47.2.15 dwinter 166: splitted=self.link.lstrip().split("/")
1.47.2.14 dwinter 167: obj=self
168: for x in splitted:
1.47.2.25 dwinter 169: if not x=="":
1.47.2.15 dwinter 170: obj=getattr(obj,x)
1.47.2.14 dwinter 171:
172: return obj
173:
174: def getWeight(self):
1.47.2.71 dwinter 175: if self.linkWeight and self.linkWeight!="":
1.47.2.14 dwinter 176: return self.linkWeight
177: else:
178: return self.getObj().weight
179:
1.47.2.63 dwinter 180: manage_options=(
1.47.2.14 dwinter 181: {'label':'main config','action':'changeLinkForm'},
1.47.2.63 dwinter 182: )+SimpleItem.manage_options
1.47.2.14 dwinter 183:
184:
185: def changeLinkForm(self):
186: """change MPIWG link"""
187: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGLinkChange.zpt')).__of__(self)
188: return pt()
189:
190: def changeLink(self,link,title,weight,RESPONSE=None):
191: """change links"""
192: self.link=link
193: self.title=title
194: self.weight=weight
195:
196: if RESPONSE is not None:
197: RESPONSE.redirect('manage')
198:
1.47.2.69 dwinter 199: def index_html(self,**argv):
1.47.2.14 dwinter 200: """index"""
1.47.2.70 dwinter 201:
202:
203:
204: try:
205: return self.getObj().pt_render(extra_context={'here':self})
206: except:
207: self.REQUEST.RESPONSE.redirect(self.getObj().absolute_url())
208:
1.47.2.69 dwinter 209:
1.47.2.14 dwinter 210:
211: def manage_addMPIWGLinkForm(self):
212: """Form for adding link"""
213: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt/AddMPIWGLink.zpt')).__of__(self)
214: return pt()
215:
216: def manage_addMPIWGLink(self,id,link,title,weight,RESPONSE=None):
217: """add link"""
218: newObj=MPIWGLink(id,link,title,weight)
219:
220: self._setObject(id,newObj)
221:
222: if RESPONSE is not None:
223: RESPONSE.redirect('manage_main')
224:
225:
1.37 dwinter 226: class MPIWGTemplate(ZopePageTemplate):
227: """Create a layout Template for different purposes"""
228:
229: meta_type="MPIWGTemplate"
230:
1.47.2.1 dwinter 231: manage_options=ZopePageTemplate.manage_options+(
232: {'label':'Change Weight','action':'changeWeightForm'},
233: )
234:
235: def changeWeightForm(self):
236: """change weight form"""
237: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGTemplateChangeWeight.zpt')).__of__(self)
238: return pt()
239:
240: def changeWeight(self,weight,RESPONSE=None):
241: """change weight"""
242: self.weight=weight
243: if RESPONSE is not None:
244: RESPONSE.redirect('manage')
245:
246:
1.37 dwinter 247: def __init__(self, id, text=None, content_type=None,MPIWGType=None):
248: self.id = str(id)
249:
250:
251:
252: self.ZBindings_edit(self._default_bindings)
253: if text is None:
254: self._default_content_fn = os.path.join(package_home(globals()),
255: 'zpt/MPIWG_%s_template_standard.zpt'%MPIWGType)
256: text = open(self._default_content_fn).read()
257: self.pt_edit(text, content_type)
258:
259:
260: """change form"""
261:
1.47.2.16 dwinter 262: def isActiveItem(self):
1.47.2.1 dwinter 263: """teste ob ausgewaehlt"""
264: if self.absolute_url()==self.REQUEST['URL']:
265: return "aktiv"
266: else:
267: return ""
1.47.2.25 dwinter 268:
1.37 dwinter 269: def manage_addMPIWGTemplateForm(self):
270: """Form for adding"""
271: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt/AddMPIWGTemplate.zpt')).__of__(self)
272: return pt()
273:
274: from urllib import quote
275:
276:
1.47.2.71 dwinter 277: def manage_addMPIWGTemplate(self, MPIWGType,id, text="",title=None,weight=0,REQUEST=None):
1.37 dwinter 278: "Add a Page Template with optional file content."
279: if type(MPIWGType)==StringType:
280: MPIWGTypes=[MPIWGType]
281: else:
282: MPIWGTypes=MPIWGType
283:
284: for singleType in MPIWGTypes:
285:
286:
287: if REQUEST is None:
288: self._setObject(id, MPIWGTemplate(id, text,EchoType=singleType))
289: ob = getattr(self, id)
290:
291: if title:
292: ob.pt_setTitle(title)
293: return ob
294: else:
295: file = REQUEST.form.get('file')
296: headers = getattr(file, 'headers', None)
297: if headers is None or not file.filename:
298: zpt = MPIWGTemplate(id,MPIWGType=singleType)
299: else:
300: zpt = MPIWGTemplate(id, file, headers.get('content_type'))
301:
302: self._setObject(id, zpt)
303: ob = getattr(self, id)
304: if title:
305: ob.pt_setTitle(title)
306:
307: try:
308: u = self.DestinationURL()
309: except AttributeError:
310: u = REQUEST['URL1']
311:
1.47.2.1 dwinter 312: ob = getattr(self, id)
313: ob.weight=weight
314:
1.37 dwinter 315: REQUEST.RESPONSE.redirect(u+'/manage_main')
316: return ''
317:
1.5 dwinter 318:
1.11 dwinter 319: class MPIWGRoot(ZSQLExtendFolder):
1.47.2.65 casties 320: """Stammordner fuer den Web-Server"""
1.1 dwinter 321:
1.9 dwinter 322: fieldLabels={'WEB_title':'WEB_Title','xdata_01':'Responsible Scientists','xdata_02':'Department',
323: 'xdata_03':'Historical Persons','xdata_04':'Time period',
324: 'xdata_05':'Sorting number','xdata_06':'Keywords','xdata_07':'Short title',
1.47.2.18 dwinter 325: 'xdata_08':'Other involved scholars' ,'xdata_09':'Disciplines','xdata_10':'Themes',
1.9 dwinter 326: 'xdata_11':'Object Digitallibrary','xdata_12':'Cooperation partners',
327: 'xdata_13':'Funding institutions','WEB_project_header':'WEB_project_header',
328: 'WEB_project_description':'WEB_project_description','WEB_related_pub':'WEB_related_pub'}
329:
1.38 dwinter 330: folders=['MPIWGProject','Folder','ECHO_Navigation']
1.1 dwinter 331: meta_type='MPIWGRoot'
1.8 dwinter 332:
1.47.2.83! dwinter 333: def transformProjectsToId(self):
! 334: """trnasformiere zu ID, Hilfsfunktion die die alten Templates analysiert und mit der neuen Liste
! 335: verantwortlicher Personen versieht"""
! 336: projects=self.getTree()
! 337: ret=""
! 338: for project in projects:
! 339: proj=project[3]
! 340: persons=proj.identifyNames(proj.getContent('xdata_01'))
! 341: if not hasattr(proj,'responsibleScientistsList'):
! 342: proj.responsibleScientistsList=[]
! 343:
! 344: for person in persons.items():
! 345: logging.info("XXXX"+repr(person))
! 346: if len(person[1]) >1: #nicht eindeutig
! 347: ret+="nicht eindeutig --- %s: %s\n"%(proj.getId(),person[0])
! 348:
! 349: elif len(person[1]) ==0: #kein eintrage
! 350: ret+="kein eintrag--- %s: %s\n"%(proj.getId(),person[0])
! 351: proj.responsibleScientistsList.append((person[0],""))
! 352: else:
! 353: proj.responsibleScientistsList.append((person[0],person[1][0].getObject().getKey()))
! 354:
! 355: return ret
! 356:
1.47.2.57 dwinter 357: def harvestProjects(self):
358: """harvest"""
359: folder="/tmp"
360: try:
361: os.mkdir("/tmp/harvest_MPIWG")
362: except:
363: pass
364: founds=self.ZopeFind(self.aq_parent.projects,obj_metatypes=['MPIWGProject'],search_sub=1)
365: for found in founds:
366: txt=found[1].harvest_page()
367:
368: if txt and (txt != ""):
369: name=found[0].replace("/","_")
370: fh=file("/tmp/harvest_MPIWG/"+name,"w")
371: fh.write(txt)
372: fh.close()
373:
1.47.2.53 dwinter 374: def decode(self,str):
375: """decoder"""
376: if not str:
377: return ""
378: if type(str) is StringType:
1.47.2.76 casties 379: try:
380: return str.decode('utf-8')
381: except:
382: return str.decode('latin-1')
1.47.2.53 dwinter 383: else:
384: return str
385:
1.47.2.63 dwinter 386:
1.47.2.76 casties 387: def getat(self,array,idx=0,default=None):
388: """return array element idx or default (but no exception)"""
1.47.2.77 casties 389: if len(array) <= idx:
1.47.2.76 casties 390: return default
391: else:
392: return array[idx]
393:
394:
1.47.2.63 dwinter 395: def browserCheck(self):
396: """check the browsers request to find out the browser type"""
397: bt = {}
398: ua = self.REQUEST.get_header("HTTP_USER_AGENT")
399: bt['ua'] = ua
400: bt['isIE'] = False
401: bt['isN4'] = False
402: if string.find(ua, 'MSIE') > -1:
403: bt['isIE'] = True
404: else:
405: bt['isN4'] = (string.find(ua, 'Mozilla/4.') > -1)
406:
407: try:
408: nav = ua[string.find(ua, '('):]
409: ie = string.split(nav, "; ")[1]
410: if string.find(ie, "MSIE") > -1:
411: bt['versIE'] = string.split(ie, " ")[1]
412: except: pass
413:
414: bt['isMac'] = string.find(ua, 'Macintosh') > -1
415: bt['isWin'] = string.find(ua, 'Windows') > -1
416: bt['isIEWin'] = bt['isIE'] and bt['isWin']
417: bt['isIEMac'] = bt['isIE'] and bt['isMac']
418: bt['staticHTML'] = False
419:
420: return bt
421:
422:
1.47.2.20 dwinter 423: def versionHeaderEN(self):
424: """version header text"""
425:
426: date= self.REQUEST.get('date',None)
427: if date:
428: txt="""<h2>This pages shows the project which existed at %s</h2>"""%str(date)
429: return txt
430: return ""
431:
432: def versionHeaderDE(self):
433: """version header text"""
434: date= self.REQUEST.get('date',None)
435: if date:
436: txt="""<h2>Auf dieser Seite finden Sie die Projekte mit Stand vom %s</h2>"""%str(date)
437: return ""
438:
1.47.2.28 dwinter 439:
440: def createOrUpdateId_raw(self):
441: """create sequence to create ids for bibliography"""
442: debug=None
443: #suche groesste existierende id
444: founds=self.ZSQLQuery("select id from bibliography")
445:
446: if founds:
447: ids=[int(x.id[1:]) for x in founds]
448: maximum=max(ids)
449:
1.47.2.32 dwinter 450: id_raw=self.ZSQLQuery("select nextval('id_raw')",debug=debug)
1.47.2.28 dwinter 451:
452: if id_raw:
1.47.2.32 dwinter 453: self.ZSQLQuery("drop sequence id_raw",debug=debug)
1.47.2.28 dwinter 454:
1.47.2.32 dwinter 455: self.ZSQLQuery("create sequence id_raw start %i"%(maximum+1),debug=debug)
1.47.2.28 dwinter 456:
457:
1.47.2.18 dwinter 458: def queryLink(self,link):
459: """append querystring to the link"""
460: return "%s?%s"%(link,self.REQUEST.get('QUERY_STRING',''))
461:
1.47.2.7 dwinter 462: def getKategory(self,url):
1.47.2.25 dwinter 463: """kategorie"""
464: splitted=url.split("/")
465: return splitted[4]
1.47.2.7 dwinter 466:
1.47.2.6 dwinter 467: def generateUrlProject(self,url,project=None):
1.47.2.5 dwinter 468: """erzeuge aus absoluter url, relative des Projektes"""
1.47.2.25 dwinter 469: if project:
1.47.2.18 dwinter 470: splitted=url.split("/")
471: length=len(splitted)
472: short=splitted[length-2:length]
473:
474: base=self.REQUEST['URL3']+"/"+"/".join(short)
475:
1.47.2.25 dwinter 476: else:
1.47.2.18 dwinter 477: findPart=url.find("/projects/")
478: base=self.REQUEST['URL1']+"/"+url[findPart:]
479:
480:
1.47.2.5 dwinter 481: return base
482:
1.47.2.1 dwinter 483: def isNewCapital(self,text=None,reset=None):
484: if reset:
485: self.REQUEST['capital']="A"
486: return True
487: else:
488: if len(text)>0 and not (text[0]==self.REQUEST['capital']):
489: self.REQUEST['capital']=text[0]
490: return True
491: else:
492: return False
1.47.2.56 dwinter 493:
494: def subNavStatic(self,obj):
495: """subnav" von self"""
496: def sortWeight(x,y):
497: x1=int(getattr(x[1],'weight','0'))
498: y1=int(getattr(y[1],'weight','0'))
499: return cmp(x1,y1)
500:
501: subs=self.ZopeFind(obj,obj_metatypes=['MPIWGTemplate','MPIWGLink'])
502: subret=[]
503:
504: for x in subs:
505: if not(x[1].title==""):
506: subret.append(x)
507: subret.sort(sortWeight)
508: return subret
509:
1.47.2.16 dwinter 510: def subNav(self,obj):
1.47.2.1 dwinter 511: """return subnav elemente"""
512: def sortWeight(x,y):
513: x1=int(getattr(x[1],'weight','0'))
514: y1=int(getattr(y[1],'weight','0'))
515: return cmp(x1,y1)
1.47.2.16 dwinter 516: #if obj.meta_type in ['MPIWGTemplate','MPIWGLink']:
517: # id=obj.aq_parent.getId()
518: #else:
519:
520: #id=obj.getId()
1.47.2.17 dwinter 521:
522:
523: #suche die zweite ebene
1.47.2.56 dwinter 524:
1.47.2.17 dwinter 525: if not obj.aq_parent.getId() in ['de','en']:
526: obj=obj.aq_parent
1.47.2.56 dwinter 527:
1.47.2.16 dwinter 528: while not self.ZopeFind(self,obj_ids=[obj.getId()]):
529: obj=obj.aq_parent
1.47.2.17 dwinter 530:
1.47.2.56 dwinter 531:
1.47.2.16 dwinter 532: if hasattr(self,obj.getId()):
533:
534: subs=self.ZopeFind(getattr(self,obj.getId()),obj_metatypes=['MPIWGTemplate','MPIWGLink'])
1.47.2.8 dwinter 535: subret=[]
1.47.2.16 dwinter 536:
1.47.2.8 dwinter 537: for x in subs:
538: if not(x[1].title==""):
539: subret.append(x)
540: subret.sort(sortWeight)
541: return subret
1.47.2.2 dwinter 542: else:
543: return None
1.47.2.16 dwinter 544:
1.47.2.1 dwinter 545: def isActive(self,name):
546: """teste ob subnavigation aktiv"""
547: for part in self.REQUEST['URL'].split("/"):
548: if part==name:
549: return True
550: return False
551:
1.47.2.62 casties 552: def getSection(self):
553: """returns the current section name"""
554: root = self.absolute_url()
555: url = self.REQUEST['URL']
1.47.2.80 dwinter 556: if not url:
557: return None
1.47.2.62 casties 558: path = string.replace(url, root, '')
559: paths = path.split('/')
560: if len(paths) > 0:
1.47.2.63 dwinter 561: sec = paths[1]
562: if sec.find('.') < 0:
563: return sec
564: else:
565: return None
1.47.2.62 casties 566: return None
567:
568: def getSectionStyle(self, name, style=""):
569: """returns a string with the given style + '-sel' if the current section == name"""
570: if self.getSection() == name:
571: return style + '-sel'
572: else:
573: return style
574:
575: def MPIWGrootURL(self):
576: """returns the URL to the root"""
577: return self.absolute_url()
1.47.2.1 dwinter 578:
1.34 dwinter 579: def upDateSQL(self,fileName):
580: """updates SQL databases using fm.jar"""
581: fmJarPath=os.path.join(package_home(globals()), 'updateSQL/fm.jar')
582: xmlPath=os.path.join(package_home(globals()), "updateSQL/%s"%fileName)
1.47.2.71 dwinter 583: logger("MPIWG Web",logging.INFO,"java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath))
1.40 dwinter 584: ret=os.popen("java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath),"r").read()
1.47.2.71 dwinter 585: logger("MPIWG Web",logging.INFO,"result convert: %s"%ret)
1.34 dwinter 586: return 1
587:
1.31 dwinter 588: def patchProjects(self,RESPONSE):
589: """patch"""
590: projects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'])
591: for project in projects:
1.47.2.25 dwinter 592: tmp=project[1].WEB_project_description[0].replace("/CD/projects/","")[0:]
593: setattr(project[1],'WEB_project_description',[tmp[0:]])
594: RESPONSE.write("<p>%s</p>\n"%project[0])
1.31 dwinter 595:
1.11 dwinter 596: def replaceNotEmpty(self,format,field):
597: """replace not empty"""
1.44 dwinter 598: if field and (not field.lstrip()==''):
1.11 dwinter 599: return format%field
600: else:
601: return ""
602:
1.29 dwinter 603:
1.45 dwinter 604: def isActual(self,project):
605: """checke if project is actual"""
606: actualTime=time.localtime()
607:
1.47.2.83! dwinter 608: if hasattr(project,'getObject'): #obj ist aus einer catalogTrefferList
! 609: obj=project.getObject()
! 610: else:
! 611: obj=project
! 612:
1.45 dwinter 613: if getattr(obj,'archiveTime',actualTime)< actualTime:
614: return False
615: else:
616: return True
617:
1.29 dwinter 618: def redirectIndex_html(self,request):
619: #return request['URL1']+'/index_html'
1.11 dwinter 620:
1.29 dwinter 621: return urllib.urlopen(request['URL1']+'/index_html').read()
622:
623:
1.11 dwinter 624: def formatBibliography(self,here,found):
625: """format"""
626: return formatBibliography(here,found)
627:
1.21 dwinter 628: def getValue(self,fieldStr):
1.9 dwinter 629: """Inhalt des Feldes"""
630:
1.21 dwinter 631: if type(fieldStr)==StringType:
632: field=fieldStr
1.9 dwinter 633: else:
1.21 dwinter 634: field=fieldStr[0]
635: try:
636: if field[len(field)-1]==";":
637: field=field[0:len(field)-1]
638: except:
639:
640: """nothing"""
641: field=re.sub(r';([^\s])','; \g<1>',field)
642: return field.encode('utf-8')
643:
1.9 dwinter 644:
645:
1.8 dwinter 646: def sortedNames(self,list):
647: """sort names"""
648:
1.12 dwinter 649: def sortLastName(x_c,y_c):
1.13 dwinter 650: try:
651: x=urllib.unquote(x_c).encode('utf-8','ignore')
652: except:
653: x=urllib.unquote(x_c)
654:
655: try:
656: y=urllib.unquote(y_c).encode('utf-8','ignore')
657: except:
658: x=urllib.unquote(y_c)
659:
660:
1.12 dwinter 661:
1.8 dwinter 662: try:
663: last_x=x.split()[len(x.split())-1]
664: last_y=y.split()[len(y.split())-1]
665:
666: except:
667:
668: last_x=""
669: last_y=""
670:
671:
672:
673: if last_x<last_y:
674: return 1
675: elif last_x>last_y:
676: return -1
677: else:
678: return 0
679:
680: list.sort(sortLastName)
681: list.reverse()
682:
683: return list
1.1 dwinter 684:
685: def __init__(self, id, title):
686: """init"""
687: self.id=id
688: self.title=title
1.12 dwinter 689:
1.47.2.57 dwinter 690: def removeStopWords(self,xo):
691: """remove stop words from xo"""
692: if not hasattr(self,'_v_stopWords'):
693: self._v_stopWords=self.stopwords_en.data.split("\n")
694:
695: x=str(xo)
696:
697: strx=x.split(" ")
698:
699: for tmp in strx:
700:
701: if tmp.lower() in self._v_stopWords:
702: del strx[strx.index(tmp)]
703:
704: return " ".join(strx)
705:
1.12 dwinter 706: def urlQuote(self,str):
707: """quote"""
708: return urllib.quote(str)
709:
710: def urlUnQuote(self,str):
711: """quote"""
712: return urllib.unquote(str)
713:
1.8 dwinter 714:
715:
1.47.2.19 dwinter 716: def getProjectsByFieldContent(self,fieldName,fieldContentsEntry, date=None):
1.47.2.65 casties 717: """gib alle Projekte aus mit Value von field mit fieldName enthaelt ein Element der Liste fieldContents"""
1.47.2.10 dwinter 718: def sort(x,y):
1.47.2.25 dwinter 719: return cmp(x.WEB_title[0],y.WEB_title[0])
1.47.2.10 dwinter 720:
1.47.2.25 dwinter 721: if type(fieldContentsEntry) is StringType:
1.47.2.13 dwinter 722: fieldContentsTmp=[fieldContentsEntry]
1.8 dwinter 723: else:
1.47.2.13 dwinter 724: fieldContentsTmp=fieldContentsEntry
725:
726: fieldContents=[]
727: for x in fieldContentsTmp:
728: fieldContents.append(" AND ".join(x.split()))
729: projects=self.ProjectCatalog({fieldName:string.join(fieldContents,' AND')})
1.8 dwinter 730: #print projects
1.47.2.25 dwinter 731: #ret=[x for x in projects]
1.47.2.19 dwinter 732: ret=[]
733: for x in projects:
734: obj=x.getObject()
735: obj=obj.getActualVersion(date)
736: if obj and (not getattr(obj,'invisible',None)):
737: #if not (x in ret):
738: ret.append(x)
739:
1.47.2.25 dwinter 740: ret.sort(sort)
1.47.2.10 dwinter 741: return ret
1.8 dwinter 742:
743: def changeMPIWGRootForm(self):
744: """edit"""
1.45 dwinter 745: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeMPIWGRootForm')).__of__(self)
1.8 dwinter 746: return pt()
747:
1.45 dwinter 748: def changeMPIWGRoot(self,title,disciplineList,themesList,connection_id,RESPONSE=None):
1.8 dwinter 749: """change"""
750: self.title=title
1.45 dwinter 751: self.connection_id=connection_id
1.8 dwinter 752: self.disciplineList=disciplineList
753: self.themesList=themesList
754:
755: if RESPONSE is not None:
756: RESPONSE.redirect('manage_main')
757:
1.47.2.71 dwinter 758:
1.9 dwinter 759:
1.47.2.54 dwinter 760: def getContexts(self,childs=None,parents=None,depth=None,date=None,onlyActive=True):
1.9 dwinter 761: """childs alle childs, alle parents"""
762: ret=[]
1.47.2.20 dwinter 763:
1.9 dwinter 764: if parents:
765: splitted=parents.split(".")
766: parentId=string.join(splitted[0:len(splitted)-1],".")
767:
1.47.2.18 dwinter 768: for project in self.getProjectFields('xdata_05',sort='int',date=date):
1.9 dwinter 769: if project[1]==parentId:
770: ret.append(project)
771:
772: if childs:
1.47.2.18 dwinter 773: for project in self.getProjectFields('xdata_05',sort='int',date=date):
1.9 dwinter 774: searchStr=childs+"(\..*)"
1.47.2.54 dwinter 775:
776: if (onlyActive and project[0].isActiveProject()) or (not onlyActive):
777: if re.match(searchStr,project[1]):
778:
779: if depth:
780:
781: if int(depth)>=len(project[1].split("."))-len(childs.split(".")):
782:
783: ret.append(project)
784: else:
1.9 dwinter 785: ret.append(project)
786: return ret
1.8 dwinter 787:
1.47.2.18 dwinter 788: def getProjectFields(self,fieldName,date=None,folder=None,sort=None):
1.1 dwinter 789: """getListofFieldNames"""
790: ret=[]
1.38 dwinter 791:
1.44 dwinter 792: objects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'],search_sub=0)
1.5 dwinter 793:
1.38 dwinter 794:
795: for object in objects:
796: obj=object[1]
1.47.2.18 dwinter 797: obj=obj.getActualVersion(date)
798: if obj and (not getattr(obj,'invisible',None)):
1.41 dwinter 799: if fieldName=="WEB_title_or_short":
800:
801: if len(obj.getContent('xdata_07'))<3: # hack weil z.Z. manchmal noch ein Trennzeichen ; oder , im Feld statt leer
802: fieldNameTmp="WEB_title"
803: else:
804: fieldNameTmp="xdata_07"
1.38 dwinter 805: else:
1.41 dwinter 806: fieldNameTmp=fieldName
807:
808: ret.append((obj,obj.getContent(fieldNameTmp)))
1.5 dwinter 809:
1.38 dwinter 810:
1.5 dwinter 811: if sort=="int":
812: ret.sort(sortI)
1.47.2.57 dwinter 813: elif sort=="stopWords":
1.47.2.58 dwinter 814:
1.47.2.57 dwinter 815: ret.sort(sortStopWords(self))
816:
1.5 dwinter 817: else:
818: ret.sort(sortF)
1.1 dwinter 819:
820: return ret
821:
1.5 dwinter 822: def showNewProjects(self):
823: projects=[]
824: for objs in self.getProjectFields('WEB_title_or_short'): # Get all Projets
1.47.2.18 dwinter 825: if objs[0].xdata_05 and (objs[0].xdata_05[0] == ""):
1.5 dwinter 826:
827: projects.append(objs)
828:
829: return projects
830:
831:
1.1 dwinter 832: manage_options = Folder.manage_options+(
1.47.2.71 dwinter 833: {'label':'Update personal homepages','action':'updatePersonalwww_html'},
1.47.2.30 dwinter 834: {'label':'Reindex catalogs','action':'reindexCatalogs'},
1.8 dwinter 835: {'label':'Main config','action':'changeMPIWGRootForm'},
1.47.2.71 dwinter 836: {'label':'add e-mails','action':'showNewDBEntries'},
837: {'label':'update the institutsbibliography','action':'updateInstitutsbiliography'},
1.47.2.30 dwinter 838: #{'label':'Edit Historical Persons','action':'editHistoricalPersonsForm'},
839: #{'label':'Store Historical Persons','action':'storeHistoricalPersons'},
1.1 dwinter 840: )
841:
842:
1.47.2.26 dwinter 843: def updatePublicationDB(self,personId=None):
1.47.2.71 dwinter 844: """updates the publication db, i.e. copy year and type into the main table"""
1.47.2.26 dwinter 845:
846: if personId:
1.47.2.71 dwinter 847: founds = self.ZSQLInlineSearch(_table="publications",key_main=personId)
1.47.2.26 dwinter 848: else:
849: founds = self.ZSQLInlineSearch(_table="publications")
850:
851: for found in founds:
1.47.2.30 dwinter 852:
853: if found.id_institutsbibliographie and (not found.id_institutsbibliographie =="") and (not found.id_institutsbibliographie =="0"):
854:
1.47.2.26 dwinter 855: entries = self.ZSQLInlineSearch(_table="institutsbiblio",id=found.id_institutsbibliographie)
856: for entry in entries:
1.47.2.27 dwinter 857: self.ZSQLChange(_table='publications',_identify='oid=%s' % found.oid,year=entry.year,referencetype=entry.reference_type)
1.47.2.26 dwinter 858:
859: if found.id_gen_bib and (not found.id_gen_bib ==""):
860: entries = self.ZSQLInlineSearch(_table="bibliography",id=found.id_gen_bib)
861: for entry in entries:
1.47.2.27 dwinter 862: self.ZSQLChange(_table='publications',_identify='oid=%s' % found.oid,year=entry.year,referencetype=entry.reference_type)
1.47.2.26 dwinter 863:
864: return True
1.47.2.71 dwinter 865:
866: def showNewDBEntries(self):
867: """zeige neue Eintraege in der Datenbank ohne e-mail adressen bzw. fuer die noch kein Object angelegt wurde"""
1.47.2.26 dwinter 868:
1.47.2.71 dwinter 869: qstr="select * from personal_www where web_object_created='no' and not key=''"
870: res=self.ZSQLQuery(qstr)
1.47.2.41 dwinter 871:
1.47.2.71 dwinter 872: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','showNewDBEntries.zpt')).__of__(self)
873: return pt(newEntries=res)
874:
1.47.2.72 dwinter 875: def createNewStaffObjects(self,RESPONSE):
1.47.2.71 dwinter 876: """create new staff object"""
877:
878: memberFolder=getattr(self,'members')
879: args=self.REQUEST.form
880: arg_k=args.keys()
881: arg_k.remove("submit")
882: ret=""
883: for key in arg_k:
884: k=self.urlUnQuote(key)
1.47.2.72 dwinter 885:
1.47.2.71 dwinter 886: qstr="select * from personal_www where key=%s"%self.ZSQLQuote(k)
887: res=self.ZSQLQuery(qstr)[0]
888: if args[key]!="": #email-adresse wurde eingetragen
889: #create the object
890: e_mail=args[key]
891: try:
1.47.2.75 casties 892: newObj=MPIWGStaff.MPIWGStaff(e_mail,res.last_name,res.first_name,k)
1.47.2.71 dwinter 893: memberFolder._setObject(e_mail,newObj)
1.47.2.72 dwinter 894: obj=getattr(memberFolder,e_mail)
895: obj.reindex_object()
1.47.2.71 dwinter 896: ret+="Created %s \n"%e_mail
897: created=True
898: except:
899: msg="Cannot create new user %s (%s %s)"%(e_mail,sys.exc_info()[0],sys.exc_info()[1])
900: logging.error(msg)
901: ret+=msg+"\n"
902: created=False
903:
904: if created:
1.47.2.78 casties 905: qstr="update personal_www set web_object_created='yes',e_mail='%s@mpiwg-berlin.mpg.de' where key=%s"%(e_mail,self.ZSQLQuote(k))
1.47.2.71 dwinter 906: self.ZSQLQuery(qstr)
1.47.2.72 dwinter 907:
1.47.2.71 dwinter 908: return ret
909:
1.47.2.28 dwinter 910:
1.47.2.71 dwinter 911: def generateNewPersonEntry(self,data):
912: """generate a new person entry for data, neue personen werden zunaechst nur in der datenbank angelegt """
1.47.2.28 dwinter 913:
1.47.2.71 dwinter 914: #memberFolder=getattr(self,'members')
915: #create the object
1.47.2.28 dwinter 916:
1.47.2.71 dwinter 917: # try:
918: # newObj=MPIWGStaff.MPIWGStaff(urllib.quote(data['key']),data['last_name'].encode('utf-8'),data['first_name'].encode('utf-8'))
919: # memberFolder._setObject(urllib.quote(data['key']),newObj)
920: # except:
921: # return False, "Cannot create new user %s (%s %s)"%(data['key'],sys.exc_info()[0],sys.exc_info()[1])
922: #
923:
924: #create the new entry in the database
925:
926:
927: result,msg=MPIWGStaff.createNewDBEntry(self,data['publish_the_data'],data['key'],data['last_name'],
928: data['first_name'],data['title'],data['status'],"",
929: "",data['date_from'],data['date_to'],
930: data['department'],data['home_inst'],data['funded_by'],
931: data['e_mail2'],data['current_work'],"yes",data['date_stay_at_mpiwg'],data['group'],"no",data['current_work'])
932:
933: return result,msg
934:
935: def updatePersonEntry(self,data,ignoreEntries=[]):
936: """update an person entry from data. but ignore all fields in ignore Entries"""
937:
938: ignoreEntries.append('current_work') # TODO:updatecurrent work
939:
940: if data['date_to']=="": # wenn date_to leer
941: data['date_to']="date_none"
942:
943: if data['date_from']=="": # wenn date_fromleer
944: data['date_from']="date_none"
945: msg=""
946:
947:
948: #eintragen
949:
950: columns=data.keys()
951: for x in ignoreEntries:
1.47.2.74 dwinter 952: logging.info("ign rem: %s"%x)
953: try: #falls in ignore entries felder sind, die nicht in columns sind, fange den fehler ab
954: columns.remove(x)
955: except:
956: pass
1.47.2.29 dwinter 957:
1.47.2.71 dwinter 958:
959: insert=[]
960: for key in columns:
961: if data[key]=="date_none": # date_none eintrag wird zu null uebersetzt
962: insert.append('%s=null'%key)
1.47.2.28 dwinter 963: else:
1.47.2.71 dwinter 964: insert.append(""" "%s"=%s"""%(key,self.ZSQLQuote(data[key])))
1.47.2.28 dwinter 965:
1.47.2.71 dwinter 966: insertStr=",".join(insert)
967: queryStr="update personal_www SET %s where key='%s'"%(insertStr,data['key'])
968: self.ZSQLQuery("SET DATESTYLE TO 'German'")
969: self.ZSQLQuery(queryStr)
970:
971: #currentwork
972: #if not (txt==""):
973: # queryStr="INSERT INTO current_work (id_main,current,publish) VALUES ('%s','%s','%s')"%(id,txt,txt_p)
974: #
975: # self.ZSQLQuery(queryStr)
976:
977: return True,msg
1.47.2.75 casties 978:
979:
1.47.2.71 dwinter 980: def updatePersonalwww_doIt(self):
981: """do the update"""
982: args=self.REQUEST.form
983: resultSet=self.REQUEST.SESSION['personal_www']['resultSet']
984: news=self.REQUEST.SESSION['personal_www']['news']
985: conflicts=self.REQUEST.SESSION['personal_www']['conflicts']
986: ret="<html><body>"
987: # generate the new entry
988:
989: if news and (len(news)>0):
1.47.2.75 casties 990: ret+="<h2>Hinzugefügt</h2>"
991: ret+="<p>Neueinträge erscheinen erst auf der Homepage, wenn ihnen eine e-mail Adresse zugeordnet wurde.</p>"
1.47.2.71 dwinter 992: ret+="<ul>"
993: for new in news:
994:
995: if args.has_key(self.urlQuote(new.encode('utf-8'))): # entry was selected
996: result,msg=self.generateNewPersonEntry(resultSet[new])
997: if not result:
998: logging.error("Error (generateNewPersonEntry) %s"%msg)
999: ret+="<li>ERROR: %s %s"%(new.encode('utf-8'),msg)
1000: else:
1001: ret+="<li>OK: %s"%(new.encode('utf-8'))
1002: if news and (len(news)>0):
1.47.2.75 casties 1003: ret+="<p>Neueinträge erscheinen erst auf der Homepage, wenn ihnen eine e-mail Adresse zugeordnet wurde.</p>"
1.47.2.71 dwinter 1004: ret+="</ul>"
1005:
1006: # update
1007:
1008: if len(conflicts.keys())>0:
1.47.2.75 casties 1009: ret+="<h2>Änderung des Benutzers übernehmen</h2>"
1010: ret+="<p>Wenn nötig in Filemaker-db ändern:</p>"
1.47.2.71 dwinter 1011:
1.47.2.74 dwinter 1012: # konflicte
1.47.2.71 dwinter 1013: for conflict in conflicts.keys():
1014: ignoreEntries=[]
1015: displayIgnored=[]
1016: for cf in conflicts[conflict]:
1017: if args[conflict.encode('utf-8')+'_'+cf[0]]=="stored": #use the stored one
1018: ignoreEntries.append(cf[0]) #so ignore field cf[0]
1019: displayIgnored.append(cf)
1020: if len(displayIgnored)>0:
1021: ret+="<h3>%s</h3>"%conflict.encode('utf-8')
1022:
1023: ret+="<table border='1'>"
1024: for iE in displayIgnored:
1025: 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'))
1026: ret+="</tabel>"
1027:
1028: self.updatePersonEntry(resultSet[conflict],ignoreEntries=ignoreEntries)
1.47.2.74 dwinter 1029:
1030: # rest
1031: cl=list(conflicts.keys())
1032:
1033: for key in resultSet.keys():
1034: if key not in cl:
1035: self.updatePersonEntry(resultSet[key])
1.47.2.71 dwinter 1036: return ret+"</body></html>"
1037:
1.47.2.75 casties 1038:
1.47.2.71 dwinter 1039: def updateInstitutsbiliography(self):
1040: """update the Institutsbibliogrpahy"""
1041: self.upDateSQL('personalwww.xml')
1042: return "<html><body>DONE</body></html>"
1.47.2.75 casties 1043:
1044:
1.47.2.71 dwinter 1045: def updatePersonalwww_html(self):
1046: """update form for the homepages web form"""
1047: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','updatePersonalwww.zpt')).__of__(self)
1048: return pt()
1.47.2.75 casties 1049:
1.47.2.30 dwinter 1050:
1.47.2.71 dwinter 1051: def updatePersonalwww(self,uploadfile):
1052: """update personalwww
1053: @param uploadfile: file handle auf das file
1054: """
1.47.2.73 dwinter 1055: dsn=self.getConnectionObj().connection_string
1056: #dsn="dbname=personalwww"
1.47.2.71 dwinter 1057: resultSet=updatePersonalWWW.importFMPXML(uploadfile)
1058: news,conflicts=updatePersonalWWW.checkImport(dsn, resultSet)
1059:
1060: self.REQUEST.SESSION['personal_www']={}
1061: self.REQUEST.SESSION['personal_www']['resultSet']=resultSet
1062: self.REQUEST.SESSION['personal_www']['news']=news
1063: self.REQUEST.SESSION['personal_www']['conflicts']=conflicts
1064:
1065: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','updatePersonalwww_check.zpt')).__of__(self)
1066: return pt()
1067:
1068:
1.47.2.30 dwinter 1069:
1070: def reindexCatalogs(self,RESPONSE=None):
1071: """reindex members and project catalog"""
1072:
1.47.2.26 dwinter 1073:
1.47.2.30 dwinter 1074: try:
1.47.2.72 dwinter 1075:
1.47.2.30 dwinter 1076: self.ProjectCatalog.manage_catalogReindex(self.REQUEST,RESPONSE,self.REQUEST['URL1'])
1077: except:
1.47.2.71 dwinter 1078: logger("MPIWG Root (updatehomepage)",logging.WARNING," %s %s"%sys.exc_info()[:2])
1.47.2.30 dwinter 1079:
1080:
1081:
1.47.2.48 dwinter 1082:
1.47.2.30 dwinter 1083:
1084: if RESPONSE:
1085: RESPONSE.redirect('manage_main')
1086:
1087:
1088:
1.3 dwinter 1089:
1.47.2.48 dwinter 1090: def getAllMembers(self):
1091: #ret=[]
1092:
1.47.2.83! dwinter 1093: def sorter(x,y):
! 1094: return cmp(x[0],y[0])
! 1095:
1.47.2.48 dwinter 1096: results=self.MembersCatalog({'isPublished':True})
1097:
1.47.2.83! dwinter 1098: ret=[(", ".join([proj.lastName, proj.firstName]).decode('utf-8'),proj.getKey) for proj in results]
1.47.2.48 dwinter 1099:
1.47.2.83! dwinter 1100: ret.sort(sorter)
1.3 dwinter 1101: return ret
1.47.2.83! dwinter 1102:
! 1103:
1.9 dwinter 1104: def printAllMembers(self):
1.47.2.50 dwinter 1105: """print"""
1.9 dwinter 1106: members=self.getAllMembers()
1107: ret=""
1108: for x in members:
1109: ret+="<p>%s</p>"%x
1110: return ret
1111:
1112:
1.5 dwinter 1113: def makeList(self,entry):
1114: """makes a list out of one entry or repeat a list"""
1115: if type(entry) is StringType:
1116: return [entry]
1117: else:
1118: return entry
1119:
1120:
1.47.2.80 dwinter 1121: def getTree(self,dep=None,date=None,onlyActive=0,onlyArchived=0):
1122: """generate Tree from project list
1123: als Liste, jeder Eintrag ist ein Tupel ,(Tiefe, ProjektNummer,ProjektObject
1124: onlyActive = 0 : alle Projekte
1125: onlyActive = 1 : nur active Projekte
1126: onlyActive = 2: nur inactive Projekte
1127:
1128: onlyArchived=0: alle Projekte
1129: onlyArchived= 1 : nur aktuelle Projekte
1130: onlyArchived = 2: nur archivierte Projekte
1131: """
1.47.2.20 dwinter 1132:
1.47.2.80 dwinter 1133: returnListTmp=[]
1.5 dwinter 1134: returnList=[]
1.47.2.80 dwinter 1135:
1.47.2.18 dwinter 1136: for project in self.getProjectFields('xdata_05',sort="int",date=date): # get Projects sorted by xdata_05
1.41 dwinter 1137:
1.5 dwinter 1138: for idNr in project[1].split(";"): # more than one number
1139: if not idNr=="":
1140: splittedId=idNr.split(".")
1141: depth=len(splittedId)
1142: nr=idNr
1.14 dwinter 1143: #title=project[0].WEB_title
1144: title=[project[0].getContent('WEB_title')]
1145: #print title
1.47.2.54 dwinter 1146:
1.47.2.65 casties 1147: if idNr[0]=="x": # kompatibilitaet mit alter Konvention, x vor der Nummer macht project inactive
1.47.2.54 dwinter 1148: project[0].setActiveFlag(False)
1149:
1.47.2.65 casties 1150: if (not dep) or (idNr[0]==dep): #falls dep gesetzt ist nur dieses hinzufuegen.
1.47.2.80 dwinter 1151:
1152: if (onlyActive==0):
1153: returnListTmp.append((depth,nr,title,project[0]))
1154: elif (onlyActive==1) and project[0].isActiveProject(): #nur active projekte
1155: returnListTmp.append((depth,nr,title,project[0]))
1156: elif (onlyActive==2) and (not project[0].isActiveProject()): #nur active projekte
1157: returnListTmp.append((depth,nr,title,project[0]))
1158:
1159:
1160: #filter jetzt die Liste nach Archived oder nicht
1161: for entry in returnListTmp:
1162: if (onlyArchived==0):
1163: returnList.append(entry)
1164: elif (onlyArchived==1) and (not entry[3].isArchivedProject()): #nur active projekte
1165: returnList.append(entry)
1166: elif (onlyArchived==2) and (entry[3].isArchivedProject()): #nur active projekte
1167: returnList.append(entry)
1168:
1169:
1.5 dwinter 1170: return returnList
1171:
1.33 casties 1172:
1.16 dwinter 1173:
1.5 dwinter 1174: def changePosition(self,treeId,select,RESPONSE=None):
1175: """Change Postion Entry"""
1176: numbers=[]
1177:
1178: # Suche hoechste bisherige nummer
1179: projects=self.getProjectFields('xdata_05') # get Projects sorted by xdata_05
1.8 dwinter 1180: #print "pj",projects
1.5 dwinter 1181: for project in projects: #suche alle subtrees der treeId
1182: #print treeId
1183:
1184: founds=re.match(treeId+"\.(.*)",project[1].split(";")[0])
1185: if founds:
1186: #print "x",founds.group(0),len(founds.group(0).split("."))
1187: if len(founds.group(0).split("."))==len(treeId.split("."))+1: # nur ein punkt mehr, d.h. untere ebene
1188: try:
1189: numbers.append(int(founds.group(0).split(".")[len(founds.group(0).split("."))-1]))
1190: except:
1.6 dwinter 1191: numbers.append(int(0))
1192:
1193: try:
1194: highest=max(numbers)
1195: except:
1196: highest=0
1.5 dwinter 1197: projects=self.showNewProjects()
1198: for i in self.makeList(select):
1199: highest+=10
1200: projects[int(i)][0].xdata_05=treeId+"."+str(highest)
1201:
1202:
1203: if RESPONSE is not None:
1204: RESPONSE.redirect('showTree')
1205:
1206: def changeTree(self,RESPONSE=None):
1207: """change the complete tree"""
1208: form=self.REQUEST.form
1209: hashList={}
1.47.2.80 dwinter 1210: onlyArchived=int(form.get("onlyArchived",0))
1211: onlyActive=int(form.get("onlyActive",0))
1212:
1213:
1214: fields=self.getTree(onlyArchived=onlyArchived,onlyActive=onlyActive)
1.5 dwinter 1215:
1.47.2.80 dwinter 1216: logging.info("GOT TREE!----------------------------------------------------")
1217: for field in form.keys():
1.47.2.54 dwinter 1218:
1.47.2.80 dwinter 1219: splitted=field.split('_')
1220: if (len(splitted)>1) and (splitted[1]=="runningNumber"): #feld hat die Form Nummer_name und runnignNumber
1.47.2.54 dwinter 1221:
1.47.2.80 dwinter 1222:
1223: nr=int(splitted[0]) # nummer des Datensatzes
1224: currentEntry = fields[nr]
1225:
1226: if form.has_key(str(nr)+'_active'): # active flag is set
1227: fields[nr][3].setActiveFlag(True)
1.47.2.54 dwinter 1228: else:
1.47.2.80 dwinter 1229: fields[nr][3].setActiveFlag(False)
1230:
1231: #nummer hat sich geŠndert
1232:
1233: entryChanged = False;
1234:
1235:
1236: if not (fields[nr][3].xdata_05==form[str(nr)+'_number']):
1237: logging.info("Changed!Number+++++++++++++++++++++++++++++++++")
1238: fields[nr][3].xdata_05=form[str(nr)+'_number']
1239: entryChanged = True
1240:
1241: #completed har sich geaendert
1242:
1243: if not (fields[nr][3].getCompletedAt()==fields[nr][3].transformDate(form[str(nr)+'_completed'])):
1244: fields[nr][3].setCompletedAt(form[str(nr)+'_completed'])
1245: logging.info("Changed!Completed+++++++++++++++++++++++++++++++++")
1246: entryChanged = True
1247:
1248:
1249: if entryChanged:
1250: logging.info("Changed!+++++++++++++++++++++++++++++++++")
1251: fields[nr][3].copyObjectToArchive()
1252:
1.47.2.54 dwinter 1253:
1.5 dwinter 1254: if RESPONSE is not None:
1255: RESPONSE.redirect('showTree')
1256:
1257: def getProjectWithId(self,id):
1258: fields=self.getProjectFields('xdata_05')
1259: for field in fields:
1260: if field[1]==id:
1261: return field[0]
1262:
1263: return None
1264:
1265:
1266:
1267:
1.15 dwinter 1268: def getRelativeUrlFromPerson(self,list):
1269: """get urls to person list"""
1270: ret=[]
1271: persons=list.split(";")
1272: for person in persons:
1273:
1274: if len(person)>1: #nicht nur Trennzeichen
1275: splitted=person.split(",")
1276: if len(splitted)==1:
1277: splitted=person.split(" ")
1278: splittedNew=[re.sub(r'\s(.*)','$1',split) for split in splitted]
1279: if splittedNew[0]=='':
1280: del splittedNew[0]
1281: search=string.join(splittedNew,' AND ')
1282:
1283: if not search=='':
1284:
1285: try:
1286: proj=self.MembersCatalog({'title':search})
1287: except:
1288: proj=None
1289:
1290: if proj:
1291: #ret.append("<a href=%s >%s</a>"%(proj[0].absolute_url,person.encode('utf-8')))
1.29 dwinter 1292: ret.append("<a href=%s >%s</a>"%('members/'+proj[0].id+'/index.html',person))
1.15 dwinter 1293: else:
1294: #ret.append("%s"%person.encode('utf-8'))
1295: ret.append("%s"%person)
1296: return string.join(ret,";")
1.5 dwinter 1297:
1.47.2.83! dwinter 1298: def getMemberIdFromKey(self,key):
! 1299: """gibt die ensprechende id im members Ordner zum key"""
! 1300:
! 1301: if key=="":
! 1302: return ""
! 1303: catalogged=self.MembersCatalog({'getKey':key})
! 1304: if len(catalogged)==0:
! 1305: return ""
! 1306: else:
! 1307: return catalogged[0].getObject().getId()
! 1308:
1.9 dwinter 1309:
1.47.2.83! dwinter 1310:
! 1311: # def getMembersFromList(self,list):
! 1312: # """get member names from person full text list"""
! 1313: # memberlist=[]
! 1314: # persons=list.split(";")
! 1315: # for person in persons:
! 1316: # if len(person)>1: #nicht nur Trennzeichen
! 1317: # splitted=person.split(",")
! 1318: # if len(splitted)==1:
! 1319: # splitted=person.lstrip().rstrip().split(" ")
! 1320: # splittedNew=[re.sub(r'\s(.*)','$1',split) for split in splitted]
! 1321: # if splittedNew[0]=='':
! 1322: # del splittedNew[0]
! 1323: # search=string.join(splittedNew,' AND ')
! 1324: #
! 1325: # if not search=='':
! 1326: # try:
! 1327: #
! 1328: # member=self.MembersCatalog({'title':search})
! 1329: #
! 1330: # except:
! 1331: # member=None
! 1332: # if member:
! 1333: # logging.error("search publ %s:"%member[0].getObject().isPublished())
! 1334: # if member and (member[0].getObject().isPublished()):
! 1335: # if person =="Otto Sibum" : person="H. Otto Sibum"
! 1336: # if person =="Norton Wise" : person="M. Norton Wise"
! 1337: #
! 1338: # #memberlist.append("<a href=%s >%s</a>"%(member[0].absolute_url,person.encode('utf-8')))
! 1339: # memberlist.append((person, member[0].getObject().getId()))
! 1340: # else:
! 1341: # #memberlist.append("%s"%person.encode('utf-8'))
! 1342: # memberlist.append((person,None))
! 1343: # return memberlist
1.3 dwinter 1344:
1.47.2.83! dwinter 1345: # def getUrlFromPerson(self,list):
! 1346: # """get urls to person list"""
! 1347: # ret=[]
! 1348: # persons=list.split(";")
! 1349: # for person in persons:
! 1350: #
! 1351: # if len(person)>1: #nicht nur Trennzeichen
! 1352: # splitted=person.split(",")
! 1353: # if len(splitted)==1:
! 1354: # splitted=person.lstrip().rstrip().split(" ")
! 1355: # splittedNew=[re.sub(r'\s(.*)','$1',split) for split in splitted]
! 1356: # if splittedNew[0]=='':
! 1357: # del splittedNew[0]
! 1358: # search=string.join(splittedNew,' AND ')
! 1359: #
! 1360: # if not search=='':
! 1361: #
! 1362: # try:
! 1363: # proj=self.MembersCatalog({'title':search})
! 1364: # except:
! 1365: # proj=None
! 1366: #
! 1367: # if proj and (proj[0].getObject().isPublished()):
! 1368: # if person =="Otto Sibum" : person="H. Otto Sibum"
! 1369: # if person =="Norton Wise" : person="M. Norton Wise"
! 1370: # #ret.append("<a href=%s >%s</a>"%(proj[0].absolute_url,person.encode('utf-8')))
! 1371: # if self.MPIWGrootURL().split("/")[-1]=='en':
! 1372: # tmpPath="/en/staff/members/"
! 1373: # else:
! 1374: # tmpPath="/de/mitarbeiter/members/"
! 1375: # ret.append("<a href=%s >%s</a>"%(tmpPath+proj[0].getObject().getId()+"/index.html",person))
! 1376: # else:
! 1377: # #ret.append("%s"%person.encode('utf-8'))
! 1378: # ret.append("%s"%person)
! 1379: # return string.join(ret,";")
! 1380: #
1.47.2.18 dwinter 1381: def getProjectsOfMembers(self,date=None):
1.3 dwinter 1382: """give tuple member /projects"""
1383: ret=[]
1384: members=self.getAllMembers()
1.47.2.48 dwinter 1385:
1.9 dwinter 1386: #return str(members)
1.3 dwinter 1387: for x in members:
1.47.2.83! dwinter 1388: projects=self.getProjectsOfMember(key=x[1],date=date)
! 1389: if len(projects)>0:
! 1390: ret.append((x[0],projects))
1.18 dwinter 1391:
1.3 dwinter 1392: return ret
1.11 dwinter 1393:
1.47.2.83! dwinter 1394: def getProjectsOfMember(self,key=None,date=None,onlyArchived=1,onlyActive=1):
1.47.2.71 dwinter 1395: """get projects of a member
1.47.2.83! dwinter 1396:
1.47.2.71 dwinter 1397: @param key: (optional) Key zur Idenfikation des Benutzer
1398: @param date: (optional) Version die zum Zeitpunkt date gueltig war
1.47.2.80 dwinter 1399: @param onlyArchived:
1400: onlyArchived=0: alle Projekte
1401: onlyArchived= 1 : nur aktuelle Projekte
1402: onlyArchived = 2: nur archivierte Projekte
1.47.2.71 dwinter 1403: """
1.47.2.75 casties 1404: # TODO: Die ganze Loesung
1.11 dwinter 1405: def sortP(x,y):
1406: """sort by sorting number"""
1.18 dwinter 1407: return cmp(x.WEB_title,y.WEB_title)
1.11 dwinter 1408:
1.47.2.80 dwinter 1409: ret=[]
1.47.2.83! dwinter 1410: if key:
! 1411: proj=self.ProjectCatalog({'getPersonKeyList':key})
1.47.2.71 dwinter 1412: else:
1.47.2.83! dwinter 1413: return ret # key muss definiert sein
1.47.2.71 dwinter 1414:
1.47.2.80 dwinter 1415:
1.11 dwinter 1416: if proj:
1.28 dwinter 1417: proj2=[]
1418: for x in proj:
1.47.2.83! dwinter 1419: if (not getattr(x.getObject(),'invisible',None)) and (getattr(x.getObject(),'archiveTime','')==''):
! 1420: proj2.append(x)
1.41 dwinter 1421:
1.18 dwinter 1422: else:
1423: proj2=[]
1424:
1.47.2.83! dwinter 1425:
! 1426:
1.18 dwinter 1427: proj2.sort(sortP)
1428:
1.47.2.80 dwinter 1429: projectListe=[]
1430:
1431: for proj in proj2:
1432: obj=proj.getObject()
1.47.2.82 dwinter 1433: add=False
1.47.2.80 dwinter 1434: if onlyArchived==1: #nur aktuell projecte
1435: if not obj.isArchivedProject():
1.47.2.82 dwinter 1436: add=True
1.47.2.80 dwinter 1437: elif onlyArchived==2: #nur archivierte
1438: if obj.isArchivedProject():
1.47.2.82 dwinter 1439: add=True
1.47.2.80 dwinter 1440: else: #alle
1.47.2.82 dwinter 1441: add=True
1442:
1443: if onlyActive==1: #nur active projecte
1444: if obj.isActiveProject():
1445: add=add & True
1446: else:
1447: add=add & False
1448:
1449: elif onlyArchived==2: #nur nicht aktvive
1450: if not obj.isActiveProject():
1451: add=add & True
1452: else: #alle
1453: add=add & True
1.47.2.80 dwinter 1454:
1.47.2.82 dwinter 1455: if add:
1.47.2.83! dwinter 1456: projectListe.append(obj)
1.47.2.80 dwinter 1457:
1.47.2.83! dwinter 1458:
! 1459: return projectListe
1.11 dwinter 1460:
1.1 dwinter 1461: def givePersonList(self,name):
1462: """check if person is in personfolder and return list of person objects"""
1.3 dwinter 1463:
1464: splitted=name.split(",")
1465: if len(splitted)==1:
1.26 dwinter 1466: splitted=name.lstrip().rstrip().split(" ")
1467: splittedNew=[split.lstrip() for split in splitted]
1468:
1.3 dwinter 1469: if splittedNew[0]=='':
1470: del splittedNew[0]
1471: search=string.join(splittedNew,' AND ')
1.47.2.54 dwinter 1472:
1.3 dwinter 1473: if not search=='':
1474: proj=self.MembersCatalog({'title':search})
1475:
1476: if proj:
1477: return [[x.lastName,x.firstName] for x in proj]
1478: else:
1479: return []
1480:
1481: ## splitted=name.split(",") # version nachname, vorname...
1482: ## if len(splitted)>1:
1483: ## lastName=splitted[0]
1484: ## firstName=splitted[1]
1485: ## else:
1486: ## splitted=name.split(" ") #version vorname irgenwas nachnamae
1487:
1488: ## lastName=splitted[len(splitted)-1]
1489: ## firstName=string.join(splitted[0:len(splitted)-1])
1490:
1491: ## objs=[]
1.1 dwinter 1492:
1.3 dwinter 1493: #print self.members
1494: ## for x in self.members.__dict__:
1495: ## obj=getattr(self.members,x)
1496: ## if hasattr(obj,'lastName') and hasattr(obj,'firstName'):
1.1 dwinter 1497:
1.3 dwinter 1498: ## if (re.match(".*"+obj.lastName+".*",lastName) or re.match(".*"+lastName+".*",obj.lastName)) and (re.match(".*"+obj.firstName+".*",firstName) or re.match(".*"+firstName+".*",obj.firstName)):
1.1 dwinter 1499:
1.3 dwinter 1500: ## objs.append((obj,lastName+", "+firstName))
1.1 dwinter 1501:
1.3 dwinter 1502:
1.47.2.71 dwinter 1503: ## return objs
1.1 dwinter 1504:
1505:
1506: def personCheck(self,names):
1507: """all persons for list"""
1.4 dwinter 1508: #print "names",names
1.1 dwinter 1509: splitted=names.split(";")
1510: ret={}
1511: for name in splitted:
1512:
1513: if not (name==""):
1.3 dwinter 1514: try:
1515: ret[name]=self.givePersonList(name)
1516: except:
1517: """NOTHIHN"""
1.4 dwinter 1518: #print "RET",ret
1.1 dwinter 1519: return ret
1520:
1521: def giveCheckList(self,person,fieldname):
1522: """return checklist"""
1523: #print "GCL",fieldname
1524: if fieldname=='xdata_01':
1525: x=self.personCheck(person.getContent(fieldname))
1.4 dwinter 1526: #print "GCLBACKX",x
1.1 dwinter 1527: return x
1528:
1529:
1530: def isCheckField(self,fieldname):
1531: """return chechfield"""
1532:
1533: return (fieldname in checkFields)
1534:
1.47.2.59 dwinter 1535:
1536: def generateNameIndex(self):
1537: """erzeuge einen index verwendeter personen"""
1.47.2.61 dwinter 1538: import psycopg
1.47.2.59 dwinter 1539: o = psycopg.connect('dbname=authorities user=dwinter password=3333',serialize=0)
1540: results={}
1541: print self.fulltext.historicalNames.items()
1542: for nameItem in self.fulltext.historicalNames.items(): #gehe durch alle namen des lexikons
1543:
1544: c = o.cursor()
1545: name=nameItem[0]
1546: print "check",name
1547: c.execute("select lastname,firstname from persons where lower(lastname) = '%s'"%quote(name))
1548: tmpres=c.fetchall()
1549: firstnames=[result[1] for result in tmpres] # find all firstnames
1550: if tmpres:
1551: lastname=tmpres[0][0]
1552:
1553: for found in self.fulltext({'names':name}):
1554: if found.getObject().isActual():
1555: for nh in found.getObject().getGetNeighbourhood(name, length=50,tagging=False): #hole umgebung
1556: #schaue nun ob der vorname hinter oder vor dem name ist
1557: position=nh.find(lastname)
1558: # vorher
1559: #print "NH",nh
1560: bevorS=nh[0:position].split()
1561: #print "BV",bevorS
1562: if len(bevorS)>1:
1563: try:
1564: bevor=[bevorS[-1],bevorS[-2]]
1565: except:
1566: bevor=[bevorS[0]]
1567: else:
1568: bevor=[]
1569: #nachher
1570: behindS= re.split("[,|;| ]",nh[position:])
1571: #print "BH",behindS
1572: if len(behindS)>2:
1573: try:
1574: behind=behindS[1:3]
1575: except:
1576: behind=[bevorS[1]]
1577: else:
1578: behind=[]
1579: for firstname in firstnames:
1580: if firstname in bevor+behind: #Namen wie mit Adelspraedikaten werden so erstmal nich gefunden
1581: id="%s,%s"%(lastname,firstname)
1582: if not results.has_key(id):
1583: results[id]=[]
1584: objId=found.getObject().getId()
1585: if not (objId in results[id]):
1.47.2.66 dwinter 1586: print "d %s for %s"%(id,objId)
1.47.2.59 dwinter 1587: results[id].append(objId)
1588: self.nameIndex=results
1589: return results
1590:
1.47.2.64 dwinter 1591: def editNameIndexHTML(self):
1592: """edit the name index"""
1593: if not hasattr(self,'nameIndexEdited'): # falls editierter index noch nicht existiert, kopiere automatisch erstellten
1594: self.nameIndexEdited=copy.copy(self.nameIndex)
1595: print "huh"
1596: #self.nameIndexEdited=copy.copy(self.nameIndex)
1597: #print self.nameIndexEdited
1598: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','editHistoricalNames.zpt')).__of__(self)
1599: return pt()
1600:
1601: def getNamesInProject(self,projectId):
1602: """get all names ofnameIndexEdited which are references in projec with projectId"""
1603:
1604: ret=[]
1605: for name in self.nameIndexEdited.keys():
1606: if projectId in self.nameIndexEdited[name]:
1607: ret.append(name)
1608:
1609: return ret
1610:
1611: def editNameIndex(self,RESPONSE=None,name=None,occurrances=None,submit=None):
1612: """edit the index"""
1613: nI=self.nameIndexEdited # mI introduced to make sure that changes to nameIndexEdited are know to ZODB
1614: if submit=="delete":
1615:
1616:
1617: dh=getattr(self,'deletedHistoricalNames',{})
1.47.2.70 dwinter 1618:
1619: if type(dh) is ListType:
1620: dh={}
1.47.2.64 dwinter 1621: if not dh.has_key(name):
1.47.2.70 dwinter 1622: dh[name]=occurrances.split("\n")
1.47.2.64 dwinter 1623: else:
1.47.2.70 dwinter 1624: dh[name]+=occurrances.split("\n")
1.47.2.64 dwinter 1625:
1626: self.deletedHistoricalNames=dh
1627:
1628: del self.nameIndexEdited[name]
1629:
1630:
1631: elif (submit=="change"):
1632:
1633: nI[name]=occurrances.split("\n")[0:]
1634:
1635: elif (submit=="add"):
1636: if not nI.has_key(name):
1637: nI[name]=occurrances.split("\n")
1638: else:
1639: nI[name]+=occurrances.split("\n")
1640:
1641: self.nameIndexEdited=nI
1642:
1643:
1644: if RESPONSE is not None:
1645: RESPONSE.redirect('editNameIndexHTML')
1646:
1647:
1648:
1649: def restoreIndex(self):
1650: """restore"""
1651: self.nameIndexEdited=self.nameIndex
1652: return "done"
1653:
1654:
1655:
1.1 dwinter 1656: def manage_addMPIWGRootForm(self):
1657: """form for adding the root"""
1.45 dwinter 1658: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addMPIWGRootForm.zpt')).__of__(self)
1.1 dwinter 1659: return pt()
1660:
1.45 dwinter 1661: def manage_addMPIWGRoot(self,id,title,connection_id="",RESPONSE=None):
1.1 dwinter 1662: """add a root folder"""
1663: newObj=MPIWGRoot(id,title)
1664: self._setObject(id,newObj)
1.45 dwinter 1665: ob=getattr(self,id)
1666: setattr(ob,'connection_id',connection_id)
1.1 dwinter 1667: if RESPONSE is not None:
1668: RESPONSE.redirect('manage_main')
1669:
1670:
1.47.2.22 dwinter 1671: class MPIWGProject_publication(SimpleItem):
1672: """publications object fuer project"""
1673:
1674: meta_type="MPIWGProject_publication"
1675:
1676: def editPublication(self,text=None,RESPONSE=None):
1677: """edit a publication"""
1678:
1679: if (not text):
1680: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_publicationForm.zpt')).__of__(self)
1681: return pt()
1682:
1683:
1684: self.text=text[0:]
1685:
1686: if RESPONSE:
1687: RESPONSE.redirect("../managePublications")
1688:
1689: class MPIWGProject_image(Image):
1690: """Images for Projects"""
1691:
1692: meta_type="MPIWGProject_image"
1693:
1694: def showImage(self,imageUrl=None):
1695: """show Images at an extra page"""
1696: self.getContent('WEB_project_description',filter='yes') #get the content and store image infos into session
1697: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','projectImageView.zpt')).__of__(self)
1698: return pt()
1699:
1700: def editImage(self,file=None,caption=None,RESPONSE=None):
1701: """edit the Image"""
1702: if (not file) and (not caption):
1703: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_imageForm.zpt')).__of__(self)
1704: return pt()
1705:
1706: if file and (not file.filename.lstrip().rstrip()==""):
1707: self.manage_upload(file)
1708:
1709: if caption:
1710: self.caption=caption[0:]
1711:
1712: if RESPONSE:
1713: RESPONSE.redirect("../manageImages")
1714:
1.45 dwinter 1715: class MPIWGProject(CatalogAware,Folder):
1.1 dwinter 1716: """Class for Projects"""
1.47.2.22 dwinter 1717:
1718:
1.47.2.21 dwinter 1719: security=ClassSecurityInfo()
1.1 dwinter 1720: meta_type='MPIWGProject'
1.45 dwinter 1721: default_catalog='ProjectCatalog'
1.47.2.22 dwinter 1722:
1.47.2.79 casties 1723: def decode(self,str):
1724: """return unicode object"""
1725: return unicodify(str)
1.47.2.57 dwinter 1726:
1.47.2.22 dwinter 1727: def sortedByPlace(self,metatype):
1728: """find metatype and sort by place"""
1729: def sort(x,y):
1730: return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0))
1731:
1732: founds=self.ZopeFind(self,obj_metatypes=[metatype]);
1733:
1734: founds.sort(sort)
1735:
1736: return founds
1.45 dwinter 1737:
1.47.2.22 dwinter 1738:
1739: def copyPublicationsToList(self,RESPONSE=None):
1740: """copy publications in to list"""
1741:
1742: publicationTxt=self.getContent('WEB_related_pub')
1743:
1744: pubSplits=publicationTxt.split("<p>")
1745:
1746: for pubSplit in pubSplits:
1747: pubSplit=pubSplit.replace("</p>","")
1748: self.addPublication(pubSplit)
1749:
1750: if RESPONSE:
1751: RESPONSE.redirect('managePublications')
1752:
1753:
1.47.2.47 dwinter 1754: def copyImageToMargin(self,RESPONSE=None):
1.47.2.22 dwinter 1755: """copy inline images to marginal images"""
1.47.2.47 dwinter 1756:
1757:
1758: #getImages from WEB_project_description
1759: description=self.getContent('WEB_project_description')
1760:
1761: text2=description
1762: splitted=text2.split("""<p class="picture">""")
1763:
1764: imageURLs=[]
1765: imageCaptions=[]
1766: for split in splitted[1:]:
1767: tmp=split.split("</p>")
1768: #return repr(splitted[1])
1.47.2.68 dwinter 1769:
1.47.2.47 dwinter 1770: try:
1771: imageURLs.append(tmp[0].split("\"")[1].encode('utf-8'))
1772: except:
1.47.2.68 dwinter 1773:
1774: try:
1.47.2.47 dwinter 1775: imageURLs.append(tmp[0].split("src=")[1].split(" ")[0].encode('utf-8'))
1.47.2.68 dwinter 1776: except:
1777: imageURLs.append("")
1.47.2.47 dwinter 1778:
1779: split2="</p>".join(tmp[1:])
1780:
1781:
1782: splitted=split2.split("""<p class="picturetitle">""")
1783: if len(splitted)>1:
1784: tmp=splitted[1].split("</p>")
1785: imageCaptions.append(tmp[0].encode('utf-8'))
1.47.2.22 dwinter 1786:
1787:
1.47.2.47 dwinter 1788: else:
1789: #keine caption
1790:
1791: imageCaptions.append("")
1.47.2.71 dwinter 1792:
1793:
1.47.2.47 dwinter 1794: #eintragen:
1795: for imageURL in imageURLs:
1796: filename=imageURL.split("/")[-1]
1797: #lege neues images object an, mit leerem bild
1798:
1799: if self.ZopeFind(self,obj_ids=[filename]):
1800: #existiert das bild schon, dann neuen filenamen
1801: filename="project_image_"+filename
1802:
1803: self.addImage(None,imageCaptions[imageURLs.index(imageURL)],filename=filename)
1804: #hole die bilddaten aus der url
1805: url=self.absolute_url()+"/"+imageURL
1806: #url=self.absolute_url()+"/"+filename
1807:
1808: try:#relative url
1809: data=urllib.urlopen(url).read()
1.47.2.34 dwinter 1810: except:
1.47.2.47 dwinter 1811: try:#absolute
1812: data=urllib.urlopen(self.imageURL).read()
1813: except:
1.47.2.71 dwinter 1814: logger("MPIWG Project",logging.ERROR,"can't open: %s"%url)
1.47.2.34 dwinter 1815:
1.47.2.47 dwinter 1816: obj=getattr(self,filename)
1817: obj.update_data(data)
1.47.2.22 dwinter 1818:
1819: if RESPONSE:
1820: RESPONSE.redirect('manageImages')
1821:
1822: def manageImages(self,imageName=None,op=None):
1823: """managage images"""
1824:
1825:
1826: if imageName and op:
1827: if op=='up':
1828: images=self.getImages()
1829: for image in images:
1830: if image[0]==imageName:
1831: nr=images.index(image)
1832: if not nr==0:
1833: images[nr-1][1].place+=1
1834: images[nr][1].place-=1
1835: pass
1836: elif op=='down':
1837: images=self.getImages()
1838: for image in images:
1839: if image[0]==imageName:
1840: nr=images.index(image)
1841: if not (nr==len(images)-1):
1842: images[nr+1][1].place-=1
1843: images[nr][1].place+=1
1844: pass
1845:
1846:
1847: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_manageImagesForm.zpt')).__of__(self)
1848: return pt()
1849:
1850: def managePublications(self,pubName=None,op=None):
1851: """managage images"""
1852:
1853:
1854: if pubName and op:
1855: if op=='up':
1856: publications=self.getPublications()
1857: for publication in publications:
1858: if publication[0]==pubName:
1859: nr=publications.index(publication)
1860: if not nr==0:
1861: publications[nr-1][1].place+=1
1862: publications[nr][1].place-=1
1863: pass
1864: elif op=='down':
1865: publications=self.getPublications()
1866: for publication in publications:
1867: if publication[0]==pubName:
1868: nr=publications.index(publication)
1869: if not (nr==len(publications)-1):
1870: publications[nr+1][1].place-=1
1871: publications[nr][1].place+=1
1872: pass
1873:
1874:
1875: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_managePublicationsForm.zpt')).__of__(self)
1876: return pt()
1877:
1878: def getPublications(self):
1879: """get all Publications"""
1880: def sort_images(x,y):
1881: return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0))
1.47.2.25 dwinter 1882:
1.47.2.22 dwinter 1883: publications=self.ZopeFind(self,obj_metatypes=['MPIWGProject_publication'])
1884:
1885: publications.sort(sort_images)
1886: return publications
1887:
1888: def addPublication(self,text,RESPONSE=None):
1889: """add an MPIWG_Publication"""
1890:
1891: name="publication_"+str(self.getLastPublicationNumber()+1)
1892:
1893: newPublication=MPIWGProject_publication(name)
1894:
1895: self._setObject(name,newPublication)
1896: obj=getattr(self,name)
1897: obj.text=text[0:]
1898: obj.enabled=True;
1899: obj.place=self.getLastPublicationNumber()+1
1900: obj.id=name
1901:
1902: if RESPONSE is not None:
1903: RESPONSE.redirect('managePublications')
1904:
1905:
1906: def getLastPublicationNumber(self):
1907: publications=self.getPublications()
1908:
1909: if not publications:
1910: return 0
1911: else:
1912: return getattr(publications[-1][1],'place',0)
1913:
1.47.2.70 dwinter 1914: def deletePublication(self,id,RESPONSE=None):
1.47.2.68 dwinter 1915: """delete Publication id"""
1916: self.manage_delObjects([id])
1917: if RESPONSE:
1918: RESPONSE.redirect('managePublications')
1919:
1.47.2.22 dwinter 1920: def getImages(self):
1921: """get all Images"""
1.47.2.68 dwinter 1922:
1.47.2.22 dwinter 1923: def sort_images(x,y):
1924: return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0))
1.47.2.25 dwinter 1925:
1.47.2.68 dwinter 1926:
1927: if (getattr(self,'imageURL','')!='') or (getattr(self,'imagecap','')!='') :
1928: try:
1929: self.addImage(None,getattr(self,'imagecap',''),RESPONSE=None,filename=getattr(self,'imageURL',''))
1930: except:
1931: pass
1932: self.imageURL=''
1933: self.imagecap=''
1934:
1.47.2.22 dwinter 1935: images=self.ZopeFind(self,obj_metatypes=['MPIWGProject_image'])
1936:
1937: images.sort(sort_images)
1938: return images
1939:
1940: def getLastImageNumber(self):
1941: images=self.getImages()
1942:
1943: if not images:
1944: return 0
1945: else:
1946: return getattr(images[-1][1],'place',0)
1947:
1948: def deleteImage(self,id,RESPONSE=None):
1949: """delete Image id"""
1950: self.manage_delObjects([id])
1951: if RESPONSE:
1952: RESPONSE.redirect('manageImages')
1953:
1.47.2.59 dwinter 1954:
1.47.2.80 dwinter 1955: def hasChildren(self,date=None,onlyActive=1,onlyArchived=1):
1.47.2.54 dwinter 1956: """check if project has children"""
1957: ct=self.getContexts(childs=self.getContent('xdata_05'),
1958: depth=1,date=date,onlyActive=onlyActive)
1959:
1960: if ct and len(ct)>0:
1961: return True
1962: else:
1963: return False
1.47.2.68 dwinter 1964:
1.47.2.54 dwinter 1965:
1.47.2.22 dwinter 1966: def addImage(self,fileHd,caption,RESPONSE=None,filename=None):
1967: """add an MPIWG_Project_image"""
1968:
1969: if not filename:
1970: filename=fileHd.filename
1971:
1972: if not fileHd:
1973: fileHd=file(os.path.join(package_home(globals()),'blank.gif'))
1974:
1975: newImage=MPIWGProject_image(filename,filename,fileHd)
1976:
1977: self._setObject(filename,newImage)
1978: obj=getattr(self,filename)
1979: obj.caption=caption[0:]
1980: obj.enabled=True;
1981: obj.place=self.getLastImageNumber()+1
1.47.2.68 dwinter 1982: obj.id=filename
1983:
1.47.2.22 dwinter 1984: if RESPONSE is not None:
1985: RESPONSE.redirect('manageImages')
1986:
1.45 dwinter 1987: def PrincipiaSearchSource(self):
1988: """Return cataloguable key for ourselves."""
1989: return str(self)
1.42 dwinter 1990:
1991: def versionHeader(self):
1992: """version Header, gibt header text entsprechend der aktuellen version aus"""
1993:
1994: actualTime=time.localtime()
1995: retTXT="""<h2>This is an outdated version, for the actual version please refer to <a href="%s">%s</a></h2>"""
1996: s=self.aq_parent.absolute_url()
1.43 dwinter 1997: #print getattr(self,'archiveTime',actualTime)
1.42 dwinter 1998: if getattr(self,'archiveTime',actualTime)< actualTime:
1999: return retTXT%(s,s)
2000: else:
2001: return ""
1.47.2.18 dwinter 2002:
2003: def getActualVersion(self,date=None):
2004: """actuelle version"""
2005: def sortProjectsByTime(x,y):
2006: return cmp(x[1].archiveTime,y[1].archiveTime)
2007:
2008: if not date:
2009: if self.isActual():
2010: return self
2011: else:
2012: return None
2013:
2014: #suche ob aeltere versionen vorhanden sind
2015:
2016: finds=self.ZopeFind(self,obj_metatypes=['MPIWGProject'])
2017: if not finds: #wenn nicht dann teste ob die aktuelle version schon existiert hat.
2018: ad=getattr(self,'creationTime','20050101000000')
2019: if int(date)>int(ad):
2020: return self
2021: else:
2022: return None
2023:
2024:
2025: else:
2026: finds.sort(sortProjectsByTime)
2027:
2028: for find in finds:
2029: #gehe durch die alten Projekte und finde das entprechende
2030: if (int(find[1].archiveTime) > int(date)) and (int(date)>int(getattr(find[1],'creationTime','20050101000000'))):
2031: return find[1]
2032:
2033: #kein passendes gefunden, dann teste ob das aktuelle in frage kommt
2034: ad=getattr(self,'creationTime','20050101000000')
2035:
2036: if int(date)>int(ad):
2037:
2038: return self
2039: else:
2040: return None
2041:
2042:
1.43 dwinter 2043: def isActual(self):
2044: """gibt 1 zurueck wenn aktuell, 0 sonst"""
2045: actualTime=time.localtime()
2046:
2047:
2048: #print getattr(self,'archiveTime',actualTime)
2049: if getattr(self,'archiveTime',actualTime)< actualTime:
2050: return 0
2051: else:
2052: return 1
1.42 dwinter 2053:
2054: def copyObjectToArchive(self):
2055: """kopiere aktuelles objekt ins archiv"""
2056: cb=self.aq_parent.manage_copyObjects(self.getId())
2057: self.manage_pasteObjects(cb)
2058: actualTime=time.localtime()
2059:
2060: self.manage_renameObject(self.getId(),self.getId()+"_"+time.strftime("%Y%m%d%H%M%S",actualTime))
2061: obj=getattr(self,self.getId()+"_"+time.strftime("%Y%m%d%H%M%S",actualTime))
2062: obj.setArchiveTime(time.strftime("%Y%m%d%H%M%S",actualTime))
2063: ids=[x[0] for x in self.ZopeFind(obj,obj_metatypes=['MPIWGProject'])]
2064: obj.manage_delObjects(ids)
2065:
2066: def setArchiveTime(self,time):
2067: """set Archive Time"""
2068: self.archiveTime=time[0:]
2069:
1.41 dwinter 2070: def versionManageForm(self):
2071: """version Manage form:currently only set to invisible"""
2072: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_versionManageForm.zpt')).__of__(self)
2073: return pt()
2074:
2075: def versionManage(self,invisible=None,RESPONSE=None):
2076: """version Manage form:currently only set to invisible"""
2077: self.invisible=invisible
2078:
2079: if RESPONSE is not None:
2080: RESPONSE.redirect('manage_main')
2081:
1.38 dwinter 2082:
1.3 dwinter 2083: def crossLinker(self):
2084: """experimental crosslinker"""
2085: splitted=self.WEB_project_description[0].split()
2086: new=[]
2087: for split in splitted:
2088: try:
2089: found=self.DescriptionCatalog({'fulltext':split})
2090:
2091: if len(found)>1:
2092:
2093: new.append("<a href=%s>%s</a>"%(split,split))
2094: else:
2095: new.append(split)
2096: except:
2097: new.append(split)
2098: return string.join(new)
2099:
2100:
2101:
1.1 dwinter 2102:
2103: def generateTemplate(self,RESPONSE=None):
1.47.2.65 casties 2104: """Erzeuge Template fuer defined fields not_used"""
1.1 dwinter 2105:
2106: id="index_html"
2107: title=id
2108: if self._getOb('index_html'):
2109: self._delObject('index_html')
2110:
2111:
2112: newObj=ZopePageTemplate(id,'TEXT')
2113: self._setObject(id,newObj)
2114: #self.manage_addPageTemplate(id,title)
2115: if RESPONSE is not None:
2116: RESPONSE.redirect('manage_main')
2117:
1.5 dwinter 2118: def __init__(self, id, argv=None):
1.47.2.18 dwinter 2119: """initiere classe"""
2120:
2121: self.creationTime=time.strftime("%Y%m%d%H%M%S",time.localtime())[0:]
1.1 dwinter 2122: self.id=id
2123: self.title=id
1.47.2.54 dwinter 2124: self.isActiveFlag=True #Flag is true is the project is still active, False if accomplished
1.47.2.83! dwinter 2125: self.responsibleScientistsList=[] # enthaelt die Lister der verantwortlichen Wissenschaftler in der Form (NAME, KEY), key ist "" flass Wissenschaftler nicht an unserem Haus
1.47.2.54 dwinter 2126:
1.5 dwinter 2127: if argv:
2128: for arg in definedFields:
1.47.2.25 dwinter 2129: try:
2130: setattr(self,arg,argv[arg])
2131: except:
2132: setattr(self,arg,"")
1.5 dwinter 2133: else:
2134: for arg in definedFields:
2135: setattr(self,arg,'')
1.1 dwinter 2136:
2137: manage_options = Folder.manage_options+(
2138: {'label':'Load New File','action':'loadNewFileForm'},
2139: {'label':'Edit ProjectInfo','action':'editMPIWGProjectForm'},
2140: {'label':'Edit BasisInfo','action':'editMPIWGBasisForm'},
2141: {'label':'Edit Publications','action':'editMPIWGRelatedPublicationsForm'},
1.9 dwinter 2142: {'label':'Edit Themes & Disciplines','action':'editMPIWGDisciplinesThemesForm'},
1.41 dwinter 2143: {'label':'Versionmanager','action':'versionManageForm'},
1.1 dwinter 2144: )
1.33 casties 2145:
2146:
1.47.2.54 dwinter 2147: def isActiveProject(self):
2148: """check if the project is still active, default is true, set to false is the project is accomplished"""
2149: return getattr(self,'isActiveFlag',True)
1.47.2.80 dwinter 2150:
2151: def isArchivedProject(self):
2152: """check if the project is archived"""
2153:
2154: completed=getattr(self,'completedAt',0)
2155:
2156: #completed leer
2157: if completed=="" :
2158: return False;
2159: if completed == 0:
2160: return False;
2161:
2162:
2163: return True
2164:
1.47.2.54 dwinter 2165:
2166: def setActiveFlag(self,status=True):
2167: """set the active flag"""
2168: self.isActiveFlag=status
2169:
1.47.2.80 dwinter 2170: def setCompletedAt(self,date):
2171: """set the date of completion, date should be in the form DD.MM.YYYY or MM.YYYY or YYYY"""
2172: logging.info("DATE:"+repr(date))
2173: transformedDate=self.transformDate(date);
2174: logging.info("transformed"+repr(transformedDate))
2175: if transformedDate is not None:
2176: setattr(self,"completedAt",transformedDate)
2177: return True;
2178: else:
2179: return False;
2180:
2181: def getCompletedAt(self):
2182: """gibt das transformierte Datum zurŸck"""
2183: date=getattr(self,'completedAt','')
2184: if date:
2185: return self.reTransformDate(date);
2186: else:
2187: return '';
2188:
2189: def reTransformDate(self,date):
2190: """transformiert , transformdate zurueck"""
2191: year=int(date/10000)
2192: month=int((date-year*10000)/100)
2193: day=int((date-year*10000-month*100))
2194: return """%s.%s.%s"""%(day,month,year);
2195:
2196:
2197: def transformDate(self,date):
2198: """transformiert ein Datum von DD.MM.YYYY, MM.YYYY,YYYY nach YYYYMMDD, alle nicht angebebenn Werte
2199: werden auf 0 gesetzt, es wird null zurŸckgegeben falls das Datum ungueltig ist"""
2200:
2201: if (date=="" ) :
2202: return "";
2203:
2204: if (date==None):
2205: return None;
2206:
2207: splitted=date.split(".")
2208: length=len(splitted)
2209: year=0
2210: month=0
2211: day=0
2212: if length > 3:
2213: return "";
2214: if length==3:
2215: day = int(splitted[0])
2216: if length>1:
2217: month=int(splitted[length-2])
2218:
2219: if length > 0:
2220: try:
2221: year = int(splitted[length-1])
2222: except:
2223: pass
2224:
2225: ## logging.info("month:"+(month))
2226: if not (0<=month<13):
2227: return None;
2228:
2229: if not(0<=day<32):
2230: return None;
2231:
2232: if (year>0) and (year<1900): #jahr nicht vierstellig eingegeben
2233: year=2000+year;
2234: return year*10000+month*100+day
2235:
2236:
2237:
1.42 dwinter 2238: def checkDate(self,date):
2239: """teste ob zum Zeitpunkt date eine andere version existierte"""
2240:
2241:
2242: def sortProjectsByTime(x,y):
2243: return cmp(x[1].archiveTime,y[1].archiveTime)
1.47.2.18 dwinter 2244:
2245: #suche ob aeltere versionen vorhanden sind
2246:
1.42 dwinter 2247: finds=self.ZopeFind(self,obj_metatypes=['MPIWGProject'])
1.47.2.18 dwinter 2248: if not finds: #wenn nicht dann teste ob die aktuelle version schon existiert hat.
2249: ad=getattr(self,'creationTime','20050101000000')
2250: if int(date)>int(ad):
2251: return self.REQUEST['URL1']+"/"+self.getId()
2252: else:
2253: return self.REQUEST['URL1']+"/no_project"
2254:
2255:
1.42 dwinter 2256: else:
2257: finds.sort(sortProjectsByTime)
2258:
2259: for find in finds:
1.47.2.18 dwinter 2260: #gehe durch die alten Projekte und finde das entprechende
2261: if (int(find[1].archiveTime) > int(date)) and (int(date)>int(getattr(find[1],'creationTime','20050101000000'))):
2262: return self.REQUEST['URL1']+"/"+find[1].getId()
1.42 dwinter 2263:
1.47.2.18 dwinter 2264: #kein passendes gefunden, dann teste ob das aktuelle in frage kommt
2265: ad=getattr(self,'creationTime','20050101000000')
2266:
2267: if int(date)>int(ad):
2268:
2269: return self.REQUEST['URL1']+"/"+self.getId()
2270: else:
2271: return self.REQUEST['URL1']+"/no_project"
1.42 dwinter 2272:
2273:
1.47.2.18 dwinter 2274: def no_project(self):
2275: """warnung: project noch nicht existent"""
2276: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','no_project')).__of__(self)
2277: return pt()
1.47.2.55 dwinter 2278:
1.47.2.59 dwinter 2279: def getGetNeighbourhood(self,wordStr, length=100,tagging=True):
1.47.2.65 casties 2280: """finde umgebung um die worte in wordStr, zurueckgegeben wird eine Array mit den Umgebungen von Fundstellen der Worte
1.47.2.55 dwinter 2281: alle Tags werden entfernt, die Fundstellen werden mit <span class="found">XX</span> getaggt, die Umgebungen werden
2282: case insensitive gesucht
2283: @param wordStr: string mit Worten getrennt durch Leerzeichen, Phrasen sind mit " gekennzeichnet
2284: "eine phrase", "*" bezeichnet wildcards und wird ignoriert"
1.47.2.65 casties 2285: @param length: optional, default wert 100, 2*length ist die groesse der Umgebung
1.47.2.59 dwinter 2286: @param tagging: optional default wert true, kein span tag wird erzweugt falls tag=false
1.47.2.55 dwinter 2287: """
2288:
1.47.2.65 casties 2289: ret=[] # nimmt das Array auf, dass spaeter zurueckgegeben wird
1.47.2.55 dwinter 2290: ranges=[] #Array mit tupeln x,y wobei x die Position des Anfang und y des Endes der i-ten Umgebung angiebt
2291:
2292: def isInRanges(nr,length):
1.47.2.65 casties 2293: """test ob eine gegeben Position nr schon irgendwo in einer Umgebung ist, gibt den Index des ersten Wertes aus ranges zurueck,
1.47.2.55 dwinter 2294: -1, wenn kein Treffer
2295:
1.47.2.65 casties 2296: @param nr: Position die geprueft werden soll
2297: @param length: Laenge des Wortes das geprueft werden soll
1.47.2.55 dwinter 2298: """
2299: for x in ranges:
2300: if (x[0]<=nr) and (nr < (x[1]-length)):
2301: return ranges.index(x)
2302: return -1
2303:
2304: # deal with phrases, in Phrasen werden die Leerzeichen durch "_" ersetzt.
2305: def rep_empty(str):
2306: x= re.sub(" ","_",str.group(0))
2307: return re.sub("\"","",x)
2308:
2309: wordStr=re.sub("\".*?\"", rep_empty,wordStr)#ersetze leerzeichen in " " durch "_" und loesche "
2310:
2311: #deal with wildcards, for our purposes it is enough to delete the wildcard
2312: wordStr=wordStr.replace("*","")
2313:
2314: words=wordStr.split(" ")
2315: #if not words is ListType:
2316: # words=[words]
2317:
2318: txt=self.harvest_page()
1.47.2.59 dwinter 2319: if not txt:
2320: return ret
1.47.2.55 dwinter 2321: txt=re.sub("<.*?>", "", txt) # loesche alle Tags
2322: for word in words:
2323: word=re.sub("_"," ",word) # ersetze zurueck "_" durch " "
2324: pos=0
2325:
2326: n=txt.lower().count(word.lower()) # wie oft tritt das Wort auf
2327:
2328: for i in range(n):
2329: pos=txt.lower().find(word.lower(),pos)
2330:
2331: if pos > 0:
2332: x=max(0,pos-length)
2333: y=min(len(txt),pos+length)
2334:
2335:
2336: #is word already in one of the results
2337: nr=isInRanges(pos,len(word))
1.47.2.65 casties 2338: if nr >=0:# word ist in einer schon gefunden Umgebung, dann vergroessere diese
1.47.2.55 dwinter 2339: x=min(ranges[nr][0],x)
2340: y=max(ranges[nr][1],y)
2341:
2342: str=txt[x:y]
2343:
2344: if nr >=0: # word ist in einer schon gefunden Umgebung
2345: ranges[nr]=(x,y) # neue Position der Umgebung
2346:
2347: ret[nr]=str # neue Umgebung
1.47.2.65 casties 2348: else: # andernfalls neue Umgebung hinzufuegen
1.47.2.55 dwinter 2349: ranges.append((x,y))
2350:
2351: ret.append(str)
2352:
2353: pos=pos+len(word)
2354: else:
2355: break;
2356:
2357: # now highlight everything
1.47.2.59 dwinter 2358: if tagging:
2359: for x in range(len(ret)):
2360: for word in words:
2361: repl=re.compile(word,re.IGNORECASE)
2362: ret[x]=repl.sub(""" <span class="found">%s</span>"""%word.upper(),ret[x])
1.47.2.55 dwinter 2363:
2364: return ret
2365:
2366: def harvest_page(self,context=None):
2367: """seite fuer harvesting fuer die Projektsuche"""
2368: if not context:
2369: context=self
2370:
2371: if self.isActiveProject() and self.isActual():
2372: ext=getattr(self,"harvest_main",None)
2373: if ext:
2374: return getattr(self,ext.getId())()
2375:
2376: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','harvest_main')).__of__(context)
2377:
2378:
2379: return pt()
2380:
1.47.2.20 dwinter 2381: def index_html(self,request=True,context=None):
1.33 casties 2382: """show homepage"""
1.47.2.20 dwinter 2383: if not context:
2384: context=self
2385: if request:
2386: if self.REQUEST.has_key('date') and self.REQUEST.SESSION.get('MPI_redirected',None)==None:
2387: self.REQUEST.SESSION['MPI_redirected']=1
2388: self.REQUEST.RESPONSE.redirect(self.checkDate(self.REQUEST['date'])+"?date="+self.REQUEST['date'])
2389: else:
2390: self.REQUEST.SESSION['MPI_redirected']=None
1.42 dwinter 2391:
1.47.2.25 dwinter 2392: #ext=self.ZopeFind(self.aq_parent,obj_ids=["project_main"])
1.47.2.18 dwinter 2393: ext=getattr(self,"project_main",None)
1.33 casties 2394: if ext:
1.47.2.18 dwinter 2395: return getattr(self,ext.getId())()
1.33 casties 2396:
1.47.2.20 dwinter 2397: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','project_main')).__of__(context)
2398:
1.33 casties 2399: return pt()
1.1 dwinter 2400:
1.38 dwinter 2401:
1.1 dwinter 2402: def getDataFields(self):
2403: """giveListofDatafields"""
2404: ret=[]
2405: for x in range(1,14):
1.17 dwinter 2406: if not x in [6,10,9]: # not used fields
2407: ret.append('xdata_%02i'%x)
1.1 dwinter 2408: return ret
2409:
2410: def getDefinedFields(self):
2411: """show all defined fields"""
2412:
2413: return definedFields
2414:
2415: def getAttribute(self,field):
2416: """get attrbiute"""
2417: return getattr(self,field)
2418:
1.47.2.4 dwinter 2419: def getContent(self,field,filter=None):
1.1 dwinter 2420: """Inhalt des Feldes"""
2421:
2422: text=u''
1.46 dwinter 2423:
1.1 dwinter 2424: for x in getattr(self,field):
2425:
2426: try:
1.46 dwinter 2427: text +=x
1.1 dwinter 2428: except:
1.46 dwinter 2429: text = x
2430:
1.9 dwinter 2431:
1.46 dwinter 2432:
1.9 dwinter 2433: try:
2434: if text[len(text)-1]==";":
1.21 dwinter 2435: text=text[0:len(text)-1]
2436:
2437:
1.9 dwinter 2438: except:
1.46 dwinter 2439: pass
2440:
2441: if text=='':
2442: text2=text
2443: else:
2444: text2=re.sub(r';([^\s])','; \g<1>',text)
1.16 dwinter 2445:
1.30 dwinter 2446: #teste ob ergebnis leer und header dann nehme title
2447:
2448: if (text2=='') and (field=='WEB_project_header'):
2449: return self.getContent('WEB_title')
2450:
1.47.2.4 dwinter 2451: if filter:
2452: splitted=text2.split("""<p class="picture">""")
1.47.2.5 dwinter 2453: if len(splitted)>1:
2454: tmp=splitted[1].split("</p>")
1.47.2.25 dwinter 2455: #return repr(splitted[1])
1.47.2.10 dwinter 2456: try:
1.47.2.25 dwinter 2457: self.imageURL=tmp[0].split("\"")[1].encode('utf-8')
2458: except:
1.47.2.68 dwinter 2459: try:
1.47.2.25 dwinter 2460: self.imageURL=tmp[0].split("src=")[1].split(" ")[0].encode('utf-8')
1.47.2.68 dwinter 2461: except:
2462: self.imageURL=""
2463:
1.47.2.5 dwinter 2464: split2="</p>".join(tmp[1:])
2465:
2466: text3=splitted[0]+split2
2467:
2468: splitted=text3.split("""<p class="picturetitle">""")
2469: if len(splitted)>1:
2470: tmp=splitted[1].split("</p>")
1.47.2.25 dwinter 2471: self.imagecap=tmp[0].encode('utf-8')
1.47.2.11 dwinter 2472:
1.47.2.5 dwinter 2473: split4="".join(tmp[1:])
1.47.2.4 dwinter 2474:
1.47.2.5 dwinter 2475: text5=splitted[0]+split4
2476: else:
2477: #keine caption
2478: text5=text3
2479: else:
2480: #kein bild
2481: text5=text2
1.47.2.4 dwinter 2482: else:
2483: text5=text2
2484:
1.47.2.65 casties 2485: #teste ob WEB_project_description und keine fuehrenden p tags
1.47.2.4 dwinter 2486: if (len(text5)>4) and (not text5[0:3]=='<p>') and (field=='WEB_project_description'):
1.47.2.11 dwinter 2487: text5= "<p>"+text5+"</p>"
1.46 dwinter 2488:
2489:
1.47.2.4 dwinter 2490: #filter image
2491:
1.47.2.68 dwinter 2492: text5=text5.lstrip().rstrip() #loescher leerzeichen und einzelndes br
2493: if (text5=="<br>") or (text5=="<br/>"):
2494: text5=""
1.47.2.11 dwinter 2495:
1.47.2.79 casties 2496: logging.debug("getcontent: field=%s filter=%s -> %s"%(field,filter,repr(text5)))
2497: #return unicodify(text5)
2498: return utf8ify(text5) # return as utf-8 byte string
2499:
1.47.2.9 dwinter 2500:
2501: def showImagesOfPage(self,imageUrl=None):
2502: """show Images of project"""
2503: self.getContent('WEB_project_description',filter='yes') #get the content and store image infos into session
2504: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','projectImageView.zpt')).__of__(self)
2505: return pt()
2506:
1.47.2.22 dwinter 2507:
1.1 dwinter 2508: def show_html(self):
2509: """simple index"""
2510: #return "HI"
1.45 dwinter 2511: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_index.zpt')).__of__(self)
1.1 dwinter 2512: return pt()
2513:
1.47.2.20 dwinter 2514: def saveFromPreview(self):
2515: """save content aus preview"""
2516: self.WEB_project_description=self.previewTemplate.WEB_project_description[0:]
2517: self.REQUEST.RESPONSE.redirect("./index.html")
2518:
2519: def saveEditedContent(self,kupu=None,preview=None):
2520: """save Edited content"""
2521:
1.47.2.23 dwinter 2522: if preview:
2523: kupu=preview
1.47.2.20 dwinter 2524: #find content of body tags
2525: start=kupu.find("<body>")
2526: end=kupu.find("</body>")
2527: newcontent= kupu[start+6:end]
1.47.2.43 dwinter 2528:
1.47.2.20 dwinter 2529: if preview:
1.47.2.23 dwinter 2530:
1.47.2.20 dwinter 2531: return self.preview(newcontent)
2532:
1.47.2.23 dwinter 2533: self.copyObjectToArchive()
1.47.2.20 dwinter 2534: self.WEB_project_description=newcontent[0:]
2535:
1.47.2.23 dwinter 2536: self.REQUEST.RESPONSE.redirect("./index.html")
1.47.2.20 dwinter 2537:
2538: return True
1.47.2.21 dwinter 2539:
1.47.2.33 dwinter 2540: security.declareProtected('View management screens','edit')
1.47.2.24 dwinter 2541: def edit(self,western=None):
1.47.2.20 dwinter 2542: """Edit pages"""
1.47.2.24 dwinter 2543: if western:
2544: self.REQUEST.RESPONSE.setCookie("MP_debug_code","western",path="/")
2545:
2546:
1.47.2.20 dwinter 2547: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGProjectNeu.zpt')).__of__(self)
2548: return pt()
1.47.2.36 casties 2549:
2550: edit_MPIWGProject_main = PageTemplateFile('zpt/edit_MPIWGProject_main', globals())
2551:
2552: def getPathStyle(self, path, selected, style=""):
2553: """returns a string with the given style + 'sel' if path == selected."""
2554:
2555: if path == selected:
2556: return style + 'sel'
2557: else:
2558: return style
1.47.2.20 dwinter 2559:
2560: def preview(self,description):
2561: """preview"""
2562: tmpPro=getattr(self,"previewTemplate",None)
2563: if not tmpPro:
2564: tmpPro=MPIWGProject("previewTemplate")
2565: self._setObject("previewTemplate",tmpPro)
2566: for field in definedFields:
2567: setattr(tmpPro,field,getattr(self,field))
2568: tmpPro.WEB_project_description=description[0:]
1.47.2.37 dwinter 2569: tmpPro.invisible=True
1.47.2.20 dwinter 2570: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','previewFrame.zpt')).__of__(self)
2571: return pt()
2572:
2573: #return self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+"/previewTemplate")
2574:
2575:
2576: def getWebProject_description(self):
2577: """get description"""
1.47.2.24 dwinter 2578: debug= self.REQUEST.cookies.get("MP_debug_code",None)
1.47.2.20 dwinter 2579:
1.47.2.24 dwinter 2580: if debug and debug=="western":
1.47.2.23 dwinter 2581: return """
2582: <html>
2583: <head>
2584: <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
2585: </head>
2586: <body>%s
2587: </html></body>
1.47.2.24 dwinter 2588: """%self.WEB_project_description[0]
2589:
2590: return """
2591: <html>
2592: <head>
2593: <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
2594: </head>
2595: <body>%s
2596: </html></body>
1.47.2.23 dwinter 2597: """%self.getContent('WEB_project_description')
1.47.2.24 dwinter 2598:
1.47.2.20 dwinter 2599:
2600:
1.1 dwinter 2601: def editMPIWGProjectForm(self):
2602: """editform"""
1.45 dwinter 2603: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGProject.zpt')).__of__(self)
1.1 dwinter 2604: return pt()
2605:
1.47.2.83! dwinter 2606: def isResponsibleScientist(self,key):
! 2607: """teste ob eine Person in der Liste der respl. scientists auftaucht"""
! 2608: #logging.info("XXXXXXXXXXXXX"+repr(self.responsibleScientistsList))
! 2609:
! 2610:
! 2611: keys = [x[1] for x in getattr(self,"responsibleScientistsList",[])]
! 2612:
! 2613: if key in keys:
! 2614: return True
! 2615: else:
! 2616: return False
! 2617:
! 2618: def getPersonKeyList(self):
! 2619: """gibt die key Lister der beteiligten Personen zurŸck"""
! 2620: return [x[1] for x in getattr(self,'responsibleScientistsList',[])]
! 2621:
! 2622:
! 2623:
! 2624:
! 2625: def identifyNames(self,nameList):
! 2626: """Bekommt eine Komma oder Semikolon getrennte Liste mit Name der Form Vorname MittelName(n) Nachname
! 2627: und ordnet diese dann Mitarbeiter IDs zu falls es schone eine Liste gibt wird im Projekte gibt wird diese Upgedated.
! 2628: @param nameList
! 2629: """
! 2630: nameList=nameList.replace(";",",") # falls ; als Trenner ersetze
! 2631: names=nameList.split(",")
! 2632:
! 2633: returnNamesDict={}
! 2634:
! 2635:
! 2636: for name in names:
! 2637: name=name.lstrip().rstrip()
! 2638: nameSplitted = name.split(" ")
! 2639: if len(nameSplitted)>1: #vor und nachname angegeben)
! 2640:
! 2641: lastname=nameSplitted[-1]
! 2642: firstname=nameSplitted[0]
! 2643: else:
! 2644: firstname =""
! 2645: lastname=nameSplitted[0]
! 2646:
! 2647: #finde Mitarbeiter mit den entsprechenden Name
! 2648: logging.info("Search: %s %s %s"%(name,firstname,lastname))
! 2649: cataloggedNames=self.MembersCatalog(firstName=firstname,lastName=lastname)
! 2650:
! 2651: #Teste ob die ensprechenden Namen schon der Liste zu geordnet sind
! 2652: #if not hasattr(self,'responsibleScientistsList'):
! 2653: # self.responsibleScientistsList={}
! 2654: #
! 2655: # if name in self.responsibleScientistsList.values()
! 2656:
! 2657: if len(cataloggedNames)>0:
! 2658: returnNamesDict[name]=cataloggedNames
! 2659: else:
! 2660: returnNamesDict[name]=[]
! 2661:
! 2662: return returnNamesDict
! 2663:
1.47.2.20 dwinter 2664: def editMPIWGProject(self,RESPONSE=None,fromEdit=None):
1.42 dwinter 2665: """edit the project and archive the old version"""
2666:
2667: self.copyObjectToArchive() # archive the object
2668:
1.22 dwinter 2669:
1.1 dwinter 2670: for x in definedFields:
2671: if self.REQUEST.has_key(x):
2672:
1.9 dwinter 2673: setattr(self,x,[self.REQUEST[x].decode('utf-8')])
1.42 dwinter 2674:
1.47.2.83! dwinter 2675:
! 2676:
1.47.2.67 casties 2677:
1.47.2.80 dwinter 2678: completedAt = self.REQUEST.get('completedAt')
2679: if not self.setCompletedAt(completedAt):
2680: RESPONSE.redirect('./editMPIWGBasisEditor?error="dateWrong')
2681:
1.47.2.67 casties 2682: if self.REQUEST.has_key('historicalNames'):
2683: self.en.changeHistoricalNames(self.getId(),self.REQUEST['historicalNames'].split("\n"))
1.47.2.64 dwinter 2684:
1.47.2.54 dwinter 2685: if self.REQUEST.has_key('active'):
2686: self.setActiveFlag(True)
2687: else:
2688: self.setActiveFlag(False)
1.47.2.83! dwinter 2689:
! 2690: self.responsibleScientistsList=[] # setze die Liste der verantwortlichen Wissenschaftler zurueck
! 2691:
! 2692: names={}
! 2693: keys={}
! 2694: tmpList=[]
! 2695: for key in self.REQUEST.keys(): #gehe durch das Formular
! 2696: splitted=key.split("_")
! 2697: if splitted[0]=="responsibleScientist": #wenn es ein Feld der Form reponsibleScientist_nr_KEY gibt
! 2698: nr=splitted[2]
! 2699: if splitted[1]=="name":
! 2700: names[nr]=self.REQUEST[key]
! 2701: elif splitted[1]=="key":
! 2702: keys[nr]=self.REQUEST[key]
! 2703:
! 2704:
! 2705: for nr in names.keys():
! 2706: tmpList.append((names[nr],keys.get(nr,"")))
! 2707:
! 2708: self.responsibleScientistsList=tmpList
1.47.2.20 dwinter 2709: if fromEdit and (RESPONSE is not None):
1.47.2.83! dwinter 2710: #RESPONSE.redirect('./editMPIWGBasisEditor')
! 2711: return self.editMPIWGBasisEditor(identifiedNames=self.identifyNames(self.REQUEST.get('xdata_01','')))
! 2712:
1.47.2.20 dwinter 2713: else:
2714: if RESPONSE is not None:
2715: RESPONSE.redirect('manage_main')
1.1 dwinter 2716:
1.47.2.20 dwinter 2717:
1.47.2.21 dwinter 2718:
2719: security.declareProtected('View managment screens','editMPIWGDisciplinesThemesEditor')
1.47.2.20 dwinter 2720: def editMPIWGDisciplinesThemesEditor(self):
2721: """edit from edit"""
2722: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGDisciplinesThemesNeu.zpt')).__of__(self)
2723: return pt()
2724:
2725:
1.9 dwinter 2726: def editMPIWGDisciplinesThemesForm(self):
2727: """edit the disciplines and themes Form"""
1.47.2.20 dwinter 2728:
1.45 dwinter 2729: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGDisciplinesThemes.zpt')).__of__(self)
1.9 dwinter 2730: return pt()
2731:
1.47.2.20 dwinter 2732: def editMPIWGDisciplinesThemes(self,disciplines=None,themes=None,RESPONSE=None,fromEdit=None):
1.9 dwinter 2733: """edit disciplin and form"""
2734: if disciplines:
2735: if type(disciplines) is StringType:
2736: self.xdata_09=disciplines
2737: else:
2738: self.xdata_09=string.join(disciplines,";")
2739: else:
2740: self.xdata_09=""
2741: if themes:
2742: if type(themes) is StringType:
2743: self.xdata_10=themes
2744: else:
2745: self.xdata_10=string.join(themes,";")
2746: else:
2747: self.xdata_10=""
1.47.2.20 dwinter 2748:
2749: if fromEdit and (RESPONSE is not None):
2750: RESPONSE.redirect('./editMPIWGDisciplinesThemesEditor')
2751:
2752: else:
2753: if RESPONSE is not None:
2754: RESPONSE.redirect('manage_main')
1.9 dwinter 2755:
2756:
2757: def isChecked(self,wert,list):
2758: """check if wert is in ; seperated list"""
1.46 dwinter 2759:
1.9 dwinter 2760: #felder sind manchmnal als liste mit einem element definiert
2761: if type(list) is StringType or UnicodeType:
2762: splitted=list.split(";")
2763: else:
2764: splitted=list[0].split(";")
2765:
1.47.2.12 dwinter 2766: splitted=[y.rstrip().lstrip() for y in splitted]
2767:
1.9 dwinter 2768: for x in splitted:
1.47.2.35 dwinter 2769: x=re.sub(r"[^A-z ]","",x)
1.9 dwinter 2770: if (not x==u'') and x in wert:
2771: return 1
2772: return 0
1.47.2.20 dwinter 2773:
1.47.2.21 dwinter 2774: security.declareProtected('View management screens','editMPIWGBasisEditor')
1.47.2.83! dwinter 2775: def editMPIWGBasisEditor(self, identifiedNames=None):
! 2776:
1.47.2.20 dwinter 2777: """editform"""
1.47.2.83! dwinter 2778: if not identifiedNames:
! 2779: identifiedNames=self.identifyNames(self.getContent('xdata_01'))
! 2780: # identifiedNames=self.getFullNameEntries()
! 2781:
1.47.2.20 dwinter 2782: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGBasisNeu.zpt')).__of__(self)
1.47.2.83! dwinter 2783: return pt(identifiedNames=identifiedNames)
1.47.2.20 dwinter 2784:
1.47.2.33 dwinter 2785: security.declareProtected('View management screens','editMPIWGBasisForm')
1.9 dwinter 2786: def editMPIWGBasisForm(self):
2787: """editform"""
1.45 dwinter 2788: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGBasis.zpt')).__of__(self)
1.9 dwinter 2789: return pt()
1.47.2.20 dwinter 2790:
1.47.2.33 dwinter 2791: security.declareProtected('View management screens','editMPIWGRelatedPublicationsForm')
1.9 dwinter 2792: def editMPIWGRelatedPublicationsForm(self):
2793: """Edit related Publications"""
1.45 dwinter 2794: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGRelatedPublications.zpt')).__of__(self)
1.9 dwinter 2795: return pt()
1.1 dwinter 2796:
1.9 dwinter 2797:
1.1 dwinter 2798: def loadNewFileForm(self):
2799: """Neues XML-File einlesen"""
1.45 dwinter 2800: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_newfile.zpt')).__of__(self)
1.1 dwinter 2801: return pt()
2802:
2803: def loadNewFile(self,RESPONSE=None):
2804: """einlesen des neuen files"""
2805: fileupload=self.REQUEST['fileupload']
2806: if fileupload:
2807: file_name=fileupload.filename
2808: filedata=fileupload.read()
2809:
2810: argv=xmlhelper.proj2hash(filedata)
2811: #print argv.keys()
2812: for arg in definedFields:
2813:
2814: #print arg,argv[arg],getattr(self,arg)
2815: try:
2816: temp=argv[arg][0:]
2817: #old=getattr(self,arg)
2818: setattr(self,arg,temp)
2819: #print old,getattr(self,arg)
2820: except:
2821: """nothing"""
2822:
2823: if RESPONSE is not None:
2824: RESPONSE.redirect('manage_main')
2825:
2826: def manage_addMPIWGProjectForm(self):
2827: """form for adding the project"""
1.45 dwinter 2828: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addMPIWGProjectForm.zpt')).__of__(self)
1.1 dwinter 2829: return pt()
2830:
2831: def manage_addMPIWGProject(self,id,RESPONSE=None):
2832: """method to add a project"""
2833: #print argv
1.20 dwinter 2834: fileupload=self.REQUEST.get('fileupload',None)
2835: if fileupload:
1.46 dwinter 2836:
1.20 dwinter 2837: file_name=fileupload.filename
2838: filedata=fileupload.read()
2839:
2840: argv=xmlhelper.proj2hash(filedata)
2841:
2842: #print argv
1.5 dwinter 2843: newObj=MPIWGProject(id,argv)
2844: else:
2845: newObj=MPIWGProject(id)
1.1 dwinter 2846:
2847: self._setObject(id,newObj)
2848:
1.47.2.18 dwinter 2849:
1.1 dwinter 2850: if RESPONSE is not None:
1.47.2.75 casties 2851: RESPONSE.redirect('manage_main')
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>