--- MPIWGWeb/MPIWGProjects.py 2004/10/21 14:28:09 1.39 +++ MPIWGWeb/MPIWGProjects.py 2012/01/18 18:55:19 1.47.2.128 @@ -1,850 +1,838 @@ """This contains the class MPIWG Projects -for organizing and maintaining the different projectspages +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 Products.MPIWGBibliography.BibliographyManager import BibliographyManager +from OFS.Image import Image from Globals import package_home import urllib -import MPIWGStaff -import string import re -import os +import os +import email from types import * - -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 OFS.Image import Image +from AccessControl import ClassSecurityInfo +from AccessControl import getSecurityManager from bibliography import * +import time +from OFS.Cache import Cacheable +import xmlrpclib +#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: - print "error",x[1],y[1] - 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""" +#import MPIWGStaff - meta_type="MPIWGTemplate" +from MPIWGHelper import * - def __init__(self, id, text=None, content_type=None,MPIWGType=None): - self.id = str(id) +import MPIWGRoot +import MPIWGLink +import MPIWGTemplate +import transaction +# die folgenden Klassen sind jetzt in einzelne Files ausgelagert aus Kompatibilitaetsgruenden, bleiben die Klassen hier noch drin. +# Sonst funktionieren die alten Webseiten nicht mehr. - 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) - +class MPIWGRoot(MPIWGRoot.MPIWGRoot): + """depricated""" - """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 - +class MPIWGLink(MPIWGLink.MPIWGLink): + """depricated""" + +class MPIWGTemplate(MPIWGTemplate.MPIWGTemplate): + """depricated""" + +class MPIWGProject_publication(Folder): + """publications object fuer project""" -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 + meta_type="MPIWGProject_publication" + def redirect(self,RESPONSE,url): + """mache ein redirect mit einem angehaengten time stamp um ein reload zu erzwingen""" - 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 + timeStamp=time.time() + + if url.find("?")>-1: #giebt es schon parameter + addStr="&time=%s" 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) + addStr="?time=%s" + + RESPONSE.setHeader('Last-Modified',email.Utils.formatdate().split("-")[0]+'GMT') + logging.debug(email.Utils.formatdate()+' GMT') + RESPONSE.redirect(url+addStr%timeStamp) - try: - u = self.DestinationURL() - except AttributeError: - u = REQUEST['URL1'] - - - REQUEST.RESPONSE.redirect(u+'/manage_main') - return '' - - -class MPIWGRoot(ZSQLExtendFolder): - """Stammordner für den Web-Server""" - - 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' - - 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) - - os.popen("java -classpath %s -Djava.awt.headless=true Convert %s"%(fmJarPath,xmlPath),"r").read() - - return 1 - - 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==''): - return format%field - else: - return "" + def hasLinkToBookPage(self,mode="not_cached"): + """teste ob eingebener link zu einer MPIWG Book page geht""" - - def redirectIndex_html(self,request): - #return request['URL1']+'/index_html' - return urllib.urlopen(request['URL1']+'/index_html').read() - + logging.debug("MPIWGProject_publication - begin hasLinkToBookPage") + if (getattr(self,'link','')==''): + return False #es gibt keinen link + + logging.debug("MPIWGProject_publication - begin hasLinkToBookPage:"+self.link) + server = xmlrpclib.ServerProxy(self.link) + + if(mode=="cached"): + if (hasattr(self,"_v_hasLinkToBookPage")): + logging.debug("haslink cached") + return self._v_hasLinkToBookPage + + try: + server.getImageUrls() + logging.debug("MPIWGProject_publication - end TRUE") + self._v_hasLinkToBookPage=True + return True + except: + logging.debug("MPIWGProject_publication - end FALSE ") + self._v_hasLinkToBookPage=True + return False + - def formatBibliography(self,here,found): - """format""" - return formatBibliography(here,found) - def getValue(self,fieldStr): - """Inhalt des Feldes""" + def getImageUrls(self,mode="not_cached"): + """get the image urls""" - if type(fieldStr)==StringType: - field=fieldStr - else: - field=fieldStr[0] + if (getattr(self,'link','')==''): + return [] #es gibt keinen link + + server = xmlrpclib.ServerProxy(self.link) + + + if(mode=="cached"): + if (hasattr(self,"_v_imageUrls")): + logging.debug("getImageURL cached") + return self._v_imageUrls + try: - if field[len(field)-1]==";": - field=field[0:len(field)-1] + urls = server.getImageUrls() + ret=[] + for url in urls: + url = os.path.join(self.link,url) + ret.append(url) + except: + self._v_imageUrls=[] + return [] + self._v_imageUrls=ret[0:] + return ret + + def editPublication(self,text=None,image1=None,image2=None,description=None,link=None,RESPONSE=None): + """edit a publication""" - """nothing""" - field=re.sub(r';([^\s])','; \g<1>',field) - return field.encode('utf-8') - - - - 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) and (not description): + 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) + + if text: + self.text=text[0:] + + if description: + self.description=description + + if link: + self.link=link[0:] + + if image1: + if hasattr(self,'publicationImage1'): + self.publicationImage1.manage_upload(image1) + else: + nO = Image('publicationImage1','',image1) + self._setObject('publicationImage1',nO) + if image2: + if hasattr(self,'publicationImage2'): + self.publicationImage2.manage_upload(image2) + else: + nO = Image('publicationImage2','',image2) + self._setObject('publicationImage2',nO) + - - try: - last_x=x.split()[len(x.split())-1] - last_y=y.split()[len(y.split())-1] + self.ZCacheable_invalidate() + if RESPONSE: + self.redirect(RESPONSE,"../managePublications") - except: +class MPIWGProject_relatedProject(Folder): + """publications object fuer project""" - last_x="" - last_y="" - - - - if last_xlast_y: - return -1 - else: - return 0 + meta_type="MPIWGProject_relatedProject" + def redirect(self,RESPONSE,url): + """mache ein redirect mit einem angehaengten time stamp um ein reload zu erzwingen""" + + timeStamp=time.time() + + if url.find("?")>-1: #giebt es schon parameter + addStr="&time=%s" + else: + addStr="?time=%s" - list.sort(sortLastName) - list.reverse() + RESPONSE.setHeader('Last-Modified',email.Utils.formatdate().split("-")[0]+'GMT') + logging.debug(email.Utils.formatdate()+' GMT') + RESPONSE.redirect(url+addStr%timeStamp) + - return list - - def __init__(self, id, title): - """init""" - self.id=id - self.title=title + def editRelatedProject(self,link=None,RESPONSE=None): + """edit a publication""" - def urlQuote(self,str): - """quote""" - return urllib.quote(str) - - def urlUnQuote(self,str): - """quote""" - return urllib.unquote(str) - - def harvestHistoricalPersons(self): - """erstelle liste aller erwaehnten actors""" - - def normalize(str): - """loesche fuhrendes space""" - if (len(str)>1) and (str[0]==" "): - ret=str[1:] - else: - ret=str - return ret + if (not link): + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_relatedProjectForm.zpt')).__of__(self) + return pt() + + + + - list={} - projects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject']) + # hole die id des projektes + splitted=link.split("/") - for project in projects: - lg=len(project[1].xdata_03[0])-1 - - if (lg>1) and (project[1].xdata_03[0][lg]==";"): - project[1].xdata_03[0]=project[1].xdata_03[0][0:lg] + #teste ob es das project gibt + if len(splitted)<1: + self.redirect(RESPONSE,'errorRelatedProjects?link='+link) + + objid=splitted[-1] + object = getattr(self.projects,objid,None) + + if object==None: + self.redirect(RESPONSE,'errorRelatedProjects?link='+link) + + - - - - 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]]) + + + self.orginallink=link[0:] + self.objid=objid[0:] + + self.projectWEB_title=object.getContent('WEB_title')[0:] + + self.enabled=True; + self.ZCacheable_invalidate() + + if RESPONSE: + self.redirect(RESPONSE,"../manageRelatedProjects") - except: - print "ERROR",project - - return list +class MPIWGProject_image(Image): + """Images 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])]) + meta_type="MPIWGProject_image" - if RESPONSE is not None: - RESPONSE.redirect("showHistoricalPersons") - + 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 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() + + if file and (not file.filename.lstrip().rstrip()==""): + self.manage_upload(file) - def getPersonDict(self,name): - """name von dict""" + if caption: + self.caption=caption[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') - + if RESPONSE: + self.redirect(RESPONSE,"../manageImages") - def showHistoricalPersons(self): - """show persons""" - pt=PageTemplateFile('Products/MPIWGWeb/zpt/showHistoricalPersons').__of__(self) - return pt() +class MPIWGProject(CatalogAware,Folder,Cacheable): + """Class for Projects""" + + def _p_resolveConflict(self, oldState, savedState, newState): + return newState + security=ClassSecurityInfo() + meta_type='MPIWGProject' + default_catalog='ProjectCatalog' + + def redirect(self,RESPONSE,url): + """mache ein redirect mit einem angehaengten time stamp um ein reload zu erzwingen""" - def editHistoricalPersonsForm(self): - """edit historical persons for consistency""" - pt=PageTemplateFile('Products/MPIWGWeb/zpt/editHistoricalPersonsForm').__of__(self) - return pt() + timeStamp=time.time() + + if url.find("?")>-1: #giebt es schon parameter + addStr="&time=%s" + else: + addStr="?time=%s" + + RESPONSE.setHeader('Last-Modified',email.Utils.formatdate().split("-")[0]+'GMT') + logging.debug(email.Utils.formatdate()+' GMT') + RESPONSE.redirect(url+addStr%timeStamp) - 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('Products/MPIWGWeb/zpt/changeMPIWGRootForm').__of__(self) - return pt() + 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)) - def changeMPIWGRoot(self,title,disciplineList,themesList,RESPONSE=None): - """change""" - self.title=title - self.disciplineList=disciplineList - self.themesList=themesList + logging.debug("MPIWGProjects begin: sorted by place: "+ metatype) + founds=self.ZopeFind(self,obj_metatypes=[metatype]); + + founds.sort(sort) + logging.debug("MPIWGProjects end: sorted by place: "+ metatype) + return founds + - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + def copyPublicationsToList(self,RESPONSE=None): + """copy publications in to list""" - 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 + publicationTxt=self.getContent('WEB_related_pub') - 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: + pubSplits=publicationTxt.split("

