--- MPIWGWeb/MPIWGProjects.py 2005/04/25 16:58:02 1.46 +++ MPIWGWeb/MPIWGProjects.py 2008/08/22 06:09:28 1.47.2.87 @@ -1,873 +1,371 @@ """This contains the class MPIWG Projects for organizing and maintaining the different project pages +$author dwinter - last change 26.06.2008 + """ from Products.PageTemplates.PageTemplateFile import PageTemplateFile -from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate -from Products.ZSQLExtend.ZSQLExtend import ZSQLExtendFolder from Products.ZCatalog.CatalogPathAwareness import CatalogAware +from OFS.Image import Image from Globals import package_home import urllib -import MPIWGStaff -import string import re import os from types import * -import zLOG -import xmlhelper # Methoden zur Verwaltung der projekt xmls +import logging +import xmlhelper # Methoden zur Verwaltung der projekt xml from OFS.SimpleItem import SimpleItem from OFS.Folder import Folder -from Products.ZSQLMethods.SQL import SQLConnectionIDs +from AccessControl import ClassSecurityInfo from bibliography import * import time +#import xml.dom.minidom +import sys +#from Ft.Xml.XPath import Evaluate +#from Ft.Xml.XPath.Context import Context +#from Ft.Xml.Domlette import NonvalidatingReader,PrettyPrint, Print +#from Ft.Xml import EMPTY_NAMESPACE +#import copy +#import updatePersonalWWW -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'] - -checkFields = ['xdata_01'] - - - -def sortF(x,y): - try: - return cmp(x[1],y[1]) - except: - try: - return cmp(str(x[1]),str(y[1])) - except: - - return 0 - -def sortI(x,y): - xsplit=x[1].split(".") - ysplit=y[1].split(".") - xret="" - yret="" - try: - for i in range(5): - try: - yret=yret+"%04i"%int(xsplit[i]) - except: - yret=yret+"%04i"%0 - - try: - xret=xret+"%04i"%int(ysplit[i]) - except: - xret=xret+"%04i"%0 - - - return cmp(int(yret),int(xret)) - except: - return cmp(x[1],y[1]) - -class MPIWGTemplate(ZopePageTemplate): - """Create a layout Template for different purposes""" - - meta_type="MPIWGTemplate" - - def __init__(self, id, text=None, content_type=None,MPIWGType=None): - self.id = str(id) - - - - self.ZBindings_edit(self._default_bindings) - if text is None: - self._default_content_fn = os.path.join(package_home(globals()), - 'zpt/MPIWG_%s_template_standard.zpt'%MPIWGType) - text = open(self._default_content_fn).read() - self.pt_edit(text, content_type) - - - """change form""" - - -def manage_addMPIWGTemplateForm(self): - """Form for adding""" - pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt/AddMPIWGTemplate.zpt')).__of__(self) - return pt() - -from urllib import quote - - -def manage_addMPIWGTemplate(self, MPIWGType,id, title=None,REQUEST=None): - "Add a Page Template with optional file content." - if type(MPIWGType)==StringType: - MPIWGTypes=[MPIWGType] - else: - MPIWGTypes=MPIWGType - - for singleType in MPIWGTypes: - - - if REQUEST is None: - self._setObject(id, MPIWGTemplate(id, text,EchoType=singleType)) - ob = getattr(self, id) - - if title: - ob.pt_setTitle(title) - return ob - else: - file = REQUEST.form.get('file') - headers = getattr(file, 'headers', None) - if headers is None or not file.filename: - zpt = MPIWGTemplate(id,MPIWGType=singleType) - else: - zpt = MPIWGTemplate(id, file, headers.get('content_type')) - - self._setObject(id, zpt) - ob = getattr(self, id) - if title: - ob.pt_setTitle(title) - - try: - u = self.DestinationURL() - except AttributeError: - u = REQUEST['URL1'] +#import MPIWGStaff - - REQUEST.RESPONSE.redirect(u+'/manage_main') - return '' +from MPIWGHelper import * - -class MPIWGRoot(ZSQLExtendFolder): - """Stammordner für den Web-Server""" +import MPIWGRoot +import MPIWGLink +import MPIWGTemplate - fieldLabels={'WEB_title':'WEB_Title','xdata_01':'Responsible Scientists','xdata_02':'Department', - 'xdata_03':'Historical Persons','xdata_04':'Time period', - 'xdata_05':'Sorting number','xdata_06':'Keywords','xdata_07':'Short title', - 'xdata_08':'Other involved scholars' ,'xdata_09':'Part of','xdata_10':'Covered by', - 'xdata_11':'Object Digitallibrary','xdata_12':'Cooperation partners', - 'xdata_13':'Funding institutions','WEB_project_header':'WEB_project_header', - 'WEB_project_description':'WEB_project_description','WEB_related_pub':'WEB_related_pub'} - - folders=['MPIWGProject','Folder','ECHO_Navigation'] - meta_type='MPIWGRoot' +# die folgenden Klassen sind jetzt in einzelne Files ausgelagert aus KompatibilitŠtsgrŸnden, bleiben die Klassen hier noch drin. +# Sonst funktionieren die alten Webseiten nicht mehr. - def upDateSQL(self,fileName): - """updates SQL databases using fm.jar""" - fmJarPath=os.path.join(package_home(globals()), 'updateSQL/fm.jar') - xmlPath=os.path.join(package_home(globals()), "updateSQL/%s"%fileName) - zLOG.LOG("MPIWG Web",zLOG.INFO,"java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath)) - ret=os.popen("java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath),"r").read() - zLOG.LOG("MPIWG Web",zLOG.INFO,"result convert: %s"%ret) - return 1 +class MPIWGRoot(MPIWGRoot.MPIWGRoot): + """depricated""" - def patchProjects(self,RESPONSE): - """patch""" - projects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject']) - for project in projects: - tmp=project[1].WEB_project_description[0].replace("/CD/projects/","")[0:] - setattr(project[1],'WEB_project_description',[tmp[0:]]) - RESPONSE.write("

%s

