Diff for /ECHO_content/ECHO_helpers.py between versions 1.103.2.7 and 1.104

version 1.103.2.7, 2012/09/03 14:48:22 version 1.104, 2012/01/03 13:02:31
Line 11  from OFS.SimpleItem import SimpleItem Line 11  from OFS.SimpleItem import SimpleItem
 from Globals import package_home  from Globals import package_home
 import Globals  import Globals
 from AccessControl import ClassSecurityInfo  from AccessControl import ClassSecurityInfo
 from Acquisition import aq_parent,aq_chain,aq_base  
 import os.path  import os.path
 from OFS.Folder import Folder  from OFS.Folder import Folder
 import ECHO_collection  import ECHO_collection
Line 20  import bz2 Line 19  import bz2
 import xmlrpclib  import xmlrpclib
 import sys  import sys
 import logging  import logging
 #import amara  import amara
   from xml.sax.saxutils import escape
   
 #erstzt logging  #erstzt logging
 def logger(txt,method,txt2):  def logger(txt,method,txt2):
Line 34  def normalizeCt(str): Line 34  def normalizeCt(str):
         #str= str.replace(" ","_")          #str= str.replace(" ","_")
         return str.replace("-"," ").lower()          return str.replace("-"," ").lower()
   
 #decode and compress for xmlrpc communication   #decode and compress for xmlrpc communication with OSAS_server
   
 def encodeRPC(string):  def encodeRPC(string):
     return base64.encodestring(bz2.compress(string))      return base64.encodestring(bz2.compress(string))
Line 132  class ECHO_basis: Line 132  class ECHO_basis:
         """return utf-8 encoded string object for string or unicode object s"""          """return utf-8 encoded string object for string or unicode object s"""
         return utf8ify(s)          return utf8ify(s)
   
     def getBrowserType(self):  
         """returns browserType object"""  
         return browserType(self)  
           
     def manage_addECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None):      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)              return ECHO_collection.manage_addECHO_locale(self,lang,title,label)
Line 147  class ECHO_basis: Line 144  class ECHO_basis:
     def showRDF(self):      def showRDF(self):
             """showrdf"""              """showrdf"""
             self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')              self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
             ret="""<?xml version="1.0" encoding="utf-8"?>\n<rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"  xmlns:ECHONAVIGATION="http://www.echo.eu/rdf#"              ret="""<?xml version="1.0" encoding="utf-8"?>\n<rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"  xmlns:echonavigation="http://www.echo.eu/rdf#"
             xmlns:MPIWG="http://www.mpiwg-berlin.mpg.de/ns/mpiwg">\n"""              xmlns:mpiwg="http://www.mpiwg-berlin.mpg.de/ns/mpiwg">\n"""
   
             ret+=self.getRDF(urn="echo:collectionroot")+"\n"              ret+=self.getRDF(urn="echo:collectionroot")+"\n"
   
Line 160  class ECHO_basis: Line 157  class ECHO_basis:
     def RDF(self):      def RDF(self):
             """showrdf"""              """showrdf"""
             self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')              self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
             ret="""<?xml version="1.0" encoding="utf-8"?>\n<rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"  xmlns:ECHONAVIGATION="http://www.echo.eu/rdf#">\n"""              ret="""<?xml version="1.0" encoding="utf-8"?>\n<rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"  xmlns:echonavigation="http://www.echo.eu/rdf#">\n"""
   
             ret+=self.getRDF(urn=self.absolute_url())+"\n"              ret+=self.getRDF(urn=self.absolute_url())+"\n"
   
Line 252  class ECHO_basis: Line 249  class ECHO_basis:
               
         return self.unicodify(getattr(self,'description',''));          return self.unicodify(getattr(self,'description',''));
           
       
     def getTitle(self):      def getTitle(self):
         """title"""          """title"""
         if hasattr(self,'getLanguage'):          if hasattr(self,'getLanguage'):
