Diff for /documentViewer/MpdlXmlTextServer.py between versions 1.238 and 1.238.2.13

version 1.238, 2011/06/14 09:57:11 version 1.238.2.13, 2011/08/12 14:41:39
Line 1 Line 1
   
 from OFS.SimpleItem import SimpleItem  from OFS.SimpleItem import SimpleItem
 from Products.PageTemplates.PageTemplateFile import PageTemplateFile   from Products.PageTemplates.PageTemplateFile import PageTemplateFile 
   
 from Ft.Xml import EMPTY_NAMESPACE, Parse  from Ft.Xml import EMPTY_NAMESPACE, Parse
 from Ft.Xml.Domlette import NonvalidatingReader  from Ft.Xml.Domlette import NonvalidatingReader
   import Ft.Xml.Domlette
   import cStringIO
   
   import xml.etree.ElementTree as ET
   
 import md5  import re
 import sys  
 import logging  import logging
 import urllib  import urllib
 import documentViewer  
 from documentViewer import getTextFromNode, serializeNode  from SrvTxtUtils import getInt, getText, getHttpData
   
   def serialize(node):
       """returns a string containing an XML snippet of node"""
       s = ET.tostring(node, 'UTF-8')
       # snip off XML declaration
       if s.startswith('<?xml'):
           i = s.find('?>')
           return s[i+3:]
   
       return s
   
   
   def getTextFromNode(node):
       """get the cdata content of a node"""
       if node is None:
           return ""
   
       # 4Suite:
       nodelist=node.childNodes
       text = ""
       for n in nodelist:
           if n.nodeType == node.TEXT_NODE:
              text = text + n.data
       
       return text
   
   def serializeNode(node, encoding="utf-8"):
       """returns a string containing node as XML"""
       #s = ET.tostring(node)
       
       # 4Suite:
       stream = cStringIO.StringIO()
       Ft.Xml.Domlette.Print(node, stream=stream, encoding=encoding)
       s = stream.getvalue()
       stream.close()
   
       return s
   
   
 class MpdlXmlTextServer(SimpleItem):  class MpdlXmlTextServer(SimpleItem):
     """TextServer implementation for MPDL-XML eXist server"""      """TextServer implementation for MPDL-XML eXist server"""