\n"%project[0]) - - def replaceNotEmpty(self,format,field): - """replace not empty""" - if field and (not field.lstrip()==''): - return format%field - else: - return "" - - - def isActual(self,project): - """checke if project is actual""" - actualTime=time.localtime() - obj= project.getObject() - - if getattr(obj,'archiveTime',actualTime)< actualTime: - return False - else: - return True - - def redirectIndex_html(self,request): - #return request['URL1']+'/index_html' - - return urllib.urlopen(request['URL1']+'/index_html').read() - +class MPIWGLink(MPIWGLink.MPIWGLink): + """depricated""" - def formatBibliography(self,here,found): - """format""" - return formatBibliography(here,found) +class MPIWGTemplate(MPIWGTemplate.MPIWGTemplate): + """depricated""" - def getValue(self,fieldStr): - """Inhalt des Feldes""" - - if type(fieldStr)==StringType: - field=fieldStr - else: - field=fieldStr[0] - try: - if field[len(field)-1]==";": - field=field[0:len(field)-1] - except: +class MPIWGProject_publication(SimpleItem): + """publications object fuer project""" - """nothing""" - field=re.sub(r';([^\s])','; \g<1>',field) - return field.encode('utf-8') + meta_type="MPIWGProject_publication" + def editPublication(self,text=None,RESPONSE=None): + """edit a publication""" - - def sortedNames(self,list): - """sort names""" - - def sortLastName(x_c,y_c): - try: - x=urllib.unquote(x_c).encode('utf-8','ignore') - except: - x=urllib.unquote(x_c) + if (not text): + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_publicationForm.zpt')).__of__(self) + return pt() - try: - y=urllib.unquote(y_c).encode('utf-8','ignore') - except: - x=urllib.unquote(y_c) - + + self.text=text[0:] + if RESPONSE: + RESPONSE.redirect("../managePublications") - try: - last_x=x.split()[len(x.split())-1] - last_y=y.split()[len(y.split())-1] +class MPIWGProject_image(Image): + """Images for Projects""" - except: - - last_x="" - last_y="" - - - - if last_xlast_y: - return -1 - else: - return 0 - - list.sort(sortLastName) - list.reverse() - - return list - - def __init__(self, id, title): - """init""" - self.id=id - self.title=title + meta_type="MPIWGProject_image" - def urlQuote(self,str): - """quote""" - return urllib.quote(str) - - def urlUnQuote(self,str): - """quote""" - return urllib.unquote(str) + def showImage(self,imageUrl=None): + """show Images at an extra page""" + self.getContent('WEB_project_description',filter='yes') #get the content and store image infos into session + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','projectImageView.zpt')).__of__(self) + return pt() - def harvestHistoricalPersons(self): - """erstelle liste aller erwaehnten actors""" + def editImage(self,file=None,caption=None,RESPONSE=None): + """edit the Image""" + if (not file) and (not caption): + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_imageForm.zpt')).__of__(self) + return pt() - def normalize(str): - """loesche fuhrendes space""" - if (len(str)>1) and (str[0]==" "): - ret=str[1:] - else: - ret=str - return ret - - list={} - projects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject']) - - for project in projects: - lg=len(project[1].xdata_03[0])-1 + if file and (not file.filename.lstrip().rstrip()==""): + self.manage_upload(file) - if (lg>1) and (project[1].xdata_03[0][lg]==";"): - project[1].xdata_03[0]=project[1].xdata_03[0][0:lg] + if caption: + self.caption=caption[0:] - - - - try: - if len(project[1].xdata_03[0].split(";"))>1: # guess if separator is ; - for person in project[1].xdata_03[0].split(";"): - personNormal=normalize(person) - if personNormal in list.keys(): - list[urllib.quote(personNormal)][1].append(project[1]) - else: - list[urllib.quote(personNormal)]=(personNormal,[project[1]]) - else: #guess , is sepeator - for person in project[1].xdata_03[0].split(","): - personNormal=normalize(person) - if urllib.quote(personNormal) in list.keys(): - list[urllib.quote(personNormal)][1].append(project[1]) - else: - list[urllib.quote(personNormal)]=(personNormal,[project[1]]) + if RESPONSE: + RESPONSE.redirect("../manageImages") - except: - zLOG.LOG("MPIWG Web (harvestHistoricalPerson)",zLOG.ERROR,"cannot annalyize: %s"%repr(project)) - - - return list +class MPIWGProject(CatalogAware,Folder): + """Class for Projects""" - def storeHistoricalPersons(self,RESPONSE=None): - """store persons""" - self.personDict={} - personDict=self.harvestHistoricalPersons() - for person in personDict.keys(): - for project in personDict[person][1]: - if person in self.personDict.keys(): - self.personDict[person][1].append((project.absolute_url(),project.WEB_title[0],project.xdata_01[0])) - else: - self.personDict[person]=(personDict[person][0],[(project.absolute_url(),project.WEB_title[0],project.xdata_01[0])]) - if RESPONSE is not None: - RESPONSE.redirect("showHistoricalPersons") - + security=ClassSecurityInfo() + meta_type='MPIWGProject' + default_catalog='ProjectCatalog' - def getPersonDict(self,name): - """name von dict""" + def decode(self,str): + """return unicode object""" + return unicodify(str) + + def sortedByPlace(self,metatype): + """find metatype and sort by place""" + def sort(x,y): + return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0)) - try: - return self.personDict[name][0].encode('utf-8') - except: - return self.personDict[name][0] - return self.personDict[name][0].decode('latin-1').encode('utf-8') + founds=self.ZopeFind(self,obj_metatypes=[metatype]); - - def showHistoricalPersons(self): - """show persons""" - pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','showHistoricalPersons')).__of__(self) - return pt() - + founds.sort(sort) - def editHistoricalPersonsForm(self): - """edit historical persons for consistency""" - pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','editHistoricalPersonsForm')).__of__(self) - return pt() - - def getProjectsByFieldContent(self,fieldName,fieldContentsEntry): - """gib alle Projekte aus mit Value von field mit fieldName enthält ein Element der Liste fieldContents""" - if type(fieldContentsEntry) is StringType: - fieldContents=[fieldContentsEntry] - else: - fieldContents=fieldContentsEntry - - projects=self.ProjectCatalog({fieldName:string.join(fieldContents,' OR')}) - #print projects - return projects - - def changeMPIWGRootForm(self): - """edit""" - pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeMPIWGRootForm')).__of__(self) - return pt() - - def changeMPIWGRoot(self,title,disciplineList,themesList,connection_id,RESPONSE=None): - """change""" - self.title=title - self.connection_id=connection_id - self.disciplineList=disciplineList - self.themesList=themesList - - if RESPONSE is not None: - RESPONSE.redirect('manage_main') - - def getDisciplineList(self): - """get disciplines as list""" - return self.disciplineList.split("\n") - - def getThemeList(self): - """get themes as list""" - return self.themesList.split("\n") - - def test(self): - """test""" - return self.getProjectsByFieldContent('xdata_09',['biology'])[0].absolute_url - - def getContexts(self,childs=None,parents=None,depth=None): - """childs alle childs, alle parents""" - ret=[] - if parents: - splitted=parents.split(".") - parentId=string.join(splitted[0:len(splitted)-1],".") - - for project in self.getProjectFields('xdata_05',sort='int'): - if project[1]==parentId: - ret.append(project) - - if childs: - for project in self.getProjectFields('xdata_05',sort='int'): - searchStr=childs+"(\..*)" - if re.match(searchStr,project[1]): - - if depth: - - if int(depth)>=len(project[1].split("."))-len(childs.split(".")): - - ret.append(project) - else: - ret.append(project) - return ret - - def getProjectFields(self,fieldName,folder=None,sort=None): - """getListofFieldNames""" - ret=[] + return founds - objects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'],search_sub=0) - - for object in objects: - obj=object[1] + def copyPublicationsToList(self,RESPONSE=None): + """copy publications in to list""" - if not getattr(obj,'invisible',None): - if fieldName=="WEB_title_or_short": + publicationTxt=self.getContent('WEB_related_pub') - if len(obj.getContent('xdata_07'))<3: # hack weil z.Z. manchmal noch ein Trennzeichen ; oder , im Feld statt leer - fieldNameTmp="WEB_title" - else: - fieldNameTmp="xdata_07" - else: - fieldNameTmp=fieldName + pubSplits=publicationTxt.split("

") - ret.append((obj,obj.getContent(fieldNameTmp))) + for pubSplit in pubSplits: + pubSplit=pubSplit.replace("

","") + self.addPublication(pubSplit) + if RESPONSE: + RESPONSE.redirect('managePublications') - if sort=="int": - ret.sort(sortI) - else: - ret.sort(sortF) - - return ret - - def showNewProjects(self): - projects=[] - for objs in self.getProjectFields('WEB_title_or_short'): # Get all Projets - if objs[0].xdata_05[0] == "": - - projects.append(objs) - - return projects + def copyImageToMargin(self,RESPONSE=None): + """copy inline images to marginal images""" - manage_options = Folder.manage_options+( - {'label':'Update Personal Homepages','action':'updateHomepages'}, - {'label':'Main config','action':'changeMPIWGRootForm'}, - {'label':'Edit Historical Persons','action':'editHistoricalPersonsForm'}, - {'label':'Store Historical Persons','action':'storeHistoricalPersons'}, - ) - - def importNamesForm(self): - """Form""" - pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGNamesForm.zpt')).__of__(self) - return pt() - - def importNames(self,fileupload,folderName,RESPONSE=None): - """import komma-sep list email,lastName,firstName""" - project=getattr(self,folderName) - load=fileupload.read() - for line in load.split('\r'): - - - splitted=line.split(",") - # print splitted + #getImages from WEB_project_description + description=self.getContent('WEB_project_description') + + text2=description + splitted=text2.split("""

