--- ECHO_content/ECHO_helpers.py 2004/12/02 12:01:08 1.29 +++ ECHO_content/ECHO_helpers.py 2005/12/13 12:45:21 1.69 @@ -1,17 +1,32 @@ +import re import string import socket import urllib import string import xml.dom.minidom -from types import * +import types from Products.PageTemplates.PageTemplateFile import PageTemplateFile +from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from OFS.SimpleItem import SimpleItem from Globals import package_home import Globals from AccessControl import ClassSecurityInfo import os.path +from OFS.Folder import Folder +import ECHO_collection +import base64 +import bz2 +import xmlrpclib -displayTypes = ['ZSQLExtendFolder','ZSQLBibliography','ECHO_group','ECHO_collection','ECHO_resource','ECHO_link','ECHO_sqlElement','ECHO_pageTemplate','ECHO_externalLink','ImageCollectionIFrame','VLP_resource','VLP_essay','ECHO_ZCatalogElement','ImageCollection','versionedFileFolder'] +displayTypes = ['ZSQLExtendFolder','ZSQLBibliography','ECHO_group','ECHO_collection','ECHO_resource','ECHO_link','ECHO_sqlElement','ECHO_pageTemplate','ECHO_externalLink','ImageCollectionIFrame','VLP_resource','VLP_essay','ECHO_ZCatalogElement','ImageCollection','versionedFileFolder','ECHO_movie'] + + +#decode and compress for xmlrpc communication with OSAS_server + +def encodeRPC(string): + return base64.encodestring(bz2.compress(string)) +def decodeRPC(string): + return bz2.decompress(base64.decodestring(string)) def content_html(self,type): """template fuer content""" @@ -24,7 +39,7 @@ def content_html(self,type): obj=getattr(self,type+"_template") return obj() else: - pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_%s_template_standard.zpt'%type).__of__(self) + pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','ECHO_%s_template_standard.zpt'%type)).__of__(self) pt.content_type="text/html" return pt() @@ -32,83 +47,131 @@ def content_html(self,type): class ECHO_basis: """basis eigenschaften fuer echo objekte""" + security=ClassSecurityInfo() + security.declarePublic('getImageTag') + + management_page_charset="utf-8" + + def manage_addECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None): + return ECHO_collection.manage_addECHO_locale(self,lang,title,label) + + def getImageTag(self): + """sollte uerberschrieben werden, falls von der Klasse eine imagetag zurueckkommt""" + + return "" + def showRDF(self): - """showrdf""" + """showrdf""" self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml') - ret="""\n\n""" - ret+=self.getRDF(urn="echo:colllectionroot")+"\n" + ret="""\n\n""" + + ret+=self.getRDF(urn="echo:collectionroot")+"\n" + - ret+="""""" - return ret + ret+="""""" + return ret + def RDF(self): + """showrdf""" + self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml') + ret="""\n\n""" + + ret+=self.getRDF(urn=self.absolute_url())+"\n" + + ret+="""""" + return ret + + def createSubElementRDF(self,urn=None): - """rdf list""" - if not urn: - urn=self.absolute_url() - ret="" - - rettemp="""\n"""%urn - flag=0 - - li="""\n""" - if not ('' in self.getFullTextXML(noredirect='Yes')): - nurn=self.absolute_url()+'/getFullTextXML' - rettemp+=li%nurn - flag=1 - if not ('' in self.getImageView(noredirect='Yes')): - nurn=self.absolute_url()+'/getImageView' - rettemp+=li%nurn - flag=1 - - - if not ('' in self.showMetaDataXML()): - nurn=self.absolute_url()+'/showMetaDataXML' - rettemp+=li%nurn - flag=1 - - rettemp+="" - - if flag==1: - ret+=rettemp - - if not ('' in self.getFullTextXML(noredirect='Yes')): - nurn=self.absolute_url()+'/getFullTextXML' - ret+=getRDFDescription(self,self.absolute_url()+'/getFullTextXML',urn=nurn,nameDef="Fulltext",typeName="ECHO_fulltext") + """rdf list""" + if not urn: + urn=self.absolute_url() + ret="" - if not ('' in self.getImageView(noredirect='Yes')): + rettemp="""\n"""%urn + flag=0 + + li="""\n""" + if not ('' in self.getFullTextXML(noredirect='Yes')): + nurn=self.absolute_url()+'/getFullTextXML' + rettemp+=li%nurn + flag=1 + if not ('' in self.getImageView(noredirect='Yes')): nurn=self.absolute_url()+'/getImageView' - ret+=getRDFDescription(self,self.absolute_url()+'/getImageView',urn=nurn,nameDef="Image View",typeName="ECHO_imageview") - - if not ('' in self.showMetaDataXML()): + rettemp+=li%nurn + flag=1 + + + if not ('' in self.showMetaDataXML()): nurn=self.absolute_url()+'/showMetaDataXML' - ret+=getRDFDescription(self,self.absolute_url()+'/showMetaDataXML',urn=nurn,nameDef="Metadata",typeName="ECHO_metaData") + rettemp+=li%nurn + flag=1 + + rettemp+="" + + if flag==1: + ret+=rettemp + + if not ('' in self.getFullTextXML(noredirect='Yes')): + nurn=self.absolute_url()+'/getFullTextXML' + ret+=getRDFDescription(self,self.absolute_url()+'/getFullTextXML',urn=nurn,nameDef="Fulltext",typeName="ECHO_fulltext") - return ret - + if not ('' in self.getImageView(noredirect='Yes')): + nurn=self.absolute_url()+'/getImageView' + ret+=getRDFDescription(self,self.absolute_url()+'/getImageView',urn=nurn,nameDef="Image View",typeName="ECHO_imageview") + + if not ('' in self.showMetaDataXML()): + nurn=self.absolute_url()+'/showMetaDataXML' + ret+=getRDFDescription(self,self.absolute_url()+'/showMetaDataXML',urn=nurn,nameDef="Metadata",typeName="ECHO_metaData") + + return ret + + def content_html_XMLRpc(self): + """xml_rpc_version""" + return encodeRPC(self.content_html()) + def content_html(self,type="collection"): - """template fuer content bei einbau und ECHO_Umgebung""" - - return content_html(self,type) + """template fuer content bei einbau und ECHO_Umgebung""" + + return content_html(self,type) def getTitle(self): - """title""" - try: - return self.title.encode('utf-8','ignore') - except: - self.title=self.title.decode('iso-8859-1','ignore')[0:] #correnct conding error - return self.title.encode('utf-8','ignore') - + """title""" + lang=self.getLanguage() + locale=None + if lang and not (lang =="de"): + locale=self.ZopeFind(self,obj_ids=["locale_"+lang]) + + if locale: + return self.decode(locale[0][1].title) + else: + return self.decode(self.title) + + def getLabel(self): - """title""" - try: - return self.label.encode('utf-8','ignore') - except: - self.label=self.label.decode('iso-8859-1','ignore')[0:] #correnct conding error - return self.label.encode('utf-8','ignore') - - + """title""" + lang=self.getLanguage() + locale=None + if lang and not (lang=="de"): + locale=self.ZopeFind(self,obj_ids=["locale_"+lang]) + + if locale: + return self.decode(locale[0][1].label) + + + if not hasattr(self,'label'): + self.label="" + + if self.label=="": + ret=self.getTitle() + if ret=="": + ret=self.getId() + return ret + + return self.decode(self.label) + def changeECHOEntriesForm(self): """change Entries for the ECHO Navigation environment""" pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeECHOEntriesForm')).__of__(self) @@ -120,62 +183,280 @@ class ECHO_basis: self.label=label self.weight=weight self.description=description - self.queryString=queryString + self.queryString=queryString if RESPONSE: RESPONSE.redirect("manage_main") manage_options=({'label':'change ECHO Navigation Entries','action':'changeECHOEntriesForm'},) + + def hasOverview(self): + """returns if there is an overview graphics""" + return hasattr(self, 'overview') + + def hasParentOverview(self): + """returns if the parent has an overview graphics""" + return hasattr(self.aq_parent, 'overview') + + def getOverview(self): + """map overview graphics""" + #return self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])[0][1] + if self.hasOverview(): + return getattr(self, 'overview') + return None + def getMapAreas(self): """returns the list of MapAreas""" - # get all contained MapAreas - areas = [res[1] for res in self.ZopeFind(self, obj_metatypes=('MapArea'))] - return areas + forcetypes = self.REQUEST.get('map_force_types', None) + if forcetypes: + typelist = forcetypes.split(',') + else: + typelist = None + areas = [] + # get all contained MapAreas + for res in self.ZopeFind(self, obj_metatypes=('MapArea')): + area = res[1] + # check the allowed types + if typelist is not None and area.getType() not in typelist: + continue + areas.append(area) + return areas def addMapArea(self, newarea): - """add a map area to this object""" - if (newarea.id is None): - # create new id - areas = self.getMapAreas() - newarea.id = "a%02d"%len(areas) - self._setObject(newarea.id, newarea) + """add a map area to this object""" + if (newarea.id is None): + # create new id + ids = [a.id for a in self.getMapAreas()] + i = len(ids) + while ("a%02d"%i in ids): + # if it exists, try the next one + i += 1 + newarea.id = "a%02d"%i + self._setObject(newarea.id, newarea) + + def getMapText(self): + """returns the MapText""" + # get (the first) contained MapText + #lang="en" + lang=self.getLanguage() + res=None + if lang and not (lang=="de"): + resTmp = self.ZopeFind(self, obj_metatypes=('ECHO_mapText')) + res = self.ZopeFind(resTmp[0][1]) + + if not res: + res = self.ZopeFind(self, obj_metatypes=('ECHO_mapText')) + if len(res) > 0: + text = res[0][1] + return text + return None + + def ECHO_graphicEntry(self): + """change map coordinates""" + if self.hasParentOverview(): + pt=zptFile(self, 'zpt/ECHO_draw.zpt') + return pt() + else: + return "NO OVERVIEW GRAPHICS" def ECHO_addCoords(self,RESPONSE=None): """change or add MapArea""" - #return self.REQUEST - # change existing areas - for area in self.getMapAreas(): - id = area.getId() - if self.REQUEST.has_key('del.'+id): - # delete this area - self._delObject(id) - # return to same menu - if RESPONSE is not None: - RESPONSE.redirect('ECHO_graphicEntry') - return - # modify this area - coordstring = self.REQUEST.get('coords.'+id, '') - coords = string.split(coordstring, ',') - angle = self.REQUEST.get('angle.'+id, '0') - type = self.REQUEST.get('type.'+id, 'area') - if len(coords) == 4: - area.setCoordString(coordstring) - area.setAngle(angle) - area.setType(type) - # add new area - if self.REQUEST.has_key('add'): - coordstring = self.REQUEST.get('coords.new', '') - coords = string.split(coordstring, ',') - angle = self.REQUEST.get('angle.new', '0') - type = self.REQUEST.get('type.new', 'area') - if len(coords) == 4: - coords.append(angle) - area = MapArea(None, coords, type=type) - self.addMapArea(area) - # return to edit area menu - if RESPONSE is not None: - RESPONSE.redirect('ECHO_graphicEntry') + #return self.REQUEST + # change existing areas + for area in self.getMapAreas(): + id = area.getId() + if self.REQUEST.has_key('del.'+id): + # delete this area + self._delObject(id) + # return to same menu + if RESPONSE is not None: + RESPONSE.redirect('ECHO_graphicEntry') + return + # modify this area + coordstring = self.REQUEST.get('coords.'+id, '') + coords = string.split(coordstring, ',') + angle = self.REQUEST.get('angle.'+id, '0') + type = self.REQUEST.get('type.'+id, 'area') + permanent = self.REQUEST.get('permanent.'+id, '') + if len(coords) == 4: + area.setCoordString(coordstring) + area.setAngle(angle) + area.setType(type) + area.setPermanent(permanent) + # add the "new" area + if self.REQUEST.has_key('add'): + coordstring = self.REQUEST.get('coords.new', '') + coords = string.split(coordstring, ',') + angle = self.REQUEST.get('angle.new', '0') + type = self.REQUEST.get('type.new', 'area') + permanent = self.REQUEST.get('permanent.new', '') + if len(coords) == 4: + coords.append(angle) + area = MapArea(None, coords, type=type, permanent=permanent) + self.addMapArea(area) + # return to edit area menu + if RESPONSE is not None: + RESPONSE.redirect('ECHO_graphicEntry') + + def createJSAreas(self, areas): + """create area calls for JavaScript""" + forceperm = self.REQUEST.get('map_force_permanent', None) + js="\n" + for ob in areas: + # check for force-permanent + if forceperm is not None: + perm = forceperm + else: + perm = ob.isPermanent() + js+="""addArea('%s', 'overview', %s, '%s', '%s');\n"""%(ob.getFullId(),ob.getCoordString(),ob.getType(),perm) + return js + + def createMapHead(self): + """create javascript include and script tags for head""" + pt=zptFile(self, 'zpt/ECHO_content_map_frag_js') + return pt() + + def createMapImg(self): + """generate img-tag for map""" + bt = BrowserCheck(self) + tag = "" + src = self.getOverview().absolute_url() + if bt.isN4: + # N4 needs ilayer to create an id + tag += ''%src + else: + # img with id + tag += ''%src + return tag + + def createParentMapImg(self): + """generate img-tag for map of parent""" + return self.aq_parent.createMapImg() + + def createMapLink(self, ob, text=None, target="_blank"): + """generate map link""" + bt = BrowserCheck(self) + id = ob.getFullId() + link = ob.getLinkId() + if text is None: + text = ob.getLabel() + if text is None: + text = "link" + tiptext = ob.getTip() + tag = "" + if bt.isN4: + # N4 needs layer for highlighting + tag += '" + else: + # a-element + tag = '" + return tag + + def createMapAux(self, ob, arrowsrc="http://nausikaa2.rz-berlin.mpg.de/digitallibrary/servlet/Scaler/?dw=15&fn=icons/pfeil", circlesrc="http://nausikaa2.rz-berlin.mpg.de/digitallibrary/servlet/Scaler/?dw=15&fn=icons/kreis", target="_blank",backLink=None,alternativArrowsrc="http://nausikaa2.rz-berlin.mpg.de/digitallibrary/servlet/Scaler/?dw=15&fn=icons/pfeil_blau"): + """generate map link image, text and other stuff""" + bt = BrowserCheck(self) + id = ob.getFullId() + link = ob.getLinkId() + tiptext = ob.getTip() + tag = "" + + if bt.isN4: + # + # N4 needs layer and img elements + # + tag += ''%(id,id,id) + if ob.isTypeArrow(): + # N4 - Arrow + rot = ob.angle + + if hasattr(getattr(self,link),'link'): + cLink=getattr(self,link).link + # if existing delete virtuell path + cLink=cLink.replace('/'.join(self.REQUEST['VirtualRootPhysicalPath']),'') + + if backLink and hasattr(getattr(self,link),'link') and backLink==self.REQUEST['SERVER_URL']+cLink.lstrip(): + marksrc=alternativArrowsrc + else: + marksrc = arrowsrc + + + if float(rot) < 0: + marksrc = circlesrc + tag += ''%(link,marksrc,rot) + elif ob.isTypeText(): + # N4 - Text + tag += '
'%(id,id,id,link,target) + if ob.isTypeArrow(): + # DOM - Arrow + rot = ob.angle + + if hasattr(getattr(self,link),'link'): + cLink=getattr(self,link).link + # if existing delete virtuell path + if hasattr(self.REQUEST,'VirtualRootPhysicalPath'): + cLink=cLink.replace('/'.join(self.REQUEST['VirtualRootPhysicalPath']),'') + + if backLink and hasattr(getattr(self,link),'link') and backLink==self.REQUEST['SERVER_URL']+cLink.lstrip(): + marksrc=alternativArrowsrc + else: + marksrc = arrowsrc + + try: + rot=float(rot) + except: + rot=0 + + if float(rot) < 0: + marksrc = circlesrc + if bt.isIEWin and bt.versIE > 5: + # IE/Win 5.5 has "feature" for PNG transparency + tag += ''%(id,marksrc,rot,marksrc,rot) + else: + # arrow image + tag += ''%(id,marksrc,rot) + elif ob.isTypeText(): + # DOM - Text + tag += '
" - except: - ret+="Error:"+entry[0]+"
" + ret+="OK:"+entry[0]+"-- "+entry[1].getTitle().decode('utf-8')+"-- "+entry[1].getTitle().decode('utf-8')+"
" + except: + ret+="Error:"+entry[0]+"
" - + return ""+ret+"Rerenderd all links to resources in: "+self.title+"" def reloadMetaDataFromStorage(self,RESPONSE=None): - """copy metadata from the storage to ECHO""" - ret="" - resources=self.ZopeFind(self,obj_metatypes=['ECHO_resource'],search_sub=1) - - for resource in resources: - x=str(resource[1].copyIndex_meta2echo_resource())+"
" - ret+=x - #print x - - - if RESPONSE is not None: - #RESPONSE.redirect('./manage_main') - return ""+ret+"" + """copy metadata from the storage to ECHO""" + ret="" + resources=self.ZopeFind(self,obj_metatypes=['ECHO_resource'],search_sub=1) + if RESPONSE is not None: + RESPONSE.setHeader("Content-Type", type) + RESPONSE.write("\n") + + for resource in resources: + x=str(resource[1].copyIndex_meta2echo_resource())+"
" + if RESPONSE is not None: + RESPONSE.write(x+"\n") + + ret+=x + + if RESPONSE is not None: + #RESPONSE.redirect('./manage_main') + RESPONSE.write( "") - return ret + return ret def getRDFDescription(self,linkURL,urn=None,nameDef=None,typeName=None): - """rdf""" - - ret="" - about="""""" - name="""%s""" - link="""%s""" - clickable="""%s""" - #link="""""" - type="""%s""" - #xlink="""""" - if not urn: - #urn="urn:"+re.sub('/',':',self.absolute_url()) - urn=self.absolute_url() - about2=about%urn - if not nameDef: - if hasattr(self,'label') and not (self.label==""): - name2=name%self.label - elif not self.title=="": - name2=name%self.title - else: - name2=name%self.getId() - - name2=re.sub('&','&',name2) - else: - name2=name%nameDef - - linkURL=re.sub('http:','',linkURL) - linkURL2=re.sub('&','&',linkURL) - link2=link%(("http:"+linkURL2),("http:"+urllib.quote(linkURL))) - clickable2=clickable%"true" - - if not typeName: - type2=type%self.meta_type - else: - type2=type%typeName - - #ret=about2+"\n"+name2+"\n"+link2+"\n"+type2+"\n"+clickable2+"\n" - ret=about2+"\n"+name2+"\n"+type2+"\n"+clickable2+"\n" - return ret + """rdf""" + + ret="" + about="""""" + name="""%s""" + link="""%s""" + clickable="""%s""" + #link="""""" + type="""%s""" + #xlink="""""" + if not urn: + #urn="urn:"+re.sub('/',':',self.absolute_url()) + urn=self.absolute_url() + about2=about%urn + if not nameDef: + if hasattr(self,'label') and not (self.label==""): + name2=name%self.label + elif not self.title=="": + name2=name%self.title + else: + name2=name%self.getId() + + name2=re.sub('&','&',name2) + else: + name2=name%nameDef + + linkURL=re.sub('http:','',linkURL) + linkURL2=re.sub('&','&',linkURL) + link2=link%(("http:"+linkURL2),("http:"+urllib.quote(linkURL))) + clickable2=clickable%"true" + + if not typeName: + type2=type%self.meta_type + else: + type2=type%typeName + + #ret=about2+"\n"+name2+"\n"+link2+"\n"+type2+"\n"+clickable2+"\n" + ret=about2+"\n"+name2+"\n"+type2+"\n"+clickable2+"\n" + return ret def getCopyrightsFromForm(self,argv): - medias={} - partners={} - copyrights={} - - copyrightsFinal=[] - for arg in argv.keys(): - - if arg[0:5]=='media': - nm=int(arg[5:]) - medias[nm]=argv[arg] - elif arg[0:5]=='partn': - nm=int(arg[5:]) - partners[nm]=argv[arg] - elif arg[0:5]=='copyr': - nm=int(arg[5:]) - copyrights[nm]=argv[arg] + medias={} + partners={} + copyrights={} + + copyrightsFinal=[] + for arg in argv.keys(): + + if arg[0:5]=='media': + nm=int(arg[5:]) + medias[nm]=argv[arg] + elif arg[0:5]=='partn': + nm=int(arg[5:]) + partners[nm]=argv[arg] + elif arg[0:5]=='copyr': + nm=int(arg[5:]) + copyrights[nm]=argv[arg] - copyrightsList=[(medias[nm],partners[nm],copyrights[nm]) for nm in medias.keys()] - for copyright in copyrightsList: - - if copyright[2]=='institution0000': - copyrightsFinal.append((copyright[0],copyright[1],self.getPartnerCopyright(copyright[1],''))) - else: - if not copyright[0]=='': - copyrightsFinal.append(copyright) - - - return copyrightsFinal + copyrightsList=[(medias[nm],partners[nm],copyrights[nm]) for nm in medias.keys()] + for copyright in copyrightsList: + + if copyright[2]=='institution0000': + copyrightsFinal.append((copyright[0],copyright[1],self.getPartnerCopyright(copyright[1],''))) + else: + if not copyright[0]=='': + copyrightsFinal.append(copyright) + + + return copyrightsFinal #List of different types for the graphical linking viewer viewClassificationListMaster=['view point','area'] def checkDiffs(self,metadict): - """check differences""" + """check differences""" - + - def NoneToEmpty(obj): - if obj: - return obj - else: - return "" - - - - diffs={} - - tags=self.findTagsFromMapping(self.contentType) - self.referencetypes=tags[2] - self.fields=tags[3] - - - for field in tags[1]: - try: - if (NoneToEmpty(self.getFieldValue(self.getFieldTag(tags,field)))==metadict[self.getFieldTag(tags,field)]): - diffs[self.getFieldTag(tags,field)]=1 - else: - - diffs[self.getFieldTag(tags,field)]=0 - except: - diffs[self.getFieldTag(tags,field)]=0 - - return diffs + def NoneToEmpty(obj): + if obj: + return obj + else: + return "" + + + + diffs={} + + tags=self.findTagsFromMapping(self.contentType) + self.referencetypes=tags[2] + self.fields=tags[3] + + + for field in tags[1]: + try: + if (NoneToEmpty(self.getMDValue(self.getFieldTag(tags,field)))==metadict[self.getFieldTag(tags,field)]): + diffs[self.getFieldTag(tags,field)]=1 + else: + + diffs[self.getFieldTag(tags,field)]=0 + except: + diffs[self.getFieldTag(tags,field)]=0 + + return diffs -def zptFile(self, path): +def zptFile(self, path, orphaned=False): """returns a page template file from the product""" - pt=PageTemplateFile(os.path.join(package_home(globals()), path)).__of__(self) + if orphaned: + # unusual case + pt=PageTemplateFile(os.path.join(package_home(globals()), path)) + else: + + pt=PageTemplateFile(os.path.join(package_home(globals()), path)).__of__(self) return pt -def sendFile(self, filename, type): - """sends an object or a local file (in the product) as response""" +def findObjectPath(startobject, filename): + """returns the object with the name filename starting at startobject""" + if startobject is None: + return None paths = filename.split('/') - object = self - # look for an object called filename + object = startobject for path in paths: + if hasattr(object, path): - object = getattr(object, path) - else: - object = None - break + object = getattr(object, path) + else: + object = None + break + return object + + +def zptObjectOrFile(self, filename, localdir='zpt', orphaned=False): + """returns a page template instance or a file from the product""" + # look for an object called path + pt = findObjectPath(self, filename) + # the object should also not be a python function + if (pt is None) or isinstance(pt, types.FunctionType): + # get a ZPT file + pt = zptFile(self, localdir+'/'+filename, orphaned=orphaned) + return pt + + +def sendFile(self, filename, type): + """sends an object or a local file (in the product) as response""" + # look for an object called filename + object = findObjectPath(self, filename) if object: - # if the object exists then send it - return object.index_html(self.REQUEST.REQUEST, self.REQUEST.RESPONSE) + # if the object exists then send it + return object.index_html(self.REQUEST.REQUEST, self.REQUEST.RESPONSE) else: - # send a local file with the given content-type - fn = os.path.join(package_home(globals()), filename) - self.REQUEST.RESPONSE.setHeader("Content-Type", type) - self.REQUEST.RESPONSE.write(file(fn).read()) + # send a local file with the given content-type + fn = os.path.join(package_home(globals()), filename) + self.REQUEST.RESPONSE.setHeader("Content-Type", type) + self.REQUEST.RESPONSE.write(file(fn).read()) return @@ -486,143 +815,142 @@ class BrowserCheck: def __init__(self, zope): """initialisiere""" - self.ua = zope.REQUEST.get_header("HTTP_USER_AGENT") - self.isN4 = False - self.isIE = False - if string.find(self.ua, 'MSIE') > -1: - self.isIE = True - else: - self.isN4 = string.find(self.ua, 'Mozilla/4.') > -1 - try: - self.nav = self.ua[string.find(self.ua, '('):] - ie = string.split(self.nav, "; ")[1] - if string.find(ie, "MSIE") > -1: - self.versIE = string.split(ie, " ")[1] - except: pass - self.isMac = string.find(self.ua, 'Macintosh') > -1 - self.isWin = string.find(self.ua, 'Windows') > -1 - self.isIEWin = self.isIE and self.isWin - self.isIEMac = self.isIE and self.isMac + self.ua = zope.REQUEST.get_header("HTTP_USER_AGENT") + self.isN4 = False + self.isIE = False + if string.find(self.ua, 'MSIE') > -1: + self.isIE = True + else: + self.isN4 = string.find(self.ua, 'Mozilla/4.') > -1 + try: + self.nav = self.ua[string.find(self.ua, '('):] + ie = string.split(self.nav, "; ")[1] + if string.find(ie, "MSIE") > -1: + self.versIE = string.split(ie, " ")[1] + except: pass + self.isMac = string.find(self.ua, 'Macintosh') > -1 + self.isWin = string.find(self.ua, 'Windows') > -1 + self.isIEWin = self.isIE and self.isWin + self.isIEMac = self.isIE and self.isMac - + def writeMetadata(url,metadict,project=None,startpage=None,xslt=None,thumbtemplate=None,topbar=None,digiLibTemplate=None,xmlfrag=None,digiliburlprefix=None): - """Einlesen der Metadaten und und erstellen des geaenderten XML file""" + """Einlesen der Metadaten und und erstellen des geaenderten XML file""" - def updateTextToolNode(tag,value): - #print dom,tag,value - metanode=dom.getElementsByTagName('texttool')[0] - try: - nodeOld=metanode.getElementsByTagName(tag) - except: - nodeOld=None - - if nodeOld: - metanode.removeChild(nodeOld[0]).unlink() - - node=dom.createElement(tag) - nodetext=dom.createTextNode(value) - node.appendChild(nodetext) - metanode.appendChild(node) + def updateTextToolNode(tag,value): - if xmlfrag: - geturl=""" + metanode=dom.getElementsByTagName('texttool')[0] + try: + nodeOld=metanode.getElementsByTagName(tag) + except: + nodeOld=None + + if nodeOld: + metanode.removeChild(nodeOld[0]).unlink() + + node=dom.createElement(tag) + nodetext=dom.createTextNode(value) + node.appendChild(nodetext) + metanode.appendChild(node) + + if xmlfrag: + geturl=""" - - - - - """ - dom=xml.dom.minidom.parseString(geturl) - else: - try: - geturl="" - for line in ECHO_helpers.urlopen(url).readlines(): - geturl=geturl+line - - - except: - return (None,"Cannot open: "+url) - - try: - dom=xml.dom.minidom.parseString(geturl) - except: - return (None,"Cannot parse: "+url+"
"+geturl) - - - - metanodes=dom.getElementsByTagName('bib') - - if not metanodes: - metanodes=dom.getElementsByTagName('archimedes') - - metanode=metanodes[0] - - for metaData in metadict.keys(): - - try: - nodeOld=metanode.getElementsByTagName(metaData) - except: - nodeOld=None - - if nodeOld: - metanode.removeChild(nodeOld[0]).unlink() - else: - # try also old writing rule - instead of _: - try: - nodeOld=metanode.getElementsByTagName(re.sub('_','-',metaData)) - except: - nodeOld=None - - if nodeOld: - metanode.removeChild(nodeOld[0]).unlink() - - metanodeneu=dom.createElement(metaData) - metanodetext=dom.createTextNode(metadict[metaData]) - #try: - #metanodetext=dom.createTextNode(unicode(metadict[metaData],"utf-8")) - #except: - #metanodetext=dom.createTextNode(metadict[metaData].encode('utf-8')) - metanodeneu.appendChild(metanodetext) - metanode.appendChild(metanodeneu) - - - - - - if project: - updateTextToolNode('project',project) - - if startpage: - updateTextToolNode('startpage',startpage) - - if topbar: - updateTextToolNode('toptemplate',topbar) - - if thumbtemplate: - updateTextToolNode('thumbtemplate',thumbtemplate) - - if xslt: - updateTextToolNode('xslt',xslt) - - - if digiliburlprefix: - updateTextToolNode('digiliburlprefix',digiliburlprefix) - - try: - return dom.toxml().encode('utf-8') - except: - return dom.toxml('utf-8') + + + + + """ + dom=xml.dom.minidom.parseString(geturl) + else: + try: + geturl="" + for line in urlopen(url).readlines(): + geturl=geturl+line + + + except: + return (None,"XCannot open: "+url) + + try: + dom=xml.dom.minidom.parseString(geturl) + except: + return (None,"Cannot parse: "+url+"
"+geturl) + + + + metanodes=dom.getElementsByTagName('bib') + + if not metanodes: + metanodes=dom.getElementsByTagName('archimedes') + + metanode=metanodes[0] + + for metaData in metadict.keys(): + + try: + nodeOld=metanode.getElementsByTagName(metaData) + except: + nodeOld=None + + if nodeOld: + metanode.removeChild(nodeOld[0]).unlink() + else: + # try also old writing rule - instead of _: + try: + nodeOld=metanode.getElementsByTagName(re.sub('_','-',metaData)) + except: + nodeOld=None + + if nodeOld: + metanode.removeChild(nodeOld[0]).unlink() + + metanodeneu=dom.createElement(metaData) + metanodetext=dom.createTextNode(metadict[metaData].decode('utf-8')) + #try: + #metanodetext=dom.createTextNode(unicode(metadict[metaData],"utf-8")) + #except: + #metanodetext=dom.createTextNode(metadict[metaData].encode('utf-8')) + metanodeneu.appendChild(metanodetext) + metanode.appendChild(metanodeneu) + + + + + + if project: + updateTextToolNode('project',project) + + if startpage: + updateTextToolNode('startpage',startpage) - - + if topbar: + updateTextToolNode('toptemplate',topbar) + + if thumbtemplate: + updateTextToolNode('thumbtemplate',thumbtemplate) + + if xslt: + updateTextToolNode('xslt',xslt) + + + if digiliburlprefix: + updateTextToolNode('digiliburlprefix',digiliburlprefix) + + try: + return dom.toxml(encoding='utf-8').encode('utf-8') + except: + return dom.toxml(encoding='utf-8') + def readMetadata(url): """Methode zum Auslesen der Metadateninformation zu einer Resource Vorerst noch Typ bib""" metadict={} + try: geturl="" - for line in ECHO_helpers.urlopen(url).readlines(): + for line in urlopen(url).readlines(): geturl=geturl+line @@ -632,7 +960,7 @@ def readMetadata(url): try: dom=xml.dom.minidom.parseString(geturl) except: - return (None,"Cannot parse: "+url+"
"+geturl) + return (None,"Cannot parse: "+url+"
"+geturl) metanode=dom.getElementsByTagName('bib') metadict['bib_type']='Book' @@ -650,14 +978,15 @@ def readMetadata(url): """nothing""" for node in metacontent: - try: - #print urllib.unquote(getText(node.childNodes)),getText(node.childNodes) - metadict[re.sub('-','_',node.tagName.lower())]=urllib.unquote(getText(node.childNodes)) - except: - """nothing""" - + try: + #print urllib.unquote(getText(node.childNodes)),getText(node.childNodes) + #metadict[re.sub('-','_',node.tagName.lower())]=urllib.unquote(getText(node.childNodes)) + metadict[re.sub('-','_',node.tagName.lower())]=getText(node.childNodes) + + except: + """nothing""" - return metadict,"" + return (metadict,"") class MapArea(SimpleItem): @@ -670,101 +999,225 @@ class MapArea(SimpleItem): # type constants TYPE_AREA = 'area' TYPE_ARROW = 'arrow' - - def __init__(self, id, coords, label=None, type=None, text=None): - """init""" - self.coords = coords[0:4] - if len(coords) > 4: - self.angle = coords[4] - else: - self.angle = 0 - self.id = id - self.label = label - self.setType(type) - self.text = text + TYPE_TEXT = 'text' + + def __init__(self, id, coords, label=None, type=None, tip=None, permanent=False): + """init""" + self.coords = coords[0:4] + if len(coords) > 4: + self.angle = coords[4] + else: + self.angle = 0 + self.id = id + self.label = label + self.setType(type) + self.tip = tip + self.permanent = permanent def setCoords(self, coords): - """sets the coords""" - self.coords = coords + """sets the coords""" + self.coords = coords def getCoordString(self): - """returns coordinates as a string""" - return string.join(self.coords, ',') + """returns coordinates as a string""" + return string.join(self.coords, ',') def setCoordString(self, coordstring): - """sets coordinates from a string""" - coords = string.split(coordstring, ',') - self.coords = [c.strip() for c in coords] + """sets coordinates from a string""" + coords = string.split(coordstring, ',') + self.coords = [c.strip() for c in coords] def getFullId(self, prefix=None): - """returns the id with prefixed parent id""" - if prefix is None: - if hasattr(self, 'aq_parent'): - prefix = self.aq_parent.id - else: - prefix = "id" - fid = prefix + "." + self.id - return fid + """returns the id with prefixed parent id""" + if prefix is None: + if hasattr(self, 'aq_parent'): + prefix = self.aq_parent.id + else: + prefix = "id" + fid = prefix + "." + self.id + return fid def getType(self): - """returns the type""" - return self.type + """returns the type""" + return self.type def setType(self, type): - """sets the type""" - if type == MapArea.TYPE_ARROW: - self.type = MapArea.TYPE_ARROW - elif type == MapArea.TYPE_AREA: - self.type = MapArea.TYPE_AREA - else: - self.type = MapArea.TYPE_AREA - + """sets the type""" + if type == MapArea.TYPE_ARROW: + self.type = MapArea.TYPE_ARROW + elif type == MapArea.TYPE_AREA: + self.type = MapArea.TYPE_AREA + elif type == MapArea.TYPE_TEXT: + self.type = MapArea.TYPE_TEXT + else: + self.type = MapArea.TYPE_AREA + def isTypeArea(self): - """returns if the type is area""" - return self.type == MapArea.TYPE_AREA + """returns if the type is area""" + return self.type == MapArea.TYPE_AREA def isTypeArrow(self): - """returns if the type is arrow""" - return self.type == MapArea.TYPE_ARROW + """returns if the type is arrow""" + return self.type == MapArea.TYPE_ARROW + + def isTypeText(self): + """returns if the type is text""" + return self.type == MapArea.TYPE_TEXT def getAngle(self): - """returns the angle""" - return self.angle + """returns the angle""" + return self.angle def setAngle(self, angle): - """sets the angle""" - self.angle = angle + """sets the angle""" + self.angle = angle + + def getTip(self): + """returns the popup text""" + # patch old version + if not hasattr(self, 'tip'): + self.tip = self.text + + if self.tip is None: + if hasattr(self, 'aq_parent'): + parent = self.aq_parent + if parent.contentType == 'text-popup': + return parent.description + return self.tip + + def setTip(self, text): + """sets the text""" + self.tiptext = text def getText(self): - """returns the popup text""" - if self.text is None: - if hasattr(self, 'aq_parent'): - parent = self.aq_parent - if parent.contentType == 'text-popup': - return parent.description - return self.text - - def setText(self, text): - """sets the text""" - self.text = text + """returns the text fpr the area""" + if hasattr(self, 'aq_parent'): + parent = self.aq_parent + text = parent.getMapText() + if text is not None: + return text.document_src() + return "" def getLabel(self): - """returns the link label""" - if self.label is None: - if hasattr(self, 'aq_parent'): - return self.aq_parent.label or self.aq_parent.id - return self.label + """returns the link label""" + if self.label is None: + if hasattr(self, 'aq_parent'): + return self.aq_parent.label or self.aq_parent.id + return self.label def setLabel(self, label): - """sets the label""" - self.label = label + """sets the label""" + self.label = label - def getLinkId(self): - if hasattr(self, 'aq_parent'): - return self.aq_parent.id - return self.id + def isPermanent(self): + """returns the permanent state""" + # patch old objects + if not hasattr(self, 'permanent'): + self.permanent = False + return self.permanent + + def setPermanent(self, state): + """sets the permanent state""" + if state: + self.permanent = True + else: + self.permanent = False + def getLinkId(self): + if hasattr(self, 'aq_parent'): + return self.aq_parent.id + return self.id # call this to initialize framework classes, which # does the right thing with the security assertions. Globals.InitializeClass(MapArea) + + +class MapText(Folder,ZopePageTemplate): + """class to hold text for map areas""" + + meta_type = 'ECHO_mapText' + # Create a SecurityInfo for this class. + security = ClassSecurityInfo() + security.setDefaultAccess("allow") + + + _default_content_fn = os.path.join(package_home(globals()), + 'html', 'ECHO_mapText_default.html') + + def __init__(self, id, text=None, content_type=None): + self.id = str(id) + self.ZBindings_edit(self._default_bindings) + if text is None: + text = open(self._default_content_fn).read() + self.pt_edit(text, content_type) + + def createLocale(self): + """create locale""" + return ECHO_collection.manage_addECHO_localeForm(self) + + manage_main=ZopePageTemplate.pt_editForm + + def manage_addECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None): + """manage add echo locale in map""" + ECHO_collection.manage_addECHO_locale(self,lang,title,label,text,content_type) + if RESPONSE is not None: + RESPONSE.redirect('manage_main') + + + def changeLocale(self): + """change locale""" + return self.locale_en.change_ECHO_localeForm() + + def change_ECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None): + """change echo locale""" + + obj= self.locale_en.change_ECHO_locale(lang,title,label,text,content_type,RESPONSE) + + + + if RESPONSE is not None: + RESPONSE.redirect('manage_main') + + +# Product registration and Add support +manage_addMapTextForm = PageTemplateFile( + 'zpt/AddECHO_mapText', globals(), __name__='manage_addMapTextForm') + +def manage_addMapText(self, id, title=None, text=None, + REQUEST=None, submit=None): + "Add a Map Text with optional file content." + + id = str(id) + if REQUEST is None: + self._setObject(id, MapText(id, text)) + ob = getattr(self, id) + if title: + ob.pt_setTitle(title) + return ob + else: + file = REQUEST.form.get('file') + headers = getattr(file, 'headers', None) + if headers is None or not file.filename: + zpt = MapText(id, text) + else: + zpt = MapText(id, file, headers.get('content_type')) + + self._setObject(id, zpt) + if title: + ob = getattr(self, id) + ob.pt_setTitle(title) + + try: + u = self.DestinationURL() + except AttributeError: + u = REQUEST['URL1'] + + if submit == " Add and Edit ": + u = "%s/%s" % (u, urllib.quote(id)) + REQUEST.RESPONSE.redirect(u+'/manage_main') + return '' + +# call this to initialize framework classes, which +# does the right thing with the security assertions. +Globals.InitializeClass(MapText)