Annotation of documentViewer/documentViewer.py, revision 1.175.2.10

1.1       dwinter     1: from OFS.Folder import Folder
                      2: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
1.22      dwinter     3: from Products.PageTemplates.PageTemplateFile import PageTemplateFile 
1.1       dwinter     4: from AccessControl import ClassSecurityInfo
1.8       casties     5: from AccessControl import getSecurityManager
1.1       dwinter     6: from Globals import package_home
                      7: 
1.175.2.1  casties     8: #from Ft.Xml import EMPTY_NAMESPACE, Parse 
                      9: #import Ft.Xml.Domlette
                     10: 
                     11: import xml.etree.ElementTree as ET
                     12: 
1.1       dwinter    13: import os.path
1.7       casties    14: import sys
1.1       dwinter    15: import urllib
1.20      dwinter    16: import logging
1.28      casties    17: import math
1.18      dwinter    18: import urlparse 
1.99      dwinter    19: import re
1.149     abukhman   20: import string
1.117     abukhman   21: 
1.175.2.5  casties    22: from SrvTxtUtils import getInt, getText, getHttpData
                     23: 
1.22      dwinter    24: def logger(txt,method,txt2):
                     25:     """logging"""
                     26:     logging.info(txt+ txt2)
                     27:     
                     28:     
1.170     abukhman   29: def serializeNode(node, encoding="utf-8"):
1.43      casties    30:     """returns a string containing node as XML"""
1.175.2.1  casties    31:     s = ET.tostring(node)
                     32:     
                     33:     # 4Suite:
                     34:     #    stream = cStringIO.StringIO()
                     35:     #    Ft.Xml.Domlette.Print(node, stream=stream, encoding=encoding)
                     36:     #    s = stream.getvalue()
                     37:     #    stream.close()
1.43      casties    38:     return s
                     39: 
1.148     abukhman   40: def browserCheck(self):
                     41:     """check the browsers request to find out the browser type"""
                     42:     bt = {}
                     43:     ua = self.REQUEST.get_header("HTTP_USER_AGENT")
                     44:     bt['ua'] = ua
                     45:     bt['isIE'] = False
                     46:     bt['isN4'] = False
1.165     abukhman   47:     bt['versFirefox']=""
                     48:     bt['versIE']=""
                     49:     bt['versSafariChrome']=""
                     50:     bt['versOpera']=""
                     51:     
1.148     abukhman   52:     if string.find(ua, 'MSIE') > -1:
                     53:         bt['isIE'] = True
                     54:     else:
                     55:         bt['isN4'] = (string.find(ua, 'Mozilla/4.') > -1)
1.165     abukhman   56:     # Safari oder Chrome identification    
                     57:     try:
                     58:         nav = ua[string.find(ua, '('):]
                     59:         nav1=ua[string.find(ua,')'):]
                     60:         nav2=nav1[string.find(nav1,'('):]
                     61:         nav3=nav2[string.find(nav2,')'):]
                     62:         ie = string.split(nav, "; ")[1]
                     63:         ie1 =string.split(nav1, " ")[2]
                     64:         ie2 =string.split(nav3, " ")[1]
                     65:         ie3 =string.split(nav3, " ")[2]
                     66:         if string.find(ie3, "Safari") >-1:
                     67:             bt['versSafariChrome']=string.split(ie2, "/")[1]
                     68:     except: pass
                     69:     # IE identification
1.148     abukhman   70:     try:
                     71:         nav = ua[string.find(ua, '('):]
                     72:         ie = string.split(nav, "; ")[1]
                     73:         if string.find(ie, "MSIE") > -1:
                     74:             bt['versIE'] = string.split(ie, " ")[1]
1.165     abukhman   75:     except:pass
                     76:     # Firefox identification
                     77:     try:
                     78:         nav = ua[string.find(ua, '('):]
                     79:         nav1=ua[string.find(ua,')'):]
                     80:         if string.find(ie1, "Firefox") >-1:
                     81:             nav5= string.split(ie1, "/")[1]
                     82:             logging.debug("FIREFOX: %s"%(nav5))
1.166     abukhman   83:             bt['versFirefox']=nav5[0:3]                   
1.165     abukhman   84:     except:pass
                     85:     #Opera identification
                     86:     try:
                     87:         if string.find(ua,"Opera") >-1:
                     88:             nav = ua[string.find(ua, '('):]
                     89:             nav1=nav[string.find(nav,')'):]
                     90:             bt['versOpera']=string.split(nav1,"/")[2]
                     91:     except:pass
1.148     abukhman   92:     
                     93:     bt['isMac'] = string.find(ua, 'Macintosh') > -1
                     94:     bt['isWin'] = string.find(ua, 'Windows') > -1
                     95:     bt['isIEWin'] = bt['isIE'] and bt['isWin']
                     96:     bt['isIEMac'] = bt['isIE'] and bt['isMac']
                     97:     bt['staticHTML'] = False
                     98: 
                     99:     return bt
1.118     abukhman  100: 
1.9       casties   101: def getParentDir(path):
                    102:     """returns pathname shortened by one"""
                    103:     return '/'.join(path.split('/')[0:-1])
                    104:         
1.175.2.8  casties   105: 
1.3       casties   106: ##
                    107: ## documentViewer class
                    108: ##
                    109: class documentViewer(Folder):
1.1       dwinter   110:     """document viewer"""
                    111:     meta_type="Document viewer"
                    112:     
                    113:     security=ClassSecurityInfo()
1.3       casties   114:     manage_options=Folder.manage_options+(
1.1       dwinter   115:         {'label':'main config','action':'changeDocumentViewerForm'},
                    116:         )
1.175.2.10! casties   117:     
        !           118:     metadataService = None
        !           119:     """MetaDataFolder instance"""
1.1       dwinter   120: 
1.3       casties   121:     # templates and forms
                    122:     viewer_main = PageTemplateFile('zpt/viewer_main', globals())
1.44      casties   123:     toc_thumbs = PageTemplateFile('zpt/toc_thumbs', globals())
                    124:     toc_text = PageTemplateFile('zpt/toc_text', globals())
                    125:     toc_figures = PageTemplateFile('zpt/toc_figures', globals())
