File:  [Repository] / ECHO_content / ECHO_helpers.py
Revision 1.52: download - view: text, annotated - select for diffs - revision graph
Thu Jun 9 15:08:01 2005 UTC (19 years, 1 month ago) by casties
Branches: MAIN
CVS tags: HEAD
arrows become circles when angle < 0

    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: 
   16: 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']
   17: 
   18: def content_html(self,type):
   19:         """template fuer content"""
   20:         #templates = self.ZopeFind(self.aq_parent,obj_ids=[type+"_template"])
   21:         #
   22:         #if templates:
   23:         #    return templates[0][1]()
   24: 
   25:         if hasattr(self,type+"_template"):
   26:             obj=getattr(self,type+"_template")
   27:             return obj()
   28:         else:
   29: 	    pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','ECHO_%s_template_standard.zpt'%type)).__of__(self)
   30:             pt.content_type="text/html"
   31:             return pt()
   32:     
   33:     
   34: 
   35: class ECHO_basis:
   36:     """basis eigenschaften fuer echo objekte"""
   37:     security=ClassSecurityInfo()
   38:     security.declarePublic('getImageTag')
   39:     def getImageTag(self):
   40: 	    """sollte uerberschrieben werden, falls von der Klasse eine imagetag zurueckkommt"""
   41: 	    
   42: 	    return ""
   43:     
   44:     def showRDF(self):
   45: 	    """showrdf"""
   46:             self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
   47: 	    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"""
   48: 
   49: 	    ret+=self.getRDF(urn="echo:collectionroot")+"\n"
   50: 
   51: 
   52: 	    ret+="""</RDF:RDF>"""
   53:     	    return ret 
   54: 
   55:   
   56:     def RDF(self):
   57: 	    """showrdf"""
   58:             self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
   59: 	    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"""
   60: 
   61: 	    ret+=self.getRDF(urn=self.absolute_url())+"\n"
   62: 
   63: 
   64: 	    ret+="""</RDF:RDF>"""
   65:     	    return ret 
   66: 
   67:   
   68:     def createSubElementRDF(self,urn=None):
   69: 	    """rdf list"""
   70: 	    if not urn:
   71: 		    urn=self.absolute_url()
   72: 	    ret=""
   73: 
   74: 	    rettemp="""<RDF:Seq RDF:about="%s">\n"""%urn
   75: 	    flag=0
   76: 	    
   77: 	    li="""<RDF:li RDF:resource="%s" />\n"""
   78: 	    if not ('<error>' in self.getFullTextXML(noredirect='Yes')):
   79: 		    nurn=self.absolute_url()+'/getFullTextXML'
   80: 		    rettemp+=li%nurn
   81: 		    flag=1
   82: 	    if not ('<error>' in self.getImageView(noredirect='Yes')):
   83: 		    nurn=self.absolute_url()+'/getImageView'
   84: 		    rettemp+=li%nurn
   85: 		    flag=1
   86: 
   87: 
   88: 	    if not ('<error>' in self.showMetaDataXML()):
   89: 		    nurn=self.absolute_url()+'/showMetaDataXML'
   90: 		    rettemp+=li%nurn
   91: 		    flag=1
   92: 		    
   93: 	    rettemp+="</RDF:Seq>"
   94: 
   95: 	    if flag==1:
   96: 		    ret+=rettemp
   97: 		    
   98: 	    if not ('<error>' in self.getFullTextXML(noredirect='Yes')):
   99:                     nurn=self.absolute_url()+'/getFullTextXML'	
  100: 		    ret+=getRDFDescription(self,self.absolute_url()+'/getFullTextXML',urn=nurn,nameDef="Fulltext",typeName="ECHO_fulltext")
  101: 
  102: 	    if not ('<error>' in self.getImageView(noredirect='Yes')):
  103:                     nurn=self.absolute_url()+'/getImageView'
  104: 		    ret+=getRDFDescription(self,self.absolute_url()+'/getImageView',urn=nurn,nameDef="Image View",typeName="ECHO_imageview")
  105: 		    
  106: 	    if not ('<error>' in self.showMetaDataXML()):
  107:                     nurn=self.absolute_url()+'/showMetaDataXML'
  108: 		    ret+=getRDFDescription(self,self.absolute_url()+'/showMetaDataXML',urn=nurn,nameDef="Metadata",typeName="ECHO_metaData")
  109: 
  110: 	    return ret
  111: 	    
  112:     def content_html(self,type="collection"):
  113: 	    """template fuer content bei einbau und ECHO_Umgebung"""
  114: 	    
  115: 	    return content_html(self,type)
  116:         
  117:     def getTitle(self):
  118: 	"""title"""
  119: 	return self.decode(self.title)
  120: 	try:
  121: 		return self.title.encode('utf-8','ignore') 
  122: 	except:
  123: 		self.title=self.title.decode('iso-8859-1','ignore')[0:] #correnct conding error
  124: 		return self.title.encode('utf-8','ignore') 
  125: 	
  126:     def getLabel(self):
  127: 	"""title"""
  128: 	if not hasattr(self,'label'):
  129: 		self.label=""
  130: 		
  131: 	if self.label=="":
  132: 		ret=self.getTitle()
  133: 		if ret=="":
  134: 			ret=self.getId()
  135: 		return ret
  136: 	
  137: 	return self.decode(self.label)
  138: 	try:
  139: 		return self.label.encode('utf-8','ignore') 
  140: 	except:
  141: 		self.label=self.label.decode('iso-8859-1','ignore')[0:] #correnct conding error
  142: 		return self.label.encode('utf-8','ignore') 
  143: 	
  144:     
  145:     def changeECHOEntriesForm(self):
  146:         """change Entries for the ECHO Navigation environment"""
  147:         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeECHOEntriesForm')).__of__(self)
  148:         return pt()
  149:     
  150:     def changeECHOEntries(self,label,weight,description,queryString,RESPONSE=None):
  151:         """change Entries for the ECHO Navigation environment
  152:         @param label: label fuer die Navigation"""
  153:         self.label=label
  154:         self.weight=weight
  155:         self.description=description
  156: 	self.queryString=queryString
  157:         
  158:         if RESPONSE:
  159:             RESPONSE.redirect("manage_main")
  160: 
  161:     manage_options=({'label':'change ECHO Navigation Entries','action':'changeECHOEntriesForm'},)
  162: 
  163: 
  164:     def hasOverview(self):
  165:         """returns if there is an overview graphics"""
  166: 	return hasattr(self, 'overview')
  167: 
  168:     def hasParentOverview(self):
  169:         """returns if the parent has an overview graphics"""
  170: 	return hasattr(self.aq_parent, 'overview')
  171: 
  172:     def getOverview(self):
  173:         """map overview graphics"""
  174:         #return self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])[0][1]
  175: 	if self.hasOverview():
  176: 	    return getattr(self, 'overview')
  177: 	return None
  178: 
  179:     def getMapAreas(self):
  180:         """returns the list of MapAreas"""
  181: 	# get all contained MapAreas
  182:         areas = [res[1] for res in self.ZopeFind(self, obj_metatypes=('MapArea'))]
  183: 	return areas
  184: 
  185:     def addMapArea(self, newarea):
  186: 	"""add a map area to this object"""
  187: 	if (newarea.id is None):
  188: 	    # create new id
  189: 	    ids = [a.id for a in self.getMapAreas()]
  190: 	    i = len(ids)
  191: 	    while ("a%02d"%i in ids):
  192: 		# if it exists, try the next one
  193: 		i += 1
  194: 	    newarea.id = "a%02d"%i
  195: 	self._setObject(newarea.id, newarea)
  196: 
  197:     def getMapText(self):
  198:         """returns the MapText"""
  199: 	# get (the first) contained MapText
  200:         res = self.ZopeFind(self, obj_metatypes=('ECHO_mapText'))
  201: 	if len(res) > 0:
  202: 	    text = res[0][1]
  203: 	    return text
  204: 	return None
  205: 
  206:     def ECHO_graphicEntry(self):
  207:         """change map coordinates"""
  208:         if self.hasParentOverview():
  209:             pt=zptFile(self, 'zpt/ECHO_draw.zpt')
  210:             return pt()
  211:         else:
  212:             return "NO OVERVIEW GRAPHICS"
  213: 
  214:     def ECHO_addCoords(self,RESPONSE=None):
  215:         """change or add MapArea"""
  216: 	#return self.REQUEST
  217: 	# change existing areas
  218: 	for area in self.getMapAreas():
  219: 	    id = area.getId()
  220: 	    if self.REQUEST.has_key('del.'+id):
  221: 		# delete this area
  222: 		self._delObject(id)
  223: 		# return to same menu
  224: 		if RESPONSE is not None:
  225: 		    RESPONSE.redirect('ECHO_graphicEntry')
  226: 		return
  227: 	    # modify this area
  228: 	    coordstring = self.REQUEST.get('coords.'+id, '')
  229: 	    coords = string.split(coordstring, ',')
  230: 	    angle = self.REQUEST.get('angle.'+id, '0')
  231: 	    type = self.REQUEST.get('type.'+id, 'area')
  232: 	    if len(coords) == 4:
  233: 		area.setCoordString(coordstring)
  234: 		area.setAngle(angle)
  235: 		area.setType(type)
  236: 	# add new area
  237: 	if self.REQUEST.has_key('add'):
  238: 	    coordstring = self.REQUEST.get('coords.new', '')
  239: 	    coords = string.split(coordstring, ',')
  240: 	    angle = self.REQUEST.get('angle.new', '0')
  241: 	    type = self.REQUEST.get('type.new', 'area')
  242: 	    if len(coords) == 4:
  243: 		coords.append(angle)
  244: 		area = MapArea(None, coords, type=type)
  245: 		self.addMapArea(area)
  246: 	# return to edit area menu
  247: 	if RESPONSE is not None:
  248: 	    RESPONSE.redirect('ECHO_graphicEntry')
  249: 
  250:     def createJSAreas(self, areas):
  251:         """create area calls for JavaScript"""
  252:         dynamical="\n"
  253:         for ob in areas:
  254: 	    dynamical+="""addArea('%s', 'overview', %s, '%s');\n"""%(ob.getFullId(),ob.getCoordString(),ob.getType())
  255:         return dynamical
  256: 
  257:     def createMapHead(self):
  258:         """create javascript include and script tags for head"""
  259:         pt=zptFile(self, 'zpt/ECHO_content_map_frag_js')
  260:         return pt()
  261: 
  262:     def createMapImg(self):
  263: 	"""generate img-tag for map"""
  264: 	bt = BrowserCheck(self)
  265: 	tag = ""
  266: 	src = self.getOverview().absolute_url()
  267: 	if bt.isN4:
  268: 	    # N4 needs ilayer to create an id
  269: 	    tag += '<ilayer id="overview" visibility="show"><img src="%s"></ilayer>'%src
  270: 	else:
  271: 	    # img with id
  272: 	    tag += '<img id="overview" src="%s" />'%src
  273: 	return tag
  274:         
  275:     def createParentMapImg(self):
  276: 	"""generate img-tag for map of parent"""
  277: 	return self.aq_parent.createMapImg()
  278: 
  279:     def createMapLink(self, ob, text=None, target="_blank"):
  280: 	"""generate map link"""
  281: 	bt = BrowserCheck(self)
  282: 	id = ob.getFullId()
  283: 	link = ob.getLinkId()
  284: 	if text is None:
  285: 	    text = ob.getLabel()
  286: 	if text is None:
  287: 	    text = "link"
  288: 	tiptext = ob.getTip()
  289: 	tag = ""
  290: 	if bt.isN4:
  291: 	    # N4 needs layer for highlighting
  292: 	    tag += '<ilayer id="a.%s"><a onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" target="%s"'%(id,id,id,link,target)
  293: 	    tag += ">" + text + "</a></ilayer>"
  294: 	else:
  295: 	    # a-element
  296: 	    tag = '<a id="a.%s" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" target="%s"'%(id,id,id,link,target)
  297: 	    if tiptext:
  298: 		tag += ' title="%s"'%tiptext
  299: 	    tag += ">" + text + "</a>"
  300: 	return tag
  301: 
  302:     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"):
  303: 	"""generate map link image, text and other stuff"""
  304: 	bt = BrowserCheck(self)
  305: 	id = ob.getFullId()
  306: 	link = ob.getLinkId()
  307: 	tiptext = ob.getTip()
  308: 	tag = ""
  309: 
  310: 	if bt.isN4:
  311: 	    #
  312: 	    # N4 needs layer and img elements
  313: 	    #
  314: 	    tag += '<layer id="i.%s" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)">'%(id,id,id)
  315: 	    if ob.isTypeArrow():
  316: 		# N4 - Arrow
  317: 	        rot = ob.angle
  318: 		marksrc = arrowsrc
  319: 		if rot < 0:
  320: 		    marksrc = circlesrc
  321: 		tag += '<a href="%s"><img border="0" src="%s&rot=%s" /></a>'%(link,marksrc,rot)
  322: 	    else:
  323: 		# N4 - Area
  324: 		tag += '<a href="%s"><img border="0" width="1000" height="1000" src="trans_img"'%(link)
  325: 		if tiptext:
  326: 		    tag += ' alt="%s"'%tiptext
  327: 		tag += ' /></a>'
  328: 	    tag += '</layer>'
  329: 	else:
  330: 	    #
  331: 	    # (more or less) DOM capable browser
  332: 	    #
  333: 	    tag = '<a id="b.%s" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" target="%s">'%(id,id,id,link,target)
  334: 	    if ob.isTypeArrow():
  335: 		# DOM - Arrow
  336: 		rot = ob.angle
  337: 		marksrc = arrowsrc
  338: 		if float(rot) < 0:
  339: 		    marksrc = circlesrc
  340: 		print "ROT: ", rot, " mark: ", marksrc
  341: 		if bt.isIEWin and bt.versIE > 5:
  342: 		    # IE/Win 5.5 has "feature" for PNG transparency
  343: 		    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)
  344: 		else:
  345: 		    # arrow image
  346: 		    tag += '<img id="i.%s" src="%s&rot=%s" border="1" style="position:absolute; top:-100px; left:-100px; border-style:none;" />'%(id,marksrc,rot)
  347: 	    elif ob.isTypeText():
  348: 		# DOM - Text
  349: 		tag += '<div id="i.%s" style="position:absolute; top:-100px; left:-100px;"'%(id)
  350: 		if tiptext:
  351: 		    tag += ' title="%s"'%tiptext
  352: 		tag += '><div id="t.%s" class="maptext" style="visibility:hidden">'%(id)
  353: 		tag += ob.getText()
  354: 		tag += '</div></div>'
  355: 	    else:
  356: 		# DOM - Area
  357: 		if bt.isIE:
  358: 		    # IE needs transparent img for area
  359: 		    tag += '<img id="i.%s" border="0" style="position:absolute; top:-100px; left:-100px;" src="trans_img"'%(id)
  360: 		    if tiptext:
  361: 			tag += ' title="%s"'%tiptext
  362: 		    tag += " />"
  363: 		else:
  364: 		    # empty div for area
  365: 		    tag += '<div id="i.%s" style="position:absolute; top:-100px; left:-100px;"'%(id)
  366: 		    if tiptext:
  367: 			tag += ' title="%s"'%tiptext
  368: 		    tag += '> </div>'
  369: 	    tag += '</a>'
  370: 	return tag
  371: 
  372: 
  373:     #ende der echo erweiterungen
  374: 
  375: 
  376: def toList(field):
  377:     """Einzelfeld in Liste umwandeln"""
  378:     if type(field)==types.StringType:
  379:         return [field]
  380:     else:
  381:         return field
  382: 
  383: def getText(nodelist):
  384:     rc = ""
  385:     for node in nodelist:
  386:     	if node.nodeType == node.TEXT_NODE:
  387:            rc = rc + node.data
  388:     return rc
  389: 
  390: def getTextFromNode(nodename):
  391:     nodelist=nodename.childNodes
  392:     rc = ""
  393:     for node in nodelist:
  394:     	if node.nodeType == node.TEXT_NODE:
  395:            rc = rc + node.data
  396:     return rc
  397: 
  398: 
  399: def readFieldFromXML(meta_url,parent,field):
  400: 	"""lesespezifisches metadatum"""
  401: 	
  402: 	try:
  403: 		dom=xml.dom.minidom.parse(meta_url)
  404: 
  405: 	except:
  406: 		try:
  407: 			fh=urllib.urlopen(meta_url)
  408: 			dom=xml.dom.minidom.parse(fh)
  409: 	        except:
  410: 			return None
  411: 	if not dom: return None
  412: 
  413: 	parent=dom.getElementsByTagName(parent)
  414: 	if not parent: return None
  415: 
  416: 	field=parent[0].getElementsByTagName(field)
  417: 
  418: 	if not field: return None
  419: 
  420: 	return getText(field[0].childNodes)
  421: 	
  422: 	
  423: 	      
  424: def urlopen(url):
  425: 	"""urlopen mit timeout"""
  426: 	socket.setdefaulttimeout(2)
  427: 	ret=urllib.urlopen(url)
  428: 	socket.setdefaulttimeout(5)
  429: 	return ret
  430: #	urlopener = urllib.URLopener()
  431: #
  432: #	try:		
  433: #		con = urlopener.open(url)
  434: #		return con
  435: #	except timeoutsocket.Timeout:
  436: #		return None
  437: 
  438: 
  439: 
  440: 
  441: 
  442: def checkOnlyOneInGroup(object): 
  443: 	"""check if object is a group and if it containt only one element it return this element"""
  444: 	displayedObjects=object.ZopeFind(object,obj_metatypes=displayTypes)
  445: 	if len(displayedObjects)==1: # nur ein Object dann redirect auf dieses Object
  446: 
  447: 		return displayedObjects[0][1]
  448: 	else:		return object
  449: 
  450: def getSubCols(self, sortfield=None, subColTypes=displayTypes, sortFieldMD=None,searchMD=None):
  451: 	
  452: 	
  453: 	def sort(x,y):
  454: 		return cmp(x[0],y[0])
  455: 	
  456: 	def sortfnc(sortfield,x,y):
  457: 		try:
  458: 			xa=x[1].getMDValue(sortfield)
  459: 		except:
  460: 			xa=""
  461: 		try:
  462: 			ya=y[1].getMDValue(sortfield)
  463: 		except:
  464: 			ya=""
  465: 		return cmp(xa,ya)
  466: 	
  467: 	sortWithMD = lambda sortfield : (lambda x,y : sortfnc(sortfield,x,y))
  468:         ids=[]
  469: 	displayedObjects=self.ZopeFind(self,obj_metatypes=subColTypes)
  470: 
  471: 	
  472: 	for entry in displayedObjects:
  473: 
  474: 			
  475: 		object=entry[1]
  476: 		if searchMD and hasattr(object,'getMDValue'):
  477: 			flag=0
  478: 			for field in searchMD.keys():
  479: 				if object.getMDValue(field)==searchMD[field]:
  480: 					flag=1
  481: 				else:
  482: 					flag=0
  483: 					break
  484: 			if flag==1:
  485: 				ids.append(object)
  486: 		else:
  487: 			ids.append(object)
  488: 
  489: 	if not sortfield:
  490:             sortfield=getattr(self,'sortfield','weight')
  491: 
  492:             
  493:         tmplist=[]
  494: 
  495:         for x in ids:
  496: 		
  497: 		if hasattr(x,sortfield):
  498: 			try:
  499: 				tmp=int(getattr(x,sortfield))
  500: 			except:
  501: 				tmp=getattr(x,sortfield)
  502: 				
  503: 		else:
  504: 			tmp=10000000
  505: 			
  506: 		tmplist.append((tmp,x))
  507: 
  508: 	if not sortFieldMD:
  509: 		tmplist.sort(sort)
  510: 	else:
  511: 		tmplist.sort(sortWithMD(sortFieldMD))
  512: 	
  513:         return [x for (key,x) in tmplist]
  514: 
  515: def ECHO_rerenderLinksMD(self,obj=None,types=['title','label']):
  516:         """Rerender all Links"""
  517: 	ret=""
  518: 	
  519:         if not obj:
  520:             obj = self
  521:             
  522:         entries=obj.ZopeFind(obj,obj_metatypes=['ECHO_resource'],search_sub=1)
  523: 
  524:         for entry in entries:
  525: 		if entry[1].meta_type == 'ECHO_resource':
  526: 			try:
  527: 				entry[1].ECHO_getResourceMD(template="no")
  528:                                 if "title" in types:
  529:                                     entry[1].generate_title()
  530:                                 if "label" in types:
  531:                                     entry[1].generate_label()
  532: 				ret+="OK:"+entry[0]+"-- "+entry[1].getTitle().decode('utf-8')+"-- "+entry[1].getTitle().decode('utf-8')+"<br>"
  533: 			except:
  534: 				ret+="Error:"+entry[0]+"<br>"
  535: 
  536: 		
  537:                 
  538:                 
  539:         return "<html><body>"+ret+"Rerenderd all links to resources in: "+self.title+"</html></body>"
  540: 
  541: def reloadMetaDataFromStorage(self,RESPONSE=None):
  542: 	    """copy metadata from the storage to ECHO"""
  543: 	    ret=""
  544: 	    resources=self.ZopeFind(self,obj_metatypes=['ECHO_resource'],search_sub=1)
  545: 
  546: 	    for resource in resources:
  547: 		    x=str(resource[1].copyIndex_meta2echo_resource())+"<br>"
  548: 		    ret+=x
  549: 
  550: 	    if RESPONSE is not None:
  551: 		    #RESPONSE.redirect('./manage_main')
  552: 		    return "<html><body>"+ret+"</html></body>"
  553: 
  554: 	    return ret
  555:     
  556: def getRDFDescription(self,linkURL,urn=None,nameDef=None,typeName=None):
  557: 	    """rdf"""
  558: 	    
  559: 	    ret=""
  560: 	    about="""<RDF:Description RDF:about="%s">"""
  561: 	    name="""<ECHONAVIGATION:name>%s</ECHONAVIGATION:name>"""
  562: 	    link="""<ECHONAVIGATION:link xlink:href="%s">%s</ECHONAVIGATION:link>"""
  563: 	    clickable="""<ECHONAVIGATION:linkClickable>%s</ECHONAVIGATION:linkClickable>"""
  564: 	    #link="""<ECHONAVIGATION:link RDF:about="%s"/>"""
  565: 	    type="""<ECHONAVIGATION:type>%s</ECHONAVIGATION:type>"""
  566:             #xlink="""<ECHONAVIGATION:xlink xlink:href="%s"/>"""	
  567: 	    if not urn:
  568: 		    #urn="urn:"+re.sub('/',':',self.absolute_url())
  569: 		    urn=self.absolute_url()
  570: 	    about2=about%urn
  571: 	    if not nameDef:
  572: 		    if hasattr(self,'label') and not (self.label==""):
  573: 			    name2=name%self.label
  574: 		    elif not self.title=="":
  575: 			    name2=name%self.title
  576: 		    else:
  577: 			    name2=name%self.getId()
  578: 
  579: 		    name2=re.sub('&','&amp;',name2)
  580: 	    else:
  581: 		    name2=name%nameDef
  582: 
  583: 	    linkURL=re.sub('http:','',linkURL)
  584: 	    linkURL2=re.sub('&','&amp;',linkURL)
  585: 	    link2=link%(("http:"+linkURL2),("http:"+urllib.quote(linkURL)))
  586: 	    clickable2=clickable%"true"
  587: 
  588: 	    if not typeName:
  589: 		    type2=type%self.meta_type
  590: 	    else:
  591: 		    type2=type%typeName
  592: 	    
  593: 	    #ret=about2+"\n"+name2+"\n"+link2+"\n"+type2+"\n"+clickable2+"\n</RDF:Description>"
  594: 	    ret=about2+"\n"+name2+"\n"+type2+"\n"+clickable2+"\n</RDF:Description>"
  595: 	    return ret
  596:     
  597: def getCopyrightsFromForm(self,argv): 
  598: 	medias={}
  599: 	partners={}
  600: 	copyrights={}
  601: 	
  602: 	copyrightsFinal=[]
  603: 	for arg in argv.keys():
  604: 		
  605: 		if arg[0:5]=='media':
  606: 			nm=int(arg[5:])
  607: 			medias[nm]=argv[arg]
  608: 		elif arg[0:5]=='partn':
  609: 			nm=int(arg[5:])
  610: 			partners[nm]=argv[arg]
  611: 		elif arg[0:5]=='copyr':
  612: 			nm=int(arg[5:])
  613: 			copyrights[nm]=argv[arg]
  614: 
  615: 
  616: 
  617: 	copyrightsList=[(medias[nm],partners[nm],copyrights[nm]) for nm in medias.keys()]
  618: 	for copyright in copyrightsList:
  619: 		
  620: 		if copyright[2]=='institution0000':
  621: 			copyrightsFinal.append((copyright[0],copyright[1],self.getPartnerCopyright(copyright[1],'')))
  622: 		else:
  623: 			if not copyright[0]=='':
  624: 				copyrightsFinal.append(copyright)
  625: 		
  626: 			
  627: 	return copyrightsFinal
  628: 
  629: #List of different types for the graphical linking viewer
  630: viewClassificationListMaster=['view point','area']
  631: 
  632: 
  633: def checkDiffs(self,metadict):
  634: 	    """check differences"""
  635: 
  636: 	    
  637: 
  638:     
  639: 	    def NoneToEmpty(obj):
  640: 		    if obj:
  641: 			    return obj
  642: 		    else:
  643: 			    return ""
  644: 
  645: 	    
  646: 	    
  647: 	    diffs={}
  648: 	    
  649: 	    tags=self.findTagsFromMapping(self.contentType)
  650: 	    self.referencetypes=tags[2]
  651: 	    self.fields=tags[3]
  652: 	    
  653:     
  654: 	    for field in tags[1]:
  655: 		    try:
  656: 			    if (NoneToEmpty(self.getFieldValue(self.getFieldTag(tags,field)))==metadict[self.getFieldTag(tags,field)]):
  657: 				    diffs[self.getFieldTag(tags,field)]=1
  658: 			    else:
  659: 				    
  660: 				    diffs[self.getFieldTag(tags,field)]=0
  661: 		    except:
  662: 			    diffs[self.getFieldTag(tags,field)]=0
  663: 			    
  664: 	    return diffs
  665:     
  666: 
  667: def zptFile(self, path, orphaned=False):
  668:     """returns a page template file from the product"""
  669:     if orphaned:
  670: 	# unusual case
  671: 	pt=PageTemplateFile(os.path.join(package_home(globals()), path))
  672:     else:
  673: 	pt=PageTemplateFile(os.path.join(package_home(globals()), path)).__of__(self)
  674:     return pt
  675: 
  676: 
  677: def findObjectPath(startobject, filename):
  678:     """returns the object with the name filename starting at startobject"""
  679:     if startobject is None:
  680: 	return None
  681:     paths = filename.split('/')
  682:     object = startobject
  683:     for path in paths:
  684: 	    
  685:         if hasattr(object, path):
  686: 	    object = getattr(object, path)
  687: 	else:
  688: 	    object = None
  689: 	    break
  690:     return object
  691: 
  692: 
  693: def zptObjectOrFile(self, filename, localdir='zpt', orphaned=False):
  694:     """returns a page template instance or a file from the product"""
  695:     # look for an object called path
  696:     pt = findObjectPath(self, filename)
  697:     # the object should also not be a python function
  698:     if (pt is None) or isinstance(pt, types.FunctionType):
  699: 	# get a ZPT file
  700: 	pt = zptFile(self, localdir+'/'+filename, orphaned=orphaned)
  701:     return pt
  702: 
  703: 
  704: def sendFile(self, filename, type):
  705:     """sends an object or a local file (in the product) as response"""
  706:     # look for an object called filename
  707:     object = findObjectPath(self, filename)
  708:     if object:
  709: 	# if the object exists then send it
  710: 	return object.index_html(self.REQUEST.REQUEST, self.REQUEST.RESPONSE)
  711:     else:
  712: 	# send a local file with the given content-type
  713: 	fn = os.path.join(package_home(globals()), filename)
  714: 	self.REQUEST.RESPONSE.setHeader("Content-Type", type)
  715: 	self.REQUEST.RESPONSE.write(file(fn).read())
  716:     return
  717: 
  718: 
  719: class BrowserCheck:
  720:     """check the browsers request to find out the browser type"""
  721:     
  722:     def __init__(self, zope):
  723:         """initialisiere"""
  724: 	self.ua = zope.REQUEST.get_header("HTTP_USER_AGENT")
  725: 	self.isN4 = False
  726: 	self.isIE = False
  727: 	if string.find(self.ua, 'MSIE') > -1:
  728: 	    self.isIE = True
  729: 	else:
  730: 	    self.isN4 = string.find(self.ua, 'Mozilla/4.') > -1
  731: 	try:
  732: 	    self.nav = self.ua[string.find(self.ua, '('):]
  733: 	    ie = string.split(self.nav, "; ")[1]
  734: 	    if string.find(ie, "MSIE") > -1:
  735: 		self.versIE = string.split(ie, " ")[1]
  736: 	except: pass
  737: 	self.isMac = string.find(self.ua, 'Macintosh') > -1
  738: 	self.isWin = string.find(self.ua, 'Windows') > -1
  739: 	self.isIEWin = self.isIE and self.isWin
  740: 	self.isIEMac = self.isIE and self.isMac
  741: 
  742: 		
  743: def writeMetadata(url,metadict,project=None,startpage=None,xslt=None,thumbtemplate=None,topbar=None,digiLibTemplate=None,xmlfrag=None,digiliburlprefix=None):
  744: 	"""Einlesen der Metadaten und und erstellen des geaenderten XML file"""
  745: 
  746: 	def updateTextToolNode(tag,value):
  747: 
  748: 		metanode=dom.getElementsByTagName('texttool')[0]
  749: 		try:
  750: 			nodeOld=metanode.getElementsByTagName(tag)
  751: 		except:
  752: 			nodeOld=None
  753: 			
  754: 		if nodeOld:
  755: 			metanode.removeChild(nodeOld[0]).unlink()
  756: 
  757: 		node=dom.createElement(tag)
  758: 		nodetext=dom.createTextNode(value)
  759: 		node.appendChild(nodetext)
  760: 		metanode.appendChild(node)
  761: 
  762: 	if xmlfrag:
  763: 		geturl="""<?xml version="1.0" ?>
  764:                            <resource type="MPIWG">
  765: 			   <meta>
  766: 			    <bib type="Book">
  767: 	                    </bib>
  768: 			    </meta>
  769: 			    </resource>"""
  770: 		dom=xml.dom.minidom.parseString(geturl)
  771: 	else:
  772: 		try:
  773: 			geturl=""
  774: 			for line in urlopen(url).readlines():
  775: 				geturl=geturl+line
  776: 
  777: 
  778: 		except:
  779: 			return (None,"XCannot open: "+url)
  780: 
  781: 		try:
  782: 			dom=xml.dom.minidom.parseString(geturl)
  783: 		except:
  784: 			return (None,"Cannot parse: "+url+"<br>"+geturl)
  785: 
  786: 	
  787: 
  788: 	metanodes=dom.getElementsByTagName('bib')
  789: 
  790: 	if not metanodes:
  791: 		metanodes=dom.getElementsByTagName('archimedes')
  792: 
  793: 	metanode=metanodes[0]
  794: 
  795: 	for metaData in metadict.keys():
  796: 		
  797: 		try:
  798: 			nodeOld=metanode.getElementsByTagName(metaData)
  799: 		except:
  800: 			nodeOld=None
  801: 			
  802: 		if nodeOld:
  803: 			metanode.removeChild(nodeOld[0]).unlink()
  804: 		else:
  805: 			# try also old writing rule - instead of _:
  806: 			try:
  807: 				nodeOld=metanode.getElementsByTagName(re.sub('_','-',metaData))
  808: 			except:
  809: 				nodeOld=None
  810: 				
  811: 			if nodeOld:
  812: 				metanode.removeChild(nodeOld[0]).unlink()
  813: 
  814: 		metanodeneu=dom.createElement(metaData)
  815:                 metanodetext=dom.createTextNode(metadict[metaData])
  816: 		#try:
  817: 			#metanodetext=dom.createTextNode(unicode(metadict[metaData],"utf-8"))
  818: 		#except:
  819: 			#metanodetext=dom.createTextNode(metadict[metaData].encode('utf-8'))
  820: 		metanodeneu.appendChild(metanodetext)
  821: 		metanode.appendChild(metanodeneu)
  822: 
  823: 
  824: 	
  825: 	
  826: 	
  827: 	if project:
  828: 		updateTextToolNode('project',project)
  829: 
  830: 	if startpage:
  831: 		updateTextToolNode('startpage',startpage)
  832: 
  833: 	if topbar:
  834: 		updateTextToolNode('toptemplate',topbar)
  835: 
  836: 	if thumbtemplate:
  837: 		updateTextToolNode('thumbtemplate',thumbtemplate)
  838: 
  839: 	if xslt:
  840: 		updateTextToolNode('xslt',xslt)
  841: 
  842: 	
  843: 	if digiliburlprefix:
  844: 		updateTextToolNode('digiliburlprefix',digiliburlprefix)
  845: 	
  846:         try:	
  847: 	 return dom.toxml().encode('utf-8')
  848: 	except:
  849: 	 return dom.toxml('utf-8')
  850: 
  851: 	
  852: 	
  853: def readMetadata(url):
  854:     """Methode zum Auslesen der Metadateninformation zu einer Resource
  855:     Vorerst noch Typ bib"""
  856:     
  857:     metadict={}
  858:     
  859:     try:
  860:         geturl=""
  861:         for line in urlopen(url).readlines():
  862:             geturl=geturl+line
  863:         
  864:         
  865:     except:
  866:         return (None,"Cannot open: "+url)
  867: 
  868:     try:
  869:         dom=xml.dom.minidom.parseString(geturl)
  870:     except:
  871: 	    return (None,"Cannot parse: "+url+"<br>"+geturl)
  872: 
  873:     metanode=dom.getElementsByTagName('bib')
  874:     metadict['bib_type']='Book'
  875:     if len(metanode)==0:
  876:         metanode=dom.getElementsByTagName('archimedes')
  877:         metadict['bib_type']='Archimedes'
  878:         
  879:         
  880:     if not len(metanode)==0:    
  881:         metacontent=metanode[0].childNodes
  882:     
  883:         try:
  884:             metadict['bib_type']=getText(dom.getElementsByTagName('bib')[0].attributes['type'].childNodes)
  885:         except:
  886:             """nothing"""
  887:         
  888:         for node in metacontent:
  889: 		try:
  890: 			#print urllib.unquote(getText(node.childNodes)),getText(node.childNodes)
  891: 			#metadict[re.sub('-','_',node.tagName.lower())]=urllib.unquote(getText(node.childNodes))
  892: 			metadict[re.sub('-','_',node.tagName.lower())]=getText(node.childNodes)
  893: 		
  894: 		except:
  895: 			"""nothing"""
  896: 
  897: 
  898:     return metadict,""
  899:     
  900: 
  901: class MapArea(SimpleItem):
  902:     """simple class to hold coordinates"""
  903: 
  904:     meta_type = 'MapArea'
  905:     # Create a SecurityInfo for this class.
  906:     security = ClassSecurityInfo()
  907:     security.setDefaultAccess("allow")
  908:     # type constants
  909:     TYPE_AREA = 'area'
  910:     TYPE_ARROW = 'arrow'
  911:     TYPE_TEXT = 'text'
  912: 	
  913:     def __init__(self, id, coords, label=None, type=None, tip=None, volatile=True):
  914: 	"""init"""
  915: 	self.coords = coords[0:4]
  916: 	if len(coords) > 4:
  917: 	    self.angle = coords[4]
  918: 	else:
  919: 	    self.angle = 0
  920: 	self.id = id
  921: 	self.label = label
  922: 	self.setType(type)
  923: 	self.tip = tip
  924: 	self.volatile = volatile
  925: 
  926:     def setCoords(self, coords):
  927: 	"""sets the coords"""
  928: 	self.coords = coords
  929: 
  930:     def getCoordString(self):
  931: 	"""returns coordinates as a string"""
  932: 	return string.join(self.coords, ',')
  933: 
  934:     def setCoordString(self, coordstring):
  935: 	"""sets coordinates from a string"""
  936: 	coords = string.split(coordstring, ',')
  937: 	self.coords = [c.strip() for c in coords]
  938: 
  939:     def getFullId(self, prefix=None):
  940: 	"""returns the id with prefixed parent id"""
  941: 	if prefix is None:
  942: 	    if hasattr(self, 'aq_parent'):
  943: 		prefix = self.aq_parent.id
  944: 	    else:
  945: 		prefix = "id"
  946: 	fid = prefix + "." + self.id
  947: 	return fid
  948: 
  949:     def getType(self):
  950: 	"""returns the type"""
  951: 	return self.type
  952: 
  953:     def setType(self, type):
  954: 	"""sets the type"""
  955: 	if type == MapArea.TYPE_ARROW:
  956: 	    self.type = MapArea.TYPE_ARROW
  957: 	elif type == MapArea.TYPE_AREA:
  958: 	    self.type = MapArea.TYPE_AREA
  959: 	elif type == MapArea.TYPE_TEXT:
  960: 	    self.type = MapArea.TYPE_TEXT
  961: 	else:
  962: 	    self.type = MapArea.TYPE_AREA
  963: 	    
  964:     def isTypeArea(self):
  965: 	"""returns if the type is area"""
  966: 	return self.type == MapArea.TYPE_AREA
  967: 
  968:     def isTypeArrow(self):
  969: 	"""returns if the type is arrow"""
  970: 	return self.type == MapArea.TYPE_ARROW
  971: 
  972:     def isTypeText(self):
  973: 	"""returns if the type is text"""
  974: 	return self.type == MapArea.TYPE_TEXT
  975: 
  976:     def getAngle(self):
  977: 	"""returns the angle"""
  978: 	return self.angle
  979: 
  980:     def setAngle(self, angle):
  981: 	"""sets the angle"""
  982: 	self.angle = angle
  983: 
  984:     def getTip(self):
  985: 	"""returns the popup text"""
  986: 	# patch old version
  987: 	if not hasattr(self, 'tip'):
  988: 	    self.tip = self.text
  989: 
  990: 	if self.tip is None:
  991: 	    if hasattr(self, 'aq_parent'):
  992: 		parent = self.aq_parent
  993: 		if parent.contentType == 'text-popup':
  994: 		    return parent.description
  995: 	return self.tip
  996: 
  997:     def setTip(self, text):
  998: 	"""sets the text"""
  999: 	self.tiptext = text
 1000: 
 1001:     def getText(self):
 1002: 	"""returns the text fpr the area"""
 1003: 	if hasattr(self, 'aq_parent'):
 1004: 	    parent = self.aq_parent
 1005: 	    text = parent.getMapText()
 1006: 	    if text is not None:
 1007: 		return text.document_src()
 1008: 	return ""
 1009: 
 1010:     def getLabel(self):
 1011: 	"""returns the link label"""
 1012: 	if self.label is None:
 1013: 	    if hasattr(self, 'aq_parent'):
 1014: 		return self.aq_parent.label or self.aq_parent.id
 1015: 	return self.label
 1016: 
 1017:     def setLabel(self, label):
 1018: 	"""sets the label"""
 1019: 	self.label = label
 1020: 
 1021:     def getLinkId(self):
 1022: 	if hasattr(self, 'aq_parent'):
 1023: 	    return self.aq_parent.id
 1024: 	return self.id
 1025: 
 1026: # call this to initialize framework classes, which
 1027: # does the right thing with the security assertions.
 1028: Globals.InitializeClass(MapArea)
 1029: 
 1030: 
 1031: class MapText(ZopePageTemplate):
 1032:     """class to hold text for map areas"""
 1033: 
 1034:     meta_type = 'ECHO_mapText'
 1035:     # Create a SecurityInfo for this class.
 1036:     security = ClassSecurityInfo()
 1037:     security.setDefaultAccess("allow")
 1038: 	
 1039:     _default_content_fn = os.path.join(package_home(globals()),
 1040:                                        'html', 'ECHO_mapText_default.html')
 1041: 
 1042:     def __init__(self, id, text=None, content_type=None):
 1043:         self.id = str(id)
 1044:         self.ZBindings_edit(self._default_bindings)
 1045:         if text is None:
 1046:             text = open(self._default_content_fn).read()
 1047:         self.pt_edit(text, content_type)
 1048: 
 1049: # Product registration and Add support
 1050: manage_addMapTextForm = PageTemplateFile(
 1051:     'zpt/AddECHO_mapText', globals(), __name__='manage_addMapTextForm')
 1052: 
 1053: def manage_addMapText(self, id, title=None, text=None,
 1054:                            REQUEST=None, submit=None):
 1055:     "Add a Map Text with optional file content."
 1056: 
 1057:     id = str(id)
 1058:     if REQUEST is None:
 1059:         self._setObject(id, MapText(id, text))
 1060:         ob = getattr(self, id)
 1061:         if title:
 1062:             ob.pt_setTitle(title)
 1063:         return ob
 1064:     else:
 1065:         file = REQUEST.form.get('file')
 1066:         headers = getattr(file, 'headers', None)
 1067:         if headers is None or not file.filename:
 1068:             zpt = MapText(id, text)
 1069:         else:
 1070:             zpt = MapText(id, file, headers.get('content_type'))
 1071: 
 1072:         self._setObject(id, zpt)
 1073:         if title:
 1074:             ob = getattr(self, id)
 1075:             ob.pt_setTitle(title)
 1076: 
 1077:         try:
 1078:             u = self.DestinationURL()
 1079:         except AttributeError:
 1080:             u = REQUEST['URL1']
 1081: 
 1082:         if submit == " Add and Edit ":
 1083:             u = "%s/%s" % (u, urllib.quote(id))
 1084:         REQUEST.RESPONSE.redirect(u+'/manage_main')
 1085:     return ''
 1086: 
 1087: # call this to initialize framework classes, which
 1088: # does the right thing with the security assertions.
 1089: Globals.InitializeClass(MapText)

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