Annotation of documentViewer/documentViewer.py, revision 1.69.2.4

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

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