1.43      casties   126:     page_main_images = PageTemplateFile('zpt/page_main_images', globals())
1.161     abukhman  127:     page_main_double = PageTemplateFile('zpt/page_main_double', globals())
1.43      casties   128:     page_main_text = PageTemplateFile('zpt/page_main_text', globals())
1.44      casties   129:     page_main_text_dict = PageTemplateFile('zpt/page_main_text_dict', globals())
1.77      abukhman  130:     page_main_gis =PageTemplateFile ('zpt/page_main_gis', globals())
1.48      abukhman  131:     page_main_xml = PageTemplateFile('zpt/page_main_xml', globals())
1.157     abukhman  132:     page_main_pureXml = PageTemplateFile('zpt/page_main_pureXml', globals())
1.3       casties   133:     head_main = PageTemplateFile('zpt/head_main', globals())
                    134:     docuviewer_css = PageTemplateFile('css/docuviewer.css', globals())
1.26      casties   135:     info_xml = PageTemplateFile('zpt/info_xml', globals())
1.70      casties   136:     
                    137:     
1.32      dwinter   138:     thumbs_main_rss = PageTemplateFile('zpt/thumbs_main_rss', globals())
1.3       casties   139: 
1.1       dwinter   140:     
1.45      abukhman  141:     def __init__(self,id,imageScalerUrl=None,textServerName=None,title="",digilibBaseUrl=None,thumbcols=2,thumbrows=5,authgroups="mpiwg"):
1.1       dwinter   142:         """init document viewer"""
                    143:         self.id=id
                    144:         self.title=title
1.4       casties   145:         self.thumbcols = thumbcols
                    146:         self.thumbrows = thumbrows
1.8       casties   147:         # authgroups is list of authorized groups (delimited by ,)
                    148:         self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
1.43      casties   149:         # create template folder so we can always use template.something
                    150:         
                    151:         templateFolder = Folder('template')
                    152:         #self['template'] = templateFolder # Zope-2.12 style
                    153:         self._setObject('template',templateFolder) # old style
                    154:         try:
1.70      casties   155:             import MpdlXmlTextServer
1.71      casties   156:             textServer = MpdlXmlTextServer.MpdlXmlTextServer(id='fulltextclient',serverName=textServerName)
1.43      casties   157:             #templateFolder['fulltextclient'] = xmlRpcClient
1.70      casties   158:             templateFolder._setObject('fulltextclient',textServer)
1.43      casties   159:         except Exception, e:
1.70      casties   160:             logging.error("Unable to create MpdlXmlTextServer for fulltextclient: "+str(e))
1.175.2.10! casties   161:             
1.43      casties   162:         try:
                    163:             from Products.zogiLib.zogiLib import zogiLib
                    164:             zogilib = zogiLib(id="zogilib", title="zogilib for docuviewer", dlServerURL=imageScalerUrl, layout="book")
                    165:             #templateFolder['zogilib'] = zogilib
                    166:             templateFolder._setObject('zogilib',zogilib)
                    167:         except Exception, e:
                    168:             logging.error("Unable to create zogiLib for zogilib: "+str(e))
1.175.2.10! casties   169:             
        !           170:         try:
        !           171:             # assume MetaDataFolder instance is called metadata 
        !           172:             self.metadataService = getattr(self, 'metadata')
        !           173:         except Exception, e:
        !           174:             logging.error("Unable to find MetaDataFolder 'metadata': "+str(e))
        !           175:             
1.70      casties   176:         
                    177:     # proxy text server methods to fulltextclient
                    178:     def getTextPage(self, **args):
                    179:         """get page"""
                    180:         return self.template.fulltextclient.getTextPage(**args)
1.171     abukhman  181: 
                    182:     def getOrigPages(self, **args):
                    183:         """get page"""
                    184:         return self.template.fulltextclient.getOrigPages(**args)
1.167     abukhman  185:     
1.171     abukhman  186:     def getOrigPagesNorm(self, **args):
                    187:         """get page"""
                    188:         return self.template.fulltextclient.getOrigPagesNorm(**args)
                    189: 
1.70      casties   190:     def getQuery(self, **args):
1.163     abukhman  191:         """get query in search"""
1.70      casties   192:         return self.template.fulltextclient.getQuery(**args)
1.163     abukhman  193:      
1.70      casties   194:     def getSearch(self, **args):
                    195:         """get search"""
                    196:         return self.template.fulltextclient.getSearch(**args)
1.120     abukhman  197:     
                    198:     def getGisPlaces(self, **args):
1.121     abukhman  199:         """get gis places"""
1.120     abukhman  200:         return self.template.fulltextclient.getGisPlaces(**args)
1.121     abukhman  201:  
                    202:     def getAllGisPlaces(self, **args):
1.122     abukhman  203:         """get all gis places """
                    204:         return self.template.fulltextclient.getAllGisPlaces(**args)
1.163     abukhman  205:        
1.70      casties   206:     def getTranslate(self, **args):
                    207:         """get translate"""
                    208:         return self.template.fulltextclient.getTranslate(**args)
                    209: 
                    210:     def getLemma(self, **args):
                    211:         """get lemma"""
                    212:         return self.template.fulltextclient.getLemma(**args)
                    213: 
1.173     abukhman  214:     def getLemmaQuery(self, **args):
                    215:         """get query"""
                    216:         return self.template.fulltextclient.getLemmaQuery(**args)
                    217: 
                    218:     def getLex(self, **args):
                    219:         """get lex"""
                    220:         return self.template.fulltextclient.getLex(**args)
                    221: 
1.70      casties   222:     def getToc(self, **args):
                    223:         """get toc"""
                    224:         return self.template.fulltextclient.getToc(**args)
                    225: 
                    226:     def getTocPage(self, **args):
                    227:         """get tocpage"""
                    228:         return self.template.fulltextclient.getTocPage(**args)
1.3       casties   229: 
1.70      casties   230:     
1.32      dwinter   231:     security.declareProtected('View','thumbs_rss')
                    232:     def thumbs_rss(self,mode,url,viewMode="auto",start=None,pn=1):
                    233:         '''
                    234:         view it
                    235:         @param mode: defines how to access the document behind url 
                    236:         @param url: url which contains display information
                    237:         @param viewMode: if images display images, if text display text, default is images (text,images or auto)
                    238:         
                    239:         '''
