Annotation of documentViewer/documentViewer.py, revision 1.26
1.18 dwinter 1:
2:
1.1 dwinter 3: from OFS.Folder import Folder
4: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
1.22 dwinter 5: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
1.1 dwinter 6: from AccessControl import ClassSecurityInfo
1.8 casties 7: from AccessControl import getSecurityManager
1.1 dwinter 8: from Globals import package_home
9:
10: from Ft.Xml.Domlette import NonvalidatingReader
11: from Ft.Xml.Domlette import PrettyPrint, Print
1.11 casties 12: from Ft.Xml import EMPTY_NAMESPACE, Parse
1.1 dwinter 13:
14: import Ft.Xml.XPath
15:
16: import os.path
1.7 casties 17: import sys
1.1 dwinter 18: import cgi
19: import urllib
1.20 dwinter 20: import logging
1.22 dwinter 21:
1.18 dwinter 22: import urlparse
1.1 dwinter 23:
1.22 dwinter 24: def logger(txt,method,txt2):
25: """logging"""
26: logging.info(txt+ txt2)
27:
28:
1.4 casties 29: def getInt(number, default=0):
30: """returns always an int (0 in case of problems)"""
31: try:
32: return int(number)
33: except:
34: return default
35:
1.1 dwinter 36: def getTextFromNode(nodename):
1.18 dwinter 37: """get the cdata content of a node"""
1.8 casties 38: if nodename is None:
39: return ""
1.1 dwinter 40: nodelist=nodename.childNodes
41: rc = ""
42: for node in nodelist:
43: if node.nodeType == node.TEXT_NODE:
44: rc = rc + node.data
45: return rc
46:
1.9 casties 47:
48: def getParentDir(path):
49: """returns pathname shortened by one"""
50: return '/'.join(path.split('/')[0:-1])
51:
52:
1.1 dwinter 53: import socket
54:
1.8 casties 55: def urlopen(url,timeout=2):
1.1 dwinter 56: """urlopen mit timeout"""
1.8 casties 57: socket.setdefaulttimeout(timeout)
1.1 dwinter 58: ret=urllib.urlopen(url)
59: socket.setdefaulttimeout(5)
60: return ret
61:
62:
1.3 casties 63: ##
64: ## documentViewer class
65: ##
66: class documentViewer(Folder):
1.1 dwinter 67: """document viewer"""
1.20 dwinter 68: #textViewerUrl="http://127.0.0.1:8080/HFQP/testXSLT/getPage?"
1.18 dwinter 69:
1.1 dwinter 70: meta_type="Document viewer"
71:
72: security=ClassSecurityInfo()
1.3 casties 73: manage_options=Folder.manage_options+(
1.1 dwinter 74: {'label':'main config','action':'changeDocumentViewerForm'},
75: )
76:
1.3 casties 77: # templates and forms
78: viewer_main = PageTemplateFile('zpt/viewer_main', globals())
79: thumbs_main = PageTemplateFile('zpt/thumbs_main', globals())
80: image_main = PageTemplateFile('zpt/image_main', globals())
81: head_main = PageTemplateFile('zpt/head_main', globals())
82: docuviewer_css = PageTemplateFile('css/docuviewer.css', globals())
1.26 ! casties 83: info_xml = PageTemplateFile('zpt/info_xml', globals())
1.3 casties 84:
85: security.declareProtected('View management screens','changeDocumentViewerForm')
86: changeDocumentViewerForm = PageTemplateFile('zpt/changeDocumentViewer', globals())
87:
1.1 dwinter 88:
1.18 dwinter 89: def __init__(self,id,imageViewerUrl,textViewerUrl=None,title="",digilibBaseUrl=None,thumbcols=2,thumbrows=10,authgroups="mpiwg"):
1.1 dwinter 90: """init document viewer"""
91: self.id=id
92: self.title=title
93: self.imageViewerUrl=imageViewerUrl
1.18 dwinter 94: self.textViewerUrl=textViewerUrl
95:
1.4 casties 96: if not digilibBaseUrl:
1.3 casties 97: self.digilibBaseUrl = self.findDigilibUrl()
1.4 casties 98: else:
99: self.digilibBaseUrl = digilibBaseUrl
100: self.thumbcols = thumbcols
101: self.thumbrows = thumbrows
1.8 casties 102: # authgroups is list of authorized groups (delimited by ,)
103: self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
1.3 casties 104: # add template folder so we can always use template.something
105: self.manage_addFolder('template')
106:
107:
108: security.declareProtected('View','index_html')
1.21 dwinter 109: def index_html(self,mode,url,viewMode="auto",start=None,pn=1):
1.3 casties 110: '''
111: view it
1.26 ! casties 112: @param mode: defines how to access the document behind url
1.3 casties 113: @param url: url which contains display information
1.26 ! casties 114: @param viewMode: if images display images, if text display text, default is images (text,images or auto)
1.18 dwinter 115:
1.3 casties 116: '''
117:
1.22 dwinter 118: logger("documentViewer (index)", logging.INFO, "mode: %s url:%s start:%s pn:%s"%(mode,url,start,pn))
1.1 dwinter 119:
1.3 casties 120: if not hasattr(self, 'template'):
121: # create template folder if it doesn't exist
122: self.manage_addFolder('template')
123:
124: if not self.digilibBaseUrl:
125: self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
126:
1.4 casties 127: docinfo = self.getDocinfo(mode=mode,url=url)
128: pageinfo = self.getPageinfo(start=start,current=pn,docinfo=docinfo)
1.3 casties 129: pt = getattr(self.template, 'viewer_main')
1.21 dwinter 130:
131: if viewMode=="auto": # automodus gewaehlt
132: if docinfo.get("textURL",'') and self.textViewerUrl: #texturl gesetzt und textViewer konfiguriert
133: viewMode="text"
134: else:
135: viewMode="images"
1.22 dwinter 136:
1.18 dwinter 137: return pt(docinfo=docinfo,pageinfo=pageinfo,viewMode=viewMode)
1.1 dwinter 138:
139:
1.4 casties 140: def getLink(self,param=None,val=None):
141: """link to documentviewer with parameter param set to val"""
1.9 casties 142: params=self.REQUEST.form.copy()
1.4 casties 143: if param is not None:
1.7 casties 144: if val is None:
145: if params.has_key(param):
146: del params[param]
1.4 casties 147: else:
1.9 casties 148: params[param] = str(val)
1.7 casties 149:
1.9 casties 150: # quote values and assemble into query string
151: ps = "&".join(["%s=%s"%(k,urllib.quote(v)) for (k, v) in params.items()])
152: url=self.REQUEST['URL1']+"?"+ps
1.4 casties 153: return url
154:
1.26 ! casties 155:
! 156: def getInfo_xml(self,url,mode):
! 157: """returns info about the document as XML"""
! 158:
! 159: if not self.digilibBaseUrl:
! 160: self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
! 161:
! 162: docinfo = self.getDocinfo(mode=mode,url=url)
! 163: pt = getattr(self.template, 'info_xml')
! 164: return pt(docinfo=docinfo)
! 165:
1.4 casties 166:
1.3 casties 167: def getStyle(self, idx, selected, style=""):
1.4 casties 168: """returns a string with the given style and append 'sel' if path == selected."""
1.22 dwinter 169: #logger("documentViewer (getstyle)", logging.INFO, "idx: %s selected: %s style: %s"%(idx,selected,style))
1.3 casties 170: if idx == selected:
171: return style + 'sel'
172: else:
1.9 casties 173: return style
1.26 ! casties 174:
1.2 dwinter 175:
1.9 casties 176: def isAccessible(self, docinfo):
1.8 casties 177: """returns if access to the resource is granted"""
178: access = docinfo.get('accessType', None)
1.22 dwinter 179: logger("documentViewer (accessOK)", logging.INFO, "access type %s"%access)
1.17 casties 180: if access is not None and access == 'free':
1.22 dwinter 181: logger("documentViewer (accessOK)", logging.INFO, "access is free")
1.8 casties 182: return True
1.17 casties 183: elif access is None or access in self.authgroups:
1.9 casties 184: # only local access -- only logged in users
185: user = getSecurityManager().getUser()
186: if user is not None:
187: #print "user: ", user
188: return (user.getUserName() != "Anonymous User")
189: else:
190: return False
1.8 casties 191:
1.22 dwinter 192: logger("documentViewer (accessOK)", logging.INFO, "unknown access type %s"%access)
1.8 casties 193: return False
1.9 casties 194:
1.8 casties 195:
1.7 casties 196: def getDirinfoFromDigilib(self,path,docinfo=None):
1.6 casties 197: """gibt param von dlInfo aus"""
1.13 casties 198: num_retries = 3
1.7 casties 199: if docinfo is None:
200: docinfo = {}
201:
1.13 casties 202: infoUrl=self.digilibBaseUrl+"/dirInfo-xml.jsp?mo=dir&fn="+path
1.6 casties 203:
1.22 dwinter 204: logger("documentViewer (getparamfromdigilib)", logging.INFO, "dirInfo from %s"%(infoUrl))
1.6 casties 205:
1.13 casties 206: for cnt in range(num_retries):
1.9 casties 207: try:
1.13 casties 208: # dom = NonvalidatingReader.parseUri(imageUrl)
209: txt=urllib.urlopen(infoUrl).read()
210: dom = Parse(txt)
1.9 casties 211: break
212: except:
1.22 dwinter 213: logger("documentViewer (getdirinfofromdigilib)", logging.ERROR, "error reading %s (try %d)"%(infoUrl,cnt))
1.9 casties 214: else:
1.13 casties 215: raise IOError("Unable to get dir-info from %s"%(infoUrl))
1.6 casties 216:
1.10 casties 217: sizes=dom.xpath("//dir/size")
1.22 dwinter 218: logger("documentViewer (getparamfromdigilib)", logging.INFO, "dirInfo:size"%sizes)
1.6 casties 219:
1.10 casties 220: if sizes:
221: docinfo['numPages'] = int(getTextFromNode(sizes[0]))
1.7 casties 222: else:
223: docinfo['numPages'] = 0
224:
225: return docinfo
1.8 casties 226:
1.6 casties 227:
1.9 casties 228: def getIndexMeta(self, url):
229: """returns dom of index.meta document at url"""
1.12 casties 230: num_retries = 3
1.9 casties 231: dom = None
1.12 casties 232: metaUrl = None
1.9 casties 233: if url.startswith("http://"):
234: # real URL
1.12 casties 235: metaUrl = url
1.9 casties 236: else:
237: # online path
238: server=self.digilibBaseUrl+"/servlet/Texter?fn="
1.13 casties 239: metaUrl=server+url.replace("/mpiwg/online","")
1.9 casties 240: if not metaUrl.endswith("index.meta"):
241: metaUrl += "/index.meta"
1.18 dwinter 242: print metaUrl
1.13 casties 243: for cnt in range(num_retries):
1.9 casties 244: try:
1.12 casties 245: # patch dirk encoding fehler treten dann nicht mehr auf
1.11 casties 246: # dom = NonvalidatingReader.parseUri(metaUrl)
1.12 casties 247: txt=urllib.urlopen(metaUrl).read()
248: dom = Parse(txt)
1.13 casties 249: break
1.9 casties 250: except:
1.22 dwinter 251: logger("ERROR documentViewer (getIndexMata)", logging.INFO,"%s (%s)"%sys.exc_info()[0:2])
1.12 casties 252:
253: if dom is None:
254: raise IOError("Unable to read index meta from %s"%(url))
1.9 casties 255:
256: return dom
1.20 dwinter 257:
258: def getPresentationInfoXML(self, url):
259: """returns dom of info.xml document at url"""
260: num_retries = 3
261: dom = None
262: metaUrl = None
263: if url.startswith("http://"):
264: # real URL
265: metaUrl = url
266: else:
267: # online path
268: server=self.digilibBaseUrl+"/servlet/Texter?fn="
269: metaUrl=server+url.replace("/mpiwg/online","")
270:
271:
272: for cnt in range(num_retries):
273: try:
274: # patch dirk encoding fehler treten dann nicht mehr auf
275: # dom = NonvalidatingReader.parseUri(metaUrl)
276: txt=urllib.urlopen(metaUrl).read()
277: dom = Parse(txt)
278: break
279: except:
1.22 dwinter 280: logger("ERROR documentViewer (getPresentationInfoXML)", logging.INFO,"%s (%s)"%sys.exc_info()[0:2])
1.20 dwinter 281:
282: if dom is None:
283: raise IOError("Unable to read infoXMLfrom %s"%(url))
284:
285: return dom
1.9 casties 286:
287:
1.8 casties 288: def getAuthinfoFromIndexMeta(self,path,docinfo=None,dom=None):
1.9 casties 289: """gets authorization info from the index.meta file at path or given by dom"""
1.22 dwinter 290: logger("documentViewer (getauthinfofromindexmeta)", logging.INFO,"path: %s"%(path))
1.8 casties 291:
292: access = None
293:
294: if docinfo is None:
295: docinfo = {}
296:
297: if dom is None:
1.9 casties 298: dom = self.getIndexMeta(getParentDir(path))
1.18 dwinter 299:
1.8 casties 300: acctype = dom.xpath("//access-conditions/access/@type")
301: if acctype and (len(acctype)>0):
302: access=acctype[0].value
1.9 casties 303: if access in ['group', 'institution']:
1.8 casties 304: access = getTextFromNode(dom.xpath("//access-conditions/access/name")[0]).lower()
305:
306: docinfo['accessType'] = access
307: return docinfo
1.6 casties 308:
1.8 casties 309:
1.3 casties 310: def getBibinfoFromIndexMeta(self,path,docinfo=None,dom=None):
1.9 casties 311: """gets bibliographical info from the index.meta file at path or given by dom"""
1.22 dwinter 312: logger("documentViewer (getbibinfofromindexmeta)", logging.INFO,"path: %s"%(path))
1.2 dwinter 313:
1.3 casties 314: if docinfo is None:
315: docinfo = {}
316:
317: if dom is None:
1.9 casties 318: dom = self.getIndexMeta(getParentDir(path))
319:
1.4 casties 320: metaData=self.metadata.main.meta.bib
321: bibtype=dom.xpath("//bib/@type")
322: if bibtype and (len(bibtype)>0):
323: bibtype=bibtype[0].value
1.2 dwinter 324: else:
1.4 casties 325: bibtype="generic"
326: bibtype=bibtype.replace("-"," ") # wrong typesiin index meta "-" instead of " " (not wrong! ROC)
327: bibmap=metaData.generateMappingForType(bibtype)
1.9 casties 328: #print "bibmap: ", bibmap, " for: ", bibtype
1.8 casties 329: # if there is no mapping bibmap is empty (mapping sometimes has empty fields)
1.7 casties 330: if len(bibmap) > 0 and len(bibmap['author'][0]) > 0:
1.4 casties 331: docinfo['author']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['author'][0])[0])
332: docinfo['title']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['title'][0])[0])
333: docinfo['year']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['year'][0])[0])
1.22 dwinter 334:
335: logging.info("bla")
336: try:
337: docinfo['lang']=getTextFromNode(dom.xpath("//bib/lang")[0])
338: except:
339: docinfo['lang']=''
1.3 casties 340: return docinfo
341:
342:
1.8 casties 343: def getDocinfoFromTextTool(self,url,dom=None,docinfo=None):
1.3 casties 344: """parse texttool tag in index meta"""
1.22 dwinter 345: logger("documentViewer (getdocinfofromtexttool)", logging.INFO,"url: %s"%(url))
1.3 casties 346: if docinfo is None:
347: docinfo = {}
348:
1.22 dwinter 349: if docinfo.get('lang',None) is None:
350: docinfo['lang']='' # default keine Sprache gesetzt
1.8 casties 351: if dom is None:
1.9 casties 352: dom = self.getIndexMeta(url)
1.8 casties 353:
1.16 casties 354: archivePath = None
355: archiveName = None
356:
1.8 casties 357: archiveNames=dom.xpath("//resource/name")
358: if archiveNames and (len(archiveNames)>0):
359: archiveName=getTextFromNode(archiveNames[0])
1.16 casties 360: else:
1.22 dwinter 361: logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/name missing in: %s"%(url))
1.3 casties 362:
363: archivePaths=dom.xpath("//resource/archive-path")
364: if archivePaths and (len(archivePaths)>0):
365: archivePath=getTextFromNode(archivePaths[0])
1.8 casties 366: # clean up archive path
367: if archivePath[0] != '/':
368: archivePath = '/' + archivePath
1.16 casties 369: if archiveName and (not archivePath.endswith(archiveName)):
1.8 casties 370: archivePath += "/" + archiveName
1.3 casties 371: else:
1.16 casties 372: # try to get archive-path from url
1.22 dwinter 373: logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/archive-path missing in: %s"%(url))
1.16 casties 374: if (not url.startswith('http')):
375: archivePath = url.replace('index.meta', '')
376:
377: if archivePath is None:
378: # we balk without archive-path
379: raise IOError("Missing archive-path (for text-tool) in %s"%(url))
1.3 casties 380:
1.9 casties 381: imageDirs=dom.xpath("//texttool/image")
382: if imageDirs and (len(imageDirs)>0):
383: imageDir=getTextFromNode(imageDirs[0])
1.3 casties 384: else:
1.22 dwinter 385: # we balk with no image tag / not necessary anymore because textmode is now standard
386: #raise IOError("No text-tool info in %s"%(url))
387: imageDir=""
388: docinfo['numPages']=1 # im moment einfach auf eins setzen, navigation ueber die thumbs geht natuerlich nicht
389:
390: docinfo['imagePath'] = "" # keine Bilder
391: docinfo['imageURL'] = ""
392:
1.9 casties 393: if imageDir and archivePath:
394: #print "image: ", imageDir, " archivepath: ", archivePath
395: imageDir=os.path.join(archivePath,imageDir)
396: imageDir=imageDir.replace("/mpiwg/online",'')
397: docinfo=self.getDirinfoFromDigilib(imageDir,docinfo=docinfo)
398: docinfo['imagePath'] = imageDir
399: docinfo['imageURL'] = self.digilibBaseUrl+"/servlet/Scaler?fn="+imageDir
1.3 casties 400:
401: viewerUrls=dom.xpath("//texttool/digiliburlprefix")
402: if viewerUrls and (len(viewerUrls)>0):
403: viewerUrl=getTextFromNode(viewerUrls[0])
1.7 casties 404: docinfo['viewerURL'] = viewerUrl
1.3 casties 405:
406: textUrls=dom.xpath("//texttool/text")
407: if textUrls and (len(textUrls)>0):
408: textUrl=getTextFromNode(textUrls[0])
1.19 dwinter 409: if urlparse.urlparse(textUrl)[0]=="": #keine url
410: textUrl=os.path.join(archivePath,textUrl)
411:
1.7 casties 412: docinfo['textURL'] = textUrl
1.20 dwinter 413:
414: presentationUrls=dom.xpath("//texttool/presentation")
1.22 dwinter 415: docinfo = self.getBibinfoFromIndexMeta(url,docinfo=docinfo,dom=dom) # get info von bib tag
416:
417: if presentationUrls and (len(presentationUrls)>0): # ueberschreibe diese durch presentation informationen
1.20 dwinter 418: # presentation url ergiebt sich ersetzen von index.meta in der url der fŸr die Metadaten
419: # durch den relativen Pfad auf die presentation infos
420: presentationUrl=url.replace('index.meta',getTextFromNode(presentationUrls[0]))
421: docinfo = self.getBibinfoFromTextToolPresentation(presentationUrl,docinfo=docinfo,dom=dom)
1.22 dwinter 422:
1.25 casties 423: docinfo = self.getAuthinfoFromIndexMeta(url,docinfo=docinfo,dom=dom) # get access info
1.3 casties 424: return docinfo
425:
1.20 dwinter 426:
427: def getBibinfoFromTextToolPresentation(self,url,docinfo=None,dom=None):
428: """gets the bibliographical information from the preseantion entry in texttools
429: """
430: dom=self.getPresentationInfoXML(url)
431: docinfo['author']=getTextFromNode(dom.xpath("//author")[0])
432: docinfo['title']=getTextFromNode(dom.xpath("//title")[0])
433: docinfo['year']=getTextFromNode(dom.xpath("//date")[0])
434: return docinfo
435:
1.3 casties 436: def getDocinfoFromImagePath(self,path,docinfo=None):
437: """path ist the path to the images it assumes that the index.meta file is one level higher."""
1.22 dwinter 438: logger("documentViewer (getdocinfofromimagepath)", logging.INFO,"path: %s"%(path))
1.3 casties 439: if docinfo is None:
440: docinfo = {}
1.6 casties 441: path=path.replace("/mpiwg/online","")
1.3 casties 442: docinfo['imagePath'] = path
1.7 casties 443: docinfo=self.getDirinfoFromDigilib(path,docinfo=docinfo)
444: imageUrl=self.digilibBaseUrl+"/servlet/Scaler?fn="+path
1.3 casties 445: docinfo['imageURL'] = imageUrl
446:
447: docinfo = self.getBibinfoFromIndexMeta(path,docinfo=docinfo)
1.8 casties 448: docinfo = self.getAuthinfoFromIndexMeta(path,docinfo=docinfo)
1.3 casties 449: return docinfo
450:
1.2 dwinter 451:
1.3 casties 452: def getDocinfo(self, mode, url):
453: """returns docinfo depending on mode"""
1.22 dwinter 454: logger("documentViewer (getdocinfo)", logging.INFO,"mode: %s, url: %s"%(mode,url))
1.3 casties 455: # look for cached docinfo in session
1.21 dwinter 456: if self.REQUEST.SESSION.has_key('docinfo'):
1.3 casties 457: docinfo = self.REQUEST.SESSION['docinfo']
458: # check if its still current
459: if docinfo is not None and docinfo.get('mode') == mode and docinfo.get('url') == url:
1.22 dwinter 460: logger("documentViewer (getdocinfo)", logging.INFO,"docinfo in session: %s"%docinfo)
1.3 casties 461: return docinfo
462: # new docinfo
463: docinfo = {'mode': mode, 'url': url}
464: if mode=="texttool": #index.meta with texttool information
465: docinfo = self.getDocinfoFromTextTool(url, docinfo=docinfo)
466: elif mode=="imagepath":
467: docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo)
468: else:
1.22 dwinter 469: logger("documentViewer (getdocinfo)", logging.ERROR,"unknown mode!")
1.10 casties 470: raise ValueError("Unknown mode %s"%(mode))
471:
1.22 dwinter 472: logger("documentViewer (getdocinfo)", logging.INFO,"docinfo: %s"%docinfo)
1.3 casties 473: self.REQUEST.SESSION['docinfo'] = docinfo
474: return docinfo
1.2 dwinter 475:
476:
1.4 casties 477: def getPageinfo(self, current, start=None, rows=None, cols=None, docinfo=None):
1.3 casties 478: """returns pageinfo with the given parameters"""
479: pageinfo = {}
1.4 casties 480: current = getInt(current)
481: pageinfo['current'] = current
482: rows = int(rows or self.thumbrows)
483: pageinfo['rows'] = rows
484: cols = int(cols or self.thumbcols)
485: pageinfo['cols'] = cols
486: grpsize = cols * rows
487: pageinfo['groupsize'] = grpsize
488: start = getInt(start, default=(int(current / grpsize) * grpsize +1))
1.3 casties 489: pageinfo['start'] = start
1.4 casties 490: pageinfo['end'] = start + grpsize
491: if docinfo is not None:
492: np = int(docinfo['numPages'])
493: pageinfo['end'] = min(pageinfo['end'], np)
494: pageinfo['numgroups'] = int(np / grpsize)
495: if np % grpsize > 0:
496: pageinfo['numgroups'] += 1
497:
1.3 casties 498: return pageinfo
499:
1.1 dwinter 500: def text(self,mode,url,pn):
501: """give text"""
502: if mode=="texttool": #index.meta with texttool information
503: (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
504:
1.9 casties 505: #print textpath
1.1 dwinter 506: try:
507: dom = NonvalidatingReader.parseUri(textpath)
508: except:
509: return None
510:
511: list=[]
512: nodes=dom.xpath("//pb")
513:
514: node=nodes[int(pn)-1]
515:
516: p=node
517:
518: while p.tagName!="p":
519: p=p.parentNode
520:
521:
522: endNode=nodes[int(pn)]
523:
524:
525: e=endNode
526:
527: while e.tagName!="p":
528: e=e.parentNode
529:
530:
531: next=node.parentNode
532:
533: #sammle s
534: while next and (next!=endNode.parentNode):
535: list.append(next)
536: next=next.nextSibling
537: list.append(endNode.parentNode)
538:
539: if p==e:# beide im selben paragraphen
1.2 dwinter 540: pass
541: # else:
542: # next=p
543: # while next!=e:
544: # print next,e
545: # list.append(next)
546: # next=next.nextSibling
547: #
548: # for x in list:
549: # PrettyPrint(x)
550: #
551: # return list
1.3 casties 552: #
553:
554: def findDigilibUrl(self):
555: """try to get the digilib URL from zogilib"""
556: url = self.imageViewerUrl[:-1] + "/getScalerUrl"
1.20 dwinter 557: #print urlparse.urlparse(url)[0]
558: #print urlparse.urljoin(self.absolute_url(),url)
559: logging.info("finddigiliburl: %s"%urlparse.urlparse(url)[0])
560: logging.info("finddigiliburl: %s"%urlparse.urljoin(self.absolute_url(),url))
561:
1.3 casties 562: try:
1.18 dwinter 563: if urlparse.urlparse(url)[0]=='': #relative path
564: url=urlparse.urljoin(self.absolute_url()+"/",url)
565:
1.3 casties 566: scaler = urlopen(url).read()
567: return scaler.replace("/servlet/Scaler?", "")
568: except:
569: return None
570:
1.18 dwinter 571: def changeDocumentViewer(self,imageViewerUrl,textViewerUrl,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=10,authgroups='mpiwg',RESPONSE=None):
1.3 casties 572: """init document viewer"""
573: self.title=title
574: self.imageViewerUrl=imageViewerUrl
1.18 dwinter 575: self.textViewerUrl=textViewerUrl
1.3 casties 576: self.digilibBaseUrl = digilibBaseUrl
1.4 casties 577: self.thumbrows = thumbrows
578: self.thumbcols = thumbcols
1.8 casties 579: self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
1.3 casties 580: if RESPONSE is not None:
581: RESPONSE.redirect('manage_main')
1.1 dwinter 582:
583:
584:
585:
586: # security.declareProtected('View management screens','renameImageForm')
587:
588: def manage_AddDocumentViewerForm(self):
589: """add the viewer form"""
1.3 casties 590: pt=PageTemplateFile('zpt/addDocumentViewer', globals()).__of__(self)
1.1 dwinter 591: return pt()
592:
1.18 dwinter 593: def manage_AddDocumentViewer(self,id,imageViewerUrl="",textViewerUrl="",title="",RESPONSE=None):
1.1 dwinter 594: """add the viewer"""
1.18 dwinter 595: newObj=documentViewer(id,imageViewerUrl,title=title,textViewerUrl=textViewerUrl)
1.1 dwinter 596: self._setObject(id,newObj)
597:
598: if RESPONSE is not None:
599: RESPONSE.redirect('manage_main')
1.3 casties 600:
601:
602: ##
603: ## DocumentViewerTemplate class
604: ##
605: class DocumentViewerTemplate(ZopePageTemplate):
606: """Template for document viewer"""
607: meta_type="DocumentViewer Template"
608:
609:
610: def manage_addDocumentViewerTemplateForm(self):
611: """Form for adding"""
612: pt=PageTemplateFile('zpt/addDocumentViewerTemplate', globals()).__of__(self)
613: return pt()
614:
615: def manage_addDocumentViewerTemplate(self, id='viewer_main', title=None, text=None,
616: REQUEST=None, submit=None):
617: "Add a Page Template with optional file content."
618:
619: self._setObject(id, DocumentViewerTemplate(id))
620: ob = getattr(self, id)
1.23 dwinter 621: txt=file(os.path.join(package_home(globals()),'zpt/viewer_main.zpt'),'r').read()
622: logging.info("txt %s:"%txt)
623: ob.pt_edit(txt,"text/html")
1.3 casties 624: if title:
625: ob.pt_setTitle(title)
626: try:
627: u = self.DestinationURL()
628: except AttributeError:
629: u = REQUEST['URL1']
630:
631: u = "%s/%s" % (u, urllib.quote(id))
632: REQUEST.RESPONSE.redirect(u+'/manage_main')
633: return ''
634:
635:
1.14 casties 636:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>