File:  [Repository] / documentViewer / documentViewer.py
Revision 1.34: download - view: text, annotated - select for diffs - revision graph
Tue Nov 4 20:19:59 2008 UTC (15 years, 7 months ago) by dwinter
Branches: MAIN
CVS tags: HEAD
minorCVS: ----------------------------------------------------------------------

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

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