1.95      abukhman  240:         logging.debug("HHHHHHHHHHHHHH:load the rss")
1.175.2.5  casties   241:         logging.debug("documentViewer (index) mode: %s url:%s start:%s pn:%s"%(mode,url,start,pn))
1.32      dwinter   242:         
                    243:         if not hasattr(self, 'template'):
                    244:             # create template folder if it doesn't exist
                    245:             self.manage_addFolder('template')
                    246:             
                    247:         if not self.digilibBaseUrl:
                    248:             self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
                    249:             
                    250:         docinfo = self.getDocinfo(mode=mode,url=url)
1.132     abukhman  251:         #pageinfo = self.getPageinfo(start=start,current=pn,docinfo=docinfo)
1.138     abukhman  252:         pageinfo = self.getPageinfo(start=start,current=pn, docinfo=docinfo)
1.126     abukhman  253:         ''' ZDES '''
1.32      dwinter   254:         pt = getattr(self.template, 'thumbs_main_rss')
                    255:         
                    256:         if viewMode=="auto": # automodus gewaehlt
1.159     casties   257:             if docinfo.has_key("textURL") or docinfo.get('textURLPath',None): #texturl gesetzt und textViewer konfiguriert
1.32      dwinter   258:                 viewMode="text"
                    259:             else:
                    260:                 viewMode="images"
                    261:                
                    262:         return pt(docinfo=docinfo,pageinfo=pageinfo,viewMode=viewMode)
                    263:   
1.3       casties   264:     security.declareProtected('View','index_html')
1.158     casties   265:     def index_html(self,url,mode="texttool",viewMode="auto",tocMode="thumbs",start=None,pn=1,mk=None):
1.3       casties   266:         '''
                    267:         view it
1.26      casties   268:         @param mode: defines how to access the document behind url 
1.3       casties   269:         @param url: url which contains display information
1.44      casties   270:         @param viewMode: if images display images, if text display text, default is auto (text,images or auto)
1.48      abukhman  271:         @param tocMode: type of 'table of contents' for navigation (thumbs, text, figures, none)
1.78      abukhman  272:         @param characterNormalization type of text display (reg, norm, none)
1.49      abukhman  273:         @param querySearch: type of different search modes (fulltext, fulltextMorph, xpath, xquery, ftIndex, ftIndexMorph, fulltextMorphLemma)
1.3       casties   274:         '''
                    275:         
1.138     abukhman  276:         logging.debug("documentViewer (index) mode: %s url:%s start:%s pn:%s"%(mode,url,start,pn))
1.1       dwinter   277:         
1.3       casties   278:         if not hasattr(self, 'template'):
1.43      casties   279:             # this won't work
                    280:             logging.error("template folder missing!")
                    281:             return "ERROR: template folder missing!"
1.3       casties   282:             
1.43      casties   283:         if not getattr(self, 'digilibBaseUrl', None):
1.71      casties   284:             self.digilibBaseUrl = self.findDigilibUrl() or "http://digilib.mpiwg-berlin.mpg.de/digitallibrary"
1.3       casties   285:             
1.4       casties   286:         docinfo = self.getDocinfo(mode=mode,url=url)
1.47      abukhman  287:         
1.44      casties   288:         if tocMode != "thumbs":
                    289:             # get table of contents
                    290:             docinfo = self.getToc(mode=tocMode, docinfo=docinfo)
1.175.2.3  casties   291: 
                    292:         # auto viewMode: text_dict if text else images
                    293:         if viewMode=="auto": 
                    294:             if docinfo.get('textURL', None) or docinfo.get('textURLPath', None): 
                    295:                 #texturl gesetzt und textViewer konfiguriert
1.68      casties   296:                 viewMode="text_dict"
1.21      dwinter   297:             else:
                    298:                 viewMode="images"
1.44      casties   299:                 
1.175.2.3  casties   300:         pageinfo = self.getPageinfo(start=start, current=pn, docinfo=docinfo, viewMode=viewMode, tocMode=tocMode)
1.68      casties   301:         
1.175.2.3  casties   302:         if viewMode != 'images' and docinfo.get('textURLPath', None):
                    303:             # get full text page
                    304:             page = self.getTextPage(mode=viewMode, pn=pn, docinfo=docinfo, pageinfo=pageinfo)
1.163     abukhman  305:             pageinfo['textPage'] = page
1.175.2.3  casties   306:             
                    307:         # get template /template/viewer_main
                    308:         pt = getattr(self.template, 'viewer_main')
                    309:         # and execute with parameters
                    310:         return pt(docinfo=docinfo, pageinfo=pageinfo, viewMode=viewMode, mk=self.generateMarks(mk))
1.1       dwinter   311:   
1.36      dwinter   312:     def generateMarks(self,mk):
                    313:         ret=""
1.44      casties   314:         if mk is None:
                    315:             return ""
1.73      casties   316:         if not isinstance(mk, list):
1.71      casties   317:             mk=[mk]
1.36      dwinter   318:         for m in mk:
1.37      dwinter   319:             ret+="mk=%s"%m
1.36      dwinter   320:         return ret
1.149     abukhman  321:     
                    322:     
1.148     abukhman  323:     def getBrowser(self):
                    324:         """getBrowser the version of browser """
1.162     casties   325:         bt = browserCheck(self)
1.164     abukhman  326:         logging.debug("BROWSER VERSION: %s"%(bt))
1.162     casties   327:         return bt
1.148     abukhman  328:         
1.43      casties   329:     def findDigilibUrl(self):
                    330:         """try to get the digilib URL from zogilib"""
                    331:         url = self.template.zogilib.getDLBaseUrl()
                    332:         return url
1.67      casties   333: 
                    334:     def getDocumentViewerURL(self):
                    335:         """returns the URL of this instance"""
                    336:         return self.absolute_url()
1.43      casties   337:     
                    338:     def getStyle(self, idx, selected, style=""):
                    339:         """returns a string with the given style and append 'sel' if path == selected."""
                    340:         #logger("documentViewer (getstyle)", logging.INFO, "idx: %s selected: %s style: %s"%(idx,selected,style))
                    341:         if idx == selected:
                    342:             return style + 'sel'
                    343:         else:
                    344:             return style
