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