Annotation of documentViewer/documentViewer.py, revision 1.46

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

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