1.36      dwinter   345:     
1.162     casties   346:     def getLink(self, param=None, val=None, params=None, baseUrl=None, paramSep='&'):
                    347:         """returns URL to documentviewer with parameter param set to val or from dict params"""
                    348:         # copy existing request params
                    349:         urlParams=self.REQUEST.form.copy()
                    350:         # change single param
1.4       casties   351:         if param is not None:
1.7       casties   352:             if val is None:
1.162     casties   353:                 if urlParams.has_key(param):
                    354:                     del urlParams[param]
1.4       casties   355:             else:
1.162     casties   356:                 urlParams[param] = str(val)
1.43      casties   357:                 
1.162     casties   358:         # change more params
                    359:         if params is not None:
                    360:             for k in params.keys():
                    361:                 v = params[k]
                    362:                 if v is None:
                    363:                     # val=None removes param
                    364:                     if urlParams.has_key(k):
                    365:                         del urlParams[k]
                    366:                         
                    367:                 else:
                    368:                     urlParams[k] = v
                    369: 
                    370:         # FIXME: does this belong here?
                    371:         if urlParams.get("mode", None) == "filepath": #wenn beim erst Aufruf filepath gesetzt wurde aendere das nun zu imagepath
                    372:                 urlParams["mode"] = "imagepath"
                    373:                 urlParams["url"] = getParentDir(urlParams["url"])
1.7       casties   374:                 
1.162     casties   375:         # quote values and assemble into query string (not escaping '/')
                    376:         ps = paramSep.join(["%s=%s"%(k,urllib.quote_plus(v,'/')) for (k, v) in urlParams.items()])
                    377:         #ps = urllib.urlencode(urlParams)
                    378:         if baseUrl is None:
                    379:             baseUrl = self.REQUEST['URL1']
                    380:             
                    381:         url = "%s?%s"%(baseUrl, ps)
1.4       casties   382:         return url
                    383: 
1.162     casties   384: 
                    385:     def getLinkAmp(self, param=None, val=None, params=None, baseUrl=None):
1.32      dwinter   386:         """link to documentviewer with parameter param set to val"""
1.162     casties   387:         return self.getLink(param, val, params, baseUrl, '&')
1.40      casties   388:     
1.26      casties   389:     def getInfo_xml(self,url,mode):
                    390:         """returns info about the document as XML"""
                    391: 
                    392:         if not self.digilibBaseUrl:
                    393:             self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
                    394:         
                    395:         docinfo = self.getDocinfo(mode=mode,url=url)
                    396:         pt = getattr(self.template, 'info_xml')
                    397:         return pt(docinfo=docinfo)
                    398: 
1.153     casties   399:     def getOptionToggle(self, newState=None, optionName='text_options_open', initialState=True):
                    400:         """returns new option state"""
1.155     casties   401:         if not self.REQUEST.SESSION.has_key(optionName):
1.153     casties   402:             # not in session -- initial
                    403:             opt = {'lastState': newState, 'state': initialState}
                    404:         else:
1.155     casties   405:             opt = self.REQUEST.SESSION.get(optionName)
1.153     casties   406:             if opt['lastState'] != newState:
                    407:                 # state in session has changed -- toggle
                    408:                 opt['state'] = not opt['state']
                    409:                 opt['lastState'] = newState
                    410:         
                    411:         self.REQUEST.SESSION[optionName] = opt
                    412:         return opt['state']
1.4       casties   413:     
1.9       casties   414:     def isAccessible(self, docinfo):
1.8       casties   415:         """returns if access to the resource is granted"""
                    416:         access = docinfo.get('accessType', None)
1.95      abukhman  417:         logging.debug("documentViewer (accessOK) access type %s"%access)
1.17      casties   418:         if access is not None and access == 'free':
1.95      abukhman  419:             logging.debug("documentViewer (accessOK) access is free")
1.8       casties   420:             return True
1.17      casties   421:         elif access is None or access in self.authgroups:
1.9       casties   422:             # only local access -- only logged in users
                    423:             user = getSecurityManager().getUser()
1.95      abukhman  424:             logging.debug("documentViewer (accessOK) user=%s ip=%s"%(user,self.REQUEST.getClientAddr()))
1.9       casties   425:             if user is not None:
                    426:                 #print "user: ", user
                    427:                 return (user.getUserName() != "Anonymous User")
                    428:             else:
                    429:                 return False
1.8       casties   430:         
1.95      abukhman  431:         logging.error("documentViewer (accessOK) unknown access type %s"%access)
1.8       casties   432:         return False
1.9       casties   433:     
1.8       casties   434:                 
1.35      dwinter   435:     def getDirinfoFromDigilib(self,path,docinfo=None,cut=0):
1.6       casties   436:         """gibt param von dlInfo aus"""
1.7       casties   437:         if docinfo is None:
                    438:             docinfo = {}
1.35      dwinter   439:         
                    440:         for x in range(cut):
1.175.2.2  casties   441:             path=getParentDir(path)
1.38      dwinter   442:        
1.13      casties   443:         infoUrl=self.digilibBaseUrl+"/dirInfo-xml.jsp?mo=dir&fn="+path
1.6       casties   444:     
1.95      abukhman  445:         logging.debug("documentViewer (getparamfromdigilib) dirInfo from %s"%(infoUrl))
1.6       casties   446:         
1.70      casties   447:         txt = getHttpData(infoUrl)
                    448:         if txt is None:
1.13      casties   449:             raise IOError("Unable to get dir-info from %s"%(infoUrl))
1.70      casties   450: 
1.175.2.1  casties   451:         dom = ET.fromstring(txt)
                    452:         #dom = Parse(txt)
                    453:         size=getText(dom.find("size"))
                    454:         #sizes=dom.xpath("//dir/size")
                    455:         logging.debug("documentViewer (getparamfromdigilib) dirInfo:size=%s"%size)
1.6       casties   456:         
1.175.2.1  casties   457:         if size:
                    458:             docinfo['numPages'] = int(size)
1.7       casties   459:         else:
                    460:             docinfo['numPages'] = 0
1.43      casties   461:             
                    462:         # TODO: produce and keep list of image names and numbers
1.7       casties   463:                         
                    464:         return docinfo