""") - if not (splitted[0]==""): - newObj=MPIWGStaff.MPIWGStaff(splitted[0],splitted[1],splitted[2]) + imageURLs=[] + imageCaptions=[] + for split in splitted[1:]: + tmp=split.split("

") + #return repr(splitted[1]) try: - project._setObject(splitted[0],newObj) - #print "done:",splitted[0] + imageURLs.append(tmp[0].split("\"")[1].encode('utf-8')) except: - zLOG.LOG("MPIWG Web (importNames)",zLOG.INFO,"cannot import: %s"%splitted[0]) - - if RESPONSE is not None: - RESPONSE.redirect('manage_main') - - def updateHomepages(self,RESPONSE): - """lege members an""" - - self.upDateSQL('personalwww.xml') - founds=self.ZSQLInlineSearch(_table='personal_www',publish_the_data='yes') - project=getattr(self,'members') - for found in founds: - - if not (found.e_mail==""): - newObj=MPIWGStaff.MPIWGStaff(found.username,found.name,found.vorname) + try: + imageURLs.append(tmp[0].split("src=")[1].split(" ")[0].encode('utf-8')) + except: + imageURLs.append("") - try: - project._setObject(found.username,newObj) - RESPONSE.write("

new:%s

\n"%found.username) - except: - RESPONSE.write("

old:%s (%s,%s)

\n"%(found.username,found.name,found.vorname)) + split2="

".join(tmp[1:]) - #delete non existing + splitted=split2.split("""

""") + if len(splitted)>1: + tmp=splitted[1].split("

") + imageCaptions.append(tmp[0].encode('utf-8')) - foundUserNames=[x.username for x in founds] - for member in self.ZopeFind(self,obj_metatypes=["MPIWGStaff"],search_sub=1): - - if member[1].getId() not in foundUserNames: - member[1].aq_parent.manage_delObjects(ids=[member[1].getId()]) - RESPONSE.write("

deleted:%s

\n"%member[1].getId()) - try: - self.MembersCatalog.manage_catalogReindex(self.REQUEST,RESPONSE,self.REQUEST['URL1']) - except: - pass - self.ProjectCatalog.manage_catalogReindex(self.REQUEST,RESPONSE,self.REQUEST['URL1']) - - - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + else: + #keine caption + imageCaptions.append("") + + + #eintragen: + for imageURL in imageURLs: + filename=imageURL.split("/")[-1] + #lege neues images object an, mit leerem bild + + if self.ZopeFind(self,obj_ids=[filename]): + #existiert das bild schon, dann neuen filenamen + filename="project_image_"+filename + + self.addImage(None,imageCaptions[imageURLs.index(imageURL)],filename=filename) + #hole die bilddaten aus der url + url=self.absolute_url()+"/"+imageURL + #url=self.absolute_url()+"/"+filename - def getAllMembers(self): - """give list of all members""" - ret=[] - - #for x in self.members.objectValues('MPIWGStaff'): - #print x.title - # ret.append(x.title.decode('utf-8')) - - for x in self.ZopeFind(self.members,obj_metatypes=['MPIWGStaff']): - ret.append(x[1].title.decode('utf-8')) + try:#relative url + data=urllib.urlopen(url).read() + except: + try:#absolute + data=urllib.urlopen(self.imageURL).read() + except: + logger("MPIWG Project",logging.ERROR,"can't open: %s"%url) - ret.sort() - #print ret - - return ret - - def printAllMembers(self): - """prin""" - members=self.getAllMembers() - ret="" - for x in members: - ret+="

%s

"%x - return ret - + obj=getattr(self,filename) + obj.update_data(data) - def makeList(self,entry): - """makes a list out of one entry or repeat a list""" - if type(entry) is StringType: - return [entry] - else: - return entry - - - def getTree(self): - """generate Tree from project list""" - returnList=[] - for project in self.getProjectFields('xdata_05',sort="int"): # get Projects sorted by xdata_05 - - for idNr in project[1].split(";"): # more than one number - if not idNr=="": - splittedId=idNr.split(".") - depth=len(splittedId) - nr=idNr - #title=project[0].WEB_title - title=[project[0].getContent('WEB_title')] - #print title - returnList.append((depth,nr,title,project[0])) - - return returnList - - - def formatElementForOverview(self,element): - """format the element for output in overview""" - if element[0]==1: #department - #print element[3].getContent('xdata_05') - if element[3].getContent('xdata_05') == "4": - return """

Ind. Research Group I: %s

"""%(element[3].absolute_url()+"/index.html",element[3].getContent('WEB_title')) - if element[3].getContent('xdata_05') == "5": - return """

Ind. Research Group II: %s

"""%(element[3].absolute_url()+"/index.html",element[3].getContent('WEB_title')) - - return """

Department %s: %s

