source: documentViewer/documentViewer.py @ 42:fbc7258e4b5c

Last change on this file since 42:fbc7258e4b5c was 42:fbc7258e4b5c, checked in by casties, 18 years ago

changed default access to deny if no access information

File size: 18.2 KB
Line 
1from OFS.Folder import Folder
2from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
3from Products.PageTemplates.PageTemplateFile import PageTemplateFile
4from AccessControl import ClassSecurityInfo
5from AccessControl import getSecurityManager
6from Globals import package_home
7
8from Ft.Xml.Domlette import NonvalidatingReader
9from Ft.Xml.Domlette import PrettyPrint, Print
10from Ft.Xml import EMPTY_NAMESPACE, Parse
11
12import Ft.Xml.XPath
13
14import os.path
15import sys
16import cgi
17import urllib
18import zLOG
19
20def 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
27def 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       
38def getParentDir(path):
39    """returns pathname shortened by one"""
40    return '/'.join(path.split('/')[0:-1])
41       
42
43import socket
44
45def 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##
56class 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 None:
147            # no information - no access
148            return False
149        elif access == 'free':
150            zLOG.LOG("documentViewer (accessOK)", zLOG.INFO, "access is free")
151            return True
152        elif access in self.authgroups:
153            # only local access -- only logged in users
154            user = getSecurityManager().getUser()
155            if user is not None:
156                #print "user: ", user
157                return (user.getUserName() != "Anonymous User")
158            else:
159                return False
160       
161        zLOG.LOG("documentViewer (accessOK)", zLOG.INFO, "unknown access type %s"%access)
162        return False
163   
164               
165    def getDirinfoFromDigilib(self,path,docinfo=None):
166        """gibt param von dlInfo aus"""
167        num_retries = 3
168        if docinfo is None:
169            docinfo = {}
170           
171        infoUrl=self.digilibBaseUrl+"/dirInfo-xml.jsp?mo=dir&fn="+path
172   
173        zLOG.LOG("documentViewer (getparamfromdigilib)", zLOG.INFO, "dirInfo from %s"%(infoUrl))
174       
175        for cnt in range(num_retries):
176            try:
177                # dom = NonvalidatingReader.parseUri(imageUrl)
178                txt=urllib.urlopen(infoUrl).read()
179                dom = Parse(txt)
180                break
181            except:
182                zLOG.LOG("documentViewer (getdirinfofromdigilib)", zLOG.ERROR, "error reading %s (try %d)"%(infoUrl,cnt))
183        else:
184            raise IOError("Unable to get dir-info from %s"%(infoUrl))
185       
186        sizes=dom.xpath("//dir/size")
187        zLOG.LOG("documentViewer (getparamfromdigilib)", zLOG.INFO, "dirInfo:size"%sizes)
188       
189        if sizes:
190            docinfo['numPages'] = int(getTextFromNode(sizes[0]))
191        else:
192            docinfo['numPages'] = 0
193                       
194        return docinfo
195   
196           
197    def getIndexMeta(self, url):
198        """returns dom of index.meta document at url"""
199        num_retries = 3
200        dom = None
201        metaUrl = None
202        if url.startswith("http://"):
203            # real URL
204            metaUrl = url
205        else:
206            # online path
207            server=self.digilibBaseUrl+"/servlet/Texter?fn="
208            metaUrl=server+url.replace("/mpiwg/online","")
209            if not metaUrl.endswith("index.meta"):
210                metaUrl += "/index.meta"
211       
212        for cnt in range(num_retries):
213            try:
214                # patch dirk encoding fehler treten dann nicht mehr auf
215                # dom = NonvalidatingReader.parseUri(metaUrl)
216                txt=urllib.urlopen(metaUrl).read()
217                dom = Parse(txt)
218                break
219            except:
220                zLOG.LOG("ERROR documentViewer (getIndexMata)", zLOG.INFO,"%s (%s)"%sys.exc_info()[0:2])
221               
222        if dom is None:
223            raise IOError("Unable to read index meta from %s"%(url))
224                 
225        return dom
226                       
227       
228    def getAuthinfoFromIndexMeta(self,path,docinfo=None,dom=None):
229        """gets authorization info from the index.meta file at path or given by dom"""
230        zLOG.LOG("documentViewer (getauthinfofromindexmeta)", zLOG.INFO,"path: %s"%(path))
231       
232        access = None
233       
234        if docinfo is None:
235            docinfo = {}
236           
237        if dom is None:
238            dom = self.getIndexMeta(getParentDir(path))
239           
240        acctype = dom.xpath("//access-conditions/access/@type")
241        if acctype and (len(acctype)>0):
242            access=acctype[0].value
243            if access in ['group', 'institution']:
244                access = getTextFromNode(dom.xpath("//access-conditions/access/name")[0]).lower()
245           
246        docinfo['accessType'] = access
247        return docinfo
248   
249       
250    def getBibinfoFromIndexMeta(self,path,docinfo=None,dom=None):
251        """gets bibliographical info from the index.meta file at path or given by dom"""
252        zLOG.LOG("documentViewer (getbibinfofromindexmeta)", zLOG.INFO,"path: %s"%(path))
253       
254        if docinfo is None:
255            docinfo = {}
256           
257        if dom is None:
258            dom = self.getIndexMeta(getParentDir(path))
259           
260        metaData=self.metadata.main.meta.bib
261        bibtype=dom.xpath("//bib/@type")
262        if bibtype and (len(bibtype)>0):
263            bibtype=bibtype[0].value
264        else:
265            bibtype="generic"
266        bibtype=bibtype.replace("-"," ") # wrong typesiin index meta "-" instead of " " (not wrong! ROC)
267        bibmap=metaData.generateMappingForType(bibtype)
268        #print "bibmap: ", bibmap, " for: ", bibtype
269        # if there is no mapping bibmap is empty (mapping sometimes has empty fields)
270        if len(bibmap) > 0 and len(bibmap['author'][0]) > 0:
271            docinfo['author']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['author'][0])[0])
272            docinfo['title']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['title'][0])[0])
273            docinfo['year']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['year'][0])[0])
274       
275        return docinfo
276
277       
278    def getDocinfoFromTextTool(self,url,dom=None,docinfo=None):
279       """parse texttool tag in index meta"""
280       zLOG.LOG("documentViewer (getdocinfofromtexttool)", zLOG.INFO,"url: %s"%(url))
281       if docinfo is None:
282           docinfo = {}
283           
284       if dom is None:
285           dom = self.getIndexMeta(url)
286       
287       archiveNames=dom.xpath("//resource/name")
288       if archiveNames and (len(archiveNames)>0):
289           archiveName=getTextFromNode(archiveNames[0])
290       
291       archivePaths=dom.xpath("//resource/archive-path")
292       if archivePaths and (len(archivePaths)>0):
293           archivePath=getTextFromNode(archivePaths[0])
294           # clean up archive path
295           if archivePath[0] != '/':
296               archivePath = '/' + archivePath
297           if not archivePath.endswith(archiveName):
298               archivePath += "/" + archiveName
299       else:
300           archivePath=None
301       
302       imageDirs=dom.xpath("//texttool/image")
303       if imageDirs and (len(imageDirs)>0):
304           imageDir=getTextFromNode(imageDirs[0])
305       else:
306           # we balk with no image tag
307           raise IOError("No text-tool info in %s"%(url))
308           
309       if imageDir and archivePath:
310           #print "image: ", imageDir, " archivepath: ", archivePath
311           imageDir=os.path.join(archivePath,imageDir)
312           imageDir=imageDir.replace("/mpiwg/online",'')
313           docinfo=self.getDirinfoFromDigilib(imageDir,docinfo=docinfo)
314           docinfo['imagePath'] = imageDir
315           docinfo['imageURL'] = self.digilibBaseUrl+"/servlet/Scaler?fn="+imageDir
316           
317       viewerUrls=dom.xpath("//texttool/digiliburlprefix")
318       if viewerUrls and (len(viewerUrls)>0):
319           viewerUrl=getTextFromNode(viewerUrls[0])
320           docinfo['viewerURL'] = viewerUrl
321                 
322       textUrls=dom.xpath("//texttool/text")
323       if textUrls and (len(textUrls)>0):
324           textUrl=getTextFromNode(textUrls[0])
325           docinfo['textURL'] = textUrl
326                     
327       docinfo = self.getBibinfoFromIndexMeta(url,docinfo=docinfo,dom=dom)
328       docinfo = self.getAuthinfoFromIndexMeta(url,docinfo=docinfo,dom=dom)
329       return docinfo
330   
331
332    def getDocinfoFromImagePath(self,path,docinfo=None):
333        """path ist the path to the images it assumes that the index.meta file is one level higher."""
334        zLOG.LOG("documentViewer (getdocinfofromimagepath)", zLOG.INFO,"path: %s"%(path))
335        if docinfo is None:
336            docinfo = {}
337        path=path.replace("/mpiwg/online","")
338        docinfo['imagePath'] = path
339        docinfo=self.getDirinfoFromDigilib(path,docinfo=docinfo)
340        imageUrl=self.digilibBaseUrl+"/servlet/Scaler?fn="+path
341        docinfo['imageURL'] = imageUrl
342       
343        docinfo = self.getBibinfoFromIndexMeta(path,docinfo=docinfo)
344        docinfo = self.getAuthinfoFromIndexMeta(path,docinfo=docinfo)
345        return docinfo
346   
347   
348    def getDocinfo(self, mode, url):
349        """returns docinfo depending on mode"""
350        zLOG.LOG("documentViewer (getdocinfo)", zLOG.INFO,"mode: %s, url: %s"%(mode,url))
351        # look for cached docinfo in session
352        if self.REQUEST.SESSION.has_key('docinfo'):
353            docinfo = self.REQUEST.SESSION['docinfo']
354            # check if its still current
355            if docinfo is not None and docinfo.get('mode') == mode and docinfo.get('url') == url:
356                zLOG.LOG("documentViewer (getdocinfo)", zLOG.INFO,"docinfo in session: %s"%docinfo)
357                return docinfo
358        # new docinfo
359        docinfo = {'mode': mode, 'url': url}
360        if mode=="texttool": #index.meta with texttool information
361            docinfo = self.getDocinfoFromTextTool(url, docinfo=docinfo)
362        elif mode=="imagepath":
363            docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo)
364        else:
365            zLOG.LOG("documentViewer (getdocinfo)", zLOG.ERROR,"unknown mode!")
366            raise ValueError("Unknown mode %s"%(mode))
367                       
368        zLOG.LOG("documentViewer (getdocinfo)", zLOG.INFO,"docinfo: %s"%docinfo)
369        self.REQUEST.SESSION['docinfo'] = docinfo
370        return docinfo
371       
372       
373    def getPageinfo(self, current, start=None, rows=None, cols=None, docinfo=None):
374        """returns pageinfo with the given parameters"""
375        pageinfo = {}
376        current = getInt(current)
377        pageinfo['current'] = current
378        rows = int(rows or self.thumbrows)
379        pageinfo['rows'] = rows
380        cols = int(cols or self.thumbcols)
381        pageinfo['cols'] = cols
382        grpsize = cols * rows
383        pageinfo['groupsize'] = grpsize
384        start = getInt(start, default=(int(current / grpsize) * grpsize +1))
385        pageinfo['start'] = start
386        pageinfo['end'] = start + grpsize
387        if docinfo is not None:
388            np = int(docinfo['numPages'])
389            pageinfo['end'] = min(pageinfo['end'], np)
390            pageinfo['numgroups'] = int(np / grpsize)
391            if np % grpsize > 0:
392                pageinfo['numgroups'] += 1
393               
394        return pageinfo
395               
396    def text(self,mode,url,pn):
397        """give text"""
398        if mode=="texttool": #index.meta with texttool information
399            (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
400       
401        #print textpath
402        try:
403            dom = NonvalidatingReader.parseUri(textpath)
404        except:
405            return None
406   
407        list=[]
408        nodes=dom.xpath("//pb")
409
410        node=nodes[int(pn)-1]
411       
412        p=node
413       
414        while p.tagName!="p":
415            p=p.parentNode
416       
417       
418        endNode=nodes[int(pn)]
419       
420       
421        e=endNode
422       
423        while e.tagName!="p":
424            e=e.parentNode
425       
426       
427        next=node.parentNode
428       
429        #sammle s
430        while next and (next!=endNode.parentNode):
431            list.append(next)   
432            next=next.nextSibling   
433        list.append(endNode.parentNode)
434       
435        if p==e:# beide im selben paragraphen
436            pass
437#    else:
438#            next=p
439#            while next!=e:
440#                print next,e
441#                list.append(next)
442#                next=next.nextSibling
443#           
444#        for x in list:
445#            PrettyPrint(x)
446#
447#        return list
448#
449
450    def findDigilibUrl(self):
451        """try to get the digilib URL from zogilib"""
452        url = self.imageViewerUrl[:-1] + "/getScalerUrl"
453        try:
454            scaler = urlopen(url).read()
455            return scaler.replace("/servlet/Scaler?", "")
456        except:
457            return None
458   
459    def changeDocumentViewer(self,imageViewerUrl,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=10,authgroups='mpiwg',RESPONSE=None):
460        """init document viewer"""
461        self.title=title
462        self.imageViewerUrl=imageViewerUrl
463        self.digilibBaseUrl = digilibBaseUrl
464        self.thumbrows = thumbrows
465        self.thumbcols = thumbcols
466        self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
467        if RESPONSE is not None:
468            RESPONSE.redirect('manage_main')
469   
470   
471       
472       
473#    security.declareProtected('View management screens','renameImageForm')
474
475def manage_AddDocumentViewerForm(self):
476    """add the viewer form"""
477    pt=PageTemplateFile('zpt/addDocumentViewer', globals()).__of__(self)
478    return pt()
479 
480def manage_AddDocumentViewer(self,id,imageViewerUrl="",title="",RESPONSE=None):
481    """add the viewer"""
482    newObj=documentViewer(id,imageViewerUrl,title)
483    self._setObject(id,newObj)
484   
485    if RESPONSE is not None:
486        RESPONSE.redirect('manage_main')
487
488
489##
490## DocumentViewerTemplate class
491##
492class DocumentViewerTemplate(ZopePageTemplate):
493    """Template for document viewer"""
494    meta_type="DocumentViewer Template"
495
496
497def manage_addDocumentViewerTemplateForm(self):
498    """Form for adding"""
499    pt=PageTemplateFile('zpt/addDocumentViewerTemplate', globals()).__of__(self)
500    return pt()
501
502def manage_addDocumentViewerTemplate(self, id='viewer_main', title=None, text=None,
503                           REQUEST=None, submit=None):
504    "Add a Page Template with optional file content."
505
506    self._setObject(id, DocumentViewerTemplate(id))
507    ob = getattr(self, id)
508    ob.pt_edit(open(os.path.join(package_home(globals()),'zpt/viewer_main.zpt')).read(),None)
509    if title:
510        ob.pt_setTitle(title)
511    try:
512        u = self.DestinationURL()
513    except AttributeError:
514        u = REQUEST['URL1']
515       
516    u = "%s/%s" % (u, urllib.quote(id))
517    REQUEST.RESPONSE.redirect(u+'/manage_main')
518    return ''
519
520
521   
Note: See TracBrowser for help on using the repository browser.