1.8       casties   465:     
1.99      dwinter   466:     def getIndexMetaPath(self,url):
                    467:         """gib nur den Pfad zurueck"""
                    468:         regexp = re.compile(r".*(experimental|permanent)/(.*)")
                    469:         regpath = regexp.match(url)
                    470:         if (regpath==None):
                    471:             return ""
1.110     abukhman  472:         logging.debug("(getDomFromIndexMeta): URLXAXA: %s"%regpath.group(2))            
1.99      dwinter   473:         return ("/mpiwg/online/"+regpath.group(1)+"/"+regpath.group(2))
                    474:      
1.111     abukhman  475:     
                    476:     
1.99      dwinter   477:     def getIndexMetaUrl(self,url):
                    478:         """returns utr  of index.meta document at url"""
                    479:       
1.12      casties   480:         metaUrl = None
1.9       casties   481:         if url.startswith("http://"):
                    482:             # real URL
1.12      casties   483:             metaUrl = url
1.9       casties   484:         else:
                    485:             # online path
                    486:             server=self.digilibBaseUrl+"/servlet/Texter?fn="
1.13      casties   487:             metaUrl=server+url.replace("/mpiwg/online","")
1.9       casties   488:             if not metaUrl.endswith("index.meta"):
                    489:                 metaUrl += "/index.meta"
1.99      dwinter   490:         
                    491:         return metaUrl
                    492:     
                    493:     def getDomFromIndexMeta(self, url):
                    494:         """get dom from index meta"""
                    495:         dom = None
                    496:         metaUrl = self.getIndexMetaUrl(url)
1.12      casties   497:                 
1.99      dwinter   498:         logging.debug("(getDomFromIndexMeta): METAURL: %s"%metaUrl)
1.70      casties   499:         txt=getHttpData(metaUrl)
                    500:         if txt is None:
1.12      casties   501:             raise IOError("Unable to read index meta from %s"%(url))
1.70      casties   502:         
1.175.2.1  casties   503:         dom = ET.fromstring(txt)
                    504:         #dom = Parse(txt)
1.9       casties   505:         return dom
1.20      dwinter   506:     
                    507:     def getPresentationInfoXML(self, url):
                    508:         """returns dom of info.xml document at url"""
                    509:         dom = None
                    510:         metaUrl = None
                    511:         if url.startswith("http://"):
                    512:             # real URL
                    513:             metaUrl = url
                    514:         else:
                    515:             # online path
                    516:             server=self.digilibBaseUrl+"/servlet/Texter?fn="
                    517:             metaUrl=server+url.replace("/mpiwg/online","")
                    518:         
1.70      casties   519:         txt=getHttpData(metaUrl)
                    520:         if txt is None:
1.20      dwinter   521:             raise IOError("Unable to read infoXMLfrom %s"%(url))
1.70      casties   522:             
1.175.2.1  casties   523:         dom = ET.fromstring(txt)
                    524:         #dom = Parse(txt)
1.20      dwinter   525:         return dom
1.9       casties   526:                         
                    527:         
1.33      dwinter   528:     def getAuthinfoFromIndexMeta(self,path,docinfo=None,dom=None,cut=0):
1.9       casties   529:         """gets authorization info from the index.meta file at path or given by dom"""
1.95      abukhman  530:         logging.debug("documentViewer (getauthinfofromindexmeta) path: %s"%(path))
1.8       casties   531:         
                    532:         access = None
                    533:         
                    534:         if docinfo is None:
                    535:             docinfo = {}
                    536:             
                    537:         if dom is None:
1.38      dwinter   538:             for x in range(cut):
1.33      dwinter   539:                 path=getParentDir(path)
1.99      dwinter   540:             dom = self.getDomFromIndexMeta(path)
1.18      dwinter   541:        
1.175.2.1  casties   542:         acc = dom.find(".//access-conditions/access")
                    543:         if acc is not None:
                    544:             acctype = acc.get('type')
                    545:             #acctype = dom.xpath("//access-conditions/access/@type")
                    546:             if acctype:
                    547:                 access=acctype
                    548:                 if access in ['group', 'institution']:
                    549:                     access = dom.find(".//access-conditions/access/name").text.lower()
1.8       casties   550:             
                    551:         docinfo['accessType'] = access
                    552:         return docinfo
1.6       casties   553:     
1.8       casties   554:         
1.33      dwinter   555:     def getBibinfoFromIndexMeta(self,path,docinfo=None,dom=None,cut=0):
1.9       casties   556:         """gets bibliographical info from the index.meta file at path or given by dom"""
1.95      abukhman  557:         logging.debug("documentViewer (getbibinfofromindexmeta) path: %s"%(path))
1.2       dwinter   558:         
1.3       casties   559:         if docinfo is None:
                    560:             docinfo = {}
1.38      dwinter   561:         
1.3       casties   562:         if dom is None:
1.38      dwinter   563:             for x in range(cut):
1.33      dwinter   564:                 path=getParentDir(path)
1.99      dwinter   565:             dom = self.getDomFromIndexMeta(path)
                    566:         
                    567:         docinfo['indexMetaPath']=self.getIndexMetaPath(path);
1.39      dwinter   568:         
1.95      abukhman  569:         logging.debug("documentViewer (getbibinfofromindexmeta cutted) path: %s"%(path))
1.175.2.10! casties   570:         if self.metadataService is not None:
1.175.2.9  casties   571:             # put all raw bib fields in dict "bib"
1.175.2.10! casties   572:             bib = self.metadataService.getBibData(dom=dom)
1.175.2.9  casties   573:             docinfo['bib'] = bib
                    574:             bibtype = bib.get('@type', None)
                    575:             docinfo['bib_type'] = bibtype
                    576:             # also store DC metadata for convenience
1.175.2.10! casties   577:             dc = self.metadataService.getDCMappedData(bib)
1.175.2.9  casties   578:             docinfo['creator'] = dc.get('creator',None)
                    579:             docinfo['title'] = dc.get('title',None)
                    580:             docinfo['date'] = dc.get('date',None)
                    581:         else:
1.175.2.10! casties   582:             logging.error("MetadataService not found!")
1.3       casties   583:         return docinfo
1.42      abukhman  584:     
1.175.2.2  casties   585:     
                    586:     # TODO: is this needed?