") - 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=[] - - objects=self.ZopeFind(self,obj_metatypes=['MPIWGProject'],search_sub=1) + for pubSplit in pubSplits: + pubSplit=pubSplit.replace("

","") + self.addPublication(pubSplit) + setattr(self,"WEB_related_pub_copied",True); + + if RESPONSE: - for object in objects: - obj=object[1] - if fieldName=="WEB_title_or_short": - - 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 - - ret.append((obj,obj.getContent(fieldNameTmp))) - + self.redirect(RESPONSE,'managePublications') - if sort=="int": - ret.sort(sortI) - else: - ret.sort(sortF) + def hasRelatedPublicationsOldVersion(self): + """teste ob es related publications gibt""" - 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 - + ret = True; + if (self.getContent('WEB_related_pub')==''): + ret=False; #nichts im alten feld + logging.debug("webrel:"+repr(ret)) + if (getattr(self,'WEB_related_pub_copied',False)): + ret=False; # alte daten sind schon kopiert worden - 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'}, - ) + logging.debug("webrel_copied:"+repr(ret)) + publications=self.ZopeFind(self,obj_metatypes=['MPIWGProject_publication']); + + if(len(publications)>0): + ret=False; # es gibt publicationen in der neuen liste + + + logging.debug("len(publ)"+repr(ret)) + + return ret; - def importNamesForm(self): - """Form""" - pt=PageTemplateFile('Products/MPIWGWeb/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() + def hasRelatedDigitalSources(self): + """test ob es digital sources gibt""" - for line in load.split('\r'): + + ret = (self.getContent('xdata_11').lstrip().rstrip()=='') + + + return not ret; - splitted=line.split(",") - # print splitted - if not (splitted[0]==""): - newObj=MPIWGStaff.MPIWGStaff(splitted[0],splitted[1],splitted[2]) + + + def copyImageToMargin(self,RESPONSE=None): + """copy inline images to marginal images""" + + + #getImages from WEB_project_description + description=self.getContent('WEB_project_description') + + text2=description + splitted=text2.split("""