Line 265  class ECHO_basis: Line 261  class ECHO_basis:
                 locale=self.ZopeFind(self,obj_ids=["locale_"+lang])                  locale=self.ZopeFind(self,obj_ids=["locale_"+lang])
   
         if locale:          if locale:
                 return unicodify(locale[0][1].title)                  return self.decode(locale[0][1].title)
                           else:
         return unicodify(self.title)              try:
                   return self.decode(self.title)
               except:    
                   return self.title
                   
     def getLabel(self):      def getLabel(self):
         """title"""          """title"""
Line 294  class ECHO_basis: Line 293  class ECHO_basis:
                         ret=self.getId()                          ret=self.getId()
                 return ret                  return ret
                   
         return unicodify(self.label)          return self.decode(self.label)
               
     def changeECHOEntriesForm(self):      def changeECHOEntriesForm(self):
         """change Entries for the ECHO Navigation environment"""          """change Entries for the ECHO Navigation environment"""
Line 326  class ECHO_basis: Line 325  class ECHO_basis:
     def getOverview(self):      def getOverview(self):
         """map overview graphics"""          """map overview graphics"""
         #return self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])[0][1]          #return self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])[0][1]
         return getattr(self, 'overview', None)          if self.hasOverview():
               return getattr(self, 'overview')
           return None
   
     def getMapAreas(self):      def getMapAreas(self):
         """returns the list of MapAreas"""          """returns the list of MapAreas"""
Line 371  class ECHO_basis: Line 372  class ECHO_basis:
                 res = self.ZopeFind(self, obj_metatypes=('ECHO_mapText'))                  res = self.ZopeFind(self, obj_metatypes=('ECHO_mapText'))
         if len(res) > 0:          if len(res) > 0:
             text = res[0][1]              text = res[0][1]
             return unicodify(text)              return text
         return None          return None
   
     def ECHO_graphicEntry(self):      def ECHO_graphicEntry(self):
Line 441  class ECHO_basis: Line 442  class ECHO_basis:
   
     def createMapImg(self):      def createMapImg(self):
         """generate img-tag for map"""          """generate img-tag for map"""
         bt = browserType(self)          bt = BrowserCheck(self)
         tag = ""          tag = ""
         src = self.getOverview().absolute_url()          src = self.getOverview().absolute_url()
         if bt['isN4']:          if bt.isN4:
             # N4 needs ilayer to create an id              # N4 needs ilayer to create an id
             tag += '<ilayer id="overview" visibility="show"><img src="%s"></ilayer>'%src              tag += '<ilayer id="overview" visibility="show"><img src="%s"></ilayer>'%src
         else:          else:
Line 458  class ECHO_basis: Line 459  class ECHO_basis:
   
     def createMapLink(self, ob, text=None, target="_blank"):      def createMapLink(self, ob, text=None, target="_blank"):
         """generate map link"""          """generate map link"""
         bt = browserType(self)          bt = BrowserCheck(self)
         id = ob.getFullId()          id = ob.getFullId()
         url = ob.getTargetUrl()          url = ob.getTargetUrl()
         if url == "":          if url == "":
Line 479  class ECHO_basis: Line 480  class ECHO_basis:
             text = "link"              text = "link"
                           
         tiptext = ob.getTip()          tiptext = ob.getTip()
   
         tag = ""          tag = ""
         if bt['isN4']:          if bt.isN4:
             # N4 needs layer for highlighting              # N4 needs layer for highlighting
             tag += '<ilayer id="a.%s"><a class="maplink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" %s %s'%(id,id,id,href,targetattr)              tag += '<ilayer id="a.%s"><a class="maplink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" %s %s'%(id,id,id,href,targetattr)
             tag += ">" + text + "</a></ilayer>"              tag += ">" + text + "</a></ilayer>"
