--- MPIWGWeb/MPIWGProjects.py 2004/09/10 19:59:28 1.30
+++ MPIWGWeb/MPIWGProjects.py 2008/08/28 18:20:09 1.47.2.92
@@ -1,731 +1,507 @@
"""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
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 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
+
+#import MPIWGStaff
+
+from MPIWGHelper import *
+
+import MPIWGRoot
+import MPIWGLink
+import MPIWGTemplate
-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']
+# die folgenden Klassen sind jetzt in einzelne Files ausgelagert aus Kompatibilitaetsgruenden, bleiben die Klassen hier noch drin.
+# Sonst funktionieren die alten Webseiten nicht mehr.
-checkFields = ['xdata_01']
+class MPIWGRoot(MPIWGRoot.MPIWGRoot):
+ """depricated"""
+
+class MPIWGLink(MPIWGLink.MPIWGLink):
+ """depricated"""
+
+class MPIWGTemplate(MPIWGTemplate.MPIWGTemplate):
+ """depricated"""
+
+class MPIWGProject_publication(Folder):
+ """publications object fuer project"""
+ meta_type="MPIWGProject_publication"
+ def editPublication(self,text=None,image1=None,image2=None,description=None,RESPONSE=None):
+ """edit a publication"""
-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
+ if (not text) and (not description):
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_publicationForm.zpt')).__of__(self)
+ return pt()
- try:
- xret=xret+"%04i"%int(ysplit[i])
- except:
- xret=xret+"%04i"%0
-
+
+ self.text=text[0:]
+ self.description=description
- return cmp(int(yret),int(xret))
- except:
- return cmp(x[1],y[1])
-
+ 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)
+
+
+ if RESPONSE:
+ RESPONSE.redirect("../managePublications")
+
+class MPIWGProject_image(Image):
+ """Images for Projects"""
+
+ meta_type="MPIWGProject_image"
+
+ 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()
-class MPIWGRoot(ZSQLExtendFolder):
- """Stammordner für den Web-Server"""
+ 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)
- 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']
- meta_type='MPIWGRoot'
+ if caption:
+ self.caption=caption[0:]
- def replaceNotEmpty(self,format,field):
- """replace not empty"""
- if field and (not field==''):
- return format%field
- else:
- return ""
-
+ if RESPONSE:
+ RESPONSE.redirect("../manageImages")
- def redirectIndex_html(self,request):
- #return request['URL1']+'/index_html'
-
- return urllib.urlopen(request['URL1']+'/index_html').read()
+class MPIWGProject(CatalogAware,Folder):
+ """Class for Projects"""
-
- def formatBibliography(self,here,found):
- """format"""
- return formatBibliography(here,found)
-
- 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:
- """nothing"""
- field=re.sub(r';([^\s])','; \g<1>',field)
- return field.encode('utf-8')
+ security=ClassSecurityInfo()
+ meta_type='MPIWGProject'
+ default_catalog='ProjectCatalog'
+ 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))
+ founds=self.ZopeFind(self,obj_metatypes=[metatype]);
+
+ founds.sort(sort)
+
+ return founds
- 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)
+ def copyPublicationsToList(self,RESPONSE=None):
+ """copy publications in to list"""
- try:
- y=urllib.unquote(y_c).encode('utf-8','ignore')
- except:
- x=urllib.unquote(y_c)
-
+ publicationTxt=self.getContent('WEB_related_pub')
-
- try:
- last_x=x.split()[len(x.split())-1]
- last_y=y.split()[len(y.split())-1]
+ pubSplits=publicationTxt.split("
")
- except:
+ for pubSplit in pubSplits:
+ pubSplit=pubSplit.replace("
","")
+ self.addPublication(pubSplit)
- last_x=""
- last_y=""
-
-
-
- if last_xlast_y:
- return -1
- else:
- return 0
-
- list.sort(sortLastName)
- list.reverse()
+ if RESPONSE:
+ RESPONSE.redirect('managePublications')
- return list
-
- def __init__(self, id, title):
- """init"""
- self.id=id
- self.title=title
-
- 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
+ def copyImageToMargin(self,RESPONSE=None):
+ """copy inline images to marginal images"""
- list={}
- projects=self.ZopeFind(self.projects,obj_metatypes=['MPIWGProject'])
- 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]
-
-
-
+ #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:
- 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]])
-
- except:
- print "ERROR",project
+ try:
+ imageURLs.append(tmp[0].split("\"")[1].encode('utf-8'))
+ except:
+
+ try:
+ imageURLs.append(tmp[0].split("src=")[1].split(" ")[0].encode('utf-8'))
+ except:
+ imageURLs.append("")
- return list
+ split2="".join(tmp[1:])
- 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")
-
-
- def getPersonDict(self,name):
- """name von dict"""
+ splitted=split2.split("""""")
+ if len(splitted)>1:
+ tmp=splitted[1].split("
")
+ imageCaptions.append(tmp[0].encode('utf-8'))
- 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')
-
- def showHistoricalPersons(self):
- """show persons"""
- pt=PageTemplateFile('Products/MPIWGWeb/zpt/showHistoricalPersons').__of__(self)
- return pt()
+ 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 editHistoricalPersonsForm(self):
- """edit historical persons for consistency"""
- pt=PageTemplateFile('Products/MPIWGWeb/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
+ 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)
+
+ obj=getattr(self,filename)
+ obj.update_data(data)
+
+ if RESPONSE:
+ RESPONSE.redirect('manageImages')
- projects=self.ProjectCatalog({fieldName:string.join(fieldContents,' OR')})
- #print projects
- return projects
+ 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
+
- def changeMPIWGRootForm(self):
- """edit"""
- pt=PageTemplateFile('Products/MPIWGWeb/zpt/changeMPIWGRootForm').__of__(self)
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_manageImagesForm.zpt')).__of__(self)
return pt()
- def changeMPIWGRoot(self,title,disciplineList,themesList,RESPONSE=None):
- """change"""
- self.title=title
- self.disciplineList=disciplineList
- self.themesList=themesList
+ def managePublications(self,pubName=None,op=None):
+ """managage images"""
- 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
+ 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 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=[]
- #print "FN",fieldName
- if not folder:
- folder=self
- for object in folder.__dict__:
-
- obj=getattr(folder,object)
- if hasattr(obj,'meta_type'):
- #print obj.meta_type
- if obj.meta_type=='MPIWGProject':
- if fieldName=="WEB_title_or_short":
- #print "HI!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
- #print len(obj.getContent('xdata_07'))
- 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)))
-
- if obj.meta_type in self.folders:
-
- ret += self.getProjectFields(fieldName,obj)
-
- if sort=="int":
- ret.sort(sortI)
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','MPIWGProject_managePublicationsForm.zpt')).__of__(self)
+ return pt()
+ def hasExtendedPublicationList(self):
+ """test if extended publication list exists"""
+ if not hasattr(self,"publicationList"):
+ return False
else:
- ret.sort(sortF)
+ return True
- 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 createExtendedPublicationList(self,RESPONSE=None):
+ """erzeuge erweiterte publications liste"""
+ pl = BibliographyManager("publicationList","","institutsbiblio",self.connection_id)
+ self._setObject("publicationList", pl)
- manage_options = Folder.manage_options+(
- {'label':'Import Persons','action':'importNamesForm'},
- {'label':'Main config','action':'changeMPIWGRootForm'},
- {'label':'Edit Historical Persons','action':'editHistoricalPersonsForm'},
- {'label':'Store Historical Persons','action':'storeHistoricalPersons'},
- )
- def importNamesForm(self):
- """Form"""
- pt=PageTemplateFile('Products/MPIWGWeb/zpt/MPIWGNamesForm.zpt').__of__(self)
- return pt()
+ 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')
- 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
-
- if not (splitted[0]==""):
- newObj=MPIWGStaff.MPIWGStaff(splitted[0],splitted[1],splitted[2])
-
- try:
- project._setObject(splitted[0],newObj)
- #print "done:",splitted[0]
- except:
- print "not done:",splitted[0]
-
- if RESPONSE is not None:
- RESPONSE.redirect('manage_main')
-
- 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'))
+
+ if RESPONSE:
+ RESPONSE.redirect("managePublications")
- ret.sort()
- #print ret
-
- return ret
+ def getPublications(self):
+ """get all Publications"""
+ def sort_images(x,y):
+ return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0))
- def printAllMembers(self):
- """prin"""
- members=self.getAllMembers()
- ret=""
- for x in members:
- ret+="%s
"%x
- return ret
-
+ publications=self.ZopeFind(self,obj_metatypes=['MPIWGProject_publication'])
- 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 """"""%(element[3].absolute_url()+"/index.html",element[3].getContent('WEB_title'))
- if element[3].getContent('xdata_05') == "5":
- return """"""%(element[3].absolute_url()+"/index.html",element[3].getContent('WEB_title'))
-
- return """"""%(element[3].absolute_url()+"/index.html",element[3].getContent('xdata_05'),element[3].getContent('WEB_title'))
-
- elif element[0]==2: #mainprojects
- return """"""%(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))
+ publications.sort(sort_images)
+ return publications
- 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 is not None:
- RESPONSE.redirect('showTree')
-
- def changeTree(self,RESPONSE=None):
- """change the complete tree"""
- form=self.REQUEST.form
- hashList={}
- fields=self.getTree()
+ def addPublication(self,text,RESPONSE=None):
+ """add an MPIWG_Publication"""
+ name="publication_"+str(self.getLastPublicationNumber()+1)
- for idNr in form.keys():
- fields[int(idNr)][3].xdata_05=form[idNr]
+ 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
-
if RESPONSE is not None:
- RESPONSE.redirect('showTree')
-
- def getProjectWithId(self,id):
- fields=self.getProjectFields('xdata_05')
- for field in fields:
- if field[1]==id:
- return field[0]
+ RESPONSE.redirect('managePublications')
- return None
-
+
+ def getLastPublicationNumber(self):
+ publications=self.getPublications()
-
+ if not publications:
+ return 0
+ else:
+ return getattr(publications[-1][1],'place',0)
- 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 ')
+ def deletePublication(self,id,RESPONSE=None):
+ """delete Publication id"""
+ self.manage_delObjects([id])
+ if RESPONSE:
+ RESPONSE.redirect('managePublications')
- if not search=='':
+ def getImages(self):
+ """get all Images"""
- try:
- proj=self.MembersCatalog({'title':search})
- except:
- proj=None
+ 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,";")
-
-
- 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 (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=''
- if proj:
- #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
+ images=self.ZopeFind(self,obj_metatypes=['MPIWGProject_image'])
+
+ images.sort(sort_images)
+ return images
- 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 getLastImageNumber(self):
+ images=self.getImages()
-
- ret=[]
- splitNeu=[]
- if email:
- members=self.ZopeFind(self.members,obj_metatypes=['MPIWGStaff'],obj_ids=[email])
- 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 images:
+ return 0
+ else:
+ return getattr(images[-1][1],'place',0)
+
+ 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
+
+ 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
- proj2.sort(sortP)
+ if RESPONSE is not None:
+ RESPONSE.redirect('manageImages')
- if len(proj2)>0:
- ret.append((y,proj2))
+ 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 ""
- return ret
-
- def givePersonList(self,name):
- """check if person is in personfolder and return list of person objects"""
-
- 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'):
-
-## 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))
+ 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
-
- return objs
+ #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 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
+ else:
+ finds.sort(sortProjectsByTime)
- 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
-
+ 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]
- def isCheckField(self,fieldname):
- """return chechfield"""
+ #kein passendes gefunden, dann teste ob das aktuelle in frage kommt
+ ad=getattr(self,'creationTime','20050101000000')
- return (fieldname in checkFields)
-
-
-
-
+ if int(date)>int(ad):
+
+ return self
+ else:
+ return None
+
+
+ def isActual(self):
+ """gibt 1 zurueck wenn aktuell, 0 sonst"""
+ actualTime=time.localtime()
-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)
-
- if RESPONSE is not None:
- RESPONSE.redirect('manage_main')
+ #print getattr(self,'archiveTime',actualTime)
+ if getattr(self,'archiveTime',actualTime)< actualTime:
+ return 0
+ else:
+ return 1
+
+ def copyObjectToArchive(self):
+ """kopiere aktuelles objekt ins archiv"""
+ cb=self.aq_parent.manage_copyObjects(self.getId())
+ self.manage_pasteObjects(cb)
+ actualTime=time.localtime()
+
+ self.manage_renameObject(self.getId(),self.getId()+"_"+time.strftime("%Y%m%d%H%M%S",actualTime))
+ 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))
+ ids=[x[0] for x in self.ZopeFind(obj,obj_metatypes=['MPIWGProject'])]
+ obj.manage_delObjects(ids)
+
+ def setArchiveTime(self,time):
+ """set Archive Time"""
+ self.archiveTime=time[0:]
+
+ 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:
+ RESPONSE.redirect('manage_main')
+
def crossLinker(self):
"""experimental crosslinker"""
splitted=self.WEB_project_description[0].split()
@@ -741,13 +517,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
@@ -762,16 +538,20 @@ class MPIWGProject(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,'')
@@ -782,8 +562,289 @@ class MPIWGProject(Folder):
{'label':'Edit BasisInfo','action':'editMPIWGBasisForm'},
{'label':'Edit Publications','action':'editMPIWGRelatedPublicationsForm'},
{'label':'Edit Themes & Disciplines','action':'editMPIWGDisciplinesThemesForm'},
+ {'label':'Versionmanager','action':'versionManageForm'},
)
+
+ 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: #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 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.getId())()
+
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','project_main')).__of__(context)
+
+ return pt()
+
+
def getDataFields(self):
"""giveListofDatafields"""
ret=[]
@@ -801,125 +862,436 @@ class MPIWGProject(Folder):
"""get attrbiute"""
return getattr(self,field)
- def getContent(self,field):
+ def getContent(self,field,filter=None):
"""Inhalt des Feldes"""
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"""
+ pass
+
+ if text=='':
+ text2=text
+ else:
+ text2=re.sub(r';([^\s])','; \g<1>',text)
- text2=re.sub(r';([^\s])','; \g<1>',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 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()
- return text2
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"""
+
+ 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 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
+ logging.debug("getbreadcrumbs,: title=%s self=%s parent=%s"%(self.title, repr(self), repr(parent)))
+ if hasattr(parent, 'getBreadcrumbs'):
+ logging.debug("getbreadcrumbs: recurse to %s"%parent)
+ 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 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('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 = [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()
+ try:
+ cataloggedNames=self.MembersCatalog(firstName=firstname,lastName=lastname)
+ except:
+ cataloggedNames=[]
+ #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
+
- #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():
+ 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','')))
- 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):
+ RESPONSE.redirect('./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()
+
+ 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):
@@ -947,7 +1319,7 @@ class MPIWGProject(Folder):
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):
@@ -955,7 +1327,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()
@@ -968,6 +1340,6 @@ def manage_addMPIWGProject(self,id,RESPO
self._setObject(id,newObj)
-
+
if RESPONSE is not None:
RESPONSE.redirect('manage_main')