""") + + 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: - print "not done:",splitted[0] - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + try: + imageURLs.append(tmp[0].split("src=")[1].split(" ")[0].encode('utf-8')) + except: + imageURLs.append("") + + split2="

".join(tmp[1:]) + - def updateHomepages(self,RESPONSE): - """lege members an""" + splitted=split2.split("""

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

") + imageCaptions.append(tmp[0].encode('utf-8')) + + + 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 - 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: - project._setObject(found.username,newObj) - RESPONSE.write("

new:%s

\n"%found.username) + try:#relative url + data=urllib.urlopen(url).read() + except: + try:#absolute + data=urllib.urlopen(self.imageURL).read() except: - RESPONSE.write("

old:%s (%s,%s)

\n"%(found.username,found.name,found.vorname)) + logger("MPIWG Project",logging.ERROR,"can't open: %s"%url) + + obj=getattr(self,filename) + obj.update_data(data) + + if RESPONSE: + + self.redirect(RESPONSE,'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 - #delete non existing + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_manageImagesForm.zpt')).__of__(self) + return pt() + def managePublications(self,pubName=None,op=None): + """managage images""" - 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()) - self.MembersCatalog.manage_catalogReindex(self.REQUEST,RESPONSE,self.REQUEST['URL1']) + 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 + + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_managePublicationsForm.zpt')).__of__(self) + return pt() - - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + def manageRelatedProjects(self,pubName=None,op=None): + """managage relatedProjectd""" - - 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')) + if pubName and op: + if op=='up': + relatedProjects=self.getRelatedProjects() + for project in relatedProjects: + if project[0]==pubName: + nr=relatedProjects.index(project) + if not nr==0: + relatedProjects[nr-1][1].place+=1 + relatedProjects[nr][1].place-=1 + pass + elif op=='down': + relatedProjects=self.getRelatedProjects() + for project in relatedProjects: + if project[0]==pubName: + nr=relatedProjects.index(project) + if not (nr==len(relatedProjects)-1): + relatedProjects[nr+1][1].place-=1 + relatedProjects[nr][1].place+=1 + pass - for x in self.ZopeFind(self.members,obj_metatypes=['MPIWGStaff']): - ret.append(x[1].title.decode('utf-8')) - - ret.sort() - #print ret - - return ret - def printAllMembers(self): - """prin""" - members=self.getAllMembers() - ret="" - for x in members: - ret+="