1.104     abukhman  587:     def getNameFromIndexMeta(self,path,docinfo=None,dom=None,cut=0):
                    588:         """gets name info from the index.meta file at path or given by dom"""
                    589:         if docinfo is None:
                    590:             docinfo = {}
                    591:         
                    592:         if dom is None:
                    593:             for x in range(cut):
                    594:                 path=getParentDir(path)
                    595:             dom = self.getDomFromIndexMeta(path)
1.125     abukhman  596: 
1.175.2.1  casties   597:         docinfo['name']=getText(dom.find("name"))
1.116     abukhman  598:         logging.debug("documentViewer docinfo[name] %s"%docinfo['name'])
1.104     abukhman  599:         return docinfo
1.175.2.10! casties   600: 
1.42      abukhman  601:     
1.43      casties   602:     def getDocinfoFromTextTool(self, url, dom=None, docinfo=None):
                    603:         """parse texttool tag in index meta"""
1.95      abukhman  604:         logging.debug("documentViewer (getdocinfofromtexttool) url: %s" % (url))
1.43      casties   605:         if docinfo is None:
                    606:            docinfo = {}
                    607:         if docinfo.get('lang', None) is None:
                    608:             docinfo['lang'] = '' # default keine Sprache gesetzt
                    609:         if dom is None:
1.99      dwinter   610:             dom = self.getDomFromIndexMeta(url)
1.175.2.10! casties   611:             
        !           612:         texttool = self.metadata.getTexttoolData(dom=dom)
1.43      casties   613:         
                    614:         archivePath = None
                    615:         archiveName = None
                    616:     
1.175.2.2  casties   617:         archiveName = getText(dom.find("name"))
1.175.2.1  casties   618:         if not archiveName:
1.70      casties   619:             logging.warning("documentViewer (getdocinfofromtexttool) resource/name missing in: %s" % (url))
1.43      casties   620:         
1.175.2.2  casties   621:         archivePath = getText(dom.find("archive-path"))
1.175.2.1  casties   622:         if archivePath:
1.43      casties   623:             # clean up archive path
                    624:             if archivePath[0] != '/':
                    625:                 archivePath = '/' + archivePath
                    626:             if archiveName and (not archivePath.endswith(archiveName)):
                    627:                 archivePath += "/" + archiveName
                    628:         else:
                    629:             # try to get archive-path from url
1.95      abukhman  630:             logging.warning("documentViewer (getdocinfofromtexttool) resource/archive-path missing in: %s" % (url))
1.43      casties   631:             if (not url.startswith('http')):
                    632:                 archivePath = url.replace('index.meta', '')
                    633:                 
                    634:         if archivePath is None:
                    635:             # we balk without archive-path
                    636:             raise IOError("Missing archive-path (for text-tool) in %s" % (url))
                    637:         
1.175.2.10! casties   638:         imageDir = texttool.get('image', None)
1.43      casties   639:             
1.175.2.1  casties   640:         if not imageDir:
1.43      casties   641:             # we balk with no image tag / not necessary anymore because textmode is now standard
                    642:             #raise IOError("No text-tool info in %s"%(url))
                    643:             imageDir = ""
                    644:             #xquery="//pb"  
                    645:             docinfo['imagePath'] = "" # keine Bilder
                    646:             docinfo['imageURL'] = ""
                    647:             
                    648:         if imageDir and archivePath:
                    649:             #print "image: ", imageDir, " archivepath: ", archivePath
                    650:             imageDir = os.path.join(archivePath, imageDir)
                    651:             imageDir = imageDir.replace("/mpiwg/online", '')
                    652:             docinfo = self.getDirinfoFromDigilib(imageDir, docinfo=docinfo)
                    653:             docinfo['imagePath'] = imageDir
                    654:             
                    655:             docinfo['imageURL'] = self.digilibBaseUrl + "/servlet/Scaler?fn=" + imageDir
                    656:             
1.175.2.10! casties   657:         viewerUrl = texttool.get('digiliburlprefix', None)
1.175.2.1  casties   658:         if viewerUrl:
1.43      casties   659:             docinfo['viewerURL'] = viewerUrl
1.70      casties   660:         
                    661:         # old style text URL
1.175.2.10! casties   662:         textUrl = texttool.get('text', None)
1.175.2.1  casties   663:         if textUrl:
1.43      casties   664:             if urlparse.urlparse(textUrl)[0] == "": #keine url
                    665:                 textUrl = os.path.join(archivePath, textUrl) 
                    666:             # fix URLs starting with /mpiwg/online
                    667:             if textUrl.startswith("/mpiwg/online"):
                    668:                 textUrl = textUrl.replace("/mpiwg/online", '', 1)
                    669:             
                    670:             docinfo['textURL'] = textUrl
                    671:     
1.70      casties   672:         # new style text-url-path
1.175.2.10! casties   673:         textUrl = texttool.get('text-url-path', None)
1.175.2.1  casties   674:         if textUrl:
1.51      casties   675:             docinfo['textURLPath'] = textUrl
1.169     abukhman  676:             textUrlkurz = string.split(textUrl, ".")[0]
                    677:             docinfo['textURLPathkurz'] = textUrlkurz
1.163     abukhman  678:             #if not docinfo['imagePath']:
1.51      casties   679:                 # text-only, no page images
1.163     abukhman  680:                 #docinfo = self.getNumTextPages(docinfo)
                    681:                   
1.175.2.10! casties   682:         # get bib info
1.43      casties   683:         docinfo = self.getBibinfoFromIndexMeta(url, docinfo=docinfo, dom=dom)   # get info von bib tag
1.175.2.2  casties   684:         # TODO: is this needed here?
1.114     abukhman  685:         docinfo = self.getNameFromIndexMeta(url, docinfo=docinfo, dom=dom)
1.147     abukhman  686:         
1.175.2.10! casties   687:         # TODO: what to do with presentation?
        !           688:         presentationUrl = texttool.get('presentation', None)
1.175.2.1  casties   689:         if presentationUrl: # ueberschreibe diese durch presentation informationen 
1.43      casties   690:              # presentation url ergiebt sich ersetzen von index.meta in der url der fuer die Metadaten
                    691:              # durch den relativen Pfad auf die presentation infos
1.175.2.1  casties   692:             presentationPath = presentationUrl
1.43      casties   693:             if url.endswith("index.meta"): 
                    694:                 presentationUrl = url.replace('index.meta', presentationPath)
                    695:             else:
                    696:                 presentationUrl = url + "/" + presentationPath
