Annotation of documentViewer/documentViewer.py, revision 1.69.2.2

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

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