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 target is None:
424: targetattr = ""
425: else:
426: targetattr = 'target="%s"'%target
427:
428: if text is None:
429: text = ob.getLabel()
430:
431: if text is None:
432: text = "link"
433:
434: tiptext = ob.getTip()
435: tag = ""
436: if bt.isN4:
437: # N4 needs layer for highlighting
438: tag += '<ilayer id="a.%s"><a class="maplink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" %s'%(id,id,id,link,targetattr)
439: tag += ">" + text + "</a></ilayer>"
440: else:
441: # a-element
442: tag = '<a id="a.%s" class="maplink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" %s'%(id,id,id,link,targetattr)
443: if tiptext:
444: tag += ' title="%s"'%tiptext
445: tag += ">" + text + "</a>"
446: return tag
447:
448: 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"):
449: """generate map link image, text and other stuff"""
450: bt = BrowserCheck(self)
451: id = ob.getFullId()
452: link = ob.getLinkId()
453: tiptext = ob.getTip()
454: tag = ""
455:
456: if bt.isN4:
457: #
458: # N4 needs layer and img elements
459: #
460: tag += '<layer id="i.%s" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)">'%(id,id,id)
461: if ob.isTypeArrow():
462: # N4 - Arrow
463: rot = ob.angle
464:
465: if hasattr(getattr(self,link),'link'):
466: cLink=getattr(self,link).link
467: # if existing delete virtuell path
468: cLink=cLink.replace('/'.join(self.REQUEST['VirtualRootPhysicalPath']),'')
469:
470: if backLink and hasattr(getattr(self,link),'link') and backLink==self.REQUEST['SERVER_URL']+cLink.lstrip():
471: marksrc=alternativArrowsrc
472: else:
473: marksrc = arrowsrc
474:
475:
476: if float(rot) < 0:
477: marksrc = circlesrc
478: tag += '<a href="%s"><img border="0" src="%s&rot=%s" /></a>'%(link,marksrc,rot)
479: elif ob.isTypeText():
480: # N4 - Text
481: tag += '<div id="t.%s" class="maptext"'%(id)
482: tag += 'style="visibility:hidden">'
483: tag += ob.getText()
484: tag += '</div>'
485: else:
486: # N4 - Area
487: tag += '<a href="%s"><img border="0" width="1000" height="1000" src="trans_img"'%(link)
488: if tiptext:
489: tag += ' alt="%s"'%tiptext
490: tag += ' /></a>'
491: tag += '</layer>'
492: else:
493: #
494: # (more or less) DOM capable browser
495: #
496: tag = '<a id="b.%s" class="mapmarklink" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" target="%s">'%(id,id,id,link,target)
497: if ob.isTypeArrow():
498: # DOM - Arrow
499: rot = ob.angle
500:
501: if hasattr(getattr(self,link),'link'):
502: cLink=getattr(self,link).link
503: # if existing delete virtuell path
504: if hasattr(self.REQUEST,'VirtualRootPhysicalPath'):
505: cLink=cLink.replace('/'.join(self.REQUEST['VirtualRootPhysicalPath']),'')
506:
507: if backLink and hasattr(getattr(self,link),'link') and backLink==self.REQUEST['SERVER_URL']+cLink.lstrip():
508: marksrc=alternativArrowsrc
509: else:
510: marksrc = arrowsrc
511:
512: try:
513: rot=float(rot)
514: except:
515: rot=0
516:
517: if float(rot) < 0:
518: marksrc = circlesrc
519: if bt.isIEWin and bt.versIE > 5:
520: # IE/Win 5.5 has "feature" for PNG transparency
521: 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)
522: else:
523: # arrow image
524: tag += '<img id="i.%s" src="%s&rot=%s" border="1" style="position:absolute; top:-100px; left:-100px; border-style:none;" />'%(id,marksrc,rot)
525: elif ob.isTypeText():
526: # DOM - Text
527: tag += '<div id="i.%s" style="position:absolute; top:-100px; left:-100px;"'%(id)
528: tag += '><div id="t.%s" class="maptext"'%(id)
529: tag += 'style="visibility:hidden">'
530: tag += ob.getText()
531: tag += '</div></div>'
532: else:
533: # DOM - Area
534: if bt.isIE:
535: # IE needs transparent img for area
536: tag += '<img id="i.%s" border="0" style="position:absolute; top:-100px; left:-100px;" src="trans_img"'%(id)
537: if tiptext:
538: tag += ' title="%s"'%tiptext
539: tag += " />"
540: else:
541: # empty div for area
542: tag += '<div id="i.%s" style="position:absolute; top:-100px; left:-100px;"'%(id)
543: if tiptext:
544: tag += ' title="%s"'%tiptext
545: tag += '> </div>'
546: tag += '</a>'
547: return tag
548:
549:
550: #ende der echo erweiterungen
551:
552:
553: def toList(field):
554: """Einzelfeld in Liste umwandeln"""
555: if type(field)==types.StringType:
556: return [field]
557: else:
558: return field
559:
560: def getText(nodelist):
561: rc = ""
562: for node in nodelist:
563: if node.nodeType == node.TEXT_NODE:
564: rc = rc + node.data
565: return rc
566:
567: def getTextFromNode(nodename):
568: nodelist=nodename.childNodes
569: rc = ""
570: for node in nodelist:
571: if node.nodeType == node.TEXT_NODE:
572: rc = rc + node.data
573: return rc
574:
575:
576: def readFieldFromXML(meta_url,parent,field):
577: """lesespezifisches metadatum"""
578:
579: try:
580: dom=xml.dom.minidom.parse(meta_url)
581:
582: except:
583: try:
584: fh=urllib.urlopen(meta_url)
585: dom=xml.dom.minidom.parse(fh)
586: except:
587: return None
588: if not dom: return None
589:
590: parent=dom.getElementsByTagName(parent)
591: if not parent: return None
592:
593: field=parent[0].getElementsByTagName(field)
594:
595: if not field: return None
596:
597: return getText(field[0].childNodes)
598:
599:
600:
601: def urlopen(url):
602: """urlopen mit timeout"""
603: socket.setdefaulttimeout(10)
604: ret=urllib.urlopen(url)
605: socket.setdefaulttimeout(5)
606: return ret
607: # urlopener = urllib.URLopener()
608: #
609: # try:
610: # con = urlopener.open(url)
611: # return con
612: # except timeoutsocket.Timeout:
613: # return None
614:
615:
616:
617:
618:
619: def checkOnlyOneInGroup(object):
620: """check if object is a group and if it containt only one element it return this element"""
621: displayedObjects=object.ZopeFind(object,obj_metatypes=displayTypes)
622: if len(displayedObjects)==1: # nur ein Object dann redirect auf dieses Object
623:
624: return displayedObjects[0][1]
625: else: return object
626:
627:
628: def getSubCols(self, sortfield=None,
629: subColTypes=displayTypes,
630: sortFieldMD=None,
631: searchMD=None,
632: searchMD_modus='search',
633: searchSimple=None,
634: generic="yes",search_sub=0,
635: isVisible=True):
636:
637: def sort(x,y):
638: try:
639: if type(x[0])==type(y[0]):
640: return cmp(x[0],y[0])
641: else:
642: if type(x[0])==types.StringType:
643: tmpX=unicodify(x[0])
644: tmpY=y[0]
645: else:
646: tmpY=unicodify(y[0])
647: tmpX=x[0]
648: return cmp(tmpX,tmpY)
649:
650: except:
651: logging.error("Error at ECHO_helpers.sort:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
652: logging.error(" : %s %s"%sys.exc_info()[0:2])
653: logging.error("Error at ECHO_helpers.sort:"+repr(x)+"--"+repr(type(x[0])))
654: logging.error("Error at ECHO_helpers.sort:"+repr(y)+"--"+repr(type(y[0])))
655: logging.error("Error at ECHO_helpers.sort:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB")
656: return 0
657: def sortfnc(sortfield,x,y):
658: try:
659: xa=x[1].getMDValue(sortfield,generic=generic)
660: except:
661: xa=""
662: try:
663: ya=y[1].getMDValue(sortfield,generic=generic)
664: except:
665: ya=""
666: return cmp(xa,ya)
667:
668: sortWithMD = lambda sortfield : (lambda x,y : sortfnc(sortfield,x,y))
669: ids=[]
670: displayedObjects=self.ZopeFind(self,obj_metatypes=subColTypes,search_sub=search_sub)
671:
672: if searchSimple and (not (searchSimple==""))and hasattr(self,'resourceCatalog'):
673: searchString=" AND ".join(searchSimple.split())
674: ids=[x.getObject() for x in self.resourceCatalog({'getMDValueSimpleSearchField':searchString,'getIsVisible':True})]
675: else:
676: for entry in displayedObjects:
677: object=entry[1]
678: if searchMD:
679: if hasattr(object,'getMDValue'):
680: flag=0
681: for field in searchMD.keys():
682: #if object.getMDValue(field,generic=generic)==searchMD[field]:
683: #if re.match(searchMD[field],object.getMDValue(field,generic=generic)):
684: if searchMD_modus=='match':
685: searchResult=re.match(searchMD[field],object.getMDValue(field,generic=generic))
686: else:
687: searchResult=re.search(searchMD[field],object.getMDValue(field,generic=generic))
688: if searchResult:
689: flag=1
690: else:
691: flag=0
692: break
693: if flag==1:
694: ids.append(object)
695: else:
696: ids.append(object)
697: if not sortfield:
698: sortfield=getattr(self,'sortfield','weight')
699: tmplist=[]
700: for x in ids:
701: if hasattr(x,sortfield):
702: try:
703: tmp=int(getattr(x,sortfield))
704: except:
705: tmp=getattr(x,sortfield)
706:
707: else:
708: tmp=10000000
709:
710: tmplist.append((tmp,x))
711:
712: if not sortFieldMD:
713: tmplist.sort(sort)
714: else:
715: tmplist.sort(sortWithMD(sortFieldMD))
716:
717: ret=[x for (key,x) in tmplist]
718:
719: return ret
720:
721: def ECHO_rerenderLinksMD(self,obj=None,types=['title','label']):
722: """Rerender all Links"""
723: ret=""
724:
725: if not obj:
726: obj = self
727:
728: entries=obj.ZopeFind(obj,obj_metatypes=['ECHO_resource'],search_sub=1)
729:
730: for entry in entries:
731: if entry[1].meta_type == 'ECHO_resource':
732: try:
733: entry[1].ECHO_getResourceMD(template="no",overwrite="yes")
734: if "title" in types:
735: entry[1].generate_title()
736: if "label" in types:
737: entry[1].generate_label()
738: ret+="OK:"+entry[0]+"-- "+entry[1].getTitle().decode('utf-8')+"-- "+entry[1].getTitle().decode('utf-8')+"<br>"
739: except:
740: ret+="Error:"+entry[0]+"<br>"
741:
742:
743:
744:
745: return "<html><body>"+ret+"Rerenderd all links to resources in: "+self.title+"</html></body>"
746:
747: def reloadMetaDataFromStorage(self,RESPONSE=None):
748: """copy metadata from the storage to ECHO"""
749: ret=""
750: resources=self.ZopeFind(self,obj_metatypes=['ECHO_resource'],search_sub=1)
751: if RESPONSE is not None:
752: RESPONSE.setHeader("Content-Type", type)
753: RESPONSE.write("<html><body>\n")
754:
755: for resource in resources:
756: x=str(resource[1].copyIndex_meta2echo_resource())+"<br>"
757: if RESPONSE is not None:
758: RESPONSE.write(x+"\n")
759:
760: ret+=x
761:
762: if RESPONSE is not None:
763: #RESPONSE.redirect('./manage_main')
764: RESPONSE.write( "</html></body>")
765:
766: return ret
767:
768: def getRDFDescription(self,linkURL,urn=None,nameDef=None,typeName=None):
769: """rdf"""
770:
771: ret=""
772: about="""<RDF:Description RDF:about="%s">"""
773: name="""<ECHONAVIGATION:name>%s</ECHONAVIGATION:name>"""
774: link="""<ECHONAVIGATION:link xlink:href="%s">%s</ECHONAVIGATION:link>"""
775: clickable="""<ECHONAVIGATION:linkClickable>%s</ECHONAVIGATION:linkClickable>"""
776: #link="""<ECHONAVIGATION:link RDF:about="%s"/>"""
777: type="""<ECHONAVIGATION:type>%s</ECHONAVIGATION:type>"""
778: #xlink="""<ECHONAVIGATION:xlink xlink:href="%s"/>"""
779: if not urn:
780: #urn="urn:"+re.sub('/',':',self.absolute_url())
781: urn=self.absolute_url()
782: about2=about%urn
783: if not nameDef:
784: if hasattr(self,'label') and not (self.label==""):
785: name2=name%self.label
786: elif not self.title=="":
787: name2=name%self.title
788: else:
789: name2=name%self.getId()
790:
791: name2=re.sub('&','&',name2)
792: else:
793: name2=name%nameDef
794:
795: linkURL=re.sub('http:','',linkURL)
796: linkURL2=re.sub('&','&',linkURL)
797: link2=link%(("http:"+linkURL2),("http:"+urllib.quote(linkURL)))
798: clickable2=clickable%"true"
799:
800: if not typeName:
801: type2=type%self.meta_type
802: else:
803: type2=type%typeName
804:
805: #ret=about2+"\n"+name2+"\n"+link2+"\n"+type2+"\n"+clickable2+"\n</RDF:Description>"
806: ret=about2+"\n"+name2+"\n"+type2+"\n"+clickable2+"\n</RDF:Description>"
807: return ret
808:
809: def getCopyrightsFromForm(self,argv):
810: medias={}
811: partners={}
812: copyrights={}
813:
814: copyrightsFinal=[]
815: for arg in argv.keys():
816:
817: if arg[0:5]=='media':
818: nm=int(arg[5:])
819: medias[nm]=argv[arg]
820: elif arg[0:5]=='partn':
821: nm=int(arg[5:])
822: partners[nm]=argv[arg]
823: elif arg[0:5]=='copyr':
824: nm=int(arg[5:])
825: copyrights[nm]=argv[arg]
826:
827:
828:
829: copyrightsList=[(medias[nm],partners[nm],copyrights[nm]) for nm in medias.keys()]
830: for copyright in copyrightsList:
831:
832: if copyright[2]=='institution0000':
833: copyrightsFinal.append((copyright[0],copyright[1],self.getPartnerCopyright(copyright[1],'')))
834: else:
835: if not copyright[0]=='':
836: copyrightsFinal.append(copyright)
837:
838:
839: return copyrightsFinal
840:
841: #List of different types for the graphical linking viewer
842: viewClassificationListMaster=['view point','area']
843:
844:
845: def checkDiffs(self,metadict):
846: """check differences"""
847:
848:
849:
850:
851: def NoneToEmpty(obj):
852: if obj:
853: return obj
854: else:
855: return ""
856:
857:
858:
859: diffs={}
860:
861: tags=self.findTagsFromMapping(self.contentType)
862: self.referencetypes=tags[2]
863: self.fields=tags[3]
864:
865:
866: for field in tags[1]:
867: try:
868: if (NoneToEmpty(self.getMDValue(self.getFieldTag(tags,field)))==metadict[self.getFieldTag(tags,field)]):
869: diffs[self.getFieldTag(tags,field)]=1
870: else:
871:
872: diffs[self.getFieldTag(tags,field)]=0
873: except:
874: diffs[self.getFieldTag(tags,field)]=0
875:
876: return diffs
877:
878:
879: def zptFile(self, path, orphaned=False):
880: """returns a page template file from the product"""
881: if orphaned:
882: # unusual case
883: pt=PageTemplateFile(os.path.join(package_home(globals()), path))
884: else:
885:
886: pt=PageTemplateFile(os.path.join(package_home(globals()), path)).__of__(self)
887: return pt
888:
889:
890: def findObjectPath(startobject, filename):
891: """returns the object with the name filename starting at startobject"""
892: if startobject is None:
893: return None
894: paths = filename.split('/')
895: object = startobject
896: for path in paths:
897:
898: if hasattr(object, path):
899: object = getattr(object, path)
900: else:
901: object = None
902: break
903: return object
904:
905:
906: def zptObjectOrFile(self, filename, localdir='zpt', orphaned=False):
907: """returns a page template instance or a file from the product"""
908: # look for an object called path
909: pt = findObjectPath(self, filename)
910: # the object should also not be a python function
911: if (pt is None) or isinstance(pt, types.FunctionType):
912: # get a ZPT file
913: pt = zptFile(self, localdir+'/'+filename, orphaned=orphaned)
914: return pt
915:
916:
917: def sendFile(self, filename, type):
918: """sends an object or a local file (in the product) as response"""
919: # look for an object called filename
920: object = findObjectPath(self, filename)
921: if object:
922: # if the object exists then send it
923: return object.index_html(self.REQUEST.REQUEST, self.REQUEST.RESPONSE)
924: else:
925: # send a local file with the given content-type
926: fn = os.path.join(package_home(globals()), filename)
927: self.REQUEST.RESPONSE.setHeader("Content-Type", type)
928: self.REQUEST.RESPONSE.write(file(fn).read())
929: return
930:
931:
932: class BrowserCheck:
933: """check the browsers request to find out the browser type"""
934:
935: def __init__(self, zope):
936: """initialisiere"""
937: self.ua = zope.REQUEST.get_header("HTTP_USER_AGENT")
938: self.isN4 = False
939: self.isIE = False
940: if string.find(self.ua, 'MSIE') > -1:
941: self.isIE = True
942: else:
943: self.isN4 = string.find(self.ua, 'Mozilla/4.') > -1
944: try:
945: self.nav = self.ua[string.find(self.ua, '('):]
946: ie = string.split(self.nav, "; ")[1]
947: if string.find(ie, "MSIE") > -1:
948: self.versIE = string.split(ie, " ")[1]
949: except: pass
950: self.isMac = string.find(self.ua, 'Macintosh') > -1
951: self.isWin = string.find(self.ua, 'Windows') > -1
952: self.isIEWin = self.isIE and self.isWin
953: self.isIEMac = self.isIE and self.isMac
954:
955:
956: def writeMetadata(url,metadict,project=None,startpage=None,xslt=None,thumbtemplate=None,topbar=None,digiLibTemplate=None,xmlfrag=None,digiliburlprefix=None):
957: """Einlesen der Metadaten und und erstellen des geaenderten XML file"""
958:
959: def updateTextToolNode(tag,value):
960:
961: metanode=dom.getElementsByTagName('texttool')[0]
962: try:
963: nodeOld=metanode.getElementsByTagName(tag)
964: except:
965: nodeOld=None
966:
967: if nodeOld:
968: metanode.removeChild(nodeOld[0]).unlink()
969:
970: node=dom.createElement(tag)
971: nodetext=dom.createTextNode(value)
972: node.appendChild(nodetext)
973: metanode.appendChild(node)
974:
975:
976: if xmlfrag:
977: geturl="""<?xml version="1.0" encoding="UTF-8" ?>
978: <resource type="MPIWG">
979: <meta>
980: <bib type="Book">
981: </bib>
982: </meta>
983: </resource>"""
984: dom=xml.dom.minidom.parseString(geturl)
985: else:
986: try:
987: geturl=""
988: for line in urlopen(url).readlines():
989: geturl=geturl+line
990:
991:
992: except:
993: logger("ECHO writeMetadata",logging.ERROR,"XCannot open: "+url)
994: return (None,"XCannot open: "+url)
995:
996: try:
997: dom=xml.dom.minidom.parseString(geturl)
998: except:
999: logger("ECHO writeMetadata",logging.ERROR,"Cannot parse: "+url+"<br>"+geturl)
1000: return (None,"Cannot parse: "+url+"<br>"+geturl)
1001:
1002:
1003:
1004: metanodes=dom.getElementsByTagName('bib')
1005:
1006: if not metanodes:
1007: metanodes=dom.getElementsByTagName('archimedes')
1008:
1009: metanode=metanodes[0]
1010:
1011: for metaData in metadict.keys():
1012: if metaData:
1013: try:
1014: nodeOld=metanode.getElementsByTagName(metaData)
1015: except:
1016: nodeOld=None
1017:
1018: if nodeOld:
1019: metanode.removeChild(nodeOld[0]).unlink()
1020: else:
1021: # try also old writing rule - instead of _:
1022: try:
1023: nodeOld=metanode.getElementsByTagName(re.sub('_','-',metaData))
1024: except:
1025: nodeOld=None
1026:
1027: if nodeOld:
1028: metanode.removeChild(nodeOld[0]).unlink()
1029:
1030:
1031: metanodeneu=dom.createElement(metaData)
1032: try:
1033: metanodetext=dom.createTextNode(metadict[metaData].decode('utf-8'))
1034: except:
1035: metanodetext=dom.createTextNode(metadict[metaData])
1036: #try:
1037:
1038: #metanodetext=dom.createTextNode(unicode(metadict[metaData],"utf-8"))
1039: #except:
1040: #metanodetext=dom.createTextNode(metadict[metaData].encode('utf-8'))
1041: metanodeneu.appendChild(metanodetext)
1042: metanode.appendChild(metanodeneu)
1043:
1044:
1045:
1046:
1047:
1048: if project:
1049: updateTextToolNode('project',project)
1050:
1051: if startpage:
1052: updateTextToolNode('startpage',startpage)
1053:
1054: if topbar:
1055: updateTextToolNode('toptemplate',topbar)
1056:
1057: if thumbtemplate:
1058: updateTextToolNode('thumbtemplate',thumbtemplate)
1059:
1060: if xslt:
1061: updateTextToolNode('xslt',xslt)
1062:
1063:
1064: if digiliburlprefix:
1065: updateTextToolNode('digiliburlprefix',digiliburlprefix)
1066:
1067: try:
1068:
1069: return dom.toxml(encoding='utf-8').encode('utf-8')
1070: except:
1071:
1072:
1073: return dom.toxml(encoding='utf-8')
1074:
1075: def readMetadata(url):
1076: """Methode zum Auslesen der Metadateninformation zu einer Resource
1077: Vorerst noch Typ bib"""
1078:
1079: metadict={}
1080:
1081: try:
1082: geturl=""
1083: for line in urlopen(url).readlines():
1084: geturl=geturl+line
1085:
1086:
1087: except:
1088: return (None,"Cannot open: "+url)
1089:
1090: try:
1091: dom=xml.dom.minidom.parseString(geturl)
1092: except:
1093: return (None,"Cannot parse: "+url+"<br>"+geturl)
1094:
1095: metanode=dom.getElementsByTagName('bib')
1096: metadict['bib_type']='Book'
1097: if len(metanode)==0:
1098: metanode=dom.getElementsByTagName('archimedes')
1099: metadict['bib_type']='Archimedes'
1100:
1101:
1102: if not len(metanode)==0:
1103: metacontent=metanode[0].childNodes
1104:
1105: try:
1106: metadict['bib_type']=getText(dom.getElementsByTagName('bib')[0].attributes['type'].childNodes)
1107: except:
1108: """nothing"""
1109:
1110: for node in metacontent:
1111: try:
1112: #print urllib.unquote(getText(node.childNodes)),getText(node.childNodes)
1113: #metadict[re.sub('-','_',node.tagName.lower())]=urllib.unquote(getText(node.childNodes))
1114: metadict[re.sub('-','_',node.tagName.lower())]=getText(node.childNodes)
1115:
1116: except:
1117: """nothing"""
1118:
1119: return (metadict,"")
1120:
1121:
1122: class MapArea(SimpleItem):
1123: """simple class to hold coordinates"""
1124:
1125: meta_type = 'MapArea'
1126: # Create a SecurityInfo for this class.
1127: security = ClassSecurityInfo()
1128: security.setDefaultAccess("allow")
1129: # type constants
1130: TYPE_AREA = 'area'
1131: TYPE_ARROW = 'arrow'
1132: TYPE_TEXT = 'text'
1133:
1134: def __init__(self, id, coords, label=None, type=None, tip=None, permanent=False):
1135: """init"""
1136: self.coords = coords[0:4]
1137: if len(coords) > 4:
1138: self.angle = coords[4]
1139: else:
1140: self.angle = 0
1141: self.id = id
1142: self.label = label
1143: self.setType(type)
1144: self.tip = tip
1145: self.permanent = permanent
1146:
1147: def setCoords(self, coords):
1148: """sets the coords"""
1149: self.coords = coords
1150:
1151: def getCoordString(self):
1152: """returns coordinates as a string"""
1153: return string.join(self.coords, ',')
1154:
1155: def setCoordString(self, coordstring):
1156: """sets coordinates from a string"""
1157: coords = string.split(coordstring, ',')
1158: self.coords = [c.strip() for c in coords]
1159:
1160: def getFullId(self, prefix=None):
1161: """returns the id with prefixed parent id"""
1162: if prefix is None:
1163: if hasattr(self, 'aq_parent'):
1164: prefix = self.aq_parent.id
1165: else:
1166: prefix = "id"
1167: fid = prefix + "." + self.id
1168: return fid
1169:
1170: def getType(self):
1171: """returns the type"""
1172: return self.type
1173:
1174: def setType(self, type):
1175: """sets the type"""
1176: if type == MapArea.TYPE_ARROW:
1177: self.type = MapArea.TYPE_ARROW
1178: elif type == MapArea.TYPE_AREA:
1179: self.type = MapArea.TYPE_AREA
1180: elif type == MapArea.TYPE_TEXT:
1181: self.type = MapArea.TYPE_TEXT
1182: else:
1183: self.type = MapArea.TYPE_AREA
1184:
1185: def isTypeArea(self):
1186: """returns if the type is area"""
1187: return self.type == MapArea.TYPE_AREA
1188:
1189: def isTypeArrow(self):
1190: """returns if the type is arrow"""
1191: return self.type == MapArea.TYPE_ARROW
1192:
1193: def isTypeText(self):
1194: """returns if the type is text"""
1195: return self.type == MapArea.TYPE_TEXT
1196:
1197: def getAngle(self):
1198: """returns the angle"""
1199: return self.angle
1200:
1201: def setAngle(self, angle):
1202: """sets the angle"""
1203: self.angle = angle
1204:
1205: def getTip(self):
1206: """returns the popup text"""
1207: # patch old version
1208: if not hasattr(self, 'tip'):
1209: self.tip = self.text
1210:
1211: if self.tip is None:
1212: if hasattr(self, 'aq_parent'):
1213: parent = self.aq_parent
1214: if parent.contentType == 'text-popup':
1215: return parent.description
1216: return self.tip
1217:
1218: def setTip(self, text):
1219: """sets the text"""
1220: self.tiptext = text
1221:
1222: def getText(self):
1223: """returns the text fpr the area"""
1224: if hasattr(self, 'aq_parent'):
1225: parent = self.aq_parent
1226: text = parent.getMapText()
1227: if text is not None:
1228: #return text.document_src()
1229: return text()
1230: return ""
1231:
1232: def getLabel(self):
1233: """returns the link label"""
1234: if self.label is None:
1235: if hasattr(self, 'aq_parent'):
1236: return self.aq_parent.label or self.aq_parent.id
1237: return self.label
1238:
1239: def setLabel(self, label):
1240: """sets the label"""
1241: self.label = label
1242:
1243: def isPermanent(self):
1244: """returns the permanent state"""
1245: # patch old objects
1246: if not hasattr(self, 'permanent'):
1247: self.permanent = False
1248: return self.permanent
1249:
1250: def setPermanent(self, state):
1251: """sets the permanent state"""
1252: if state:
1253: self.permanent = True
1254: else:
1255: self.permanent = False
1256:
1257: def getLinkId(self):
1258: if hasattr(self, 'aq_parent'):
1259: return self.aq_parent.id
1260: return self.id
1261:
1262: # call this to initialize framework classes, which
1263: # does the right thing with the security assertions.
1264: Globals.InitializeClass(MapArea)
1265:
1266:
1267: class MapText(Folder,ZopePageTemplate):
1268: """class to hold text for map areas"""
1269:
1270: meta_type = 'ECHO_mapText'
1271: # Create a SecurityInfo for this class.
1272: security = ClassSecurityInfo()
1273: security.setDefaultAccess("allow")
1274:
1275:
1276: _default_content_fn = os.path.join(package_home(globals()),
1277: 'html', 'ECHO_mapText_default.html')
1278:
1279: def __init__(self, id, text=None, content_type=None):
1280: self.id = str(id)
1281: self.ZBindings_edit(self._default_bindings)
1282: if text is None:
1283: text = open(self._default_content_fn).read()
1284: if content_type is None:
1285: content_type = self.content_type
1286: self.pt_edit(text, content_type)
1287:
1288: def createLocale(self):
1289: """create locale"""
1290: return ECHO_collection.manage_addECHO_localeForm(self)
1291:
1292: manage_main=ZopePageTemplate.pt_editForm
1293:
1294: def manage_addECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None):
1295: """manage add echo locale in map"""
1296: ECHO_collection.manage_addECHO_locale(self,lang,title,label,text,content_type)
1297: if RESPONSE is not None:
1298: RESPONSE.redirect('manage_main')
1299:
1300:
1301: def changeLocale(self):
1302: """change locale"""
1303: return self.locale_en.change_ECHO_localeForm()
1304:
1305: def change_ECHO_locale(self,lang,title,label,text=None,content_type=None,RESPONSE=None):
1306: """change echo locale"""
1307:
1308: obj= self.locale_en.change_ECHO_locale(lang,title,label,text,content_type,RESPONSE)
1309:
1310:
1311:
1312: if RESPONSE is not None:
1313: RESPONSE.redirect('manage_main')
1314:
1315:
1316: # Product registration and Add support
1317: manage_addMapTextForm = PageTemplateFile(
1318: 'zpt/AddECHO_mapText', globals(), __name__='manage_addMapTextForm')
1319:
1320: def manage_addMapText(self, id, title=None, text=None,
1321: REQUEST=None, submit=None):
1322: "Add a Map Text with optional file content."
1323:
1324: id = str(id)
1325: if REQUEST is None:
1326: self._setObject(id, MapText(id, text))
1327: ob = getattr(self, id)
1328: if title:
1329: ob.pt_setTitle(title)
1330: return ob
1331: else:
1332: file = REQUEST.form.get('file')
1333: headers = getattr(file, 'headers', None)
1334: if headers is None or not file.filename:
1335: zpt = MapText(id, text)
1336: else:
1337: zpt = MapText(id, file, headers.get('content_type'))
1338:
1339: self._setObject(id, zpt)
1340: if title:
1341: ob = getattr(self, id)
1342: ob.pt_setTitle(title)
1343:
1344: try:
1345: u = self.DestinationURL()
1346: except AttributeError:
1347: u = REQUEST['URL1']
1348:
1349: if submit == " Add and Edit ":
1350: u = "%s/%s" % (u, urllib.quote(id))
1351: REQUEST.RESPONSE.redirect(u+'/manage_main')
1352: return ''
1353:
1354: # call this to initialize framework classes, which
1355: # does the right thing with the security assertions.
1356: Globals.InitializeClass(MapText)
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>