Line 490  class ECHO_basis: Line 490  class ECHO_basis:
             tag = '<a id="a.%s" class="maplink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" %s %s'%(id,id,id,href,targetattr)              tag = '<a id="a.%s" class="maplink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" %s %s'%(id,id,id,href,targetattr)
             if tiptext:              if tiptext:
                 tag += ' title="%s"'%tiptext                  tag += ' title="%s"'%tiptext
               tag += ">" + text + "</a>"
             logging.debug("createMapLink: text=%s"%repr(text))  
             tag += ">%s</a>"%text  
   
         return 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"):      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"""          """generate map link image, text and other stuff"""
         bt = browserType(self)          bt = BrowserCheck(self)
         id = ob.getFullId()          id = ob.getFullId()
         link = ob.getLinkId()          link = ob.getLinkId()
         url = ob.getTargetUrl()          url = ob.getTargetUrl()
Line 513  class ECHO_basis: Line 510  class ECHO_basis:
         else:          else:
             targetattr = 'target="%s"'%target              targetattr = 'target="%s"'%target
         tiptext = ob.getTip()          tiptext = ob.getTip()
   
         tag = ""          tag = ""
         if bt['isN4']:  
           if bt.isN4:
             #              #
             # N4 needs layer and img elements              # N4 needs layer and img elements
             #              #
Line 578  class ECHO_basis: Line 575  class ECHO_basis:
   
                 if float(rot) < 0:                  if float(rot) < 0:
                     marksrc = circlesrc                      marksrc = circlesrc
                 if bt['isIEWin'] and bt['versIE'] > 5:                  if bt.isIEWin and bt.versIE > 5:
                     # IE/Win 5.5 has "feature" for PNG transparency                      # IE/Win 5.5 has "feature" for PNG transparency
                     tag += '<span id="i.%s" style="position:absolute; top:-100px; left:-100px; border-style:none; border-width=1px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'%s&rot=%s\');"><img style="visibility:hidden" src="%s&rot=%s" /></span>'%(id,marksrc,rot,marksrc,rot)                      tag += '<span id="i.%s" style="position:absolute; top:-100px; left:-100px; border-style:none; border-width=1px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'%s&rot=%s\');"><img style="visibility:hidden" src="%s&rot=%s" /></span>'%(id,marksrc,rot,marksrc,rot)
                 else:                  else:
Line 593  class ECHO_basis: Line 590  class ECHO_basis:
                 tag += '</div></div>'                  tag += '</div></div>'
             else:              else:
                 # DOM - Area                  # DOM - Area
                 if bt['isIE']:                  if bt.isIE:
                     # IE needs transparent img for area                      # IE needs transparent img for area
                     tag += '<img id="i.%s" border="0" style="position:absolute; top:-100px; left:-100px;" src="trans_img"'%(id)                      tag += '<img id="i.%s" border="0" style="position:absolute; top:-100px; left:-100px;" src="trans_img"'%(id)
                     if tiptext:                      if tiptext:
