File:  [Repository] / documentViewer / documentViewer.py
Revision 1.40: download - view: text, annotated - select for diffs - revision graph
Fri Feb 12 13:17:09 2010 UTC (14 years, 4 months ago) by casties
Branches: MAIN
CVS tags: HEAD
fixed problem with info.xml when url without index.meta

    1: 
    2: 
    3: from OFS.Folder import Folder
    4: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
    5: from Products.PageTemplates.PageTemplateFile import PageTemplateFile 
    6: from AccessControl import ClassSecurityInfo
    7: from AccessControl import getSecurityManager
    8: from Globals import package_home
    9: 
   10: from Ft.Xml.Domlette import NonvalidatingReader
   11: from Ft.Xml.Domlette import PrettyPrint, Print
   12: from Ft.Xml import EMPTY_NAMESPACE, Parse
   13: 
   14: import Ft.Xml.XPath
   15: 
   16: import os.path
   17: import sys
   18: import cgi
   19: import urllib
   20: import logging
   21: import math
   22: 
   23: import urlparse 
   24: from types import *
   25: def logger(txt,method,txt2):
   26:     """logging"""
   27:     logging.info(txt+ txt2)
   28:     
   29:     
   30: def 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: 
   37: def 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:         
   49: def getParentDir(path):
   50:     """returns pathname shortened by one"""
   51:     return '/'.join(path.split('/')[0:-1])
   52:         
   53: 
   54: import socket
   55: 
   56: def 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: ##
   67: class 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:     
  217:     def getInfo_xml(self,url,mode):
  218:         """returns info about the document as XML"""
  219: 
  220:         if not self.digilibBaseUrl:
  221:             self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
  222:         
  223:         docinfo = self.getDocinfo(mode=mode,url=url)
  224:         pt = getattr(self.template, 'info_xml')
  225:         return pt(docinfo=docinfo)
  226: 
  227:     
  228:     def getStyle(self, idx, selected, style=""):
  229:         """returns a string with the given style and append 'sel' if path == selected."""
  230:         #logger("documentViewer (getstyle)", logging.INFO, "idx: %s selected: %s style: %s"%(idx,selected,style))
  231:         if idx == selected:
  232:             return style + 'sel'
  233:         else:
  234:             return style
  235: 
  236:         
  237:     def isAccessible(self, docinfo):
  238:         """returns if access to the resource is granted"""
  239:         access = docinfo.get('accessType', None)
  240:         logger("documentViewer (accessOK)", logging.INFO, "access type %s"%access)
  241:         if access is not None and access == 'free':
  242:             logger("documentViewer (accessOK)", logging.INFO, "access is free")
  243:             return True
  244:         elif access is None or access in self.authgroups:
  245:             # only local access -- only logged in users
  246:             user = getSecurityManager().getUser()
  247:             if user is not None:
  248:                 #print "user: ", user
  249:                 return (user.getUserName() != "Anonymous User")
  250:             else:
  251:                 return False
  252:         
  253:         logger("documentViewer (accessOK)", logging.INFO, "unknown access type %s"%access)
  254:         return False
  255:     
  256:                 
  257:     def getDirinfoFromDigilib(self,path,docinfo=None,cut=0):
  258:         """gibt param von dlInfo aus"""
  259:         num_retries = 3
  260:         if docinfo is None:
  261:             docinfo = {}
  262:         
  263:         for x in range(cut):
  264:                
  265:                 path=getParentDir(path)
  266:        
  267:         infoUrl=self.digilibBaseUrl+"/dirInfo-xml.jsp?mo=dir&fn="+path
  268:     
  269:         logger("documentViewer (getparamfromdigilib)", logging.INFO, "dirInfo from %s"%(infoUrl))
  270:         
  271:         for cnt in range(num_retries):
  272:             try:
  273:                 # dom = NonvalidatingReader.parseUri(imageUrl)
  274:                 txt=urllib.urlopen(infoUrl).read()
  275:                 dom = Parse(txt)
  276:                 break
  277:             except:
  278:                 logger("documentViewer (getdirinfofromdigilib)", logging.ERROR, "error reading %s (try %d)"%(infoUrl,cnt))
  279:         else:
  280:             raise IOError("Unable to get dir-info from %s"%(infoUrl))
  281:         
  282:         sizes=dom.xpath("//dir/size")
  283:         logger("documentViewer (getparamfromdigilib)", logging.INFO, "dirInfo:size"%sizes)
  284:         
  285:         if sizes:
  286:             docinfo['numPages'] = int(getTextFromNode(sizes[0]))
  287:         else:
  288:             docinfo['numPages'] = 0
  289:                         
  290:         return docinfo
  291:     
  292:             
  293:     def getIndexMeta(self, url):
  294:         """returns dom of index.meta document at url"""
  295:         num_retries = 3
  296:         dom = None
  297:         metaUrl = None
  298:         if url.startswith("http://"):
  299:             # real URL
  300:             metaUrl = url
  301:         else:
  302:             # online path
  303:             server=self.digilibBaseUrl+"/servlet/Texter?fn="
  304:             metaUrl=server+url.replace("/mpiwg/online","")
  305:             if not metaUrl.endswith("index.meta"):
  306:                 metaUrl += "/index.meta"
  307:         logging.debug("METAURL: %s"%metaUrl)
  308:         for cnt in range(num_retries):
  309:             try:
  310:                 # patch dirk encoding fehler treten dann nicht mehr auf
  311:                 # dom = NonvalidatingReader.parseUri(metaUrl)
  312:                 txt=urllib.urlopen(metaUrl).read()
  313:                 dom = Parse(txt)
  314:                 break
  315:             except:
  316:                 logger("ERROR documentViewer (getIndexMata)", logging.INFO,"%s (%s)"%sys.exc_info()[0:2])
  317:                 
  318:         if dom is None:
  319:             raise IOError("Unable to read index meta from %s"%(url))
  320:                  
  321:         return dom
  322:     
  323:     def getPresentationInfoXML(self, url):
  324:         """returns dom of info.xml document at url"""
  325:         num_retries = 3
  326:         dom = None
  327:         metaUrl = None
  328:         if url.startswith("http://"):
  329:             # real URL
  330:             metaUrl = url
  331:         else:
  332:             # online path
  333:             server=self.digilibBaseUrl+"/servlet/Texter?fn="
  334:             metaUrl=server+url.replace("/mpiwg/online","")
  335:            
  336:         
  337:         for cnt in range(num_retries):
  338:             try:
  339:                 # patch dirk encoding fehler treten dann nicht mehr auf
  340:                 # dom = NonvalidatingReader.parseUri(metaUrl)
  341:                 logging.debug("getpresentationinfoxml: metaurl=%s"%metaUrl)
  342:                 txt=urllib.urlopen(metaUrl).read()
  343:                 dom = Parse(txt)
  344:                 break
  345:             except:
  346:                 logger("ERROR documentViewer (getPresentationInfoXML)", logging.INFO,"%s (%s)"%sys.exc_info()[0:2])
  347:                 
  348:         if dom is None:
  349:             raise IOError("Unable to read infoXMLfrom %s"%(url))
  350:                  
  351:         return dom
  352:                         
  353:         
  354:     def getAuthinfoFromIndexMeta(self,path,docinfo=None,dom=None,cut=0):
  355:         """gets authorization info from the index.meta file at path or given by dom"""
  356:         logger("documentViewer (getauthinfofromindexmeta)", logging.INFO,"path: %s"%(path))
  357:         
  358:         access = None
  359:         
  360:         if docinfo is None:
  361:             docinfo = {}
  362:             
  363:         if dom is None:
  364:             for x in range(cut):
  365:                 path=getParentDir(path)
  366:             dom = self.getIndexMeta(path)
  367:        
  368:         acctype = dom.xpath("//access-conditions/access/@type")
  369:         if acctype and (len(acctype)>0):
  370:             access=acctype[0].value
  371:             if access in ['group', 'institution']:
  372:                 access = getTextFromNode(dom.xpath("//access-conditions/access/name")[0]).lower()
  373:             
  374:         docinfo['accessType'] = access
  375:         return docinfo
  376:     
  377:         
  378:     def getBibinfoFromIndexMeta(self,path,docinfo=None,dom=None,cut=0):
  379:         """gets bibliographical info from the index.meta file at path or given by dom"""
  380:         logging.debug("documentViewer (getbibinfofromindexmeta) path: %s"%(path))
  381:         
  382:         if docinfo is None:
  383:             docinfo = {}
  384:         
  385:         if dom is None:
  386:             for x in range(cut):
  387:                 path=getParentDir(path)
  388:             dom = self.getIndexMeta(path)
  389:         
  390:         logging.debug("documentViewer (getbibinfofromindexmeta cutted) path: %s"%(path))
  391:         # put in all raw bib fields as dict "bib"
  392:         bib = dom.xpath("//bib/*")
  393:         if bib and len(bib)>0:
  394:             bibinfo = {}
  395:             for e in bib:
  396:                 bibinfo[e.localName] = getTextFromNode(e)
  397:             docinfo['bib'] = bibinfo
  398:         
  399:         # extract some fields (author, title, year) according to their mapping
  400:         metaData=self.metadata.main.meta.bib
  401:         bibtype=dom.xpath("//bib/@type")
  402:         if bibtype and (len(bibtype)>0):
  403:             bibtype=bibtype[0].value
  404:         else:
  405:             bibtype="generic"
  406:             
  407:         bibtype=bibtype.replace("-"," ") # wrong typesiin index meta "-" instead of " " (not wrong! ROC)
  408:         docinfo['bib_type'] = bibtype
  409:         bibmap=metaData.generateMappingForType(bibtype)
  410:         # if there is no mapping bibmap is empty (mapping sometimes has empty fields)
  411:         if len(bibmap) > 0 and len(bibmap['author'][0]) > 0:
  412:             try:
  413:                 docinfo['author']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['author'][0])[0])
  414:             except: pass
  415:             try:
  416:                 docinfo['title']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['title'][0])[0])
  417:             except: pass
  418:             try:
  419:                 docinfo['year']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['year'][0])[0])
  420:             except: pass
  421:             logging.debug("documentViewer (getbibinfofromindexmeta) using mapping for %s"%bibtype)
  422:             try:
  423:                 docinfo['lang']=getTextFromNode(dom.xpath("//bib/lang")[0])
  424:             except:
  425:                 docinfo['lang']=''
  426: 
  427:         return docinfo
  428: 
  429:         
  430:     def getDocinfoFromTextTool(self,url,dom=None,docinfo=None):
  431:        """parse texttool tag in index meta"""
  432:        logger("documentViewer (getdocinfofromtexttool)", logging.INFO,"url: %s"%(url))
  433:        if docinfo is None:
  434:            docinfo = {}
  435:            
  436:        if docinfo.get('lang',None) is None:
  437:            docinfo['lang']='' # default keine Sprache gesetzt
  438:        if dom is None:
  439:            dom = self.getIndexMeta(url)
  440:        
  441:        archivePath = None
  442:        archiveName = None
  443: 
  444:        archiveNames=dom.xpath("//resource/name")
  445:        if archiveNames and (len(archiveNames)>0):
  446:            archiveName=getTextFromNode(archiveNames[0])
  447:        else:
  448:            logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/name missing in: %s"%(url))
  449:        
  450:        archivePaths=dom.xpath("//resource/archive-path")
  451:        if archivePaths and (len(archivePaths)>0):
  452:            archivePath=getTextFromNode(archivePaths[0])
  453:            # clean up archive path
  454:            if archivePath[0] != '/':
  455:                archivePath = '/' + archivePath
  456:            if archiveName and (not archivePath.endswith(archiveName)):
  457:                archivePath += "/" + archiveName
  458:        else:
  459:            # try to get archive-path from url
  460:            logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/archive-path missing in: %s"%(url))
  461:            if (not url.startswith('http')):
  462:                archivePath = url.replace('index.meta', '')
  463:                
  464:        if archivePath is None:
  465:            # we balk without archive-path
  466:            raise IOError("Missing archive-path (for text-tool) in %s"%(url))
  467:        
  468:        imageDirs=dom.xpath("//texttool/image")
  469:        if imageDirs and (len(imageDirs)>0):
  470:            imageDir=getTextFromNode(imageDirs[0])
  471:        else:
  472:            # we balk with no image tag / not necessary anymore because textmode is now standard
  473:            #raise IOError("No text-tool info in %s"%(url))
  474:            imageDir=""
  475:            docinfo['numPages']=1 # im moment einfach auf eins setzen, navigation ueber die thumbs geht natuerlich nicht
  476:        
  477:            docinfo['imagePath'] = "" # keine Bilder
  478:            docinfo['imageURL'] = ""
  479: 
  480:        if imageDir and archivePath:
  481:            #print "image: ", imageDir, " archivepath: ", archivePath
  482:            imageDir=os.path.join(archivePath,imageDir)
  483:            imageDir=imageDir.replace("/mpiwg/online",'')
  484:            docinfo=self.getDirinfoFromDigilib(imageDir,docinfo=docinfo)
  485:            docinfo['imagePath'] = imageDir
  486:            
  487:            docinfo['imageURL'] = self.digilibBaseUrl+"/servlet/Scaler?fn="+imageDir
  488:            
  489:        viewerUrls=dom.xpath("//texttool/digiliburlprefix")
  490:        if viewerUrls and (len(viewerUrls)>0):
  491:            viewerUrl=getTextFromNode(viewerUrls[0])
  492:            docinfo['viewerURL'] = viewerUrl
  493:                   
  494:        textUrls=dom.xpath("//texttool/text")
  495:        if textUrls and (len(textUrls)>0):
  496:            textUrl=getTextFromNode(textUrls[0])
  497:            if urlparse.urlparse(textUrl)[0]=="": #keine url
  498:                textUrl=os.path.join(archivePath,textUrl) 
  499:            # fix URLs starting with /mpiwg/online
  500:            if textUrl.startswith("/mpiwg/online"):
  501:                textUrl = textUrl.replace("/mpiwg/online",'',1)
  502:            
  503:            docinfo['textURL'] = textUrl
  504:    
  505:        presentationUrls=dom.xpath("//texttool/presentation")
  506:        docinfo = self.getBibinfoFromIndexMeta(url,docinfo=docinfo,dom=dom)   # get info von bib tag
  507:        
  508:        if presentationUrls and (len(presentationUrls)>0): # ueberschreibe diese durch presentation informationen 
  509:            # presentation url ergiebt sich ersetzen von index.meta in der url der fuer die Metadaten
  510:            # durch den relativen Pfad auf die presentation infos
  511:            presentationPath = getTextFromNode(presentationUrls[0])
  512:            if url.endswith("index.meta"): 
  513:                presentationUrl=url.replace('index.meta',presentationPath)
  514:            else:
  515:                presentationUrl=url + "/" + presentationPath
  516:                
  517:            docinfo = self.getBibinfoFromTextToolPresentation(presentationUrl,docinfo=docinfo,dom=dom)
  518: 
  519:        docinfo = self.getAuthinfoFromIndexMeta(url,docinfo=docinfo,dom=dom)   # get access info
  520:        return docinfo
  521:    
  522:    
  523:     def getBibinfoFromTextToolPresentation(self,url,docinfo=None,dom=None):
  524:         """gets the bibliographical information from the preseantion entry in texttools
  525:         """
  526:         dom=self.getPresentationInfoXML(url)
  527:         try:
  528:             docinfo['author']=getTextFromNode(dom.xpath("//author")[0])
  529:         except:
  530:             pass
  531:         try:
  532:             docinfo['title']=getTextFromNode(dom.xpath("//title")[0])
  533:         except:
  534:             pass
  535:         try:
  536:             docinfo['year']=getTextFromNode(dom.xpath("//date")[0])
  537:         except:
  538:             pass
  539:         return docinfo
  540:     
  541:     def getDocinfoFromImagePath(self,path,docinfo=None,cut=0):
  542:         """path ist the path to the images it assumes that the index.meta file is one level higher."""
  543:         logger("documentViewer (getdocinfofromimagepath)", logging.INFO,"path: %s"%(path))
  544:         if docinfo is None:
  545:             docinfo = {}
  546:         path=path.replace("/mpiwg/online","")
  547:         docinfo['imagePath'] = path
  548:         docinfo=self.getDirinfoFromDigilib(path,docinfo=docinfo,cut=cut)
  549:         
  550:         pathorig=path
  551:         for x in range(cut):       
  552:                 path=getParentDir(path)
  553:         logging.error("PATH:"+path)
  554:         imageUrl=self.digilibBaseUrl+"/servlet/Scaler?fn="+path
  555:         docinfo['imageURL'] = imageUrl
  556:         
  557:         #path ist the path to the images it assumes that the index.meta file is one level higher.
  558:         docinfo = self.getBibinfoFromIndexMeta(pathorig,docinfo=docinfo,cut=cut+1)
  559:         docinfo = self.getAuthinfoFromIndexMeta(pathorig,docinfo=docinfo,cut=cut+1)
  560:         return docinfo
  561:     
  562:     
  563:     def getDocinfo(self, mode, url):
  564:         """returns docinfo depending on mode"""
  565:         logger("documentViewer (getdocinfo)", logging.INFO,"mode: %s, url: %s"%(mode,url))
  566:         # look for cached docinfo in session
  567:         if self.REQUEST.SESSION.has_key('docinfo'):
  568:             docinfo = self.REQUEST.SESSION['docinfo']
  569:             # check if its still current
  570:             if docinfo is not None and docinfo.get('mode') == mode and docinfo.get('url') == url:
  571:                 logger("documentViewer (getdocinfo)", logging.INFO,"docinfo in session: %s"%docinfo)
  572:                 return docinfo
  573:         # new docinfo
  574:         docinfo = {'mode': mode, 'url': url}
  575:         if mode=="texttool": #index.meta with texttool information
  576:             docinfo = self.getDocinfoFromTextTool(url, docinfo=docinfo)
  577:         elif mode=="imagepath":
  578:             docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo)
  579:         elif mode=="filepath":
  580:             docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo,cut=1)
  581:         else:
  582:             logger("documentViewer (getdocinfo)", logging.ERROR,"unknown mode!")
  583:             raise ValueError("Unknown mode %s"%(mode))
  584:                         
  585:         logger("documentViewer (getdocinfo)", logging.INFO,"docinfo: %s"%docinfo)
  586:         self.REQUEST.SESSION['docinfo'] = docinfo
  587:         return docinfo
  588:         
  589:         
  590:     def getPageinfo(self, current, start=None, rows=None, cols=None, docinfo=None):
  591:         """returns pageinfo with the given parameters"""
  592:         pageinfo = {}
  593:         current = getInt(current)
  594:         pageinfo['current'] = current
  595:         rows = int(rows or self.thumbrows)
  596:         pageinfo['rows'] = rows
  597:         cols = int(cols or self.thumbcols)
  598:         pageinfo['cols'] = cols
  599:         grpsize = cols * rows
  600:         pageinfo['groupsize'] = grpsize
  601:         start = getInt(start, default=(math.ceil(float(current)/float(grpsize))*grpsize-(grpsize-1)))
  602:         # int(current / grpsize) * grpsize +1))
  603:         pageinfo['start'] = start
  604:         pageinfo['end'] = start + grpsize
  605:         if docinfo is not None:
  606:             np = int(docinfo['numPages'])
  607:             pageinfo['end'] = min(pageinfo['end'], np)
  608:             pageinfo['numgroups'] = int(np / grpsize)
  609:             if np % grpsize > 0:
  610:                 pageinfo['numgroups'] += 1
  611: 
  612:         return pageinfo
  613:                 
  614:     def text(self,mode,url,pn):
  615:         """give text"""
  616:         if mode=="texttool": #index.meta with texttool information
  617:             (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
  618:         
  619:         #print textpath
  620:         try:
  621:             dom = NonvalidatingReader.parseUri(textpath)
  622:         except:
  623:             return None
  624:     
  625:         list=[]
  626:         nodes=dom.xpath("//pb")
  627: 
  628:         node=nodes[int(pn)-1]
  629:         
  630:         p=node
  631:         
  632:         while p.tagName!="p":
  633:             p=p.parentNode
  634:         
  635:         
  636:         endNode=nodes[int(pn)]
  637:         
  638:         
  639:         e=endNode
  640:         
  641:         while e.tagName!="p":
  642:             e=e.parentNode
  643:         
  644:         
  645:         next=node.parentNode
  646:         
  647:         #sammle s
  648:         while next and (next!=endNode.parentNode):
  649:             list.append(next)    
  650:             next=next.nextSibling    
  651:         list.append(endNode.parentNode)
  652:         
  653:         if p==e:# beide im selben paragraphen
  654:             pass
  655: #    else:
  656: #            next=p
  657: #            while next!=e:
  658: #                print next,e
  659: #                list.append(next)
  660: #                next=next.nextSibling
  661: #            
  662: #        for x in list:
  663: #            PrettyPrint(x)
  664: #
  665: #        return list
  666: #
  667: 
  668:     def findDigilibUrl(self):
  669:         """try to get the digilib URL from zogilib"""
  670:         url = self.imageViewerUrl[:-1] + "/getScalerUrl"
  671:         #print urlparse.urlparse(url)[0]
  672:         #print urlparse.urljoin(self.absolute_url(),url)
  673:         logging.info("finddigiliburl: %s"%urlparse.urlparse(url)[0])
  674:         logging.info("finddigiliburl: %s"%urlparse.urljoin(self.absolute_url(),url))
  675:         
  676:         try:
  677:             if urlparse.urlparse(url)[0]=='': #relative path
  678:                 url=urlparse.urljoin(self.absolute_url()+"/",url)
  679:                 
  680:             scaler = urlopen(url).read()
  681:             return scaler.replace("/servlet/Scaler?", "")
  682:         except:
  683:             return None
  684:     
  685:     def changeDocumentViewer(self,imageViewerUrl,textViewerUrl,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=10,authgroups='mpiwg',RESPONSE=None):
  686:         """init document viewer"""
  687:         self.title=title
  688:         self.imageViewerUrl=imageViewerUrl
  689:         self.textViewerUrl=textViewerUrl
  690:         self.digilibBaseUrl = digilibBaseUrl
  691:         self.thumbrows = thumbrows
  692:         self.thumbcols = thumbcols
  693:         self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
  694:         if RESPONSE is not None:
  695:             RESPONSE.redirect('manage_main')
  696:     
  697:     
  698:         
  699:         
  700: #    security.declareProtected('View management screens','renameImageForm')
  701: 
  702: def manage_AddDocumentViewerForm(self):
  703:     """add the viewer form"""
  704:     pt=PageTemplateFile('zpt/addDocumentViewer', globals()).__of__(self)
  705:     return pt()
  706:   
  707: def manage_AddDocumentViewer(self,id,imageViewerUrl="",textViewerUrl="",title="",RESPONSE=None):
  708:     """add the viewer"""
  709:     newObj=documentViewer(id,imageViewerUrl,title=title,textViewerUrl=textViewerUrl)
  710:     self._setObject(id,newObj)
  711:     
  712:     if RESPONSE is not None:
  713:         RESPONSE.redirect('manage_main')
  714: 
  715: 
  716: ##
  717: ## DocumentViewerTemplate class
  718: ##
  719: class DocumentViewerTemplate(ZopePageTemplate):
  720:     """Template for document viewer"""
  721:     meta_type="DocumentViewer Template"
  722: 
  723: 
  724: def manage_addDocumentViewerTemplateForm(self):
  725:     """Form for adding"""
  726:     pt=PageTemplateFile('zpt/addDocumentViewerTemplate', globals()).__of__(self)
  727:     return pt()
  728: 
  729: def manage_addDocumentViewerTemplate(self, id='viewer_main', title=None, text=None,
  730:                            REQUEST=None, submit=None):
  731:     "Add a Page Template with optional file content."
  732: 
  733:     self._setObject(id, DocumentViewerTemplate(id))
  734:     ob = getattr(self, id)
  735:     txt=file(os.path.join(package_home(globals()),'zpt/viewer_main.zpt'),'r').read()
  736:     logging.info("txt %s:"%txt)
  737:     ob.pt_edit(txt,"text/html")
  738:     if title:
  739:         ob.pt_setTitle(title)
  740:     try:
  741:         u = self.DestinationURL()
  742:     except AttributeError:
  743:         u = REQUEST['URL1']
  744:         
  745:     u = "%s/%s" % (u, urllib.quote(id))
  746:     REQUEST.RESPONSE.redirect(u+'/manage_main')
  747:     return ''
  748: 
  749: 
  750:     

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