1.51      casties   697:                 
1.43      casties   698:             docinfo = self.getBibinfoFromTextToolPresentation(presentationUrl, docinfo=docinfo, dom=dom)
                    699:     
1.175.2.10! casties   700:         # get authorization
1.43      casties   701:         docinfo = self.getAuthinfoFromIndexMeta(url, docinfo=docinfo, dom=dom)   # get access info
1.3       casties   702:         
1.43      casties   703:         return docinfo
1.3       casties   704:    
1.20      dwinter   705:    
                    706:     def getBibinfoFromTextToolPresentation(self,url,docinfo=None,dom=None):
                    707:         """gets the bibliographical information from the preseantion entry in texttools
                    708:         """
                    709:         dom=self.getPresentationInfoXML(url)
1.175.2.2  casties   710:         docinfo['author']=getText(dom.find(".//author"))
                    711:         docinfo['title']=getText(dom.find(".//title"))
                    712:         docinfo['year']=getText(dom.find(".//date"))
1.20      dwinter   713:         return docinfo
                    714:     
1.33      dwinter   715:     def getDocinfoFromImagePath(self,path,docinfo=None,cut=0):
1.3       casties   716:         """path ist the path to the images it assumes that the index.meta file is one level higher."""
1.95      abukhman  717:         logging.debug("documentViewer (getdocinfofromimagepath) path: %s"%(path))
1.3       casties   718:         if docinfo is None:
                    719:             docinfo = {}
1.6       casties   720:         path=path.replace("/mpiwg/online","")
1.3       casties   721:         docinfo['imagePath'] = path
1.35      dwinter   722:         docinfo=self.getDirinfoFromDigilib(path,docinfo=docinfo,cut=cut)
1.38      dwinter   723:         
1.39      dwinter   724:         pathorig=path
1.38      dwinter   725:         for x in range(cut):       
                    726:                 path=getParentDir(path)
1.95      abukhman  727:         logging.debug("documentViewer (getdocinfofromimagepath) PATH:"+path)
1.7       casties   728:         imageUrl=self.digilibBaseUrl+"/servlet/Scaler?fn="+path
1.3       casties   729:         docinfo['imageURL'] = imageUrl
                    730:         
1.175.2.7  casties   731:         #TODO: use getDocinfoFromIndexMeta
1.39      dwinter   732:         #path ist the path to the images it assumes that the index.meta file is one level higher.
                    733:         docinfo = self.getBibinfoFromIndexMeta(pathorig,docinfo=docinfo,cut=cut+1)
                    734:         docinfo = self.getAuthinfoFromIndexMeta(pathorig,docinfo=docinfo,cut=cut+1)
1.3       casties   735:         return docinfo
                    736:     
1.2       dwinter   737:     
1.3       casties   738:     def getDocinfo(self, mode, url):
                    739:         """returns docinfo depending on mode"""
1.95      abukhman  740:         logging.debug("documentViewer (getdocinfo) mode: %s, url: %s"%(mode,url))
1.3       casties   741:         # look for cached docinfo in session
1.21      dwinter   742:         if self.REQUEST.SESSION.has_key('docinfo'):
1.3       casties   743:             docinfo = self.REQUEST.SESSION['docinfo']
                    744:             # check if its still current
                    745:             if docinfo is not None and docinfo.get('mode') == mode and docinfo.get('url') == url:
1.175.2.3  casties   746:                 logging.debug("documentViewer (getdocinfo) docinfo in session. keys=%s"%docinfo.keys())
1.3       casties   747:                 return docinfo
1.175.2.3  casties   748:             
1.3       casties   749:         # new docinfo
                    750:         docinfo = {'mode': mode, 'url': url}
1.175.2.3  casties   751:         # add self url
                    752:         docinfo['viewerUrl'] = self.getDocumentViewerURL()
                    753:         if mode=="texttool": 
                    754:             # index.meta with texttool information
1.3       casties   755:             docinfo = self.getDocinfoFromTextTool(url, docinfo=docinfo)
                    756:         elif mode=="imagepath":
1.175.2.3  casties   757:             # folder with images, index.meta optional
1.3       casties   758:             docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo)
1.33      dwinter   759:         elif mode=="filepath":
1.175.2.3  casties   760:             # filename
1.37      dwinter   761:             docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo,cut=1)
1.3       casties   762:         else:
1.95      abukhman  763:             logging.error("documentViewer (getdocinfo) unknown mode: %s!"%mode)
1.44      casties   764:             raise ValueError("Unknown mode %s! Has to be one of 'texttool','imagepath','filepath'."%(mode))
1.159     casties   765:                 
1.175.2.5  casties   766:         logging.debug("documentViewer (getdocinfo) docinfo: keys=%s"%docinfo.keys())
                    767:         #logging.debug("documentViewer (getdocinfo) docinfo: %s"%docinfo)
1.175.2.7  casties   768:         # store in session
1.3       casties   769:         self.REQUEST.SESSION['docinfo'] = docinfo
                    770:         return docinfo
1.69      abukhman  771:                
1.158     casties   772:     def getPageinfo(self, current, start=None, rows=None, cols=None, docinfo=None, viewMode=None, tocMode=None):
1.3       casties   773:         """returns pageinfo with the given parameters"""
                    774:         pageinfo = {}
1.4       casties   775:         current = getInt(current)
1.132     abukhman  776:     
1.4       casties   777:         pageinfo['current'] = current
                    778:         rows = int(rows or self.thumbrows)
                    779:         pageinfo['rows'] = rows
                    780:         cols = int(cols or self.thumbcols)
                    781:         pageinfo['cols'] = cols
                    782:         grpsize = cols * rows
                    783:         pageinfo['groupsize'] = grpsize
1.175.2.7  casties   784:         # what does this do?
1.28      casties   785:         start = getInt(start, default=(math.ceil(float(current)/float(grpsize))*grpsize-(grpsize-1)))
                    786:         # int(current / grpsize) * grpsize +1))