Line 21  class MpdlXmlTextServer(SimpleItem): Line 62  class MpdlXmlTextServer(SimpleItem):
           
     manage_changeMpdlXmlTextServerForm = PageTemplateFile("zpt/manage_changeMpdlXmlTextServer", globals())      manage_changeMpdlXmlTextServerForm = PageTemplateFile("zpt/manage_changeMpdlXmlTextServer", globals())
                   
     def __init__(self,id,title="",serverUrl="http://mpdl-system.mpiwg-berlin.mpg.de/mpdl/interface/", serverName=None, timeout=40):      def __init__(self,id,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpdl/interface/", serverName=None, timeout=40):
     #def __init__(self,id,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de:30030/mpdl/interface/", serverName=None, timeout=40):      
           
         """constructor"""          """constructor"""
         self.id=id          self.id=id
         self.title=title          self.title=title
Line 35  class MpdlXmlTextServer(SimpleItem): Line 74  class MpdlXmlTextServer(SimpleItem):
                   
     def getHttpData(self, url, data=None):      def getHttpData(self, url, data=None):
         """returns result from url+data HTTP request"""          """returns result from url+data HTTP request"""
         return documentViewer.getHttpData(url,data,timeout=self.timeout)          return getHttpData(url,data,timeout=self.timeout)
           
     def getServerData(self, method, data=None):      def getServerData(self, method, data=None):
         """returns result from text server for method+data"""          """returns result from text server for method+data"""
         url = self.serverUrl+method          url = self.serverUrl+method
         return documentViewer.getHttpData(url,data,timeout=self.timeout)          return getHttpData(url,data,timeout=self.timeout)
   
       # WTF: what does this really do? can it be integrated in getPage?
     def getSearch(self, pageinfo=None,  docinfo=None):      def getSearch(self, pageinfo=None,  docinfo=None):
         """get search list"""          """get search list"""
           logging.debug("getSearch()")
         docpath = docinfo['textURLPath']           docpath = docinfo['textURLPath'] 
         url = docinfo['url']          url = docinfo['url']
         pagesize = pageinfo['queryPageSize']          pagesize = pageinfo['queryPageSize']
         pn = pageinfo.get('searchPN',1)          pn = pageinfo.get('searchPN',1)
         sn = pageinfo['sn']          sn = pageinfo.get('sn',None) #TODO: is this s now?
         highlightQuery = pageinfo['highlightQuery']          highlightQuery = pageinfo['highlightQuery']
         query =pageinfo['query']          query =pageinfo['query']
         queryType =pageinfo['queryType']          queryType =pageinfo['queryType']
Line 140  class MpdlXmlTextServer(SimpleItem): Line 181  class MpdlXmlTextServer(SimpleItem):
         if not docpath:          if not docpath:
             return None              return None
   
         url = docinfo['url']  
         selfurl = self.absolute_url()  
         pn = pageinfo['current']          pn = pageinfo['current']
         hrefList=[]          hrefList=[]
         myList= ""          myList= ""
         text=self.getServerData("xpath.xql", "document=%s&xpath=%s&pn=%s"%(docinfo['textURLPath'],xpath,pn))          text=self.getServerData("xpath.xql", "document=%s&xpath=%s&pn=%s"%(docinfo['textURLPath'],xpath,pn))
         dom = Parse(text)          dom = ET.fromstring(text)
         result = dom.xpath("//result/resultPage/place")          result = dom.findall(".//result/resultPage/place")
         for l in result:          for l in result:
             hrefNode= l.getAttributeNodeNS(None, u"id")              href = l.get("id")
             href= hrefNode.nodeValue  
             hrefList.append(href)              hrefList.append(href)
               # WTF: what does this do?
             myList = ",".join(hrefList)              myList = ",".join(hrefList)
         #logging.debug("getGisPlaces :%s"%(myList))                                       #logging.debug("getGisPlaces :%s"%(myList))                             
         return myList          return myList
Line 159  class MpdlXmlTextServer(SimpleItem): Line 198  class MpdlXmlTextServer(SimpleItem):
     def getAllGisPlaces (self, docinfo=None, pageinfo=None):      def getAllGisPlaces (self, docinfo=None, pageinfo=None):
         """Show all Gis Places of whole Book """          """Show all Gis Places of whole Book """
         xpath ='//echo:place'          xpath ='//echo:place'
         docpath =docinfo['textURLPath']  
         url = docinfo['url']  
         selfurl =self.absolute_url()  
         pn =pageinfo['current']  
         hrefList=[]          hrefList=[]
         myList=""          myList=""
         text=self.getServerData("xpath.xql", "document=%s&xpath=%s"%(docinfo['textURLPath'],xpath))          text=self.getServerData("xpath.xql", "document=%s&xpath=%s"%(docinfo['textURLPath'],xpath))
         dom =Parse(text)          dom = ET.fromstring(text)
         result = dom.xpath("//result/resultPage/place")          result = dom.findall(".//result/resultPage/place")
                   
         for l in result:          for l in result:
             hrefNode = l.getAttributeNodeNS(None, u"id")              href = l.get("id")
             href= hrefNode.nodeValue  
             hrefList.append(href)              hrefList.append(href)
               # WTF: what does this do?
             myList = ",".join(hrefList)              myList = ",".join(hrefList)
             #logging.debug("getALLGisPlaces :%s"%(myList))              #logging.debug("getALLGisPlaces :%s"%(myList))
         return myList          return myList
                       
       def processPageInfo(self, dom, docinfo, pageinfo):
           """processes page info divs from dom and stores in docinfo and pageinfo"""
           # assume first second level div is pageMeta
           alldivs = dom.find("div")
           
           if alldivs is None or alldivs.get('class', '') != 'pageMeta':
               logging.error("processPageInfo: pageMeta div not found!")
               return
           
           for div in alldivs:
               dc = div.get('class')
               
               # pageNumberOrig  
               if dc == 'pageNumberOrig':
                   pageinfo['pageNumberOrig'] = div.text
                   
               # pageNumberOrigNorm
               elif dc == 'pageNumberOrigNorm':
                   pageinfo['pageNumberOrigNorm'] = div.text
                   
               # pageHeaderTitle
               elif dc == 'pageHeaderTitle':
                   pageinfo['pageHeaderTitle'] = div.text
                   
               # numFigureEntries
               elif dc == 'countFigureEntries':
                   docinfo['numFigureEntries'] = getInt(div.text)
                   
               # numTocEntries
               elif dc == 'countTocEntries':
                   # WTF: s1 = int(s)/30+1
                   docinfo['numTocEntries'] = getInt(div.text)
                   
               # numPlaces
               elif dc == 'countPlaces':
                   docinfo['numPlaces'] = getInt(div.text)
                         
     def getTextPage(self, mode="text_dict", pn=1, docinfo=None, pageinfo=None):              # numTextPages
         """returns single page from fulltext"""              elif dc == 'countPages':
         docpath = docinfo['textURLPath']                  np = getInt(div.text)                    
         path = docinfo['textURLPath']                  if np > 0:
         url = docinfo.get('url',None)                      docinfo['numTextPages'] = np
         name = docinfo.get('name',None)                      if docinfo.get('numPages', 0) == 0:
         pn =pageinfo['current']                          # seems to be text-only - update page count
         sn = pageinfo['sn']                          docinfo['numPages'] = np
         #optionToggle =pageinfo ['optionToggle']                          #pageinfo['end'] = min(pageinfo['end'], np)
         highlightQuery = pageinfo['highlightQuery']                          pageinfo['numgroups'] = int(np / pageinfo['groupsize'])
         #mode = pageinfo ['viewMode']                          if np % pageinfo['groupsize'] > 0:
         tocMode = pageinfo['tocMode']                              pageinfo['numgroups'] += 1
         characterNormalization=pageinfo['characterNormalization']  
         tocPN = pageinfo['tocPN']  
         selfurl = self.absolute_url()     
         if mode == "text_dict":  
             textmode = "textPollux"  
         else:  
             textmode = mode  
                   
         textParam = "document=%s&mode=%s&pn=%s&characterNormalization=%s"%(docpath,textmode,pn,characterNormalization)          #logging.debug("processPageInfo: pageinfo=%s"%repr(pageinfo))
         if highlightQuery is not None:          return
             textParam +="&highlightQuery=%s&sn=%s"%(urllib.quote(highlightQuery),sn)             
                   
         pagexml = self.getServerData("page-fragment.xql",textParam)  
         dom = Parse(pagexml)  
         #dom = NonvalidatingReader.parseStream(pagexml)  
                   
         #original Pages      def getTextPage(self, mode="text", pn=1, docinfo=None, pageinfo=None):
         pagedivs = dom.xpath("//div[@class='pageNumberOrig']")                 """returns single page from fulltext"""
           logging.debug("getTextPage mode=%s, pn=%s"%(mode,pn))
           # check for cached text -- but ideally this shouldn't be called twice
           if pageinfo.has_key('textPage'):
               logging.debug("getTextPage: using cached text")
               return pageinfo['textPage']
                   
         """if pagedivs == dom.xpath("//div[@class='pageNumberOrig']"):          docpath = docinfo['textURLPath']
             if len(pagedivs)>0:          # just checking
                 docinfo['pageNumberOrig']= getTextFromNode(pagedivs[0])          if pageinfo['current'] != pn:
                 logging.debug("ORIGINAL PAGE: %s"%(docinfo['pageNumberOrig']))              logging.warning("getTextPage: current!=pn!")
                   
         #original Pages Norm          # stuff for constructing full urls
         pagedivs = dom.xpath("//div[@class='pageNumberOrigNorm']")          url = docinfo['url']
         if pagedivs == dom.xpath("//div[@class='pageNumberOrigNorm']"):          urlmode = docinfo['mode']
             if len(pagedivs)>0:          sn = pageinfo.get('sn', None)
                 docinfo['pageNumberOrigNorm']= getTextFromNode(pagedivs[0])          highlightQuery = pageinfo.get('highlightQuery', None)
                 logging.debug("ORIGINAL PAGE NORM: %s"%(docinfo['pageNumberOrigNorm']))          tocMode = pageinfo.get('tocMode', None)
         """          tocPN = pageinfo.get('tocPN',None)
         #figureEntries          characterNormalization = pageinfo.get('characterNormalization', None)
         pagedivs = dom.xpath("//div[@class='countFigureEntries']")  
         if pagedivs == dom.xpath("//div[@class='countFigureEntries']"):  
             if len(pagedivs)>0:  
                 docinfo['countFigureEntries'] = getTextFromNode(pagedivs[0])  
                 s = getTextFromNode(pagedivs[0])  
                 if s=='0':  
                     try:  
                         docinfo['countFigureEntries'] = int(s)  
                     except:  
                         docinfo['countFigureEntries'] = 0  
                 else:  
                     s1 = int(s)/30+1  
                     try:  
                         docinfo['countFigureEntries'] = int(s1)  
                     except:  
                         docinfo['countFigureEntries'] = 0        
                   
         #allPlaces          selfurl = docinfo['viewerUrl']
         pagedivs = dom.xpath("//div[@class='countPlaces']")  
         if pagedivs == dom.xpath("//div[@class='countPlaces']"):  
             if len(pagedivs)>0:  
                 docinfo['countPlaces']= getTextFromNode(pagedivs[0])  
                 s = getTextFromNode(pagedivs[0])  
                 try:  
                     docinfo['countPlaces'] = int(s)  
                 except:  
                     docinfo['countPlaces'] = 0  
                   
         #tocEntries          if mode == "dict" or mode == "text_dict":
         pagedivs = dom.xpath("//div[@class='countTocEntries']")              # dict is called textPollux in the backend
         if pagedivs == dom.xpath("//div[@class='countTocEntries']"):              textmode = "textPollux"
             if len(pagedivs)>0:          elif not mode:
                 docinfo['countTocEntries'] = int(getTextFromNode(pagedivs[0]))              # default is text
                 s = getTextFromNode(pagedivs[0])              mode = "text"
                 if s=='0':              textmode = "text"
                     try:  
                         docinfo['countTocEntries'] = int(s)  
                     except:  
                         docinfo['countTocEntries'] = 0  
                 else:                  else:
                     s1 = int(s)/30+1              textmode = mode
                     try:  
                         docinfo['countTocEntries'] = int(s1)  
                     except:  
                         docinfo['countTocEntries'] = 0  
           
         #numTextPages  
         pagedivs = dom.xpath("//div[@class='countPages']")  
         if pagedivs == dom.xpath("//div[@class='countPages']"):  
             if len(pagedivs)>0:  
                 docinfo['numPages'] = getTextFromNode(pagedivs[0])  
                 s = getTextFromNode(pagedivs[0])  
                   
                 try:  
                     docinfo['numPages'] = int(s)  
                     #logging.debug("PAGE NUMBER: %s"%(s))  
                                   
                     np = docinfo['numPages']          textParam = "document=%s&mode=%s&pn=%s&characterNormalization=%s"%(docpath,textmode,pn,characterNormalization)
                     pageinfo['end'] = min(pageinfo['end'], np)          if highlightQuery:
                     pageinfo['numgroups'] = int(np / pageinfo['groupsize'])              textParam +="&highlightQuery=%s&sn=%s"%(urllib.quote(highlightQuery),sn)           
                     if np % pageinfo['groupsize'] > 0:  
                         pageinfo['numgroups'] += 1                  
                 except:  
                     docinfo['numPages'] = 0  
                                       
         else:          # fetch the page
          #no full text -- init to 0          pagexml = self.getServerData("page-fragment.xql",textParam)
             docinfo['pageNumberOrig'] = 0          dom = ET.fromstring(pagexml)
             docinfo['countFigureEntries'] = 0          # extract additional info
             docinfo['countPlaces'] = 0          self.processPageInfo(dom, docinfo, pageinfo)
             docinfo['countTocEntries'] = 0          # page content is in <div class="pageContent">
             docinfo['numPages'] = 0          pagediv = None
             docinfo['pageNumberOrigNorm'] = 0          # ElementTree 1.2 in Python 2.6 can't do div[@class='pageContent']
         #return docinfo          # so we look at the second level divs
           alldivs = dom.findall("div")
           for div in alldivs:
               dc = div.get('class')
               # page content div
               if dc == 'pageContent':
                   pagediv = div
                   break
                   
         # plain text mode          # plain text mode
         if mode == "text":          if mode == "text":
             # first div contains text              # get full url assuming documentViewer is parent
             pagedivs = dom.xpath("/div")              selfurl = self.getLink()
             if len(pagedivs) > 0:                    if pagediv is not None:
                 pagenode = pagedivs[0]                  links = pagediv.findall(".//a")
                 links = pagenode.xpath("//a")  
                 for l in links:                  for l in links:
                     hrefNode = l.getAttributeNodeNS(None, u"href")                      href = l.get('href')
                     if hrefNode:                      if href and href.startswith('#note-'):
                         href= hrefNode.nodeValue                          href = href.replace('#note-',"%s#note-"%selfurl)
                         if href.startswith('#note-'):                          l.set('href', href)
                             hrefNode.nodeValue = href.replace('#note-',"?url=%s&viewMode=text&tocMode=%s&tocPN=%s&pn=%s#note-"%(url,tocMode,tocPN,pn))  
                 return serializeNode(pagenode)                  return serialize(pagediv)
         if mode == "xml":  
               # first div contains text  
               pagedivs = dom.xpath("/div")  
               if len(pagedivs) > 0:  
                   pagenode = pagedivs[0]  
                   return serializeNode(pagenode)  
         if mode == "gis":  
               # first div contains text  
               pagedivs = dom.xpath("/div")  
               if len(pagedivs) > 0:  
                   pagenode = pagedivs[0]  
                   links =pagenode.xpath("//a")  
                   for l in links:  
                       hrefNode =l.getAttributeNodeNS(None, u"href")  
                       if hrefNode:  
                           href=hrefNode.nodeValue  
                           if href.startswith('http://chinagis.mpiwg-berlin.mpg.de'):  
                               hrefNode.nodeValue =href.replace('chinagis_REST/REST/db/chgis/mpdl','chinagis/REST/db/mpdl/%s'%name)  
                               l.setAttributeNS(None, 'target', '_blank')   
                   return serializeNode(pagenode)  
                                           
         if mode == "pureXml":  
               # first div contains text  
               pagedivs = dom.xpath("/div")  
               if len(pagedivs) > 0:  
                   pagenode = pagedivs[0]  
                   return serializeNode(pagenode)        
         # text-with-links mode          # text-with-links mode
         if mode == "text_dict":          elif mode == "dict":
             # first div contains text              if pagediv is not None:
             #mode = pageinfo ['viewMode']                  viewerurl = docinfo['viewerUrl']
             pagedivs = dom.xpath("/div")                  selfurl = self.getLink()
             if len(pagedivs) > 0:  
                 pagenode = pagedivs[0]  
                 # check all a-tags                  # check all a-tags
                 links = pagenode.xpath("//a")                  links = pagediv.findall(".//a")
                   
                 for l in links:                  for l in links:
                     hrefNode = l.getAttributeNodeNS(None, u"href")                      href = l.get('href')
                                           
                     if hrefNode:                      if href:
                         # is link with href                          # is link with href
                         href = hrefNode.nodeValue  
                         if href.startswith('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/lt/wordInfo.xql'):                          if href.startswith('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/lt/wordInfo.xql'):
                             # is pollux link                              # is dictionary link - change href (keeping parameters)
                             selfurl = self.absolute_url()                              l.set('href', href.replace('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/lt/wordInfo.xql','%s/template/viewer_wordinfo'%viewerurl))
                             # change href                              # add target to open new page
                             hrefNode.nodeValue = href.replace('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/interface/lt/wordInfo.xql','%s/head_main_voc'%selfurl)                              l.set('target', '_blank')
                             # add target  
                             l.setAttributeNS(None, 'target', '_blank')  
                             #l.setAttributeNS(None, 'onclick',"popupWin = window.open(this.href, 'InfoWindow', 'menubar=no, location,width=500,height=600,top=180, left=700, toolbar=no, scrollbars=1'); return false;")  
                             #l.setAttributeNS(None, "ondblclick", "popupWin.focus();")  
                             #window.open("this.href, 'InfoWindow', 'menubar=no, location,width=500,height=600,top=180, left=700, toolbar=yes, scrollbars=1'"); return false;")   
                                                                                                                       
                           # TODO: is this needed?
                         if href.startswith('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/lt/lemma.xql'):                              if href.startswith('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/lt/lemma.xql'):    
                             selfurl = self.absolute_url()                              selfurl = self.absolute_url()
                             hrefNode.nodeValue = href.replace('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/lt/lemma.xql','%s/head_main_lemma'%selfurl)                              l.set('href', href.replace('http://mpdl-proto.mpiwg-berlin.mpg.de/mpdl/lt/lemma.xql','%s/head_main_lemma'%selfurl))
                             l.setAttributeNS(None, 'target', '_blank')                              l.set('target', '_blank')
                             l.setAttributeNS(None, 'onclick',"popupWin = window.open(this.href, 'InfoWindow', 'menubar=no, location,width=500,height=600,top=180, left=700, toolbar=no, scrollbars=1'); return false;")                              l.set('onclick',"popupWin = window.open(this.href, 'InfoWindow', 'menubar=no, location,width=500,height=600,top=180, left=700, toolbar=no, scrollbars=1'); return false;")
                             l.setAttributeNS(None, 'ondblclick', 'popupWin.focus();')                                 l.set('ondblclick', 'popupWin.focus();')   
                                           
                         if href.startswith('#note-'):                          if href.startswith('#note-'):
                             hrefNode.nodeValue = href.replace('#note-',"?url=%s&viewMode=text_dict&tocMode=%s&tocPN=%s&pn=%s#note-"%(url,tocMode,tocPN,pn))                                # note link
                               l.set('href', href.replace('#note-',"%s#note-"%selfurl))
                                                               
                 return serializeNode(pagenode)                  return serialize(pagediv)
         return "no text here"  
           
     def getOrigPages(self, docinfo=None, pageinfo=None):          # xml mode
         docpath = docinfo['textURLPath']          elif mode == "xml":
         pn =pageinfo['current']              if pagediv is not None:
         selfurl = self.absolute_url()                     return serialize(pagediv)
         pagexml = self.getServerData("page-fragment.xql","document=%s&pn=%s"%(docpath, pn))              
         dom = Parse(pagexml)          # pureXml mode
         pagedivs = dom.xpath("//div[@class='pageNumberOrig']")          elif mode == "pureXml":
         if pagedivs == dom.xpath("//div[@class='pageNumberOrig']"):              if pagediv is not None:
             if len(pagedivs)>0:                  return serialize(pagediv)
                 docinfo['pageNumberOrig']= getTextFromNode(pagedivs[0])                            
                 return docinfo['pageNumberOrig']          # gis mode
           elif mode == "gis":
               name = docinfo['name']
               if pagediv is not None:
                   # check all a-tags
                   links = pagediv.findall(".//a")
                   for l in links:
                       href = l.get('href')
                       if href:
                           if href.startswith('http://chinagis.mpiwg-berlin.mpg.de'):
                               l.set('href', href.replace('chinagis_REST/REST/db/chgis/mpdl','chinagis/REST/db/mpdl/%s'%name))
                               l.set('target', '_blank') 
           
     def getOrigPagesNorm(self, docinfo=None, pageinfo=None):                  return serialize(pagediv)
         docpath = docinfo['textURLPath']  
         pn =pageinfo['current']  
         selfurl = self.absolute_url()     
         pagexml = self.getServerData("page-fragment.xql","document=%s&pn=%s"%(docpath, pn))  
         dom = Parse(pagexml)  
         pagedivs = dom.xpath("//div[@class='pageNumberOrigNorm']")  
         if pagedivs == dom.xpath("//div[@class='pageNumberOrigNorm']"):  
             if len(pagedivs)>0:  
                 docinfo['pageNumberOrigNorm']= getTextFromNode(pagedivs[0])          
                 return docinfo['pageNumberOrigNorm']  
   
           return "no text here"
                                   
     def getTranslate(self, word=None, language=None):      # TODO: should be getWordInfo
         """translate into another languages"""      def getWordInfo(self, word='', language='', display=''):
         data = self.getServerData("lt/wordInfo.xql","language="+str(language)+"&word="+urllib.quote(word)+"&output=html")          """show information (like dictionaries) about word"""
         #pagexml=self.template.fulltextclient.eval("/mpdl/interface/lt/lex.xql","document=&language="+str(language)+"&query="+url_quote(str(query)))          data = self.getServerData("lt/wordInfo.xql","language=%s&word=%s&display=%s&output=html"%(language,urllib.quote(word),urllib.quote(display)))
         return data          return data
           
       # WTF: what does this do?
     def getLemma(self, lemma=None, language=None):      def getLemma(self, lemma=None, language=None):
         """simular words lemma """          """simular words lemma """
         data = self.getServerData("lt/lemma.xql","language="+str(language)+"&lemma="+urllib.quote(lemma)+"&output=html")          data = self.getServerData("lt/lemma.xql","language="+str(language)+"&lemma="+urllib.quote(lemma)+"&output=html")
         return data          return data
           
       # WTF: what does this do?
     def getLemmaQuery(self, query=None, language=None):      def getLemmaQuery(self, query=None, language=None):
         """simular words lemma """          """simular words lemma """
         data = self.getServerData("lt/lemma.xql","language="+str(language)+"&query="+urllib.quote(query)+"&output=html")          data = self.getServerData("lt/lemma.xql","language="+str(language)+"&query="+urllib.quote(query)+"&output=html")
         return data          return data
           
       # WTF: what does this do?
     def getLex(self, query=None, language=None):      def getLex(self, query=None, language=None):
         #simular words lemma          #simular words lemma
         data = self.getServerData("lt/lex.xql","document=&language="+str(language)+"&query="+urllib.quote(query))          data = self.getServerData("lt/lex.xql","document=&language="+str(language)+"&query="+urllib.quote(query))
         return data          return data
           
       # WTF: what does this do?
     def getQuery (self,  docinfo=None, pageinfo=None, query=None, queryType=None, pn=1):      def getQuery (self,  docinfo=None, pageinfo=None, query=None, queryType=None, pn=1):
          #number of           #number of
          docpath = docinfo['textURLPath']            docpath = docinfo['textURLPath'] 
Line 442  class MpdlXmlTextServer(SimpleItem): Line 437  class MpdlXmlTextServer(SimpleItem):
          return tc           return tc
           
     def getToc(self, mode="text", docinfo=None):      def getToc(self, mode="text", docinfo=None):
         """loads table of contents and stores in docinfo"""          """loads table of contents and stores XML in docinfo"""
           logging.debug("getToc mode=%s"%mode)
         if mode == "none":          if mode == "none":
             return docinfo                      return docinfo        
                 
         if 'tocSize_%s'%mode in docinfo:          if 'tocSize_%s'%mode in docinfo:
             # cached toc              # cached toc
             return docinfo              return docinfo
Line 460  class MpdlXmlTextServer(SimpleItem): Line 457  class MpdlXmlTextServer(SimpleItem):
         # number of entries in toc          # number of entries in toc
         tocSize = 0          tocSize = 0
         tocDiv = None          tocDiv = None
                   # fetch full toc
         pagexml = self.getServerData("doc-query.xql","document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath,queryType, pagesize, pn))          pagexml = self.getServerData("doc-query.xql","document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s"%(docpath,queryType, pagesize, pn))
           dom = ET.fromstring(pagexml)
           # page content is in <div class="queryResultPage">
           pagediv = None
           # ElementTree 1.2 in Python 2.6 can't do div[@class='queryResultPage']
           alldivs = dom.findall("div")
           for div in alldivs:
               dc = div.get('class')
               # page content div
               if dc == 'queryResultPage':
                   pagediv = div
                   
               elif dc == 'queryResultHits':
                   docinfo['tocSize_%s'%mode] = getInt(div.text)
   
           if pagediv:
               # store XML in docinfo
               docinfo['tocXML_%s'%mode] = ET.tostring(pagediv, 'UTF-8')
                   
         # post-processing downloaded xml  
         pagedom = Parse(pagexml)  
         # get number of entries  
         numdivs = pagedom.xpath("//div[@class='queryResultHits']")  
         if len(numdivs) > 0:  
             tocSize = int(getTextFromNode(numdivs[0]))  
         docinfo['tocSize_%s'%mode] = tocSize  
         return docinfo          return docinfo
           
     def getTocPage(self, mode="text", pn=1, pageinfo=None, docinfo=None):      def getTocPage(self, mode="text", pn=0, pageinfo=None, docinfo=None):
         """returns single page from the table of contents"""          """returns single page from the table of contents"""
         # TODO: this should use the cached TOC          logging.debug("getTocPage mode=%s, pn=%s"%(mode,pn))
         if mode == "text":          if mode == "text":
             queryType = "toc"              queryType = "toc"
         else:          else:
             queryType = mode              queryType = mode
         docpath = docinfo['textURLPath']              
         path = docinfo['textURLPath']                 # check for cached TOC
           if not docinfo.has_key('tocXML_%s'%mode):
               self.getToc(mode=mode, docinfo=docinfo)
               
           tocxml = docinfo.get('tocXML_%s'%mode, None)
           if not tocxml:
               logging.error("getTocPage: unable to find tocXML")
               return "No ToC"
           
         pagesize = pageinfo['tocPageSize']          pagesize = pageinfo['tocPageSize']
         pn = pageinfo['tocPN']  
         url = docinfo['url']  
         selfurl = self.absolute_url()    
         viewMode=  pageinfo['viewMode']  
         characterNormalization = pageinfo ['characterNormalization']  
         #optionToggle =pageinfo ['optionToggle']  
         tocMode = pageinfo['tocMode']  
         tocPN = pageinfo['tocPN']            tocPN = pageinfo['tocPN']  
           if not pn:
               pn = tocPN
   
           fulltoc = ET.fromstring(tocxml)
           
           if fulltoc:
               # paginate
               start = (pn - 1) * pagesize * 2
               len = pagesize * 2
               del fulltoc[:start]
               del fulltoc[len:]
               tocdivs = fulltoc
               
               # check all a-tags
               links = tocdivs.findall(".//a")
               for l in links:
                   href = l.get('href')
                   if href:
                       # take pn from href
                       m = re.match(r'page-fragment\.xql.*pn=(\d+)', href)
                       if m is not None:
                           # and create new url (assuming parent is documentViewer)
                           url = self.getLink('pn', m.group(1))
                           l.set('href', url)
                       else:
                           logging.warning("getTocPage: Problem with link=%s"%href)
                           
               return serialize(tocdivs)
                   
         data = self.getServerData("doc-query.xql","document=%s&queryType=%s&queryResultPageSize=%s&queryResultPN=%s&characterNormalization=regPlusNorm"%(docpath,queryType, pagesize, pn))    
         page = data.replace('page-fragment.xql?document=%s'%str(path),'%s?url=%s&viewMode=%s&tocMode=%s&tocPN=%s'%(selfurl,url, viewMode, tocMode, tocPN))  
         text = page.replace('mode=image','mode=texttool')  
         return text  
           
     def manage_changeMpdlXmlTextServer(self,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):      def manage_changeMpdlXmlTextServer(self,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de/mpdl/interface/",timeout=40,RESPONSE=None):
     #def manage_changeMpdlXmlTextServer(self,title="",serverUrl="http://mpdl-text.mpiwg-berlin.mpg.de:30030/mpdl/interface/",timeout=40,RESPONSE=None):  
         """change settings"""          """change settings"""
         self.title=title          self.title=title
         self.timeout = timeout          self.timeout = timeout
Line 518  def manage_addMpdlXmlTextServer(self,id, Line 549  def manage_addMpdlXmlTextServer(self,id,
     self.Destination()._setObject(id, newObj)      self.Destination()._setObject(id, newObj)
     if RESPONSE is not None:      if RESPONSE is not None:
         RESPONSE.redirect('manage_main')          RESPONSE.redirect('manage_main')
   
           
           
   

Removed from v.1.238  
changed lines
  Added in v.1.238.2.13


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