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