1.3       casties   787:         pageinfo['start'] = start
1.4       casties   788:         pageinfo['end'] = start + grpsize
1.44      casties   789:         if (docinfo is not None) and ('numPages' in docinfo):
1.4       casties   790:             np = int(docinfo['numPages'])
                    791:             pageinfo['end'] = min(pageinfo['end'], np)
                    792:             pageinfo['numgroups'] = int(np / grpsize)
                    793:             if np % grpsize > 0:
1.175.2.7  casties   794:                 pageinfo['numgroups'] += 1
                    795:                 
1.44      casties   796:         pageinfo['viewMode'] = viewMode
                    797:         pageinfo['tocMode'] = tocMode
1.161     abukhman  798:         pageinfo['characterNormalization'] = self.REQUEST.get('characterNormalization','reg')
1.174     abukhman  799:         #pageinfo['optionToggle'] = self.REQUEST.get('optionToggle','1')
1.156     abukhman  800:         pageinfo['query'] = self.REQUEST.get('query','') 
1.146     abukhman  801:         pageinfo['queryType'] = self.REQUEST.get('queryType','')
1.45      abukhman  802:         pageinfo['querySearch'] =self.REQUEST.get('querySearch', 'fulltext')
1.48      abukhman  803:         pageinfo['textPN'] = self.REQUEST.get('textPN','1')
1.146     abukhman  804:         pageinfo['highlightQuery'] = self.REQUEST.get('highlightQuery','')
1.45      abukhman  805:         pageinfo['tocPageSize'] = self.REQUEST.get('tocPageSize', '30')
1.54      abukhman  806:         pageinfo['queryPageSize'] =self.REQUEST.get('queryPageSize', '10')
1.175.2.7  casties   807:         pageinfo['tocPN'] = self.REQUEST.get('tocPN', '1')
                    808:         # WTF?:
                    809:         toc = int(pageinfo['tocPN'])
                    810:         pageinfo['textPages'] =int(toc)
1.90      abukhman  811:         
1.175.2.7  casties   812:         # What does this do?
1.48      abukhman  813:         if 'tocSize_%s'%tocMode in docinfo:
                    814:             tocSize = int(docinfo['tocSize_%s'%tocMode])
                    815:             tocPageSize = int(pageinfo['tocPageSize'])
1.69      abukhman  816:             # cached toc           
1.48      abukhman  817:             if tocSize%tocPageSize>0:
                    818:                 tocPages=tocSize/tocPageSize+1
                    819:             else:
                    820:                 tocPages=tocSize/tocPageSize
1.175.2.7  casties   821:                 
                    822:             pageinfo['tocPN'] = min(tocPages,toc)
                    823:             
1.45      abukhman  824:         pageinfo['searchPN'] =self.REQUEST.get('searchPN','1')
1.59      abukhman  825:         pageinfo['sn'] =self.REQUEST.get('sn','')
1.3       casties   826:         return pageinfo
1.175.2.7  casties   827: 
1.175.2.10! casties   828: 
        !           829:     security.declareProtected('View management screens','changeDocumentViewerForm')    
        !           830:     changeDocumentViewerForm = PageTemplateFile('zpt/changeDocumentViewer', globals())
1.3       casties   831:     
1.175.2.7  casties   832:     def changeDocumentViewer(self,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=5,authgroups='mpiwg',RESPONSE=None):
1.3       casties   833:         """init document viewer"""
                    834:         self.title=title
                    835:         self.digilibBaseUrl = digilibBaseUrl
1.4       casties   836:         self.thumbrows = thumbrows
                    837:         self.thumbcols = thumbcols
1.8       casties   838:         self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
1.175.2.10! casties   839:         try:
        !           840:             # assume MetaDataFolder instance is called metadata 
        !           841:             self.metadataService = getattr(self, 'metadata')
        !           842:         except Exception, e:
        !           843:             logging.error("Unable to find MetaDataFolder 'metadata': "+str(e))
        !           844: 
1.3       casties   845:         if RESPONSE is not None:
                    846:             RESPONSE.redirect('manage_main')
1.1       dwinter   847:         
                    848: def manage_AddDocumentViewerForm(self):
                    849:     """add the viewer form"""
1.3       casties   850:     pt=PageTemplateFile('zpt/addDocumentViewer', globals()).__of__(self)
1.1       dwinter   851:     return pt()
                    852:   
1.43      casties   853: def manage_AddDocumentViewer(self,id,imageScalerUrl="",textServerName="",title="",RESPONSE=None):
1.1       dwinter   854:     """add the viewer"""
1.43      casties   855:     newObj=documentViewer(id,imageScalerUrl=imageScalerUrl,title=title,textServerName=textServerName)
1.1       dwinter   856:     self._setObject(id,newObj)
                    857:     
                    858:     if RESPONSE is not None:
                    859:         RESPONSE.redirect('manage_main')
1.3       casties   860: 
                    861: ## DocumentViewerTemplate class
                    862: class DocumentViewerTemplate(ZopePageTemplate):
                    863:     """Template for document viewer"""
                    864:     meta_type="DocumentViewer Template"
                    865: 
                    866: 
                    867: def manage_addDocumentViewerTemplateForm(self):
                    868:     """Form for adding"""
                    869:     pt=PageTemplateFile('zpt/addDocumentViewerTemplate', globals()).__of__(self)
                    870:     return pt()
                    871: 
                    872: def manage_addDocumentViewerTemplate(self, id='viewer_main', title=None, text=None,
                    873:                            REQUEST=None, submit=None):
                    874:     "Add a Page Template with optional file content."
                    875: 
                    876:     self._setObject(id, DocumentViewerTemplate(id))
                    877:     ob = getattr(self, id)
1.23      dwinter   878:     txt=file(os.path.join(package_home(globals()),'zpt/viewer_main.zpt'),'r').read()
1.95      abukhman  879:     logging.info("txt %s:"%txt)
1.23      dwinter   880:     ob.pt_edit(txt,"text/html")
1.3       casties   881:     if title:
                    882:         ob.pt_setTitle(title)
                    883:     try:
                    884:         u = self.DestinationURL()
                    885:     except AttributeError:
                    886:         u = REQUEST['URL1']
                    887:         
                    888:     u = "%s/%s" % (u, urllib.quote(id))
                    889:     REQUEST.RESPONSE.redirect(u+'/manage_main')
                    890:     return ''
                    891: 
                    892: 
1.14      casties   893:     

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