File:  [Repository] / ECHO_content / ECHO_helpers.py
Revision 1.93: download - view: text, annotated - select for diffs - revision graph
Wed Nov 19 14:22:42 2008 UTC (15 years, 6 months ago) by dwinter
Branches: MAIN
CVS tags: HEAD
unicode errors in VLp subcollection generator fixed

    1: import re
    2: import string
    3: import socket
    4: import urllib
    5: import string
    6: import xml.dom.minidom
    7: import types
    8: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
    9: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
   10: from OFS.SimpleItem import SimpleItem
   11: from Globals import package_home
   12: import Globals
   13: from AccessControl import ClassSecurityInfo
   14: import os.path
   15: from OFS.Folder import Folder
   16: import ECHO_collection
   17: import base64
   18: import bz2
   19: import xmlrpclib
   20: import sys
   21: import logging
   22: 
   23: #erstzt logging
   24: def logger(txt,method,txt2):
   25:     """logging"""
   26:     logging.info(txt+ txt2)
   27: 
   28: 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','extVersionedFileFolder','ECHO_movie']
   29: 
   30: 
   31: #decode and compress for xmlrpc communication with OSAS_server
   32: 
   33: def encodeRPC(string):
   34:     return base64.encodestring(bz2.compress(string))
   35: def decodeRPC(string):
   36:     return bz2.decompress(base64.decodestring(string))
   37: 
   38: def unicodify(s):
   39:     """decode str (utf-8 or latin-1 representation) into unicode object"""
   40:     if not s:
   41:         return u""
   42:     if isinstance(s, str):
   43:         try:
   44:             return s.decode('utf-8')
   45:         except:
   46:             return s.decode('latin-1')
   47:     else:
   48:         return s
   49: 
   50: def utf8ify(s):
   51:     """encode unicode object or string into byte string in utf-8 representation.
   52:        assumes string objects to be utf-8"""
   53:     if not s:
   54:         return ""
   55:     if isinstance(s, str):
   56:         return s
   57:     else:
   58:         return s.encode('utf-8')
   59: 
   60: 
   61: def content_html(self,type):
   62:         """template fuer content"""
   63:         #templates = self.ZopeFind(self.aq_parent,obj_ids=[type+"_template"])
   64:         #
   65:         #if templates:
   66:         #    return templates[0][1]()
   67: 
   68:         if hasattr(self,type+"_template"):
   69: 
   70:             obj=getattr(self,type+"_template")
   71:             return obj()
   72:         else:
   73:             pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','ECHO_%s_template_standard.zpt'%type)).__of__(self)
   74:             pt.content_type="text/html"
   75:             return pt()
   76:     
   77:     
   78: 
   79: class ECHO_basis:
   80:     """basis eigenschaften fuer echo objekte"""
   81:     security=ClassSecurityInfo()
   82:     security.declarePublic('getImageTag')
   83:     
   84:     management_page_charset="utf-8"
   85:     isVisible = True
   86:     
   87:     # Managment for the PID
   88:     def setPID(self,pid):
   89:         """set the pid"""
   90:         self.pid=pid
   91:         return True
   92:         
   93:     def getPID(self):
   94:         """get the pid"""
   95:         return getattr(self,'pid',None)
   96:         
   97: 
   98:     def unicodify(self, s):
   99:         """return unicode object for string (utf-8 or latin1) or unicode object s"""
  100:         return unicodify(s)
  101:     
  102:     # compatibility of old decode method
  103:     decode = unicodify
  104: 
  105: 
  106:     def utf8ify(self, s):
  107:         """return utf-8 encoded string object for string or unicode object s"""
  108:         return utf8ify(s)
  109: 
  110:     
  111:     def manage_addECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None):
  112:             return ECHO_collection.manage_addECHO_locale(self,lang,title,label)
  113:             
  114:     def getImageTag(self):
  115:             """sollte uerberschrieben werden, falls von der Klasse eine imagetag zurueckkommt"""
  116:             
  117:             return ""
  118:     
  119:     def showRDF(self):
  120:             """showrdf"""
  121:             self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
  122:             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"""
  123: 
  124:             ret+=self.getRDF(urn="echo:collectionroot")+"\n"
  125: 
  126: 
  127:             ret+="""</RDF:RDF>"""
  128:             return ret 
  129: 
  130:   
  131:     def RDF(self):
  132:             """showrdf"""
  133:             self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
  134:             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"""
  135: 
  136:             ret+=self.getRDF(urn=self.absolute_url())+"\n"
  137: 
  138: 
  139:             ret+="""</RDF:RDF>"""
  140:             return ret 
  141: 
  142:   
  143:     def createSubElementRDF(self,urn=None):
  144:             """rdf list"""
  145:             if not urn:
  146:                     urn=self.absolute_url()
  147:             ret=""
  148: 
  149:             rettemp="""<RDF:Seq RDF:about="%s">\n"""%urn
  150:             flag=0
  151:             
  152:             li="""<RDF:li RDF:resource="%s" />\n"""
  153:             if not ('<error>' in self.getFullTextXML(noredirect='Yes')):
  154:                     nurn=self.absolute_url()+'/getFullTextXML'
  155:                     rettemp+=li%nurn
  156:                     flag=1
  157:             if not ('<error>' in self.getImageView(noredirect='Yes')):
  158:                     nurn=self.absolute_url()+'/getImageView'
  159:                     rettemp+=li%nurn
  160:                     flag=1
  161: 
  162: 
  163:             if not ('<error>' in self.showMetaDataXML()):
  164:                     nurn=self.absolute_url()+'/showMetaDataXML'
  165:                     rettemp+=li%nurn
  166:                     flag=1
  167:                     
  168:             rettemp+="</RDF:Seq>"
  169: 
  170:             if flag==1:
  171:                     ret+=rettemp
  172:                     
  173:             if not ('<error>' in self.getFullTextXML(noredirect='Yes')):
  174:                     nurn=self.absolute_url()+'/getFullTextXML'  
  175:                     ret+=getRDFDescription(self,self.absolute_url()+'/getFullTextXML',urn=nurn,nameDef="Fulltext",typeName="ECHO_fulltext")
  176: 
  177:             if not ('<error>' in self.getImageView(noredirect='Yes')):
  178:                     nurn=self.absolute_url()+'/getImageView'
  179:                     ret+=getRDFDescription(self,self.absolute_url()+'/getImageView',urn=nurn,nameDef="Image View",typeName="ECHO_imageview")
  180:                     
  181:             if not ('<error>' in self.showMetaDataXML()):
  182:                     nurn=self.absolute_url()+'/showMetaDataXML'
  183:                     ret+=getRDFDescription(self,self.absolute_url()+'/showMetaDataXML',urn=nurn,nameDef="Metadata",typeName="ECHO_metaData")
  184: 
  185:             return ret
  186:             
  187:     def content_html_XMLRpc(self):
  188:         """xml_rpc_version"""
  189:         return encodeRPC(self.content_html())
  190:     
  191:     def content_html(self,type="collection"):
  192:             """template fuer content bei einbau und ECHO_Umgebung"""
  193:             
  194:             return content_html(self,type)
  195:     
  196:     def getIsVisible(self):
  197:         """return if object and all parents are visible"""
  198:         
  199:         # if object is not visible return False
  200:         if hasattr(self,'isVisible'):
  201:             if not self.isVisible : return False
  202:             
  203:         # else if parent of object is not ECHO_root, ECHO_basis or None
  204:         if not self.aq_parent.meta_type in ['ECHO_root','ECHO_basis',None] :
  205:             return self.aq_parent.getIsVisible()
  206: 
  207:         # else return True
  208:         return True
  209: 
  210:     def setIsVisible(self, isVisible):
  211:         """ set object attribute isVisible"""
  212:         self.isVisible = isVisible
  213: 
  214:     def getAttributeIsVisible(self):
  215:         """ return object attribute isVisible"""
  216:         if hasattr(self,'isVisible'):
  217:             return self.isVisible
  218:         return True
  219:     
  220:     def getDescription(self):
  221:         """get content of description field"""
  222:         
  223:       
  224:         return self.unicodify(getattr(self,'description',''));
  225:     
  226:     def getTitle(self):
  227:         """title"""
  228:         if hasattr(self,'getLanguage'):
  229:             lang=self.getLanguage()    
  230:         else:
  231:             lang=None
  232: 
  233:         locale=None
  234:         if lang and not (lang =="de"):
  235:                 locale=self.ZopeFind(self,obj_ids=["locale_"+lang])
  236: 
  237:         if locale:
  238:                 return self.decode(locale[0][1].title)
  239:         else:
  240:             try:
  241:                 return self.decode(self.title)
  242:             except:    
  243:                 return self.title
  244:         
  245:     def getLabel(self):
  246:         """title"""
  247:         if hasattr(self,'getLanguage'):
  248:             lang=self.getLanguage()    
  249:         else:
  250:             lang=None
  251: 
  252:         locale=None
  253:                 
  254:         if lang and not (lang=="de"):
  255:                 locale=self.ZopeFind(self,obj_ids=["locale_"+lang])
  256: 
  257:         if locale:
  258:                 return self.decode(locale[0][1].label)
  259:         
  260: 
  261:         if not hasattr(self,'label'):
  262:                 self.label=""
  263:                 
  264:         if self.label=="":
  265:                 ret=self.getTitle()
  266:                 if ret=="":
  267:                         ret=self.getId()
  268:                 return ret
  269:         
  270:         return self.decode(self.label)
  271:       
  272:     def changeECHOEntriesForm(self):
  273:         """change Entries for the ECHO Navigation environment"""
  274:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeECHOEntriesForm')).__of__(self)
  275:         return pt()
  276:     
  277:     def changeECHOEntries(self,label,weight,description,queryString,RESPONSE=None):
  278:         """change Entries for the ECHO Navigation environment
  279:         @param label: label fuer die Navigation"""
  280:         self.label=label
  281:         self.weight=weight
  282:         self.description=description
  283:         self.queryString=queryString
  284:         
  285:         if RESPONSE:
  286:             RESPONSE.redirect("manage_main")
  287: 
  288:     manage_options=({'label':'change ECHO Navigation Entries','action':'changeECHOEntriesForm'},)
  289: 
  290: 
  291:     def hasOverview(self):
  292:         """returns if there is an overview graphics"""
  293:         return hasattr(self, 'overview')
  294: 
  295:     def hasParentOverview(self):
  296:         """returns if the parent has an overview graphics"""
  297:         return hasattr(self.aq_parent, 'overview')
  298: 
  299:     def getOverview(self):
  300:         """map overview graphics"""
  301:         #return self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])[0][1]
  302:         if self.hasOverview():
  303:             return getattr(self, 'overview')
  304:         return None
  305: 
  306:     def getMapAreas(self):
  307:         """returns the list of MapAreas"""
  308:         forcetypes = self.REQUEST.get('map_force_types', None)
  309:         if forcetypes:
  310:             typelist = forcetypes.split(',')
  311:         else:
  312:             typelist = None
  313:         areas = []
  314:         # get all contained MapAreas
  315:         for res in self.ZopeFind(self, obj_metatypes=('MapArea')):
  316:             area = res[1]
  317:             # check the allowed types
  318:             if typelist is not None and area.getType() not in typelist:
  319:                 continue
  320:             areas.append(area)
  321:         return areas
  322: 
  323:     def addMapArea(self, newarea):
  324:         """add a map area to this object"""
  325:         if (newarea.id is None):
  326:             # create new id
  327:             ids = [a.id for a in self.getMapAreas()]
  328:             i = len(ids)
  329:             while ("a%02d"%i in ids):
  330:                 # if it exists, try the next one
  331:                 i += 1
  332:             newarea.id = "a%02d"%i
  333:         self._setObject(newarea.id, newarea)
  334: 
  335:     def getMapText(self):
  336:         """returns the MapText"""
  337:         # get (the first) contained MapText
  338:         #lang="en"
  339:         lang=self.getLanguage()
  340:         res=None
  341:         if lang and not (lang=="de"):
  342:                 resTmp = self.ZopeFind(self, obj_metatypes=('ECHO_mapText'))
  343:                 res = self.ZopeFind(resTmp[0][1])
  344: 
  345:         if not res:
  346:                 res = self.ZopeFind(self, obj_metatypes=('ECHO_mapText'))
  347:         if len(res) > 0:
  348:             text = res[0][1]
  349:             return text
  350:         return None
  351: 
  352:     def ECHO_graphicEntry(self):
  353:         """change map coordinates"""
  354:         if self.hasParentOverview():
  355:             pt=zptFile(self, 'zpt/ECHO_draw.zpt')
  356:             return pt()
  357:         else:
  358:             return "NO OVERVIEW GRAPHICS"
  359: 
  360:     def ECHO_addCoords(self,RESPONSE=None):
  361:         """change or add MapArea"""
  362:         #return self.REQUEST
  363:         # change existing areas
  364:         for area in self.getMapAreas():
  365:             id = area.getId()
  366:             if self.REQUEST.has_key('del.'+id):
  367:                 # delete this area
  368:                 self._delObject(id)
  369:                 # return to same menu
  370:                 if RESPONSE is not None:
  371:                     RESPONSE.redirect('ECHO_graphicEntry')
  372:                 return
  373:             # modify this area
  374:             coordstring = self.REQUEST.get('coords.'+id, '')
  375:             coords = string.split(coordstring, ',')
  376:             angle = self.REQUEST.get('angle.'+id, '0')
  377:             type = self.REQUEST.get('type.'+id, 'area')
  378:             permanent = self.REQUEST.get('permanent.'+id, '')
  379:             if len(coords) == 4:
  380:                 area.setCoordString(coordstring)
  381:                 area.setAngle(angle)
  382:                 area.setType(type)
  383:                 area.setPermanent(permanent)
  384:         # add the "new" area
  385:         if self.REQUEST.has_key('add'):
  386:             coordstring = self.REQUEST.get('coords.new', '')
  387:             coords = string.split(coordstring, ',')
  388:             angle = self.REQUEST.get('angle.new', '0')
  389:             type = self.REQUEST.get('type.new', 'area')
  390:             permanent = self.REQUEST.get('permanent.new', '')
  391:             if len(coords) == 4:
  392:                 coords.append(angle)
  393:                 area = MapArea(None, coords, type=type, permanent=permanent)
  394:                 self.addMapArea(area)
  395:         # return to edit area menu
  396:         if RESPONSE is not None:
  397:             RESPONSE.redirect('ECHO_graphicEntry')
  398: 
  399:     def createJSAreas(self, areas):
  400:         """create area calls for JavaScript"""
  401:         forceperm = self.REQUEST.get('map_force_permanent', None)
  402:         js="\n"
  403:         for ob in areas:
  404:             # check for force-permanent
  405:             if forceperm is not None:
  406:                 perm = forceperm
  407:             else:
  408:                 perm = ob.isPermanent()
  409:             js+="""addArea('%s', 'overview', %s, '%s', '%s');\n"""%(ob.getFullId(),ob.getCoordString(),ob.getType(),perm)
  410:         return js
  411: 
  412:     def createMapHead(self,mapColTypes=None):
  413:         """create javascript include and script tags for head"""
  414:         pt=zptFile(self, 'zpt/ECHO_content_map_frag_js')
  415:         return pt(mapColTypes=mapColTypes)
  416: 
  417:     def createMapImg(self):
  418:         """generate img-tag for map"""
  419:         bt = BrowserCheck(self)
  420:         tag = ""
  421:         src = self.getOverview().absolute_url()
  422:         if bt.isN4:
  423:             # N4 needs ilayer to create an id
  424:             tag += '<ilayer id="overview" visibility="show"><img src="%s"></ilayer>'%src
  425:         else:
  426:             # img with id
  427:             tag += '<img id="overview" src="%s" />'%src
  428:         return tag
  429:         
  430:     def createParentMapImg(self):
  431:         """generate img-tag for map of parent"""
  432:         return self.aq_parent.createMapImg()
  433: 
  434:     def createMapLink(self, ob, text=None, target="_blank"):
  435:         """generate map link"""
  436:         bt = BrowserCheck(self)
  437:         id = ob.getFullId()
  438:         url = ob.getTargetUrl()
  439:         if url == "":
  440:             # ECHOResource with empty link -> no link
  441:             href = 'href="#" onclick="return false;"'
  442:         else:
  443:             href = 'href="%s"'%ob.getLinkId()
  444:         
  445:         if target is None:
  446:             targetattr = ""
  447:         else:
  448:             targetattr = 'target="%s"'%target
  449:              
  450:         if text is None:
  451:             text = ob.getLabel()
  452:             
  453:         if text is None:
  454:             text = "link"
  455:             
  456:         tiptext = ob.getTip()
  457:         tag = ""
  458:         if bt.isN4:
  459:             # N4 needs layer for highlighting
  460:             tag += '<ilayer id="a.%s"><a class="maplink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" %s %s'%(id,id,id,href,targetattr)
  461:             tag += ">" + text + "</a></ilayer>"
  462:         else:
  463:             # a-element
  464:             tag = '<a id="a.%s" class="maplink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" %s %s'%(id,id,id,href,targetattr)
  465:             if tiptext:
  466:                 tag += ' title="%s"'%tiptext
  467:             tag += ">" + text + "</a>"
  468:         return tag
  469: 
  470:     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"):
  471:         """generate map link image, text and other stuff"""
  472:         bt = BrowserCheck(self)
  473:         id = ob.getFullId()
  474:         link = ob.getLinkId()
  475:         url = ob.getTargetUrl()
  476:         if url == "":
  477:             # ECHOResource with empty link -> no link
  478:             href = 'href="#" onclick="return false;"'
  479:         else:
  480:             href = 'href="%s"'%ob.getLinkId()
  481:         
  482:         if target is None:
  483:             targetattr = ""
  484:         else:
  485:             targetattr = 'target="%s"'%target
  486:         tiptext = ob.getTip()
  487:         tag = ""
  488: 
  489:         if bt.isN4:
  490:             #
  491:             # N4 needs layer and img elements
  492:             #
  493:             tag += '<layer id="i.%s" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)">'%(id,id,id)
  494:             if ob.isTypeArrow():
  495:                 # N4 - Arrow
  496:                 rot = ob.angle
  497:                 
  498:                 if hasattr(getattr(self,link),'link'):
  499:                         cLink=getattr(self,link).link
  500:                         # if existing delete virtuell path 
  501:                         cLink=cLink.replace('/'.join(self.REQUEST['VirtualRootPhysicalPath']),'')
  502: 
  503:                 if backLink and hasattr(getattr(self,link),'link') and backLink==self.REQUEST['SERVER_URL']+cLink.lstrip():
  504:                         marksrc=alternativArrowsrc
  505:                 else:
  506:                         marksrc = arrowsrc
  507: 
  508:                 
  509:                 if float(rot) < 0:
  510:                     marksrc = circlesrc
  511:                 tag += '<a %s><img border="0" src="%s&rot=%s" /></a>'%(href,marksrc,rot)
  512:             elif ob.isTypeText():
  513:                 # N4 - Text
  514:                 tag += '<div id="t.%s" class="maptext"'%(id)
  515:                 tag += 'style="visibility:hidden">'
  516:                 tag += ob.getText()
  517:                 tag += '</div>'
  518:             else:
  519:                 # N4 - Area
  520:                 tag += '<a %s><img border="0" width="1000" height="1000" src="trans_img"'%(href)
  521:                 if tiptext:
  522:                     tag += ' alt="%s"'%tiptext
  523:                 tag += ' /></a>'
  524:             tag += '</layer>'
  525:         else:
  526:             #
  527:             # (more or less) DOM capable browser
  528:             #
  529:             tag = '<a id="b.%s" class="mapmarklink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" %s %s>'%(id,id,id,href,targetattr)
  530:             if ob.isTypeArrow():
  531:                 # DOM - Arrow
  532:                 rot = ob.angle
  533:                                 
  534:                 if hasattr(getattr(self,link),'link'):
  535:                         cLink=getattr(self,link).link
  536:                         # if existing delete virtuell path 
  537:                         if hasattr(self.REQUEST,'VirtualRootPhysicalPath'):
  538:                             cLink=cLink.replace('/'.join(self.REQUEST['VirtualRootPhysicalPath']),'')
  539: 
  540:                 if backLink and hasattr(getattr(self,link),'link') and backLink==self.REQUEST['SERVER_URL']+cLink.lstrip():
  541:                         marksrc=alternativArrowsrc
  542:                 else:
  543:                         marksrc = arrowsrc
  544: 
  545:                 try:
  546:                    rot=float(rot)
  547:                 except:
  548:                    rot=0
  549: 
  550:                 if float(rot) < 0:
  551:                     marksrc = circlesrc
  552:                 if bt.isIEWin and bt.versIE > 5:
  553:                     # IE/Win 5.5 has "feature" for PNG transparency
  554:                     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)
  555:                 else:
  556:                     # arrow image
  557:                     tag += '<img id="i.%s" src="%s&rot=%s" border="1" style="position:absolute; top:-100px; left:-100px; border-style:none;" />'%(id,marksrc,rot)
  558:             elif ob.isTypeText():
  559:                 # DOM - Text
  560:                 tag += '<div id="i.%s" style="position:absolute; top:-100px; left:-100px;"'%(id)
  561:                 tag += '><div id="t.%s" class="maptext"'%(id)
  562:                 tag += 'style="visibility:hidden">'
  563:                 tag += ob.getText()
  564:                 tag += '</div></div>'
  565:             else:
  566:                 # DOM - Area
  567:                 if bt.isIE:
  568:                     # IE needs transparent img for area
  569:                     tag += '<img id="i.%s" border="0" style="position:absolute; top:-100px; left:-100px;" src="trans_img"'%(id)
  570:                     if tiptext:
  571:                         tag += ' title="%s"'%tiptext
  572:                     tag += " />"
  573:                 else:
  574:                     # empty div for area
  575:                     tag += '<div id="i.%s" style="position:absolute; top:-100px; left:-100px;"'%(id)
  576:                     if tiptext:
  577:                         tag += ' title="%s"'%tiptext
  578:                     tag += '> </div>'
  579:             tag += '</a>'
  580:         return tag
  581: 
  582: 
  583:     #ende der echo erweiterungen
  584: 
  585: 
  586: def toList(field):
  587:     """Einzelfeld in Liste umwandeln"""
  588:     if type(field)==types.StringType:
  589:         return [field]
  590:     else:
  591:         return field
  592: 
  593: def getText(nodelist):
  594:     rc = ""
  595:     for node in nodelist:
  596:         if node.nodeType == node.TEXT_NODE:
  597:            rc = rc + node.data
  598:     return rc
  599: 
  600: def getTextFromNode(nodename):
  601:     nodelist=nodename.childNodes
  602:     rc = ""
  603:     for node in nodelist:
  604:         if node.nodeType == node.TEXT_NODE:
  605:            rc = rc + node.data
  606:     return rc
  607: 
  608: 
  609: def readFieldFromXML(meta_url,parent,field):
  610:         """lesespezifisches metadatum"""
  611:         
  612:         try:
  613:                 dom=xml.dom.minidom.parse(meta_url)
  614: 
  615:         except:
  616:                 try:
  617:                         fh=urllib.urlopen(meta_url)
  618:                         dom=xml.dom.minidom.parse(fh)
  619:                 except:
  620:                         return None
  621:         if not dom: return None
  622: 
  623:         parent=dom.getElementsByTagName(parent)
  624:         if not parent: return None
  625: 
  626:         field=parent[0].getElementsByTagName(field)
  627: 
  628:         if not field: return None
  629: 
  630:         return getText(field[0].childNodes)
  631:         
  632:         
  633:               
  634: def urlopen(url):
  635:         """urlopen mit timeout"""
  636:         socket.setdefaulttimeout(10)
  637:         ret=urllib.urlopen(url)
  638:         socket.setdefaulttimeout(5)
  639:         return ret
  640: #       urlopener = urllib.URLopener()
  641: #
  642: #       try:            
  643: #               con = urlopener.open(url)
  644: #               return con
  645: #       except timeoutsocket.Timeout:
  646: #               return None
  647: 
  648: 
  649: 
  650: 
  651: 
  652: def checkOnlyOneInGroup(object): 
  653:         """check if object is a group and if it containt only one element it return this element"""
  654:         displayedObjects=object.ZopeFind(object,obj_metatypes=displayTypes)
  655:         if len(displayedObjects)==1: # nur ein Object dann redirect auf dieses Object
  656: 
  657:                 return displayedObjects[0][1]
  658:         else:           return object
  659: 
  660: 
  661: def getSubCols(self, sortfield=None, 
  662:                subColTypes=displayTypes, 
  663:                sortFieldMD=None,
  664:                searchMD=None,
  665:                searchMD_modus='search',
  666:                searchSimple=None,
  667:                generic="yes",search_sub=0,
  668:                isVisible=True):
  669:         
  670:         def sort(x,y):
  671:                 try:
  672:                         if type(x[0])==type(y[0]):
  673:                                 return  cmp(x[0],y[0])
  674:                         else:
  675:                                 if type(x[0])==types.StringType:
  676:                                         tmpX=unicodify(x[0])
  677:                                         tmpY=y[0]
  678:                                 else:
  679:                                         tmpY=unicodify(y[0])
  680:                                         tmpX=x[0]
  681:                                 return cmp(tmpX,tmpY)
  682: 
  683:                 except:
  684:                         logging.error("Error at ECHO_helpers.sort:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
  685:                         logging.error("                         : %s %s"%sys.exc_info()[0:2])
  686:                         logging.error("Error at ECHO_helpers.sort:"+repr(x)+"--"+repr(type(x[0])))
  687:                         logging.error("Error at ECHO_helpers.sort:"+repr(y)+"--"+repr(type(y[0])))
  688:                         logging.error("Error at ECHO_helpers.sort:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB")
  689:                         return 0
  690:         def sortfnc(sortfield,x,y):
  691:                 try:
  692:                         xa=x[1].getMDValue(sortfield,generic=generic)
  693:                 except:
  694:                         xa=""
  695:                 try:
  696:                         ya=y[1].getMDValue(sortfield,generic=generic)
  697:                 except:
  698:                         ya=""
  699:                 return cmp(xa,ya)
  700:         
  701:         sortWithMD = lambda sortfield : (lambda x,y : sortfnc(sortfield,x,y))
  702:         ids=[]
  703:         displayedObjects=self.ZopeFind(self,obj_metatypes=subColTypes,search_sub=search_sub)
  704:         
  705:         if searchSimple and (not (searchSimple==""))and hasattr(self,'resourceCatalog'):         
  706:             searchString=" AND ".join(searchSimple.split())         
  707:             ids=[x.getObject() for x in self.resourceCatalog({'getMDValueSimpleSearchField':searchString,'getIsVisible':True})]         
  708:         else:
  709:             for entry in displayedObjects:       
  710:                     object=entry[1]
  711:                     if searchMD:
  712:                          if hasattr(object,'getMDValue'):
  713:                             flag=0
  714:                             for field in searchMD.keys():
  715:                                     #if object.getMDValue(field,generic=generic)==searchMD[field]:
  716:                                     #if re.match(searchMD[field],object.getMDValue(field,generic=generic)):
  717:                                     if searchMD_modus=='match':
  718:                                         searchResult=re.match(searchMD[field],object.getMDValue(field,generic=generic))
  719:                                     else:
  720:                                         searchResult=re.search(searchMD[field],object.getMDValue(field,generic=generic))
  721:                                     if searchResult:
  722:                                             flag=1
  723:                                     else:
  724:                                             flag=0
  725:                                             break
  726:                             if flag==1:
  727:                                     ids.append(object)                            
  728:                     else:
  729:                             ids.append(object)
  730:         if not sortfield:
  731:             sortfield=getattr(self,'sortfield','weight')
  732:         tmplist=[]
  733:         for x in ids:
  734:                 if hasattr(x,sortfield):
  735:                         try:
  736:                                 tmp=int(getattr(x,sortfield))
  737:                         except:
  738:                                 tmp=getattr(x,sortfield)
  739:                                 
  740:                 else:
  741:                         tmp=10000000
  742:                         
  743:                 tmplist.append((tmp,x))
  744: 
  745:         if not sortFieldMD:
  746:                 tmplist.sort(sort)
  747:         else:
  748:                 tmplist.sort(sortWithMD(sortFieldMD))
  749:         
  750:         ret=[x for (key,x) in tmplist]
  751:       
  752:         return ret
  753: 
  754: def ECHO_rerenderLinksMD(self,obj=None,types=['title','label']):
  755:         """Rerender all Links"""
  756:         ret=""
  757:         
  758:         if not obj:
  759:             obj = self
  760:             
  761:         entries=obj.ZopeFind(obj,obj_metatypes=['ECHO_resource'],search_sub=1)
  762: 
  763:         for entry in entries:
  764:                 if entry[1].meta_type == 'ECHO_resource':
  765:                         try:
  766:                                 entry[1].ECHO_getResourceMD(template="no",overwrite="yes")
  767:                                 if "title" in types:
  768:                                     entry[1].generate_title()
  769:                                 if "label" in types:
  770:                                     entry[1].generate_label()
  771:                                 ret+="OK:"+entry[0]+"-- "+entry[1].getTitle().decode('utf-8')+"-- "+entry[1].getTitle().decode('utf-8')+"<br>"
  772:                         except:
  773:                                 ret+="Error:"+entry[0]+"<br>"
  774: 
  775:                 
  776:                 
  777:                 
  778:         return "<html><body>"+ret+"Rerenderd all links to resources in: "+self.title+"</html></body>"
  779: 
  780: def reloadMetaDataFromStorage(self,RESPONSE=None):
  781:             """copy metadata from the storage to ECHO"""
  782:             ret=""
  783:             resources=self.ZopeFind(self,obj_metatypes=['ECHO_resource'],search_sub=1)
  784:             if RESPONSE is not None:
  785:                 RESPONSE.setHeader("Content-Type", type)
  786:                 RESPONSE.write("<html><body>\n")
  787:                 
  788:             for resource in resources:
  789:                     x=str(resource[1].copyIndex_meta2echo_resource())+"<br>"
  790:                     if RESPONSE is not None:
  791:                         RESPONSE.write(x+"\n")
  792:                     
  793:                     ret+=x
  794: 
  795:             if RESPONSE is not None:
  796:                     #RESPONSE.redirect('./manage_main')
  797:                     RESPONSE.write( "</html></body>")
  798: 
  799:             return ret
  800:     
  801: def getRDFDescription(self,linkURL,urn=None,nameDef=None,typeName=None):
  802:             """rdf"""
  803:             
  804:             ret=""
  805:             about="""<RDF:Description RDF:about="%s">"""
  806:             name="""<ECHONAVIGATION:name>%s</ECHONAVIGATION:name>"""
  807:             link="""<ECHONAVIGATION:link xlink:href="%s">%s</ECHONAVIGATION:link>"""
  808:             clickable="""<ECHONAVIGATION:linkClickable>%s</ECHONAVIGATION:linkClickable>"""
  809:             #link="""<ECHONAVIGATION:link RDF:about="%s"/>"""
  810:             type="""<ECHONAVIGATION:type>%s</ECHONAVIGATION:type>"""
  811:             #xlink="""<ECHONAVIGATION:xlink xlink:href="%s"/>"""        
  812:             if not urn:
  813:                     #urn="urn:"+re.sub('/',':',self.absolute_url())
  814:                     urn=self.absolute_url()
  815:             about2=about%urn
  816:             if not nameDef:
  817:                     if hasattr(self,'label') and not (self.label==""):
  818:                             name2=name%self.label
  819:                     elif not self.title=="":
  820:                             name2=name%self.title
  821:                     else:
  822:                             name2=name%self.getId()
  823: 
  824:                     name2=re.sub('&','&amp;',name2)
  825:             else:
  826:                     name2=name%nameDef
  827: 
  828:             linkURL=re.sub('http:','',linkURL)
  829:             linkURL2=re.sub('&','&amp;',linkURL)
  830:             link2=link%(("http:"+linkURL2),("http:"+urllib.quote(linkURL)))
  831:             clickable2=clickable%"true"
  832: 
  833:             if not typeName:
  834:                     type2=type%self.meta_type
  835:             else:
  836:                     type2=type%typeName
  837:             
  838:             #ret=about2+"\n"+name2+"\n"+link2+"\n"+type2+"\n"+clickable2+"\n</RDF:Description>"
  839:             ret=about2+"\n"+name2+"\n"+type2+"\n"+clickable2+"\n</RDF:Description>"
  840:             return ret
  841:     
  842: def getCopyrightsFromForm(self,argv): 
  843:         medias={}
  844:         partners={}
  845:         copyrights={}
  846:         
  847:         copyrightsFinal=[]
  848:         for arg in argv.keys():
  849:                 
  850:                 if arg[0:5]=='media':
  851:                         nm=int(arg[5:])
  852:                         medias[nm]=argv[arg]
  853:                 elif arg[0:5]=='partn':
  854:                         nm=int(arg[5:])
  855:                         partners[nm]=argv[arg]
  856:                 elif arg[0:5]=='copyr':
  857:                         nm=int(arg[5:])
  858:                         copyrights[nm]=argv[arg]
  859: 
  860: 
  861: 
  862:         copyrightsList=[(medias[nm],partners[nm],copyrights[nm]) for nm in medias.keys()]
  863:         for copyright in copyrightsList:
  864:                 
  865:                 if copyright[2]=='institution0000':
  866:                         copyrightsFinal.append((copyright[0],copyright[1],self.getPartnerCopyright(copyright[1],'')))
  867:                 else:
  868:                         if not copyright[0]=='':
  869:                                 copyrightsFinal.append(copyright)
  870:                 
  871:                         
  872:         return copyrightsFinal
  873: 
  874: #List of different types for the graphical linking viewer
  875: viewClassificationListMaster=['view point','area']
  876: 
  877: 
  878: def checkDiffs(self,metadict):
  879:             """check differences"""
  880: 
  881:             
  882: 
  883:     
  884:             def NoneToEmpty(obj):
  885:                     if obj:
  886:                             return obj
  887:                     else:
  888:                             return ""
  889: 
  890:             
  891:             
  892:             diffs={}
  893:             
  894:             tags=self.findTagsFromMapping(self.contentType)
  895:             self.referencetypes=tags[2]
  896:             self.fields=tags[3]
  897:             
  898:     
  899:             for field in tags[1]:
  900:                     try:
  901:                             if (NoneToEmpty(self.getMDValue(self.getFieldTag(tags,field)))==metadict[self.getFieldTag(tags,field)]):
  902:                                     diffs[self.getFieldTag(tags,field)]=1
  903:                             else:
  904:                                     
  905:                                     diffs[self.getFieldTag(tags,field)]=0
  906:                     except:
  907:                             diffs[self.getFieldTag(tags,field)]=0
  908:                             
  909:             return diffs
  910:     
  911: 
  912: def zptFile(self, path, orphaned=False):
  913:     """returns a page template file from the product"""
  914:     if orphaned:
  915:         # unusual case
  916:         pt=PageTemplateFile(os.path.join(package_home(globals()), path))
  917:     else:
  918:       
  919:             pt=PageTemplateFile(os.path.join(package_home(globals()), path)).__of__(self)
  920:     return pt
  921: 
  922: 
  923: def findObjectPath(startobject, filename):
  924:     """returns the object with the name filename starting at startobject"""
  925:     if startobject is None:
  926:         return None
  927:     paths = filename.split('/')
  928:     object = startobject
  929:     for path in paths:
  930:             
  931:         if hasattr(object, path):
  932:             object = getattr(object, path)
  933:         else:
  934:             object = None
  935:             break
  936:     return object
  937: 
  938: 
  939: def zptObjectOrFile(self, filename, localdir='zpt', orphaned=False):
  940:     """returns a page template instance or a file from the product"""
  941:     # look for an object called path
  942:     pt = findObjectPath(self, filename)
  943:     # the object should also not be a python function
  944:     if (pt is None) or isinstance(pt, types.FunctionType):
  945:         # get a ZPT file
  946:         pt = zptFile(self, localdir+'/'+filename, orphaned=orphaned)
  947:     return pt
  948: 
  949: 
  950: def sendFile(self, filename, type):
  951:     """sends an object or a local file (in the product) as response"""
  952:     # look for an object called filename
  953:     object = findObjectPath(self, filename)
  954:     if object:
  955:         # if the object exists then send it
  956:         return object.index_html(self.REQUEST.REQUEST, self.REQUEST.RESPONSE)
  957:     else:
  958:         # send a local file with the given content-type
  959:         fn = os.path.join(package_home(globals()), filename)
  960:         self.REQUEST.RESPONSE.setHeader("Content-Type", type)
  961:         self.REQUEST.RESPONSE.write(file(fn).read())
  962:     return
  963: 
  964: 
  965: class BrowserCheck:
  966:     """check the browsers request to find out the browser type"""
  967:     
  968:     def __init__(self, zope):
  969:         """initialisiere"""
  970:         self.ua = zope.REQUEST.get_header("HTTP_USER_AGENT")
  971:         self.isN4 = False
  972:         self.isIE = False
  973:         if string.find(self.ua, 'MSIE') > -1:
  974:             self.isIE = True
  975:         else:
  976:             self.isN4 = string.find(self.ua, 'Mozilla/4.') > -1
  977:         try:
  978:             self.nav = self.ua[string.find(self.ua, '('):]
  979:             ie = string.split(self.nav, "; ")[1]
  980:             if string.find(ie, "MSIE") > -1:
  981:                 self.versIE = string.split(ie, " ")[1]
  982:         except: pass
  983:         self.isMac = string.find(self.ua, 'Macintosh') > -1
  984:         self.isWin = string.find(self.ua, 'Windows') > -1
  985:         self.isIEWin = self.isIE and self.isWin
  986:         self.isIEMac = self.isIE and self.isMac
  987: 
  988:                 
  989: def writeMetadata(url,metadict,project=None,startpage=None,xslt=None,thumbtemplate=None,topbar=None,digiLibTemplate=None,xmlfrag=None,digiliburlprefix=None):
  990:         """Einlesen der Metadaten und und erstellen des geaenderten XML file"""
  991:         
  992:         def updateTextToolNode(tag,value):
  993: 
  994:                 metanode=dom.getElementsByTagName('texttool')[0]
  995:                 try:
  996:                         nodeOld=metanode.getElementsByTagName(tag)
  997:                 except:
  998:                         nodeOld=None
  999:                         
 1000:                 if nodeOld:
 1001:                         metanode.removeChild(nodeOld[0]).unlink()
 1002: 
 1003:                 node=dom.createElement(tag)
 1004:                 nodetext=dom.createTextNode(value)
 1005:                 node.appendChild(nodetext)
 1006:                 metanode.appendChild(node)
 1007: 
 1008: 
 1009:         if xmlfrag:
 1010:                 geturl="""<?xml version="1.0" encoding="UTF-8" ?>
 1011:                            <resource type="MPIWG">
 1012:                            <meta>
 1013:                             <bib type="Book">
 1014:                             </bib>
 1015:                             </meta>
 1016:                             </resource>"""
 1017:                 dom=xml.dom.minidom.parseString(geturl)
 1018:         else:
 1019:                 try:
 1020:                         geturl=""
 1021:                         for line in urlopen(url).readlines():
 1022:                                 geturl=geturl+line
 1023: 
 1024: 
 1025:                 except:
 1026:                     logger("ECHO writeMetadata",logging.ERROR,"XCannot open: "+url)
 1027:                     return (None,"XCannot open: "+url)
 1028: 
 1029:                 try:
 1030:                         dom=xml.dom.minidom.parseString(geturl)
 1031:                 except:
 1032:                     logger("ECHO writeMetadata",logging.ERROR,"Cannot parse: "+url+"<br>"+geturl)
 1033:                     return (None,"Cannot parse: "+url+"<br>"+geturl)
 1034: 
 1035:         
 1036: 
 1037:         metanodes=dom.getElementsByTagName('bib')
 1038: 
 1039:         if not metanodes:
 1040:                 metanodes=dom.getElementsByTagName('archimedes')
 1041: 
 1042:         metanode=metanodes[0]
 1043: 
 1044:         for metaData in metadict.keys():
 1045:                 if metaData: 
 1046:                     try:
 1047:                         nodeOld=metanode.getElementsByTagName(metaData)
 1048:                     except:
 1049:                         nodeOld=None
 1050:                         
 1051:                     if nodeOld:
 1052:                         metanode.removeChild(nodeOld[0]).unlink()
 1053:                     else:
 1054:                         # try also old writing rule - instead of _:
 1055:                         try:
 1056:                                 nodeOld=metanode.getElementsByTagName(re.sub('_','-',metaData))
 1057:                         except:
 1058:                                 nodeOld=None
 1059:                                 
 1060:                         if nodeOld:
 1061:                                 metanode.removeChild(nodeOld[0]).unlink()
 1062: 
 1063: 
 1064:                     metanodeneu=dom.createElement(metaData)
 1065:                     try:
 1066:                         metanodetext=dom.createTextNode(metadict[metaData].decode('utf-8'))
 1067:                     except:
 1068:                         metanodetext=dom.createTextNode(metadict[metaData])
 1069:                     #try:
 1070: 
 1071:                         #metanodetext=dom.createTextNode(unicode(metadict[metaData],"utf-8"))
 1072:                     #except:
 1073:                         #metanodetext=dom.createTextNode(metadict[metaData].encode('utf-8'))
 1074:                     metanodeneu.appendChild(metanodetext)
 1075:                     metanode.appendChild(metanodeneu)
 1076:                 
 1077:                 
 1078:         
 1079:         
 1080:         
 1081:         if project:
 1082:                 updateTextToolNode('project',project)
 1083: 
 1084:         if startpage:
 1085:                 updateTextToolNode('startpage',startpage)
 1086: 
 1087:         if topbar:
 1088:                 updateTextToolNode('toptemplate',topbar)
 1089: 
 1090:         if thumbtemplate:
 1091:                 updateTextToolNode('thumbtemplate',thumbtemplate)
 1092: 
 1093:         if xslt:
 1094:                 updateTextToolNode('xslt',xslt)
 1095: 
 1096:         
 1097:         if digiliburlprefix:
 1098:                 updateTextToolNode('digiliburlprefix',digiliburlprefix)
 1099:                 
 1100:         try:   
 1101: 
 1102:          return dom.toxml(encoding='utf-8').encode('utf-8')
 1103:         except:
 1104:             
 1105:             
 1106:             return dom.toxml(encoding='utf-8')    
 1107:         
 1108: def readMetadata(url):
 1109:     """Methode zum Auslesen der Metadateninformation zu einer Resource
 1110:     Vorerst noch Typ bib"""
 1111:     
 1112:     metadict={}
 1113:     
 1114:     try:
 1115:         geturl=""
 1116:         for line in urlopen(url).readlines():
 1117:             geturl=geturl+line
 1118:         
 1119:         
 1120:     except:
 1121:         return (None,"Cannot open: "+url)
 1122: 
 1123:     try:
 1124:         dom=xml.dom.minidom.parseString(geturl)
 1125:     except:
 1126:             return (None,"Cannot parse: "+url+"<br>"+geturl)
 1127: 
 1128:     metanode=dom.getElementsByTagName('bib')
 1129:     metadict['bib_type']='Book'
 1130:     if len(metanode)==0:
 1131:         metanode=dom.getElementsByTagName('archimedes')
 1132:         metadict['bib_type']='Archimedes'
 1133:         
 1134:         
 1135:     if not len(metanode)==0:    
 1136:         metacontent=metanode[0].childNodes
 1137:     
 1138:         try:
 1139:             metadict['bib_type']=getText(dom.getElementsByTagName('bib')[0].attributes['type'].childNodes)
 1140:         except:
 1141:             """nothing"""
 1142:         
 1143:         for node in metacontent:
 1144:                 try:
 1145:                         #print urllib.unquote(getText(node.childNodes)),getText(node.childNodes)
 1146:                         #metadict[re.sub('-','_',node.tagName.lower())]=urllib.unquote(getText(node.childNodes))
 1147:                         metadict[re.sub('-','_',node.tagName.lower())]=getText(node.childNodes)
 1148:                 
 1149:                 except:
 1150:                         """nothing"""
 1151: 
 1152:     return (metadict,"")
 1153:     
 1154: 
 1155: class MapArea(SimpleItem):
 1156:     """simple class to hold coordinates"""
 1157: 
 1158:     meta_type = 'MapArea'
 1159:     # Create a SecurityInfo for this class.
 1160:     security = ClassSecurityInfo()
 1161:     security.setDefaultAccess("allow")
 1162:     # type constants
 1163:     TYPE_AREA = 'area'
 1164:     TYPE_ARROW = 'arrow'
 1165:     TYPE_TEXT = 'text'
 1166:         
 1167:     def __init__(self, id, coords, label=None, type=None, tip=None, permanent=False):
 1168:         """init"""
 1169:         self.coords = coords[0:4]
 1170:         if len(coords) > 4:
 1171:             self.angle = coords[4]
 1172:         else:
 1173:             self.angle = 0
 1174:         self.id = id
 1175:         self.label = label
 1176:         self.setType(type)
 1177:         self.tip = tip
 1178:         self.permanent = permanent
 1179: 
 1180:     def setCoords(self, coords):
 1181:         """sets the coords"""
 1182:         self.coords = coords
 1183: 
 1184:     def getCoordString(self):
 1185:         """returns coordinates as a string"""
 1186:         return string.join(self.coords, ',')
 1187: 
 1188:     def setCoordString(self, coordstring):
 1189:         """sets coordinates from a string"""
 1190:         coords = string.split(coordstring, ',')
 1191:         self.coords = [c.strip() for c in coords]
 1192: 
 1193:     def getFullId(self, prefix=None):
 1194:         """returns the id with prefixed parent id"""
 1195:         if prefix is None:
 1196:             if hasattr(self, 'aq_parent'):
 1197:                 prefix = self.aq_parent.id
 1198:             else:
 1199:                 prefix = "id"
 1200:         fid = prefix + "." + self.id
 1201:         return fid
 1202: 
 1203:     def getType(self):
 1204:         """returns the type"""
 1205:         return self.type
 1206: 
 1207:     def setType(self, type):
 1208:         """sets the type"""
 1209:         if type == MapArea.TYPE_ARROW:
 1210:             self.type = MapArea.TYPE_ARROW
 1211:         elif type == MapArea.TYPE_AREA:
 1212:             self.type = MapArea.TYPE_AREA
 1213:         elif type == MapArea.TYPE_TEXT:
 1214:             self.type = MapArea.TYPE_TEXT
 1215:         else:
 1216:             self.type = MapArea.TYPE_AREA
 1217:             
 1218:     def isTypeArea(self):
 1219:         """returns if the type is area"""
 1220:         return self.type == MapArea.TYPE_AREA
 1221: 
 1222:     def isTypeArrow(self):
 1223:         """returns if the type is arrow"""
 1224:         return self.type == MapArea.TYPE_ARROW
 1225: 
 1226:     def isTypeText(self):
 1227:         """returns if the type is text"""
 1228:         return self.type == MapArea.TYPE_TEXT
 1229: 
 1230:     def getAngle(self):
 1231:         """returns the angle"""
 1232:         return self.angle
 1233: 
 1234:     def setAngle(self, angle):
 1235:         """sets the angle"""
 1236:         self.angle = angle
 1237: 
 1238:     def getTip(self):
 1239:         """returns the popup text"""
 1240:         # patch old version
 1241:         if not hasattr(self, 'tip'):
 1242:             self.tip = self.text
 1243: 
 1244:         if self.tip is None:
 1245:             if hasattr(self, 'aq_parent'):
 1246:                 parent = self.aq_parent
 1247:                 if parent.contentType == 'text-popup':
 1248:                     return parent.description
 1249:         return self.tip
 1250: 
 1251:     def setTip(self, text):
 1252:         """sets the text"""
 1253:         self.tiptext = text
 1254: 
 1255:     def getText(self):
 1256:         """returns the text fpr the area"""
 1257:         if hasattr(self, 'aq_parent'):
 1258:             parent = self.aq_parent
 1259:             text = parent.getMapText()
 1260:             if text is not None:
 1261:                 #return text.document_src()
 1262:                 return text()
 1263:         return ""
 1264: 
 1265:     def getLabel(self):
 1266:         """returns the link label"""
 1267:         if self.label is None:
 1268:             if hasattr(self, 'aq_parent'):
 1269:                 return self.aq_parent.label or self.aq_parent.id
 1270:         return self.label
 1271: 
 1272:     def getTargetUrl(self):
 1273:         """returns the URL of the linked object"""
 1274:         if hasattr(self, 'aq_parent'):
 1275:             p = self.aq_parent
 1276:             # ECHOResource and ECHOLink have 'link' attribute
 1277:             if hasattr(p, 'link'):
 1278:                 if p.link is None:
 1279:                     # return empty string for empty link
 1280:                     return ""
 1281:                 else:
 1282:                     return p.link
 1283:                 
 1284:         # return None for unknown type
 1285:         return None
 1286: 
 1287:     def setLabel(self, label):
 1288:         """sets the label"""
 1289:         self.label = label
 1290: 
 1291:     def isPermanent(self):
 1292:         """returns the permanent state"""
 1293:         # patch old objects
 1294:         if not hasattr(self, 'permanent'):
 1295:             self.permanent = False
 1296:         return self.permanent
 1297: 
 1298:     def setPermanent(self, state):
 1299:         """sets the permanent state"""
 1300:         if state:
 1301:             self.permanent = True
 1302:         else:
 1303:             self.permanent = False
 1304: 
 1305:     def getLinkId(self):
 1306:         if hasattr(self, 'aq_parent'):
 1307:             return self.aq_parent.id
 1308:         return self.id
 1309: 
 1310: # call this to initialize framework classes, which
 1311: # does the right thing with the security assertions.
 1312: Globals.InitializeClass(MapArea)
 1313: 
 1314: 
 1315: class MapText(Folder,ZopePageTemplate):
 1316:     """class to hold text for map areas"""
 1317: 
 1318:     meta_type = 'ECHO_mapText'
 1319:     # Create a SecurityInfo for this class.
 1320:     security = ClassSecurityInfo()
 1321:     security.setDefaultAccess("allow")
 1322: 
 1323:     
 1324:     _default_content_fn = os.path.join(package_home(globals()),
 1325:                                        'html', 'ECHO_mapText_default.html')
 1326: 
 1327:     def __init__(self, id, text=None, content_type=None):
 1328:         self.id = str(id)
 1329:         self.ZBindings_edit(self._default_bindings)
 1330:         if text is None:
 1331:             text = open(self._default_content_fn).read()
 1332:         if content_type is None:
 1333:             content_type = self.content_type
 1334:         self.pt_edit(text, content_type)
 1335: 
 1336:     def createLocale(self):
 1337:             """create locale"""
 1338:             return ECHO_collection.manage_addECHO_localeForm(self)
 1339: 
 1340:     manage_main=ZopePageTemplate.pt_editForm
 1341: 
 1342:     def manage_addECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None):
 1343:             """manage add echo locale in map"""
 1344:             ECHO_collection.manage_addECHO_locale(self,lang,title,label,text,content_type)
 1345:             if RESPONSE is not None:
 1346:                         RESPONSE.redirect('manage_main')
 1347: 
 1348: 
 1349:     def changeLocale(self):
 1350:            """change locale"""
 1351:            return self.locale_en.change_ECHO_localeForm()
 1352: 
 1353:     def change_ECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None):
 1354:                 """change echo locale"""
 1355: 
 1356:                 obj= self.locale_en.change_ECHO_locale(lang,title,label,text,content_type,RESPONSE)
 1357:         
 1358: 
 1359: 
 1360:                 if RESPONSE is not None:
 1361:                         RESPONSE.redirect('manage_main')
 1362: 
 1363:                 
 1364: # Product registration and Add support
 1365: manage_addMapTextForm = PageTemplateFile(
 1366:     'zpt/AddECHO_mapText', globals(), __name__='manage_addMapTextForm')
 1367: 
 1368: def manage_addMapText(self, id, title=None, text=None,
 1369:                            REQUEST=None, submit=None):
 1370:     "Add a Map Text with optional file content."
 1371: 
 1372:     id = str(id)
 1373:     if REQUEST is None:
 1374:         self._setObject(id, MapText(id, text))
 1375:         ob = getattr(self, id)
 1376:         if title:
 1377:             ob.pt_setTitle(title)
 1378:         return ob
 1379:     else:
 1380:         file = REQUEST.form.get('file')
 1381:         headers = getattr(file, 'headers', None)
 1382:         if headers is None or not file.filename:
 1383:             zpt = MapText(id, text)
 1384:         else:
 1385:             zpt = MapText(id, file, headers.get('content_type'))
 1386: 
 1387:         self._setObject(id, zpt)
 1388:         if title:
 1389:             ob = getattr(self, id)
 1390:             ob.pt_setTitle(title)
 1391: 
 1392:         try:
 1393:             u = self.DestinationURL()
 1394:         except AttributeError:
 1395:             u = REQUEST['URL1']
 1396: 
 1397:         if submit == " Add and Edit ":
 1398:             u = "%s/%s" % (u, urllib.quote(id))
 1399:         REQUEST.RESPONSE.redirect(u+'/manage_main')
 1400:     return ''
 1401: 
 1402: # call this to initialize framework classes, which
 1403: # does the right thing with the security assertions.
 1404: Globals.InitializeClass(MapText)

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