%s

"%x - return ret + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_manageRelatedProjectsForm.zpt')).__of__(self) + return pt() + + def hasExtendedPublicationList(self): + """test if extended publication list exists""" + if not hasattr(self,"publicationList"): + return False + else: + return True - 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)) + def createExtendedPublicationList(self,RESPONSE=None): + """erzeuge erweiterte publications liste""" + pl = BibliographyManager("publicationList","","institutsbiblio",self.connection_id) + self._setObject("publicationList", pl) + + + zt=ZopePageTemplate('index.html') + pl._setObject('index.html',zt) + default_content_fn = os.path.join(package_home(globals()), + 'zpt/showExtendedProjectBibliography.zpt') + text = open(default_content_fn).read() + zt.pt_edit(text, 'text/html') - 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: + self.redirect(RESPONSE,"managePublications") + + def getPublications(self): + """get all Publications""" + def sort_images(x,y): + return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0)) - if RESPONSE is not None: - RESPONSE.redirect('showTree') + publications=self.ZopeFind(self,obj_metatypes=['MPIWGProject_publication']) - def changeTree(self,RESPONSE=None): - """change the complete tree""" - form=self.REQUEST.form - hashList={} - fields=self.getTree() + publications.sort(sort_images) + return publications + def getRelatedProjects(self): + """get all Publications""" + def sort_images(x,y): + return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0)) + + publications=self.ZopeFind(self,obj_metatypes=['MPIWGProject_relatedProject']) - for idNr in form.keys(): - fields[int(idNr)][3].xdata_05=form[idNr] + publications.sort(sort_images) + return publications + def addPublication(self,text,RESPONSE=None): + """add an MPIWG_Publication""" + number=self.getLastPublicationNumber()+1 + name="publication_"+str(number) + while hasattr(self,name): + number+=1 + name="publication_"+str(number) + newPublication=MPIWGProject_publication(name) + self._setObject(name,newPublication) + obj=getattr(self,name) + obj.text=text[0:] + obj.enabled=True; + obj.place=self.getLastPublicationNumber()+1 + obj.id=name + self.ZCacheable_invalidate() if RESPONSE is not None: - RESPONSE.redirect('showTree') + + self.redirect(RESPONSE,'managePublications') - def getProjectWithId(self,id): - fields=self.getProjectFields('xdata_05') - for field in fields: - if field[1]==id: - return field[0] + def errorRelatedProjects(self,link): + """error creating a related project""" + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_project_error_relatedProject.zpt')).__of__(self) + return pt(link=link) + + def addRelatedProject(self,link,RESPONSE=None): + """add an MPIWG_Publication""" - 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=='': - - try: - proj=self.MembersCatalog({'title':search}) - except: - proj=None - - 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,";") + number=self.getLastPublicationNumber()+1 + name="RelatedProject"+str(number) + while hasattr(self,name): + number+=1 + name="RelatedProject_"+str(number) + + # hole die id des projektes + splitted=link.split("/") + + #teste ob es das project gibt + if len(splitted)<1: + self.redirect(RESPONSE,'errorRelatedProjects?link='+link) + + objid=splitted[-1] + object = getattr(self.projects,objid,None) + + if object==None: + self.redirect(RESPONSE,'errorRelatedProjects?link='+link) + return + + newPublication=MPIWGProject_relatedProject(name) + + self._setObject(name,newPublication) + obj=getattr(self,name) + obj.orginallink=link[0:] + obj.objid=objid[0:] + logging.debug("add relobj:objid"+repr(obj.objid)) + obj.projectWEB_title=object.getContent('WEB_title')[0:] + logging.debug("add relobj:webtitle"+repr(obj.projectWEB_title)) + obj.enabled=True; + obj.place=self.getLastRelatedProjectNumber()+1 + obj.id=name + self.ZCacheable_invalidate() + if RESPONSE is not None: - - 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=='': - - 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 + self.redirect(RESPONSE,'manageRelatedProjects') - 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) - + + + def getLastPublicationNumber(self): + publications=self.getPublications() - 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') - - y=name - splitted=y.split(",") - #XXXX - splitNeu=["\'"+splitted[1]+" "+splitted[0]+"\'"] - - #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((splitted[1]==" Christoph") and (splitted[0]=="Hoffmann") and (str(x.WEB_title).find('Einstein')>0)): - - #print repr(splitted[1]),repr(splitted[0]),repr(x.WEB_title) - proj2.append(x) - # proj2.sort(sortP) - # ret.append((y,proj2)) - 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) + if not publications: + return 0 + else: + return getattr(publications[-1][1],'place',0) + + def getLastRelatedProjectNumber(self): + publications=self.getRelatedProjects() + + if not publications: + return 0 + else: + return getattr(publications[-1][1],'place',0) + + def deletePublication(self,id,RESPONSE=None): + """delete Publication id""" + self.manage_delObjects([id]) + self.ZCacheable_invalidate() + if RESPONSE: + + self.redirect(RESPONSE,'managePublications') + + def deleteRelatedProject(self,id,RESPONSE=None): + """delete Publication id""" + self.manage_delObjects([id]) + self.ZCacheable_invalidate() + if RESPONSE: + + self.redirect(RESPONSE,'manageRelatedProjects') + + def getImages(self): + """get all Images""" + def sort_images(x,y): + return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0)) - proj2.sort(sortP) - if len(proj2)>0: - ret.append((y,proj2)) + 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='' - return ret - - def givePersonList(self,name): - """check if person is in personfolder and return list of person objects""" + images=self.ZopeFind(self,obj_metatypes=['MPIWGProject_image']) - 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}) + images.sort(sort_images) + return images - if proj: - return [[x.lastName,x.firstName] for x in proj] + def getLastImageNumber(self): + images=self.getImages() + + if not images: + return 0 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'): - -## 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 getattr(images[-1][1],'place',0) + + def deleteImage(self,id,RESPONSE=None): + """delete Image id""" + try: + self.manage_delObjects([id]) + except: + logging.error("ERROR MPIWG: %s %s"%sys.exc_info()[0:2]) + if RESPONSE: + self.redirect(RESPONSE,'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) - return objs + if ct and len(ct)>0: + return True + else: + return False + + 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 - def personCheck(self,names): - """all persons for list""" - #print "names",names - splitted=names.split(";") - ret={} - for name in splitted: + if RESPONSE is not None: + + self.redirect(RESPONSE,'manageImages') - if not (name==""): - try: - ret[name]=self.givePersonList(name) - except: - """NOTHIHN""" - #print "RET",ret - return ret + def PrincipiaSearchSource(self): + """Return cataloguable key for ourselves.""" + return str(self) + + def versionHeader(self): + """version Header, gibt header text entsprechend der aktuellen version aus""" + + actualTime=time.localtime() + retTXT="""