"""%(element[3].absolute_url()+"/index.html",element[3].getContent('xdata_05'),element[3].getContent('WEB_title')) - - elif element[0]==2: #mainprojects - return """

%s

"""%(element[3].absolute_url()+"/index.html",element[3].getContent('WEB_title')) - - elif element[0]==3: - return """

%s

"""%(element[3].absolute_url()+"/index.html",element[3].getContent('WEB_title')) - - - def changePosition(self,treeId,select,RESPONSE=None): - """Change Postion Entry""" - numbers=[] - - # Suche hoechste bisherige nummer - projects=self.getProjectFields('xdata_05') # get Projects sorted by xdata_05 - #print "pj",projects - for project in projects: #suche alle subtrees der treeId - #print treeId - - founds=re.match(treeId+"\.(.*)",project[1].split(";")[0]) - if founds: - #print "x",founds.group(0),len(founds.group(0).split(".")) - if len(founds.group(0).split("."))==len(treeId.split("."))+1: # nur ein punkt mehr, d.h. untere ebene - try: - numbers.append(int(founds.group(0).split(".")[len(founds.group(0).split("."))-1])) - except: - numbers.append(int(0)) - - try: - highest=max(numbers) - except: - highest=0 - projects=self.showNewProjects() - for i in self.makeList(select): - highest+=10 - projects[int(i)][0].xdata_05=treeId+"."+str(highest) + if RESPONSE: + RESPONSE.redirect('manageImages') + + def manageImages(self,imageName=None,op=None): + """managage images""" + + + if imageName and op: + if op=='up': + images=self.getImages() + for image in images: + if image[0]==imageName: + nr=images.index(image) + if not nr==0: + images[nr-1][1].place+=1 + images[nr][1].place-=1 + pass + elif op=='down': + images=self.getImages() + for image in images: + if image[0]==imageName: + nr=images.index(image) + if not (nr==len(images)-1): + images[nr+1][1].place-=1 + images[nr][1].place+=1 + pass - if RESPONSE is not None: - RESPONSE.redirect('showTree') - - def changeTree(self,RESPONSE=None): - """change the complete tree""" - form=self.REQUEST.form - hashList={} - fields=self.getTree() + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_manageImagesForm.zpt')).__of__(self) + return pt() - - for idNr in form.keys(): - fields[int(idNr)][3].xdata_05=form[idNr] + def managePublications(self,pubName=None,op=None): + """managage images""" - - if RESPONSE is not None: - RESPONSE.redirect('showTree') + if pubName and op: + if op=='up': + publications=self.getPublications() + for publication in publications: + if publication[0]==pubName: + nr=publications.index(publication) + if not nr==0: + publications[nr-1][1].place+=1 + publications[nr][1].place-=1 + pass + elif op=='down': + publications=self.getPublications() + for publication in publications: + if publication[0]==pubName: + nr=publications.index(publication) + if not (nr==len(publications)-1): + publications[nr+1][1].place-=1 + publications[nr][1].place+=1 + pass - def getProjectWithId(self,id): - fields=self.getProjectFields('xdata_05') - for field in fields: - if field[1]==id: - return field[0] - return None - - - - - def getRelativeUrlFromPerson(self,list): - """get urls to person list""" - ret=[] - persons=list.split(";") - for person in persons: - - if len(person)>1: #nicht nur Trennzeichen - splitted=person.split(",") - if len(splitted)==1: - splitted=person.split(" ") - splittedNew=[re.sub(r'\s(.*)','$1',split) for split in splitted] - if splittedNew[0]=='': - del splittedNew[0] - search=string.join(splittedNew,' AND ') - - if not search=='': + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_managePublicationsForm.zpt')).__of__(self) + return pt() - try: - proj=self.MembersCatalog({'title':search}) - except: - proj=None + def getPublications(self): + """get all Publications""" + def sort_images(x,y): + return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0)) - if proj: - #ret.append("%s"%(proj[0].absolute_url,person.encode('utf-8'))) - ret.append("%s"%('members/'+proj[0].id+'/index.html',person)) - else: - #ret.append("%s"%person.encode('utf-8')) - ret.append("%s"%person) - return string.join(ret,";") + publications=self.ZopeFind(self,obj_metatypes=['MPIWGProject_publication']) - - def getUrlFromPerson(self,list): - """get urls to person list""" - ret=[] - persons=list.split(";") - for person in persons: - - if len(person)>1: #nicht nur Trennzeichen - splitted=person.split(",") - if len(splitted)==1: - splitted=person.lstrip().rstrip().split(" ") - splittedNew=[re.sub(r'\s(.*)','$1',split) for split in splitted] - if splittedNew[0]=='': - del splittedNew[0] - search=string.join(splittedNew,' AND ') - - if not search=='': + publications.sort(sort_images) + return publications - try: - proj=self.MembersCatalog({'title':search}) - except: - proj=None - - if proj: - if person =="Otto Sibum" : person="H. Otto Sibum" - if person =="Norton Wise" : person="M. Norton Wise" - #ret.append("%s"%(proj[0].absolute_url,person.encode('utf-8'))) - ret.append("%s"%(proj[0].absolute_url+"/index.html",person)) - else: - #ret.append("%s"%person.encode('utf-8')) - ret.append("%s"%person) - return string.join(ret,";") - - def getProjectsOfMembers(self): - """give tuple member /projects""" - ret=[] - members=self.getAllMembers() - #return str(members) - for x in members: - ret+=self.getProjectsOfMember(name=x) - - return ret + def addPublication(self,text,RESPONSE=None): + """add an MPIWG_Publication""" - def getProjectsOfMember(self,name=None,email=None): - """get project of a member""" - def sortP(x,y): - """sort by sorting number""" - #print x.xdata_05,y.xdata_05 - return cmp(x.WEB_title,y.WEB_title) + name="publication_"+str(self.getLastPublicationNumber()+1) - - ret=[] - splitNeu=[] - if email: - #print "IIII:",self.getId() - members=self.ZopeFind(self,obj_metatypes=['MPIWGStaff'],obj_ids=[email],search_sub=1) - name = members[0][1].title.decode('utf-8') + newPublication=MPIWGProject_publication(name) - y=name - splitted=y.split(",") - #XXXX - splitNeu=["\'"+splitted[1]+" "+splitted[0]+"\'"] + self._setObject(name,newPublication) + obj=getattr(self,name) + obj.text=text[0:] + obj.enabled=True; + obj.place=self.getLastPublicationNumber()+1 + obj.id=name - #for s in splitted: - # splitNeu.append("\""+s+"\"") - search=string.join(splitNeu,' AND ') - - proj=self.ProjectCatalog({'xdata_01':search}) - - if proj: - proj2=[] - for x in proj: - - if not getattr(x.getObject(),'invisible',None): - if not((splitted[1]==" Christoph") and (splitted[0]=="Hoffmann") and (str(x.WEB_title).find('Einstein')>0)): - proj2.append(x) + if RESPONSE is not None: + RESPONSE.redirect('managePublications') + + def getLastPublicationNumber(self): + publications=self.getPublications() + + if not publications: + return 0 else: - proj2=[] - - proj=self.ProjectCatalog({'xdata_08':search}) - if proj: - names=[x.WEB_title for x in proj] - for x in proj: - - if not x.WEB_title in names: - proj2.append(x) - - - proj2.sort(sortP) - - if len(proj2)>0: - ret.append((y,proj2)) - - return ret - - def givePersonList(self,name): - """check if person is in personfolder and return list of person objects""" + return getattr(publications[-1][1],'place',0) - splitted=name.split(",") - if len(splitted)==1: - splitted=name.lstrip().rstrip().split(" ") - splittedNew=[split.lstrip() for split in splitted] - - if splittedNew[0]=='': - del splittedNew[0] - search=string.join(splittedNew,' AND ') - if not search=='': - proj=self.MembersCatalog({'title':search}) - - if proj: - return [[x.lastName,x.firstName] for x in proj] - else: - return [] - -## splitted=name.split(",") # version nachname, vorname... -## if len(splitted)>1: -## lastName=splitted[0] -## firstName=splitted[1] -## else: -## splitted=name.split(" ") #version vorname irgenwas nachnamae - -## lastName=splitted[len(splitted)-1] -## firstName=string.join(splitted[0:len(splitted)-1]) - -## objs=[] - - #print self.members - ## for x in self.members.__dict__: -## obj=getattr(self.members,x) -## if hasattr(obj,'lastName') and hasattr(obj,'firstName'): + def deletePublication(self,id,RESPONSE=None): + """delete Publication id""" + self.manage_delObjects([id]) + if RESPONSE: + RESPONSE.redirect('managePublications') -## if (re.match(".*"+obj.lastName+".*",lastName) or re.match(".*"+lastName+".*",obj.lastName)) and (re.match(".*"+obj.firstName+".*",firstName) or re.match(".*"+firstName+".*",obj.firstName)): - -## objs.append((obj,lastName+", "+firstName)) - - - return objs + def getImages(self): + """get all Images""" + def sort_images(x,y): + return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0)) - def personCheck(self,names): - """all persons for list""" - #print "names",names - splitted=names.split(";") - ret={} - for name in splitted: - if not (name==""): - try: - ret[name]=self.givePersonList(name) - except: - """NOTHIHN""" - #print "RET",ret - return ret + if (getattr(self,'imageURL','')!='') or (getattr(self,'imagecap','')!='') : + try: + self.addImage(None,getattr(self,'imagecap',''),RESPONSE=None,filename=getattr(self,'imageURL','')) + except: + pass + self.imageURL='' + self.imagecap='' - def giveCheckList(self,person,fieldname): - """return checklist""" - #print "GCL",fieldname - if fieldname=='xdata_01': - x=self.personCheck(person.getContent(fieldname)) - #print "GCLBACKX",x - return x + images=self.ZopeFind(self,obj_metatypes=['MPIWGProject_image']) + images.sort(sort_images) + return images - def isCheckField(self,fieldname): - """return chechfield""" + def getLastImageNumber(self): + images=self.getImages() - return (fieldname in checkFields) - - - - + if not images: + return 0 + else: + return getattr(images[-1][1],'place',0) -def manage_addMPIWGRootForm(self): - """form for adding the root""" - pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addMPIWGRootForm.zpt')).__of__(self) - return pt() - -def manage_addMPIWGRoot(self,id,title,connection_id="",RESPONSE=None): - """add a root folder""" - newObj=MPIWGRoot(id,title) - self._setObject(id,newObj) - ob=getattr(self,id) - setattr(ob,'connection_id',connection_id) - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + def deleteImage(self,id,RESPONSE=None): + """delete Image id""" + self.manage_delObjects([id]) + if RESPONSE: + RESPONSE.redirect('manageImages') + + + def hasChildren(self,date=None,onlyActive=1,onlyArchived=1): + """check if project has children""" + ct=self.getContexts(childs=self.getContent('xdata_05'), + depth=1,date=date,onlyActive=onlyActive) + if ct and len(ct)>0: + return True + else: + return False -class MPIWGProject(CatalogAware,Folder): - """Class for Projects""" + + def addImage(self,fileHd,caption,RESPONSE=None,filename=None): + """add an MPIWG_Project_image""" + + if not filename: + filename=fileHd.filename + + if not fileHd: + fileHd=file(os.path.join(package_home(globals()),'blank.gif')) + + newImage=MPIWGProject_image(filename,filename,fileHd) + + self._setObject(filename,newImage) + obj=getattr(self,filename) + obj.caption=caption[0:] + obj.enabled=True; + obj.place=self.getLastImageNumber()+1 + obj.id=filename + + if RESPONSE is not None: + RESPONSE.redirect('manageImages') - meta_type='MPIWGProject' - default_catalog='ProjectCatalog' - def PrincipiaSearchSource(self): """Return cataloguable key for ourselves.""" return str(self) @@ -883,6 +381,47 @@ class MPIWGProject(CatalogAware,Folder): return retTXT%(s,s) else: return "" + + def getActualVersion(self,date=None): + """actuelle version""" + def sortProjectsByTime(x,y): + return cmp(x[1].archiveTime,y[1].archiveTime) + + if not date: + if self.isActual(): + return self + else: + return None + + #suche ob aeltere versionen vorhanden sind + + finds=self.ZopeFind(self,obj_metatypes=['MPIWGProject']) + if not finds: #wenn nicht dann teste ob die aktuelle version schon existiert hat. + ad=getattr(self,'creationTime','20050101000000') + if int(date)>int(ad): + return self + else: + return None + + + else: + finds.sort(sortProjectsByTime) + + for find in finds: + #gehe durch die alten Projekte und finde das entprechende + if (int(find[1].archiveTime) > int(date)) and (int(date)>int(getattr(find[1],'creationTime','20050101000000'))): + return find[1] + + #kein passendes gefunden, dann teste ob das aktuelle in frage kommt + ad=getattr(self,'creationTime','20050101000000') + + if int(date)>int(ad): + + return self + else: + return None + + def isActual(self): """gibt 1 zurueck wenn aktuell, 0 sonst""" actualTime=time.localtime() @@ -938,13 +477,13 @@ class MPIWGProject(CatalogAware,Folder): new.append(split) except: new.append(split) - return string.join(new) + return " ".join(new) def generateTemplate(self,RESPONSE=None): - """Erzeuge Template für defined fields not_used""" + """Erzeuge Template fuer defined fields not_used""" id="index_html" title=id @@ -959,16 +498,20 @@ class MPIWGProject(CatalogAware,Folder): RESPONSE.redirect('manage_main') def __init__(self, id, argv=None): - """initieriere classe""" - + """initiere classe""" + + self.creationTime=time.strftime("%Y%m%d%H%M%S",time.localtime())[0:] self.id=id self.title=id + self.isActiveFlag=True #Flag is true is the project is still active, False if accomplished + self.responsibleScientistsList=[] # enthaelt die Lister der verantwortlichen Wissenschaftler in der Form (NAME, KEY), key ist "" flass Wissenschaftler nicht an unserem Haus + if argv: for arg in definedFields: - try: - setattr(self,arg,argv[arg]) - except: - setattr(self,arg,"") + try: + setattr(self,arg,argv[arg]) + except: + setattr(self,arg,"") else: for arg in definedFields: setattr(self,arg,'') @@ -983,42 +526,282 @@ class MPIWGProject(CatalogAware,Folder): ) + def isActiveProject(self): + """check if the project is still active, default is true, set to false is the project is accomplished""" + return getattr(self,'isActiveFlag',True) + + def isArchivedProject(self): + """check if the project is archived""" + + completed=getattr(self,'completedAt',0) + + #completed leer + if completed=="" : + return False; + if completed == 0: + return False; + + + return True + + + def setActiveFlag(self,status=True): + """set the active flag""" + self.isActiveFlag=status + + def setCompletedAt(self,date): + """set the date of completion, date should be in the form DD.MM.YYYY or MM.YYYY or YYYY""" + logging.info("DATE:"+repr(date)) + transformedDate=self.transformDate(date); + logging.info("transformed"+repr(transformedDate)) + if transformedDate is not None: + setattr(self,"completedAt",transformedDate) + return True; + else: + return False; + + def setStartedAt(self,date): + """set the date of start, date should be in the form DD.MM.YYYY or MM.YYYY or YYYY""" + logging.info("DATE:"+repr(date)) + transformedDate=self.transformDate(date); + logging.info("transformed"+repr(transformedDate)) + if transformedDate is not None: + setattr(self,"startedAt",transformedDate) + return True; + else: + return False; + def getCompletedAt(self): + """gibt das transformierte Datum zurueck, an dem das Projekt beendet wurde.""" + date=getattr(self,'completedAt','') + if date: + return self.reTransformDate(date); + else: + return ''; + + def getStartedAt(self): + """gibt das transformierte Datum zurŸck, an dem Projekt begonnen wurde.""" + date=getattr(self,'startedAt','') + if date: + return self.reTransformDate(date); + else: + return ''; + + def reTransformDate(self,date): + """transformiert , transformdate zurueck""" + year=int(date/10000) + month=int((date-year*10000)/100) + day=int((date-year*10000-month*100)) + if (day==0) and (month==0): + return """%s"""%year; + if day==0 : + return """%s.%s"""%(month,year); + + return """%s.%s.%s"""%(day,month,year); + + + def transformDate(self,date): + """transformiert ein Datum von DD.MM.YYYY, MM.YYYY,YYYY nach YYYYMMDD, alle nicht angebebenn Werte + werden auf 0 gesetzt, es wird null zurŸckgegeben falls das Datum ungueltig ist""" + + if (date==None): + return None; + + + if (date.lstrip().rstrip()=="" ) : + return ""; + + splitted=date.split(".") + length=len(splitted) + year=0 + month=0 + day=0 + if length > 3: + return ""; + if length==3: + day = int(splitted[0]) + if length>1: + month=int(splitted[length-2]) + + if length > 0: + try: + year = int(splitted[length-1]) + except: + pass + + ## logging.info("month:"+(month)) + if not (0<=month<13): + return None; + + if not(0<=day<32): + return None; + + if (year>0) and (year<1900): #jahr nicht vierstellig eingegeben + year=2000+year; + return year*10000+month*100+day + + + def checkDate(self,date): """teste ob zum Zeitpunkt date eine andere version existierte""" def sortProjectsByTime(x,y): return cmp(x[1].archiveTime,y[1].archiveTime) - + + #suche ob aeltere versionen vorhanden sind + finds=self.ZopeFind(self,obj_metatypes=['MPIWGProject']) - if not finds: - return self.absolute_url() + if not finds: #wenn nicht dann teste ob die aktuelle version schon existiert hat. + ad=getattr(self,'creationTime','20050101000000') + if int(date)>int(ad): + return self.REQUEST['URL1']+"/"+self.getId() + else: + return self.REQUEST['URL1']+"/no_project" + + else: finds.sort(sortProjectsByTime) for find in finds: - if int(find[1].archiveTime) > int(date): - return find[1].absolute_url() + #gehe durch die alten Projekte und finde das entprechende + if (int(find[1].archiveTime) > int(date)) and (int(date)>int(getattr(find[1],'creationTime','20050101000000'))): + return self.REQUEST['URL1']+"/"+find[1].getId() - return self.absolute_url() + #kein passendes gefunden, dann teste ob das aktuelle in frage kommt + ad=getattr(self,'creationTime','20050101000000') - - - def index_html(self): - """show homepage""" + if int(date)>int(ad): - if self.REQUEST.has_key('date') and self.REQUEST.SESSION.get('MPI_redirected',None)==None: - self.REQUEST.SESSION['MPI_redirected']=1 - self.REQUEST.RESPONSE.redirect(self.checkDate(self.REQUEST['date'])) + return self.REQUEST['URL1']+"/"+self.getId() else: - self.REQUEST.SESSION['MPI_redirected']=None + return self.REQUEST['URL1']+"/no_project" - ext=self.ZopeFind(self.aq_parent,obj_ids=["project_main"]) + + def no_project(self): + """warnung: project noch nicht existent""" + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','no_project')).__of__(self) + return pt() + + def getGetNeighbourhood(self,wordStr, length=100,tagging=True): + """finde umgebung um die worte in wordStr, zurueckgegeben wird eine Array mit den Umgebungen von Fundstellen der Worte + alle Tags werden entfernt, die Fundstellen werden mit XX getaggt, die Umgebungen werden + case insensitive gesucht + @param wordStr: string mit Worten getrennt durch Leerzeichen, Phrasen sind mit " gekennzeichnet + "eine phrase", "*" bezeichnet wildcards und wird ignoriert" + @param length: optional, default wert 100, 2*length ist die groesse der Umgebung + @param tagging: optional default wert true, kein span tag wird erzweugt falls tag=false + """ + + ret=[] # nimmt das Array auf, dass spaeter zurueckgegeben wird + ranges=[] #Array mit tupeln x,y wobei x die Position des Anfang und y des Endes der i-ten Umgebung angiebt + + def isInRanges(nr,length): + """test ob eine gegeben Position nr schon irgendwo in einer Umgebung ist, gibt den Index des ersten Wertes aus ranges zurueck, + -1, wenn kein Treffer + + @param nr: Position die geprueft werden soll + @param length: Laenge des Wortes das geprueft werden soll + """ + for x in ranges: + if (x[0]<=nr) and (nr < (x[1]-length)): + return ranges.index(x) + return -1 + + # deal with phrases, in Phrasen werden die Leerzeichen durch "_" ersetzt. + def rep_empty(str): + x= re.sub(" ","_",str.group(0)) + return re.sub("\"","",x) + + wordStr=re.sub("\".*?\"", rep_empty,wordStr)#ersetze leerzeichen in " " durch "_" und loesche " + + #deal with wildcards, for our purposes it is enough to delete the wildcard + wordStr=wordStr.replace("*","") + + words=wordStr.split(" ") + #if not words is ListType: + # words=[words] + + txt=self.harvest_page() + if not txt: + return ret + txt=re.sub("<.*?>", "", txt) # loesche alle Tags + for word in words: + word=re.sub("_"," ",word) # ersetze zurueck "_" durch " " + pos=0 + + n=txt.lower().count(word.lower()) # wie oft tritt das Wort auf + + for i in range(n): + pos=txt.lower().find(word.lower(),pos) + + if pos > 0: + x=max(0,pos-length) + y=min(len(txt),pos+length) + + + #is word already in one of the results + nr=isInRanges(pos,len(word)) + if nr >=0:# word ist in einer schon gefunden Umgebung, dann vergroessere diese + x=min(ranges[nr][0],x) + y=max(ranges[nr][1],y) + + str=txt[x:y] + + if nr >=0: # word ist in einer schon gefunden Umgebung + ranges[nr]=(x,y) # neue Position der Umgebung + ret[nr]=str # neue Umgebung + else: # andernfalls neue Umgebung hinzufuegen + ranges.append((x,y)) + + ret.append(str) + + pos=pos+len(word) + else: + break; + + # now highlight everything + if tagging: + for x in range(len(ret)): + for word in words: + repl=re.compile(word,re.IGNORECASE) + ret[x]=repl.sub(""" %s"""%word.upper(),ret[x]) + + return ret + + def harvest_page(self,context=None): + """seite fuer harvesting fuer die Projektsuche""" + if not context: + context=self + + if self.isActiveProject() and self.isActual(): + ext=getattr(self,"harvest_main",None) + if ext: + return getattr(self,ext.getId())() + + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','harvest_main')).__of__(context) + + + return pt() + + def index_html(self,request=True,context=None): + """show homepage""" + if not context: + context=self + if request: + if self.REQUEST.has_key('date') and self.REQUEST.SESSION.get('MPI_redirected',None)==None: + self.REQUEST.SESSION['MPI_redirected']=1 + self.REQUEST.RESPONSE.redirect(self.checkDate(self.REQUEST['date'])+"?date="+self.REQUEST['date']) + else: + self.REQUEST.SESSION['MPI_redirected']=None + + #ext=self.ZopeFind(self.aq_parent,obj_ids=["project_main"]) + ext=getattr(self,"project_main",None) if ext: - return getattr(self,ext[0][1].getId())() + return getattr(self,ext.getId())() + + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','project_main')).__of__(context) - pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','project_main')).__of__(self) return pt() @@ -1039,7 +822,7 @@ class MPIWGProject(CatalogAware,Folder): """get attrbiute""" return getattr(self,field) - def getContent(self,field): + def getContent(self,field,filter=None): """Inhalt des Feldes""" text=u'' @@ -1071,12 +854,62 @@ class MPIWGProject(CatalogAware,Folder): if (text2=='') and (field=='WEB_project_header'): return self.getContent('WEB_title') - #teste ob WEB_project_description und keine führenden p tags - if (len(text2)>4) and (not text2[0:3]=='

') and (field=='WEB_project_description'): - return "

"+text2+"

" + if filter: + splitted=text2.split("""