Line 697  def checkOnlyOneInGroup(object): Line 694  def checkOnlyOneInGroup(object):
         else:           return object          else:           return object
   
   
   
 def getCrumb(self):  
     """returns breadcrumb for this object"""  
     # ignore this object if title is empty  
     if not self.title:  
         return None  
       
     crumb = {'obj': self,  
              'url': self.absolute_url(),  
              'label': self.getLabel()}  
     return crumb          
   
 # roots of the ECHO hierarchy  
 rootMetaTypes = ['ECHO_root', 'ECHO_main', 'ECHO_nav']  
   
 def getHierCrumbs(self):  
     """returns a list of hierarchical breadcrumbs from self to the ECHO_root"""  
     crumbs = []  
     # walk the acquisition chain  
     for obj in aq_chain(self):  
         #logging.debug("getHiercrumbs: obj=%s"%(obj))  
         # test if the object really has a getCrumb method  
         if hasattr(aq_base(obj), 'getCrumb'):  
             crumb = obj.getCrumb()  
             #logging.debug("getHiercrumbs: got %s from %s"%(crumb,obj))  
             if crumb is not None:  
                 crumbs.insert(0, crumb)  
                   
             if obj.meta_type in rootMetaTypes:  
                 # stop when we reach the ECHO root  
                 return crumbs  
           
     return crumbs          
   
   
 def getSubCols(self, sortfield=None,   def getSubCols(self, sortfield=None, 
                subColTypes=displayTypes,                  subColTypes=displayTypes, 
                sortFieldMD=None,                 sortFieldMD=None,
Line 856  def ECHO_rerenderLinksMD(self,obj=None,t Line 818  def ECHO_rerenderLinksMD(self,obj=None,t
                                   
         return "<html><body>"+ret+"Rerenderd all links to resources in: "+self.title+"</html></body>"          return "<html><body>"+ret+"Rerenderd all links to resources in: "+self.title+"</html></body>"
   
   def reloadMetaDataFromStorage(self,RESPONSE=None):
               """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("<html><body>\n")
                   
               for resource in resources:
                       x=str(resource[1].copyIndex_meta2echo_resource())+"<br>"
                       if RESPONSE is not None:
                           RESPONSE.write(x+"\n")
                       
                       ret+=x
   
               if RESPONSE is not None:
                       #RESPONSE.redirect('./manage_main')
                       RESPONSE.write( "</html></body>")
   
               return ret
           
 def getRDFDescription(self,linkURL,urn=None,nameDef=None,typeName=None,ap=""):  def getRDFDescription(self,linkURL,urn=None,nameDef=None,typeName=None,ap=""):
             """rdf"""              """rdf"""
Line 882  def getRDFDescription(self,linkURL,urn=N Line 863  def getRDFDescription(self,linkURL,urn=N
             about2=about%urn              about2=about%urn
             if not nameDef:              if not nameDef:
                     if hasattr(self,'label') and not (self.label==""):                      if hasattr(self,'label') and not (self.label==""):
                             name2=name%self.label                              name2=name%escape(self.label)
                     elif not self.title=="":                      elif not self.title=="":
                             name2=name%self.title                              name2=name%escape(self.title)
                     else:                      else:
                             name2=name%self.getId()                              name2=name%escape(self.getId())
   
                     name2=re.sub('&','&amp;',name2)                      name2=re.sub('&','&amp;',name2)
             else:              else:
Line 1035  def sendFile(self, filename, type): Line 1016  def sendFile(self, filename, type):
     return      return
   
   
 def browserType(zope):  class BrowserCheck:
     """check the browsers request to find out the browser type"""      """check the browsers request to find out the browser type"""
     bt = {}      
     ua = zope.REQUEST.get_header("HTTP_USER_AGENT")      def __init__(self, zope):
     bt['ua'] = ua          """initialisiere"""
     bt['isN4'] = False          self.ua = zope.REQUEST.get_header("HTTP_USER_AGENT")
     bt['isIE'] = False          self.isN4 = False
     if string.find(ua, 'MSIE') > -1:          self.isIE = False
         bt['isIE'] = True          if string.find(self.ua, 'MSIE') > -1:
     else:              self.isIE = True
         bt['isN4'] = string.find(ua, 'Mozilla/4.') > -1          else:
     try:              self.isN4 = string.find(self.ua, 'Mozilla/4.') > -1
         nav = ua[string.find(ua, '('):]          try:
         bt['nav'] = nav              self.nav = self.ua[string.find(self.ua, '('):]
         ie = string.split(nav, "; ")[1]              ie = string.split(self.nav, "; ")[1]
         if string.find(ie, "MSIE") > -1:          if string.find(ie, "MSIE") > -1:
             bt['versIE'] = string.split(ie, " ")[1]                  self.versIE = string.split(ie, " ")[1]
     except: pass      except: pass
               self.isMac = string.find(self.ua, 'Macintosh') > -1
     bt['isMac'] = string.find(ua, 'Macintosh') > -1          self.isWin = string.find(self.ua, 'Windows') > -1
     bt['isWin'] = string.find(ua, 'Windows') > -1          self.isIEWin = self.isIE and self.isWin
     bt['isIEWin'] = bt['isIE'] and bt['isWin']          self.isIEMac = self.isIE and self.isMac
     bt['isIEMac'] = bt['isIE'] and bt['isMac']  
     return bt  
   
                                   
 def writeMetadata(url,metadict,project=None,startpage=None,xslt=None,thumbtemplate=None,topbar=None,digiLibTemplate=None,xmlfrag=None,digiliburlprefix=None):  def writeMetadata(url,metadict,project=None,startpage=None,xslt=None,thumbtemplate=None,topbar=None,digiLibTemplate=None,xmlfrag=None,digiliburlprefix=None):
Line 1103  def writeMetadata(url,metadict,project=N Line 1082  def writeMetadata(url,metadict,project=N
   
                 try:                  try:
                         dom=xml.dom.minidom.parseString(geturl)                          dom=xml.dom.minidom.parseString(geturl)
                           
                 except:                  except:
                     logger("ECHO writeMetadata",logging.ERROR,"Cannot parse: "+url+"<br>"+geturl)                      logger("ECHO writeMetadata",logging.ERROR,"Cannot parse: "+url+"<br>"+geturl)
                     return (None,"Cannot parse: "+url+"<br>"+geturl)                      return (None,"Cannot parse: "+url+"<br>"+geturl)
   
                   
           logging.debug("getting:"+geturl)
         metanodes=dom.getElementsByTagName('bib')          metanodes=dom.getElementsByTagName('bib')
   
         if not metanodes:          if not metanodes:
Line 1180  def writeMetadata(url,metadict,project=N Line 1160  def writeMetadata(url,metadict,project=N
                           
             return dom.toxml(encoding='utf-8')                  return dom.toxml(encoding='utf-8')    
                   
   def readMetadata(url):
       """Methode zum Auslesen der Metadateninformation zu einer Resource
       Vorerst noch Typ bib"""
       
       logging.debug("getting:" +url)
       metadict={}
       
       try:
           geturl=""
           for line in 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+"<br>"+geturl)
   
       metanode=dom.getElementsByTagName('bib')
       metadict['bib_type']='Book'
       if len(metanode)==0:
           metanode=dom.getElementsByTagName('archimedes')
           metadict['bib_type']='Archimedes'
           
           
       if not len(metanode)==0:    
           metacontent=metanode[0].childNodes
       
           try:
               metadict['bib_type']=getText(dom.getElementsByTagName('bib')[0].attributes['type'].childNodes)
           except:
               """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))
                           metadict[node.tagName]=getText(node.childNodes)
                   
                   except:
                           """nothing"""
   
       return (metadict,"")
           
   
 class MapArea(SimpleItem):  class MapArea(SimpleItem):
Line 1275  class MapArea(SimpleItem): Line 1300  class MapArea(SimpleItem):
         if self.tip is None:          if self.tip is None:
             if hasattr(self, 'aq_parent'):              if hasattr(self, 'aq_parent'):
                 parent = self.aq_parent                  parent = self.aq_parent
                 # text-popup type  
                 if parent.contentType == 'text-popup':                  if parent.contentType == 'text-popup':
                     return unicodify(parent.description)                      return parent.description
           return self.tip
                 # use map-text  
                 text = parent.getMapText()  
                 if text is not None:  
                     return text()  
   
         return unicodify(self.tip)  
   
     def setTip(self, text):      def setTip(self, text):
         """sets the text"""          """sets the text"""
         self.tiptext = text          self.tiptext = text
   
     def getText(self):      def getText(self):
         """returns the text for the area"""          """returns the text fpr the area"""
         if hasattr(self, 'aq_parent'):          if hasattr(self, 'aq_parent'):
             parent = self.aq_parent              parent = self.aq_parent
             text = parent.getMapText()              text = parent.getMapText()
Line 1304  class MapArea(SimpleItem): Line 1322  class MapArea(SimpleItem):
         """returns the link label"""          """returns the link label"""
         if self.label is None:          if self.label is None:
             if hasattr(self, 'aq_parent'):              if hasattr(self, 'aq_parent'):
                 return unicodify(self.aq_parent.label or self.aq_parent.id)                  return self.aq_parent.label or self.aq_parent.id
         return unicodify(self.label)          return self.label
   
     def getTargetUrl(self):      def getTargetUrl(self):
         """returns the URL of the linked object"""          """returns the URL of the linked object"""

Removed from v.1.103.2.7  
changed lines
  Added in v.1.104


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>