This is an outdated version, for the actual version please refer to %s

""" + s=self.aq_parent.absolute_url() + #print getattr(self,'archiveTime',actualTime) + if getattr(self,'archiveTime',actualTime)< actualTime: + return retTXT%(s,s) + else: + return "" - 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 - + 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 - def isCheckField(self,fieldname): - """return chechfield""" - - return (fieldname in checkFields) + #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 - - - -def manage_addMPIWGRootForm(self): - """form for adding the root""" - pt=PageTemplateFile('Products/MPIWGWeb/zpt/addMPIWGRootForm.zpt').__of__(self) - return pt() -def manage_addMPIWGRoot(self,id,title,RESPONSE=None): - """add a root folder""" - newObj=MPIWGRoot(id,title) - self._setObject(id,newObj) + else: + finds.sort(sortProjectsByTime) - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + 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() + + + #print getattr(self,'archiveTime',actualTime) + if getattr(self,'archiveTime',actualTime)< actualTime: + return 0 + else: + return 1 + def isActualForIndex(self): #isActual kann nicht indiziert werden, da intern fom ZCAtalog verwendete Funktion + """gibt 1 zurueck wenn aktuell, 0 sonst""" + actualTime=time.localtime() + + + #print getattr(self,'archiveTime',actualTime) + if getattr(self,'archiveTime',actualTime)< actualTime: + return 0 + else: + return 1 + + def copyObjectToArchive(self): + """kopiere aktuelles objekt ins archiv""" + logging.info("copytoarchive 1") + cb=self.aq_parent.manage_copyObjects(self.getId()) + logging.info("copytoarchive 2") + self.manage_pasteObjects(cb) + logging.info("copytoarchive 3") + actualTime=time.localtime() + + self.manage_renameObject(self.getId(),self.getId()+"_"+time.strftime("%Y%m%d%H%M%S",actualTime)) + logging.info("copytoarchive 4") + obj=getattr(self,self.getId()+"_"+time.strftime("%Y%m%d%H%M%S",actualTime)) + obj.setArchiveTime(time.strftime("%Y%m%d%H%M%S",actualTime)) + logging.info("copytoarchive 5") + ids=[x[0] for x in self.ZopeFind(obj,obj_metatypes=['MPIWGProject'])] + logging.info("copytoarchive 6") + obj.manage_delObjects(ids) + logging.info("copytoarchive 7") + + def setArchiveTime(self,time): + """set Archive Time""" + self.archiveTime=time[0:] + + def delArchiveTime(self): + """delete archive time""" + del self.archiveTime + + def versionManageForm(self): + """version Manage form:currently only set to invisible""" + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_versionManageForm.zpt')).__of__(self) + return pt() -class MPIWGProject(Folder): - """Class for Projects""" + def versionManage(self,invisible=None,RESPONSE=None): + """version Manage form:currently only set to invisible""" + self.invisible=invisible - meta_type='MPIWGProject' + if RESPONSE is not None: + + self.redirect(RESPONSE,'manage_main') def crossLinker(self): @@ -862,13 +850,13 @@ class MPIWGProject(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 @@ -880,19 +868,23 @@ class MPIWGProject(Folder): self._setObject(id,newObj) #self.manage_addPageTemplate(id,title) if RESPONSE is not None: - RESPONSE.redirect('manage_main') + self.redirect(RESPONSE,'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,'') @@ -903,17 +895,280 @@ class MPIWGProject(Folder): {'label':'Edit BasisInfo','action':'editMPIWGBasisForm'}, {'label':'Edit Publications','action':'editMPIWGRelatedPublicationsForm'}, {'label':'Edit Themes & Disciplines','action':'editMPIWGDisciplinesThemesForm'}, + {'label':'Versionmanager','action':'versionManageForm'}, ) - def index_html(self): + 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=self.getCompletedAt() + + #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 "" + # test ob parent abgeschlossen ist + try: #TODO: ersetzte try except durch vernuenftige abfrage + ct=self.getContexts(parents=self.getContent('xdata_05'),depth=1) + if (len(ct)>0): #is there are parent + return ct[0][0].getCompletedAt() + return ''; + except: + return ''; + + def getStartedAt(self): + """gibt das transformierte Datum zurueck, 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 angebenen Werte + werden auf 0 gesetzt, es wird null zurueckgegeben 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: #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: + #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() + + #kein passendes gefunden, dann teste ob das aktuelle in frage kommt + ad=getattr(self,'creationTime','20050101000000') + + if int(date)>int(ad): + + return self.REQUEST['URL1']+"/"+self.getId() + else: + return self.REQUEST['URL1']+"/no_project" + + + 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 harvest_page(self,context=None,mode="normal"): + """seite fuer harvesting fuer die Projektsuche""" + + if not context: + context=self + + if self.isActiveProject() and self.isActual(): + templates = self.en.getHarvestCache() + + ext=getattr(self,"harvest_main",None) + if ext: + rendered = getattr(self,ext.getId())() + templates[self.absolute_url()]=rendered + transaction.commit() + return rendered + + + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','harvest_main')).__of__(context) + + rendered = pt() + templates[self.absolute_url()]=rendered + transaction.commit() + return rendered + + + + def index_html(self,request=True,context=None): """show homepage""" - ext=self.ZopeFind(self.aq_parent,obj_ids=["project_main"]) + + bound_names={} + + 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"]) + + + request2=getattr(self,'REQUEST',None) + + if request2 is not None: + response = request2.response + if not response.headers.has_key('content-type'): + response.setHeader('content-type', 'text/html') + + security = getSecurityManager() + bound_names['user'] = security.getUser() + + # Retrieve the value from the cache. + keyset = None + if self.ZCacheable_isCachingEnabled(): + + # Prepare a cache key. + keyset = {'here': self, 'params':request2['QUERY_STRING']} + + result = self.ZCacheable_get(keywords=keyset) + + if result is not None: + # Got a cached value. + return result + + pt = getTemplate(self, "project_main") + # Execute the template in a new security context. + security.addContext(self) + try: + #logging.debug("index_html pt=%s"%repr(pt)) + result = pt.pt_render(extra_context=bound_names) + #logging.debug("index_html result=%s"%repr(result)) + if keyset is not None: + # Store the result in the cache. + self.ZCacheable_set(result, keywords=keyset) + + return result + finally: + security.removeContext(self) + + + + def index_html_old(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('Products/MPIWGWeb/zpt/project_main').__of__(self) return pt() @@ -934,126 +1189,505 @@ class MPIWGProject(Folder): """get attrbiute""" return getattr(self,field) - def getContent(self,field): + def getContent(self,field,filter=None): """Inhalt des Feldes""" + #logging.debug("getContent field=%s filter=%s"%(field,filter)) + if field=="short_title": + text = self.getContent("xdata_07") + if text=="": + text = self.getContent("WEB_title") + return text + text=u'' - #print "FIELD",field + for x in getattr(self,field): - #print "HIHIIII" try: - text +=x.encode('utf-8') + text +=x except: - try: - text =x.encode('utf-8') - except: - text=x.decode('latin-1').encode('utf-8') + text = x + - #delete separator (;) if is there is one - ## try: -## print text, text[len(text)-1] -## except: -## print "error:",text + try: if text[len(text)-1]==";": text=text[0:len(text)-1] except: - """nothing""" - - text2=re.sub(r';([^\s])','; \g<1>',text) + pass + + if text=='': ## wozu die folgenden Zeilen?? + text2=text + else: + text2=re.sub(r';([^\s])','; \g<1>',text) + + if field=="WEB_project_description":##Jedenfalls darf letzteres nicht gemacht werden, falls normaler text + text2=text + #teste ob ergebnis leer und header dann nehme title 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 text2=="Otto Sibum": - #text2="H. Otto Sibum" - 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+"