""") + if len(splitted)>1: + tmp=splitted[1].split("

") + #return repr(splitted[1]) + try: + self.imageURL=tmp[0].split("\"")[1].encode('utf-8') + except: + try: + self.imageURL=tmp[0].split("src=")[1].split(" ")[0].encode('utf-8') + except: + self.imageURL="" + + split2="

".join(tmp[1:]) + + text3=splitted[0]+split2 + + splitted=text3.split("""

""") + if len(splitted)>1: + tmp=splitted[1].split("

") + self.imagecap=tmp[0].encode('utf-8') + + split4="".join(tmp[1:]) + + text5=splitted[0]+split4 + else: + #keine caption + text5=text3 + else: + #kein bild + text5=text2 + else: + text5=text2 + + #teste ob WEB_project_description und keine fuehrenden p tags + if (len(text5)>4) and (not text5[0:3]=='

') and (field=='WEB_project_description'): + text5= "

"+text5+"

" - return text2.encode('utf-8') + #filter image + + text5=text5.lstrip().rstrip() #loescher leerzeichen und einzelndes br + if (text5=="
") or (text5=="
"): + text5="" + + logging.debug("getcontent: field=%s filter=%s -> %s"%(field,filter,repr(text5))) + #return unicodify(text5) + return utf8ify(text5) # return as utf-8 byte string + + + def showImagesOfPage(self,imageUrl=None): + """show Images of project""" + self.getContent('WEB_project_description',filter='yes') #get the content and store image infos into session + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','projectImageView.zpt')).__of__(self) + return pt() + def show_html(self): """simple index""" @@ -1084,12 +917,159 @@ class MPIWGProject(CatalogAware,Folder): pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_index.zpt')).__of__(self) return pt() + def saveFromPreview(self): + """save content aus preview""" + self.WEB_project_description=self.previewTemplate.WEB_project_description[0:] + self.REQUEST.RESPONSE.redirect("./index.html") + + def saveEditedContent(self,kupu=None,preview=None): + """save Edited content""" + + if preview: + kupu=preview + #find content of body tags + start=kupu.find("") + end=kupu.find("") + newcontent= kupu[start+6:end] + + if preview: + + return self.preview(newcontent) + + self.copyObjectToArchive() + self.WEB_project_description=newcontent[0:] + + self.REQUEST.RESPONSE.redirect("./index.html") + + return True + + security.declareProtected('View management screens','edit') + def edit(self,western=None): + """Edit pages""" + if western: + self.REQUEST.RESPONSE.setCookie("MP_debug_code","western",path="/") + + + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGProjectNeu.zpt')).__of__(self) + return pt() + + edit_MPIWGProject_main = PageTemplateFile('zpt/edit_MPIWGProject_main', globals()) + + def getPathStyle(self, path, selected, style=""): + """returns a string with the given style + 'sel' if path == selected.""" + + if path == selected: + return style + 'sel' + else: + return style + + def preview(self,description): + """preview""" + tmpPro=getattr(self,"previewTemplate",None) + if not tmpPro: + tmpPro=MPIWGProject("previewTemplate") + self._setObject("previewTemplate",tmpPro) + for field in definedFields: + setattr(tmpPro,field,getattr(self,field)) + tmpPro.WEB_project_description=description[0:] + tmpPro.invisible=True + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','previewFrame.zpt')).__of__(self) + return pt() + + #return self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+"/previewTemplate") + + + def getWebProject_description(self): + """get description""" + debug= self.REQUEST.cookies.get("MP_debug_code",None) + + if debug and debug=="western": + return """ + + + + + %s + + """%self.WEB_project_description[0] + + return """ + + + + + %s + + """%self.getContent('WEB_project_description') + + + def editMPIWGProjectForm(self): """editform""" pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGProject.zpt')).__of__(self) return pt() - def editMPIWGProject(self,RESPONSE=None): + def isResponsibleScientist(self,key): + """teste ob eine Person in der Liste der respl. scientists auftaucht""" + #logging.info("XXXXXXXXXXXXX"+repr(self.responsibleScientistsList)) + + + keys = [x[1] for x in getattr(self,"responsibleScientistsList",[])] + + if key in keys: + return True + else: + return False + + def getPersonKeyList(self): + """gibt die key Lister der beteiligten Personen zurŸck""" + return [x[1] for x in getattr(self,'responsibleScientistsList',[])] + + + + + def identifyNames(self,nameList): + """Bekommt eine Komma oder Semikolon getrennte Liste mit Name der Form Vorname MittelName(n) Nachname + und ordnet diese dann Mitarbeiter IDs zu falls es schone eine Liste gibt wird im Projekte gibt wird diese Upgedated. + @param nameList + """ + nameList=nameList.replace(";",",") # falls ; als Trenner ersetze + names=nameList.split(",") + + returnNamesDict={} + + + for name in names: + name=name.lstrip().rstrip() + nameSplitted = name.split(" ") + if len(nameSplitted)>1: #vor und nachname angegeben) + + lastname=nameSplitted[-1] + firstname=nameSplitted[0] + else: + firstname ="" + lastname=nameSplitted[0] + + #finde Mitarbeiter mit den entsprechenden Name + logging.info("Search: %s %s %s"%(name,firstname,lastname)) + firstname=firstname.capitalize() + lastname=lastname.capitalize() + cataloggedNames=self.MembersCatalog(firstName=firstname,lastName=lastname) + + #Teste ob die ensprechenden Namen schon der Liste zu geordnet sind + #if not hasattr(self,'responsibleScientistsList'): + # self.responsibleScientistsList={} + # + # if name in self.responsibleScientistsList.values() + + if len(cataloggedNames)>0: + returnNamesDict[name]=cataloggedNames + else: + returnNamesDict[name]=[] + + return returnNamesDict + + def editMPIWGProject(self,RESPONSE=None,fromEdit=None): """edit the project and archive the old version""" self.copyObjectToArchive() # archive the object @@ -1100,35 +1080,90 @@ class MPIWGProject(CatalogAware,Folder): setattr(self,x,[self.REQUEST[x].decode('utf-8')]) + + + completedAt = self.REQUEST.get('completedAt') + if not self.setCompletedAt(completedAt): + RESPONSE.redirect('./editMPIWGBasisEditor?error="dateWrong') + + startedAt = self.REQUEST.get('startedAt') + if not self.setStartedAt(startedAt): + RESPONSE.redirect('./editMPIWGBasisEditor?error="dateWrong') - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + if self.REQUEST.has_key('historicalNames'): + self.en.changeHistoricalNames(self.getId(),self.REQUEST['historicalNames'].split("\n")) + + if self.REQUEST.has_key('active'): + self.setActiveFlag(True) + else: + self.setActiveFlag(False) + + self.responsibleScientistsList=[] # setze die Liste der verantwortlichen Wissenschaftler zurueck + + names={} + keys={} + tmpList=[] + for key in self.REQUEST.keys(): #gehe durch das Formular + splitted=key.split("_") + if splitted[0]=="responsibleScientist": #wenn es ein Feld der Form reponsibleScientist_nr_KEY gibt + nr=splitted[2] + if splitted[1]=="name": + names[nr]=self.REQUEST[key] + elif splitted[1]=="key": + keys[nr]=self.REQUEST[key] + + + for nr in names.keys(): + tmpList.append((names[nr],keys.get(nr,""))) + + self.responsibleScientistsList=tmpList + if fromEdit and (RESPONSE is not None): + #RESPONSE.redirect('./editMPIWGBasisEditor') + return self.editMPIWGBasisEditor(identifiedNames=self.identifyNames(self.REQUEST.get('xdata_01',''))) + + else: + if RESPONSE is not None: + RESPONSE.redirect('manage_main') + + + security.declareProtected('View managment screens','editMPIWGDisciplinesThemesEditor') + def editMPIWGDisciplinesThemesEditor(self): + """edit from edit""" + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGDisciplinesThemesNeu.zpt')).__of__(self) + return pt() + + def editMPIWGDisciplinesThemesForm(self): """edit the disciplines and themes Form""" + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGDisciplinesThemes.zpt')).__of__(self) return pt() - def editMPIWGDisciplinesThemes(self,disciplines=None,themes=None,RESPONSE=None): + def editMPIWGDisciplinesThemes(self,disciplines=None,themes=None,RESPONSE=None,fromEdit=None): """edit disciplin and form""" if disciplines: if type(disciplines) is StringType: self.xdata_09=disciplines else: - self.xdata_09=string.join(disciplines,";") + self.xdata_09=";".join(disciplines) else: self.xdata_09="" if themes: if type(themes) is StringType: self.xdata_10=themes else: - self.xdata_10=string.join(themes,";") + self.xdata_10=";".join(themes) else: self.xdata_10="" - - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + + if fromEdit and (RESPONSE is not None): + RESPONSE.redirect('./editMPIWGDisciplinesThemesEditor') + + else: + if RESPONSE is not None: + RESPONSE.redirect('manage_main') def isChecked(self,wert,list): @@ -1140,16 +1175,32 @@ class MPIWGProject(CatalogAware,Folder): else: splitted=list[0].split(";") - + splitted=[y.rstrip().lstrip() for y in splitted] + for x in splitted: + x=re.sub(r"[^A-z ]","",x) if (not x==u'') and x in wert: return 1 return 0 - + + security.declareProtected('View management screens','editMPIWGBasisEditor') + def editMPIWGBasisEditor(self, identifiedNames=None): + + """editform""" + if not identifiedNames: + identifiedNames=self.identifyNames(self.getContent('xdata_01')) + # identifiedNames=self.getFullNameEntries() + + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGBasisNeu.zpt')).__of__(self) + return pt(identifiedNames=identifiedNames) + + security.declareProtected('View management screens','editMPIWGBasisForm') def editMPIWGBasisForm(self): """editform""" pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGBasis.zpt')).__of__(self) return pt() + + security.declareProtected('View management screens','editMPIWGRelatedPublicationsForm') def editMPIWGRelatedPublicationsForm(self): """Edit related Publications""" pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGRelatedPublications.zpt')).__of__(self) @@ -1207,6 +1258,6 @@ def manage_addMPIWGProject(self,id,RESPO self._setObject(id,newObj) - + if RESPONSE is not None: RESPONSE.redirect('manage_main')