source: documentViewer/documentViewer.py @ 79:df6952ac93e9

Root_integrate_imageArchive
Last change on this file since 79:df6952ac93e9 was 79:df6952ac93e9, checked in by dwinter, 15 years ago

bug in getDocInforFromImagePath, relative lage der index.meta zu path war falsch.

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