--- MPIWGWeb/MPIWGProjects.py 2004/03/10 09:17:31 1.5
+++ MPIWGWeb/MPIWGProjects.py 2008/06/24 11:16:26 1.47.2.84
@@ -1,349 +1,465 @@
-"""This files contains the class MPIWG Projects"""
+"""This contains the class MPIWG Projects
+for organizing and maintaining the different project pages
+
+"""
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.PageTemplates.PageTemplate import PageTemplate
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
-
+from Products.ZSQLExtend.ZSQLExtend import ZSQLExtendFolder
+from Products.ZCatalog.CatalogPathAwareness import CatalogAware
+from OFS.Image import Image
+from Globals import package_home
+import urllib
import MPIWGStaff
import string
import re
+import os
from types import *
-
-import xmlhelper # Methoden zur Verwaltung der projekt xmls
+import logging
+import xmlhelper # Methoden zur Verwaltung der projekt xml
from OFS.SimpleItem import SimpleItem
from OFS.Folder import Folder
+from Products.ZSQLMethods.SQL import SQLConnectionIDs
+from AccessControl import ClassSecurityInfo
+from bibliography import *
+import time
+import xml.dom.minidom
+import sys
+from Ft.Xml.XPath import Evaluate
+from Ft.Xml.XPath.Context import Context
+from Ft.Xml.Domlette import NonvalidatingReader,PrettyPrint, Print
+from Ft.Xml import EMPTY_NAMESPACE
+import copy
+import updatePersonalWWW
+import MPIWGStaff
-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']
+from MPIWGHelper import *
-checkFields = ['xdata_01']
+import MPIWGRoot
+import MPIWGLink
+import MPIWGTemplate
-def sortF(x,y):
+class MPIWGRoot(MPIWGRoot.MPIWGRoot):
+ """depricated"""
+
+class MPIWGLink(MPIWGLink.MPIWGLink):
+ """depricated"""
+
+class MPIWGTemplate(MPIWGTemplate.MPIWGTemplate):
+ """depricated"""
- return cmp(x[1],y[1])
+class MPIWGProject_publication(SimpleItem):
+ """publications object fuer project"""
-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
+ meta_type="MPIWGProject_publication"
- 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])
+ def editPublication(self,text=None,RESPONSE=None):
+ """edit a publication"""
-
-class MPIWGRoot(Folder):
- """Stammordner für den Web-Server"""
+ if (not text):
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_publicationForm.zpt')).__of__(self)
+ return pt()
- folders=['MPIWGProject','Folder']
- meta_type='MPIWGRoot'
-
- def __init__(self, id, title):
- """init"""
- self.id=id
- self.title=title
+
+ self.text=text[0:]
- 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 RESPONSE:
+ RESPONSE.redirect("../managePublications")
+
+class MPIWGProject_image(Image):
+ """Images for Projects"""
- if obj.meta_type in self.folders:
-
- ret += self.getProjectFields(fieldName,obj)
+ meta_type="MPIWGProject_image"
- if sort=="int":
- ret.sort(sortI)
- else:
- ret.sort(sortF)
-
- return ret
-
- def showNewProjects(self):
- projects=[]
- for objs in self.getProjectFields('WEB_title_or_short'): # Get all Projets
- if objs[0].xdata_05[0] == "":
-
- projects.append(objs)
-
- return projects
-
-
- manage_options = Folder.manage_options+(
- {'label':'Import Persons','action':'importNamesForm'},
- )
-
- def importNamesForm(self):
- """Form"""
- pt=PageTemplateFile('Products/MPIWGWeb/zpt/MPIWGNamesForm.zpt').__of__(self)
+ 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 importNames(self,fileupload,folderName,RESPONSE=None):
- """import komma-sep list email,lastName,firstName"""
- project=getattr(self,folderName)
-
- for line in fileupload.readlines():
- #print line
- splitted=line.split(",")
- if not (splitted[0]==""):
- newObj=MPIWGStaff.MPIWGStaff(splitted[0],splitted[1],splitted[2])
- try:
- project._setObject(splitted[0],newObj)
- except:
- print "not done:",splitted[0]
- if RESPONSE is not None:
- RESPONSE.redirect('manage_main')
+ if caption:
+ self.caption=caption[0:]
- def getAllMembers(self):
- """give list of all members"""
- ret=[]
+ if RESPONSE:
+ RESPONSE.redirect("../manageImages")
- for x in self.members.objectValues('MPIWGStaff'):
- #print x.title
- ret.append(x.title)
-
- ret.sort()
- return ret
+class MPIWGProject(CatalogAware,Folder):
+ """Class for Projects"""
- 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
- returnList.append((depth,nr,title,project[0]))
-
- return returnList
-
- 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
- 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(0)
- numbers.sort()
- highest=int(numbers[len(numbers)-1])
- projects=self.showNewProjects()
- for i in self.makeList(select):
- highest+=10
- projects[int(i)][0].xdata_05=treeId+"."+str(highest)
+ security=ClassSecurityInfo()
+ meta_type='MPIWGProject'
+ default_catalog='ProjectCatalog'
- 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 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]);
- for idNr in form.keys():
- fields[int(idNr)][3].xdata_05=form[idNr]
-
+ founds.sort(sort)
+ return founds
+
- if RESPONSE is not None:
- RESPONSE.redirect('showTree')
+ def copyPublicationsToList(self,RESPONSE=None):
+ """copy publications in to list"""
- def getProjectWithId(self,id):
- fields=self.getProjectFields('xdata_05')
- for field in fields:
- if field[1]==id:
- return field[0]
+ publicationTxt=self.getContent('WEB_related_pub')
- return None
-
+ pubSplits=publicationTxt.split("
")
+
+ for pubSplit in pubSplits:
+ pubSplit=pubSplit.replace("
","")
+ self.addPublication(pubSplit)
+
+ if RESPONSE:
+ RESPONSE.redirect('managePublications')
-
+
+ def copyImageToMargin(self,RESPONSE=None):
+ """copy inline images to marginal images"""
-
- def getUrlFromPerson(self,list):
- """get urls to person list"""
- ret=[]
- persons=list.split(";")
- for person in persons:
-
- 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=='':
+ #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:
- proj=self.MembersCatalog({'title':search})
+ imageURLs.append(tmp[0].split("\"")[1].encode('utf-8'))
except:
- proj=None
+
+ try:
+ imageURLs.append(tmp[0].split("src=")[1].split(" ")[0].encode('utf-8'))
+ except:
+ imageURLs.append("")
+
+ split2="".join(tmp[1:])
+
+
+ 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
- if proj:
- ret.append("%s"%(proj[0].absolute_url,person))
- else:
- ret.append("%s"%person)
- return string.join(ret,";")
-
- def getProjectsOfMembers(self):
- """give tuple member /projects"""
- ret=[]
- members=self.getAllMembers()
- for x in members:
- splitted=x.split(",")
-
- proj=self.ProjectCatalog({'xdata_01':string.join(splitted,' AND')})
- if proj:
- ret.append((x,proj))
- return ret
- def givePersonList(self,name):
- """check if person is in personfolder and return list of person objects"""
+ 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)
- splitted=name.split(",")
- if len(splitted)==1:
- splitted=name.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=='':
- 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))
+ if RESPONSE:
+ RESPONSE.redirect('manageImages')
+
+ def manageImages(self,imageName=None,op=None):
+ """managage images"""
+
+
+ if imageName and op:
+ if op=='up':
+ images=self.getImages()
+ for image in images:
+ if image[0]==imageName:
+ nr=images.index(image)
+ if not nr==0:
+ images[nr-1][1].place+=1
+ images[nr][1].place-=1
+ pass
+ elif op=='down':
+ images=self.getImages()
+ for image in images:
+ if image[0]==imageName:
+ nr=images.index(image)
+ if not (nr==len(images)-1):
+ images[nr+1][1].place-=1
+ images[nr][1].place+=1
+ pass
+
+
+ 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"""
+
+
+ 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()
+
+ def getPublications(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_publication'])
- return objs
+ publications.sort(sort_images)
+ return publications
+ def addPublication(self,text,RESPONSE=None):
+ """add an MPIWG_Publication"""
- def personCheck(self,names):
- """all persons for list"""
- #print "names",names
- splitted=names.split(";")
- ret={}
- for name in splitted:
+ name="publication_"+str(self.getLastPublicationNumber()+1)
+
+ newPublication=MPIWGProject_publication(name)
- if not (name==""):
- try:
- ret[name]=self.givePersonList(name)
- except:
- """NOTHIHN"""
- #print "RET",ret
- return ret
+ 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('managePublications')
- 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 getLastPublicationNumber(self):
+ publications=self.getPublications()
+ 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])
+ if RESPONSE:
+ RESPONSE.redirect('managePublications')
+
+ def getImages(self):
+ """get all Images"""
+
+ def sort_images(x,y):
+ return cmp(getattr(x[1],'place',0),getattr(y[1],'place',0))
+
+
+ if (getattr(self,'imageURL','')!='') or (getattr(self,'imagecap','')!='') :
+ try:
+ self.addImage(None,getattr(self,'imagecap',''),RESPONSE=None,filename=getattr(self,'imageURL',''))
+ except:
+ pass
+ self.imageURL=''
+ self.imagecap=''
- def isCheckField(self,fieldname):
- """return chechfield"""
+ images=self.ZopeFind(self,obj_metatypes=['MPIWGProject_image'])
- return (fieldname in checkFields)
+ images.sort(sort_images)
+ return images
-
-
+ def getLastImageNumber(self):
+ images=self.getImages()
-def manage_addMPIWGRootForm(self):
- """form for adding the root"""
- pt=PageTemplateFile('Products/MPIWGWeb/zpt/addMPIWGRootForm.zpt').__of__(self)
- return pt()
+ 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 manage_addMPIWGRoot(self,id,title,RESPONSE=None):
- """add a root folder"""
- newObj=MPIWGRoot(id,title)
- self._setObject(id,newObj)
+
+ def addImage(self,fileHd,caption,RESPONSE=None,filename=None):
+ """add an MPIWG_Project_image"""
- if RESPONSE is not None:
- RESPONSE.redirect('manage_main')
+ if not filename:
+ filename=fileHd.filename
+
+ if not fileHd:
+ fileHd=file(os.path.join(package_home(globals()),'blank.gif'))
+
+ newImage=MPIWGProject_image(filename,filename,fileHd)
+
+ self._setObject(filename,newImage)
+ obj=getattr(self,filename)
+ obj.caption=caption[0:]
+ obj.enabled=True;
+ obj.place=self.getLastImageNumber()+1
+ obj.id=filename
+
+ if RESPONSE is not None:
+ RESPONSE.redirect('manageImages')
+
+ 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 getActualVersion(self,date=None):
+ """actuelle version"""
+ def sortProjectsByTime(x,y):
+ return cmp(x[1].archiveTime,y[1].archiveTime)
+
+ if not date:
+ if self.isActual():
+ return self
+ else:
+ return None
+
+ #suche ob aeltere versionen vorhanden sind
+
+ finds=self.ZopeFind(self,obj_metatypes=['MPIWGProject'])
+ if not finds: #wenn nicht dann teste ob die aktuelle version schon existiert hat.
+ ad=getattr(self,'creationTime','20050101000000')
+ if int(date)>int(ad):
+ return self
+ else:
+ return None
+
+
+ else:
+ finds.sort(sortProjectsByTime)
+
+ for find in finds:
+ #gehe durch die alten Projekte und finde das entprechende
+ if (int(find[1].archiveTime) > int(date)) and (int(date)>int(getattr(find[1],'creationTime','20050101000000'))):
+ return find[1]
+
+ #kein passendes gefunden, dann teste ob das aktuelle in frage kommt
+ ad=getattr(self,'creationTime','20050101000000')
+
+ if int(date)>int(ad):
+
+ return self
+ else:
+ return None
+
+
+ def isActual(self):
+ """gibt 1 zurueck wenn aktuell, 0 sonst"""
+ actualTime=time.localtime()
+
+
+ #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()
@@ -365,7 +481,7 @@ class MPIWGProject(Folder):
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
@@ -380,13 +496,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:
- setattr(self,arg,argv[arg])
+ try:
+ setattr(self,arg,argv[arg])
+ except:
+ setattr(self,arg,"")
else:
for arg in definedFields:
setattr(self,arg,'')
@@ -396,13 +519,272 @@ class MPIWGProject(Folder):
{'label':'Edit ProjectInfo','action':'editMPIWGProjectForm'},
{'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 getCompletedAt(self):
+ """gibt das transformierte Datum zurŸck"""
+ date=getattr(self,'completedAt','')
+ 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))
+ 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=="" ) :
+ return "";
+
+ if (date==None):
+ return None;
+
+ 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=[]
for x in range(1,14):
- ret.append('xdata_%02i'%x)
+ if not x in [6,10,9]: # not used fields
+ ret.append('xdata_%02i'%x)
return ret
def getDefinedFields(self):
@@ -414,60 +796,388 @@ 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
except:
+ text = x
+
+
+
+ try:
+ if text[len(text)-1]==";":
+ text=text[0:len(text)-1]
+
+
+ except:
+ pass
+
+ if text=='':
+ text2=text
+ else:
+ 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')
+
+ if filter:
+ splitted=text2.split("""""")
+ if len(splitted)>1:
+ tmp=splitted[1].split("
")
+ #return repr(splitted[1])
try:
- text =x
+ self.imageURL=tmp[0].split("\"")[1].encode('utf-8')
except:
- text="ERROR"
- #print "TEXT",text.encode('ascii','ignore')
- return text
+ 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 editMPIWGProjectForm(self):
- """editform"""
- pt=PageTemplateFile('Products/MPIWGWeb/zpt/edit_MPIWGProject.zpt').__of__(self)
+ 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 editMPIWGBasisForm(self):
- """editform"""
- pt=PageTemplateFile('Products/MPIWGWeb/zpt/edit_MPIWGBasis.zpt').__of__(self)
+ def getPathStyle(self, path, selected, style=""):
+ """returns a string with the given style + 'sel' if path == selected."""
+
+ if path == selected:
+ return style + 'sel'
+ else:
+ return style
+
+ def preview(self,description):
+ """preview"""
+ tmpPro=getattr(self,"previewTemplate",None)
+ if not tmpPro:
+ tmpPro=MPIWGProject("previewTemplate")
+ self._setObject("previewTemplate",tmpPro)
+ for field in definedFields:
+ setattr(tmpPro,field,getattr(self,field))
+ tmpPro.WEB_project_description=description[0:]
+ tmpPro.invisible=True
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','previewFrame.zpt')).__of__(self)
return pt()
- def editMPIWGRelatedPublicationsForm(self):
- """Edit related Publications"""
- pt=PageTemplateFile('Products/MPIWGWeb/zpt/edit_MPIWGRelatedPublications.zpt').__of__(self)
+
+ #return self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+"/previewTemplate")
+
+
+ def getWebProject_description(self):
+ """get description"""
+ debug= self.REQUEST.cookies.get("MP_debug_code",None)
+
+ if debug and debug=="western":
+ return """
+
+
+
+
+ %s
+
+ """%self.WEB_project_description[0]
+
+ return """
+
+
+
+
+ %s
+
+ """%self.getContent('WEB_project_description')
+
+
+
+ def editMPIWGProjectForm(self):
+ """editform"""
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGProject.zpt')).__of__(self)
return pt()
+
+ def 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 editMPIWGProject(self,RESPONSE=None):
- """edit the project"""
+ def getPersonKeyList(self):
+ """gibt die key Lister der beteiligten Personen zurŸck"""
+ return [x[1] for x in getattr(self,'responsibleScientistsList',[])]
+
- #return self.REQUEST
+
+
+ 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))
+ cataloggedNames=self.MembersCatalog(firstName=firstname,lastName=lastname)
+
+ #Teste ob die ensprechenden Namen schon der Liste zu geordnet sind
+ #if not hasattr(self,'responsibleScientistsList'):
+ # self.responsibleScientistsList={}
+ #
+ # if name in self.responsibleScientistsList.values()
+
+ if len(cataloggedNames)>0:
+ returnNamesDict[name]=cataloggedNames
+ else:
+ returnNamesDict[name]=[]
+
+ return returnNamesDict
+
+ def editMPIWGProject(self,RESPONSE=None,fromEdit=None):
+ """edit the project and archive the old version"""
+
+ self.copyObjectToArchive() # archive the object
+
+
for x in definedFields:
if self.REQUEST.has_key(x):
- setattr(self,x,[self.REQUEST[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')
+
+ 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(os.path.join(package_home(globals()),'zpt','edit_MPIWGDisciplinesThemes.zpt')).__of__(self)
+ return pt()
+
+ 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,";")
+ else:
+ self.xdata_09=""
+ if themes:
+ if type(themes) is StringType:
+ self.xdata_10=themes
+ else:
+ self.xdata_10=string.join(themes,";")
+ else:
+ self.xdata_10=""
+
+ 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"""
+
+ #felder sind manchmnal als liste mit einem element definiert
+ if type(list) is StringType or UnicodeType:
+ splitted=list.split(";")
+ else:
+ splitted=list[0].split(";")
+
+ splitted=[y.rstrip().lstrip() for y in splitted]
+
+ for x in splitted:
+ x=re.sub(r"[^A-z ]","",x)
+ if (not x==u'') and x in wert:
+ return 1
+ return 0
+
+ security.declareProtected('View management screens','editMPIWGBasisEditor')
+ def editMPIWGBasisEditor(self, identifiedNames=None):
+
+ """editform"""
+ if not identifiedNames:
+ identifiedNames=self.identifyNames(self.getContent('xdata_01'))
+ # identifiedNames=self.getFullNameEntries()
+
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGBasisNeu.zpt')).__of__(self)
+ return pt(identifiedNames=identifiedNames)
+
+ security.declareProtected('View management screens','editMPIWGBasisForm')
+ def editMPIWGBasisForm(self):
+ """editform"""
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGBasis.zpt')).__of__(self)
+ return pt()
+
+ security.declareProtected('View management screens','editMPIWGRelatedPublicationsForm')
+ def editMPIWGRelatedPublicationsForm(self):
+ """Edit related Publications"""
+ pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','edit_MPIWGRelatedPublications.zpt')).__of__(self)
+ 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):
@@ -495,27 +1205,27 @@ 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):
"""method to add a project"""
#print argv
- if self.REQUEST.has_key('fileupload'):
- fileupload=self.REQUEST['fileupload']
- if fileupload:
- file_name=fileupload.filename
- filedata=fileupload.read()
-
- argv=xmlhelper.proj2hash(filedata)
+ fileupload=self.REQUEST.get('fileupload',None)
+ if fileupload:
- #print argv
+ file_name=fileupload.filename
+ filedata=fileupload.read()
+
+ argv=xmlhelper.proj2hash(filedata)
+
+ #print argv
newObj=MPIWGProject(id,argv)
else:
newObj=MPIWGProject(id)
self._setObject(id,newObj)
-
+
if RESPONSE is not None:
RESPONSE.redirect('manage_main')