Annotation of documentViewer/documentViewer.py, revision 1.38

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>