Annotation of documentViewer/documentViewer.py, revision 1.69.2.7

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

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