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