" + + + #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""" #return "HI" - pt=PageTemplateFile('Products/MPIWGWeb/zpt/MPIWGProject_index.zpt').__of__(self) + 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""" + #logging.debug("saveEditedContent kupu=%s preview=%s"%(kupu,preview)) + + 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.ZCacheable_invalidate() + 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 getLabel(self): + """returns label (or title) of this project""" + l = self.getContent('xdata_07') + if l: + return l + l = self.getContent('WEB_title') + if l: + return l + return self.title + + def getBreadcrumbs(self): + """return list of breadcrumbs from here to the root""" + crumbs = [] + # skip direct parent Folder /projects/ + parent = self.aq_parent.aq_parent + # get parents breadcrumbs + if hasattr(parent, 'getBreadcrumbs'): + crumbs = parent.getBreadcrumbs() + + # try to get acquisition URL from parent + if hasattr(parent, 'absolute_url'): + baseUrl = "%s/%s/"%(parent.absolute_url(), 'projects') + else: + baseUrl = "/en/research/projects/" + + # add in the internal project hierarchy + + ct=self.getContexts(parents=self.getContent('xdata_05')) + # start with grandparents + ct.reverse() + for c in ct: + label = shortenString(c[0].getLabel(), 13) + crumbs.append((label, baseUrl+c[0].getId(), c[0])) + + # add this project + crumbs.append((self.getLabel(), baseUrl+self.getId(), self)) + + return crumbs + + def getRootProject(self): + """returns the root (=top level) project of the current project""" + + ct=self.getContexts(parents=self.getContent('xdata_05')) + if len(ct) > 0: + return ct[-1][0] + else: + return self + + + def preview(self,description): + """preview""" + #logging.debug("preview description=%s"%description) + 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('zpt/previewFrame.zpt',globals()).__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('Products/MPIWGWeb/zpt/edit_MPIWGProject.zpt').__of__(self) + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGProject.zpt')).__of__(self) return pt() - def editMPIWGProject(self,RESPONSE=None): - """edit the project""" + def isResponsibleScientist(self,key): + """teste ob eine Person in der Liste der respl. scientists auftaucht""" + #logging.info("XXXXXXXXXXXXX"+repr(self.responsibleScientistsList)) + + + keys = [unicodify(x[1]) for x in getattr(self,"responsibleScientistsList",[])] + #logging.error("RESP. SCIEN:%s"%getattr(self,"responsibleScientistsList",[])) + #logging.error("RESP. SCIEN:%s"%unicodify(key)) + + if unicodify(key) in keys: + return True + else: + return False + + def getPersonKeyList(self): + """gibt die key Liste der beteiligten Personen zurueck (utf8 codiert)""" + #logging.error("getPersonKeyList:%s"%getattr(self,'responsibleScientistsList',[])) + try: + return [utf8ify(x[1]) for x in getattr(self,'responsibleScientistsList',[])] + except: + return[] + + + def myCapitalize(self,txt): + """kapitalisiere auch Namen mit -""" + splitted=[x.capitalize() for x in txt.split("-")] + return "-".join(splitted) + + def getNamesOrdered(self,list): + """Sortiert die Liste nach der Reihenfolge in xdata_01""" + + nameList=self.getContent('xdata_01') + if nameList.find(";")>-1: # rate Trenner ist ; + names=nameList.split(";") + else: + names=nameList.split(",") + + self._v_names=[] + for name in names: + self._v_names.append(name.rstrip().lstrip()) + + + def sort(x,y): + try: + return cmp(self._v_names.index(x[0]),self._v_names.index(y[0])) + except: + return 0 + + list.sort(sort) + + return list + + ##nameList=nameList.replace(";",",") # falls ; als Trenner ersetze + + + + + 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 + """ + + if nameList.find(";")>-1: # rate Trenner ist ; + names=nameList.split(";") + + else: + names=nameList.split(",") + + ##nameList=nameList.replace(";",",") # falls ; als Trenner ersetze + 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 + + firstname=self.myCapitalize(firstname).encode('utf-8') + lastname=self.myCapitalize(lastname).encode('utf-8') + logging.info("Search: %s %s %s"%(name,repr(firstname),repr(lastname))) + try: + cataloggedNames=self.MembersCatalog(firstName=firstname,lastName=lastname) + except: + cataloggedNames=[] + logging.error("ERROR: identifyNames %s %s"%sys.exc_info()[0:2]) + + #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]=[] + + logging.error("id: %s"%repr(returnNamesDict)) + return returnNamesDict + + def editMPIWGProject(self,RESPONSE=None,fromEdit=None): + """edit the project and archive the old version""" + + self.copyObjectToArchive() # archive the object + self.ZCacheable_invalidate() - #return self.REQUEST for x in definedFields: if self.REQUEST.has_key(x): 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 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():#schreibe keys und namen in die Liste, stelle ausserdem sicher, dass name unicode + tmpList.append((unicodify(names[nr]),unicodify(keys.get(nr,"")))) + + self.responsibleScientistsList=tmpList + if fromEdit and (RESPONSE is not None): + #RESPONSE.redirect('./editMPIWGBasisEditor') + return self.editMPIWGBasisEditor(identifiedNames=self.identifyNames(self.decode(self.REQUEST.get('xdata_01','')))) - if RESPONSE is not None: - RESPONSE.redirect('manage_main') + 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('Products/MPIWGWeb/zpt/edit_MPIWGDisciplinesThemes.zpt').__of__(self) + + 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): + self.redirect(RESPONSE,'./editMPIWGDisciplinesThemesEditor') + + else: + if RESPONSE is not None: + RESPONSE.redirect('manage_main') def isChecked(self,wert,list): """check if wert is in ; seperated list""" - print "W:",wert - print "L:",list,type(list) + #felder sind manchmnal als liste mit einem element definiert if type(list) is StringType or UnicodeType: splitted=list.split(";") else: splitted=list[0].split(";") - print splitted + 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() + + logging.error("IdentifiedNames: %s"% repr(identifiedNames)) + 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('Products/MPIWGWeb/zpt/edit_MPIWGBasis.zpt').__of__(self) + 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('Products/MPIWGWeb/zpt/edit_MPIWGRelatedPublications.zpt').__of__(self) + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGRelatedPublications.zpt')).__of__(self) return pt() def loadNewFileForm(self): """Neues XML-File einlesen""" - pt=PageTemplateFile('Products/MPIWGWeb/zpt/MPIWGProject_newfile.zpt').__of__(self) + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_newfile.zpt')).__of__(self) return pt() def loadNewFile(self,RESPONSE=None): @@ -1079,9 +1713,17 @@ class MPIWGProject(Folder): if RESPONSE is not None: RESPONSE.redirect('manage_main') + def tagTheProject(self,RESPONSE=None): + """TAG""" + id=self.getId(); + tmpl =getattr(self.thesaurus,"main.html") + if RESPONSE: + RESPONSE.redirect("./thesaurus/main.html?project="+id) + return + def manage_addMPIWGProjectForm(self): """form for adding the project""" - pt=PageTemplateFile('Products/MPIWGWeb/zpt/addMPIWGProjectForm.zpt').__of__(self) + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addMPIWGProjectForm.zpt')).__of__(self) return pt() def manage_addMPIWGProject(self,id,RESPONSE=None): @@ -1089,7 +1731,7 @@ def manage_addMPIWGProject(self,id,RESPO #print argv fileupload=self.REQUEST.get('fileupload',None) if fileupload: - print fileupload + file_name=fileupload.filename filedata=fileupload.read() @@ -1102,6 +1744,6 @@ def manage_addMPIWGProject(self,id,RESPO self._setObject(id,newObj) - + if RESPONSE is not None: RESPONSE.redirect('manage_main')