File:  [Repository] / documentViewer / documentViewer.py
Revision 1.27: download - view: text, annotated - select for diffs - revision graph
Fri Jun 8 18:10:22 2007 UTC (17 years ago) by casties
Branches: MAIN
CVS tags: HEAD
added all fields from bib tag to docinfo

    1: 
    2: 
    3: from OFS.Folder import Folder
    4: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
    5: from Products.PageTemplates.PageTemplateFile import PageTemplateFile 
    6: from AccessControl import ClassSecurityInfo
    7: from AccessControl import getSecurityManager
    8: from Globals import package_home
    9: 
   10: from Ft.Xml.Domlette import NonvalidatingReader
   11: from Ft.Xml.Domlette import PrettyPrint, Print
   12: from Ft.Xml import EMPTY_NAMESPACE, Parse
   13: 
   14: import Ft.Xml.XPath
   15: 
   16: import os.path
   17: import sys
   18: import cgi
   19: import urllib
   20: import logging
   21: 
   22: import urlparse 
   23: 
   24: def logger(txt,method,txt2):
   25:     """logging"""
   26:     logging.info(txt+ txt2)
   27:     
   28:     
   29: def getInt(number, default=0):
   30:     """returns always an int (0 in case of problems)"""
   31:     try:
   32:         return int(number)
   33:     except:
   34:         return default
   35: 
   36: def getTextFromNode(nodename):
   37:     """get the cdata content of a node"""
   38:     if nodename is None:
   39:         return ""
   40:     nodelist=nodename.childNodes
   41:     rc = ""
   42:     for node in nodelist:
   43:         if node.nodeType == node.TEXT_NODE:
   44:            rc = rc + node.data
   45:     return rc
   46: 
   47:         
   48: def getParentDir(path):
   49:     """returns pathname shortened by one"""
   50:     return '/'.join(path.split('/')[0:-1])
   51:         
   52: 
   53: import socket
   54: 
   55: def urlopen(url,timeout=2):
   56:         """urlopen mit timeout"""
   57:         socket.setdefaulttimeout(timeout)
   58:         ret=urllib.urlopen(url)
   59:         socket.setdefaulttimeout(5)
   60:         return ret
   61: 
   62: 
   63: ##
   64: ## documentViewer class
   65: ##
   66: class documentViewer(Folder):
   67:     """document viewer"""
   68:     #textViewerUrl="http://127.0.0.1:8080/HFQP/testXSLT/getPage?"
   69:     
   70:     meta_type="Document viewer"
   71:     
   72:     security=ClassSecurityInfo()
   73:     manage_options=Folder.manage_options+(
   74:         {'label':'main config','action':'changeDocumentViewerForm'},
   75:         )
   76: 
   77:     # templates and forms
   78:     viewer_main = PageTemplateFile('zpt/viewer_main', globals())
   79:     thumbs_main = PageTemplateFile('zpt/thumbs_main', globals())
   80:     image_main = PageTemplateFile('zpt/image_main', globals())
   81:     head_main = PageTemplateFile('zpt/head_main', globals())
   82:     docuviewer_css = PageTemplateFile('css/docuviewer.css', globals())
   83:     info_xml = PageTemplateFile('zpt/info_xml', globals())
   84: 
   85:     security.declareProtected('View management screens','changeDocumentViewerForm')    
   86:     changeDocumentViewerForm = PageTemplateFile('zpt/changeDocumentViewer', globals())
   87: 
   88:     
   89:     def __init__(self,id,imageViewerUrl,textViewerUrl=None,title="",digilibBaseUrl=None,thumbcols=2,thumbrows=10,authgroups="mpiwg"):
   90:         """init document viewer"""
   91:         self.id=id
   92:         self.title=title
   93:         self.imageViewerUrl=imageViewerUrl
   94:         self.textViewerUrl=textViewerUrl
   95:         
   96:         if not digilibBaseUrl:
   97:             self.digilibBaseUrl = self.findDigilibUrl()
   98:         else:
   99:             self.digilibBaseUrl = digilibBaseUrl
  100:         self.thumbcols = thumbcols
  101:         self.thumbrows = thumbrows
  102:         # authgroups is list of authorized groups (delimited by ,)
  103:         self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
  104:         # add template folder so we can always use template.something
  105:         self.manage_addFolder('template')
  106: 
  107: 
  108:     security.declareProtected('View','index_html')
  109:     def index_html(self,mode,url,viewMode="auto",start=None,pn=1):
  110:         '''
  111:         view it
  112:         @param mode: defines how to access the document behind url 
  113:         @param url: url which contains display information
  114:         @param viewMode: if images display images, if text display text, default is images (text,images or auto)
  115:         
  116:         '''
  117:         
  118:         logger("documentViewer (index)", logging.INFO, "mode: %s url:%s start:%s pn:%s"%(mode,url,start,pn))
  119:         
  120:         if not hasattr(self, 'template'):
  121:             # create template folder if it doesn't exist
  122:             self.manage_addFolder('template')
  123:             
  124:         if not self.digilibBaseUrl:
  125:             self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
  126:             
  127:         docinfo = self.getDocinfo(mode=mode,url=url)
  128:         pageinfo = self.getPageinfo(start=start,current=pn,docinfo=docinfo)
  129:         pt = getattr(self.template, 'viewer_main')
  130:         
  131:         if viewMode=="auto": # automodus gewaehlt
  132:             if docinfo.get("textURL",'') and self.textViewerUrl: #texturl gesetzt und textViewer konfiguriert
  133:                 viewMode="text"
  134:             else:
  135:                 viewMode="images"
  136:                
  137:         return pt(docinfo=docinfo,pageinfo=pageinfo,viewMode=viewMode)
  138:   
  139:   
  140:     def getLink(self,param=None,val=None):
  141:         """link to documentviewer with parameter param set to val"""
  142:         params=self.REQUEST.form.copy()
  143:         if param is not None:
  144:             if val is None:
  145:                 if params.has_key(param):
  146:                     del params[param]
  147:             else:
  148:                 params[param] = str(val)
  149:                 
  150:         # quote values and assemble into query string
  151:         ps = "&".join(["%s=%s"%(k,urllib.quote(v)) for (k, v) in params.items()])
  152:         url=self.REQUEST['URL1']+"?"+ps
  153:         return url
  154: 
  155: 
  156:     def getInfo_xml(self,url,mode):
  157:         """returns info about the document as XML"""
  158: 
  159:         if not self.digilibBaseUrl:
  160:             self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
  161:         
  162:         docinfo = self.getDocinfo(mode=mode,url=url)
  163:         pt = getattr(self.template, 'info_xml')
  164:         return pt(docinfo=docinfo)
  165: 
  166:     
  167:     def getStyle(self, idx, selected, style=""):
  168:         """returns a string with the given style and append 'sel' if path == selected."""
  169:         #logger("documentViewer (getstyle)", logging.INFO, "idx: %s selected: %s style: %s"%(idx,selected,style))
  170:         if idx == selected:
  171:             return style + 'sel'
  172:         else:
  173:             return style
  174: 
  175:         
  176:     def isAccessible(self, docinfo):
  177:         """returns if access to the resource is granted"""
  178:         access = docinfo.get('accessType', None)
  179:         logger("documentViewer (accessOK)", logging.INFO, "access type %s"%access)
  180:         if access is not None and access == 'free':
  181:             logger("documentViewer (accessOK)", logging.INFO, "access is free")
  182:             return True
  183:         elif access is None or access in self.authgroups:
  184:             # only local access -- only logged in users
  185:             user = getSecurityManager().getUser()
  186:             if user is not None:
  187:                 #print "user: ", user
  188:                 return (user.getUserName() != "Anonymous User")
  189:             else:
  190:                 return False
  191:         
  192:         logger("documentViewer (accessOK)", logging.INFO, "unknown access type %s"%access)
  193:         return False
  194:     
  195:                 
  196:     def getDirinfoFromDigilib(self,path,docinfo=None):
  197:         """gibt param von dlInfo aus"""
  198:         num_retries = 3
  199:         if docinfo is None:
  200:             docinfo = {}
  201:             
  202:         infoUrl=self.digilibBaseUrl+"/dirInfo-xml.jsp?mo=dir&fn="+path
  203:     
  204:         logger("documentViewer (getparamfromdigilib)", logging.INFO, "dirInfo from %s"%(infoUrl))
  205:         
  206:         for cnt in range(num_retries):
  207:             try:
  208:                 # dom = NonvalidatingReader.parseUri(imageUrl)
  209:                 txt=urllib.urlopen(infoUrl).read()
  210:                 dom = Parse(txt)
  211:                 break
  212:             except:
  213:                 logger("documentViewer (getdirinfofromdigilib)", logging.ERROR, "error reading %s (try %d)"%(infoUrl,cnt))
  214:         else:
  215:             raise IOError("Unable to get dir-info from %s"%(infoUrl))
  216:         
  217:         sizes=dom.xpath("//dir/size")
  218:         logger("documentViewer (getparamfromdigilib)", logging.INFO, "dirInfo:size"%sizes)
  219:         
  220:         if sizes:
  221:             docinfo['numPages'] = int(getTextFromNode(sizes[0]))
  222:         else:
  223:             docinfo['numPages'] = 0
  224:                         
  225:         return docinfo
  226:     
  227:             
  228:     def getIndexMeta(self, url):
  229:         """returns dom of index.meta document at url"""
  230:         num_retries = 3
  231:         dom = None
  232:         metaUrl = None
  233:         if url.startswith("http://"):
  234:             # real URL
  235:             metaUrl = url
  236:         else:
  237:             # online path
  238:             server=self.digilibBaseUrl+"/servlet/Texter?fn="
  239:             metaUrl=server+url.replace("/mpiwg/online","")
  240:             if not metaUrl.endswith("index.meta"):
  241:                 metaUrl += "/index.meta"
  242:         print metaUrl
  243:         for cnt in range(num_retries):
  244:             try:
  245:                 # patch dirk encoding fehler treten dann nicht mehr auf
  246:                 # dom = NonvalidatingReader.parseUri(metaUrl)
  247:                 txt=urllib.urlopen(metaUrl).read()
  248:                 dom = Parse(txt)
  249:                 break
  250:             except:
  251:                 logger("ERROR documentViewer (getIndexMata)", logging.INFO,"%s (%s)"%sys.exc_info()[0:2])
  252:                 
  253:         if dom is None:
  254:             raise IOError("Unable to read index meta from %s"%(url))
  255:                  
  256:         return dom
  257:     
  258:     def getPresentationInfoXML(self, url):
  259:         """returns dom of info.xml document at url"""
  260:         num_retries = 3
  261:         dom = None
  262:         metaUrl = None
  263:         if url.startswith("http://"):
  264:             # real URL
  265:             metaUrl = url
  266:         else:
  267:             # online path
  268:             server=self.digilibBaseUrl+"/servlet/Texter?fn="
  269:             metaUrl=server+url.replace("/mpiwg/online","")
  270:            
  271:         
  272:         for cnt in range(num_retries):
  273:             try:
  274:                 # patch dirk encoding fehler treten dann nicht mehr auf
  275:                 # dom = NonvalidatingReader.parseUri(metaUrl)
  276:                 txt=urllib.urlopen(metaUrl).read()
  277:                 dom = Parse(txt)
  278:                 break
  279:             except:
  280:                 logger("ERROR documentViewer (getPresentationInfoXML)", logging.INFO,"%s (%s)"%sys.exc_info()[0:2])
  281:                 
  282:         if dom is None:
  283:             raise IOError("Unable to read infoXMLfrom %s"%(url))
  284:                  
  285:         return dom
  286:                         
  287:         
  288:     def getAuthinfoFromIndexMeta(self,path,docinfo=None,dom=None):
  289:         """gets authorization info from the index.meta file at path or given by dom"""
  290:         logger("documentViewer (getauthinfofromindexmeta)", logging.INFO,"path: %s"%(path))
  291:         
  292:         access = None
  293:         
  294:         if docinfo is None:
  295:             docinfo = {}
  296:             
  297:         if dom is None:
  298:             dom = self.getIndexMeta(getParentDir(path))
  299:        
  300:         acctype = dom.xpath("//access-conditions/access/@type")
  301:         if acctype and (len(acctype)>0):
  302:             access=acctype[0].value
  303:             if access in ['group', 'institution']:
  304:                 access = getTextFromNode(dom.xpath("//access-conditions/access/name")[0]).lower()
  305:             
  306:         docinfo['accessType'] = access
  307:         return docinfo
  308:     
  309:         
  310:     def getBibinfoFromIndexMeta(self,path,docinfo=None,dom=None):
  311:         """gets bibliographical info from the index.meta file at path or given by dom"""
  312:         logging.debug("documentViewer (getbibinfofromindexmeta) path: %s"%(path))
  313:         
  314:         if docinfo is None:
  315:             docinfo = {}
  316:             
  317:         if dom is None:
  318:             dom = self.getIndexMeta(getParentDir(path))
  319:             
  320:         # put in all raw bib fields as dict "bib"
  321:         bib = dom.xpath("//bib/*")
  322:         if bib and len(bib)>0:
  323:             bibinfo = {}
  324:             for e in bib:
  325:                 bibinfo[e.localName] = getTextFromNode(e)
  326:             docinfo['bib'] = bibinfo
  327:         
  328:         # extract some fields (author, title, year) according to their mapping
  329:         metaData=self.metadata.main.meta.bib
  330:         bibtype=dom.xpath("//bib/@type")
  331:         if bibtype and (len(bibtype)>0):
  332:             bibtype=bibtype[0].value
  333:         else:
  334:             bibtype="generic"
  335:             
  336:         bibtype=bibtype.replace("-"," ") # wrong typesiin index meta "-" instead of " " (not wrong! ROC)
  337:         docinfo['bib_type'] = bibtype
  338:         bibmap=metaData.generateMappingForType(bibtype)
  339:         # if there is no mapping bibmap is empty (mapping sometimes has empty fields)
  340:         if len(bibmap) > 0 and len(bibmap['author'][0]) > 0:
  341:             docinfo['author']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['author'][0])[0])
  342:             docinfo['title']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['title'][0])[0])
  343:             docinfo['year']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['year'][0])[0])
  344:             logging.debug("documentViewer (getbibinfofromindexmeta) using mapping for %s"%bibtype)
  345:             try:
  346:                 docinfo['lang']=getTextFromNode(dom.xpath("//bib/lang")[0])
  347:             except:
  348:                 docinfo['lang']=''
  349: 
  350:         return docinfo
  351: 
  352:         
  353:     def getDocinfoFromTextTool(self,url,dom=None,docinfo=None):
  354:        """parse texttool tag in index meta"""
  355:        logger("documentViewer (getdocinfofromtexttool)", logging.INFO,"url: %s"%(url))
  356:        if docinfo is None:
  357:            docinfo = {}
  358:            
  359:        if docinfo.get('lang',None) is None:
  360:            docinfo['lang']='' # default keine Sprache gesetzt
  361:        if dom is None:
  362:            dom = self.getIndexMeta(url)
  363:        
  364:        archivePath = None
  365:        archiveName = None
  366: 
  367:        archiveNames=dom.xpath("//resource/name")
  368:        if archiveNames and (len(archiveNames)>0):
  369:            archiveName=getTextFromNode(archiveNames[0])
  370:        else:
  371:            logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/name missing in: %s"%(url))
  372:        
  373:        archivePaths=dom.xpath("//resource/archive-path")
  374:        if archivePaths and (len(archivePaths)>0):
  375:            archivePath=getTextFromNode(archivePaths[0])
  376:            # clean up archive path
  377:            if archivePath[0] != '/':
  378:                archivePath = '/' + archivePath
  379:            if archiveName and (not archivePath.endswith(archiveName)):
  380:                archivePath += "/" + archiveName
  381:        else:
  382:            # try to get archive-path from url
  383:            logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/archive-path missing in: %s"%(url))
  384:            if (not url.startswith('http')):
  385:                archivePath = url.replace('index.meta', '')
  386:                
  387:        if archivePath is None:
  388:            # we balk without archive-path
  389:            raise IOError("Missing archive-path (for text-tool) in %s"%(url))
  390:        
  391:        imageDirs=dom.xpath("//texttool/image")
  392:        if imageDirs and (len(imageDirs)>0):
  393:            imageDir=getTextFromNode(imageDirs[0])
  394:        else:
  395:            # we balk with no image tag / not necessary anymore because textmode is now standard
  396:            #raise IOError("No text-tool info in %s"%(url))
  397:            imageDir=""
  398:            docinfo['numPages']=1 # im moment einfach auf eins setzen, navigation ueber die thumbs geht natuerlich nicht
  399:        
  400:            docinfo['imagePath'] = "" # keine Bilder
  401:            docinfo['imageURL'] = ""
  402: 
  403:        if imageDir and archivePath:
  404:            #print "image: ", imageDir, " archivepath: ", archivePath
  405:            imageDir=os.path.join(archivePath,imageDir)
  406:            imageDir=imageDir.replace("/mpiwg/online",'')
  407:            docinfo=self.getDirinfoFromDigilib(imageDir,docinfo=docinfo)
  408:            docinfo['imagePath'] = imageDir
  409:            docinfo['imageURL'] = self.digilibBaseUrl+"/servlet/Scaler?fn="+imageDir
  410:            
  411:        viewerUrls=dom.xpath("//texttool/digiliburlprefix")
  412:        if viewerUrls and (len(viewerUrls)>0):
  413:            viewerUrl=getTextFromNode(viewerUrls[0])
  414:            docinfo['viewerURL'] = viewerUrl
  415:                   
  416:        textUrls=dom.xpath("//texttool/text")
  417:        if textUrls and (len(textUrls)>0):
  418:            textUrl=getTextFromNode(textUrls[0])
  419:            if urlparse.urlparse(textUrl)[0]=="": #keine url
  420:                textUrl=os.path.join(archivePath,textUrl) 
  421: 
  422:            docinfo['textURL'] = textUrl
  423:    
  424:        presentationUrls=dom.xpath("//texttool/presentation")
  425:        docinfo = self.getBibinfoFromIndexMeta(url,docinfo=docinfo,dom=dom)   # get info von bib tag
  426:        
  427:        if presentationUrls and (len(presentationUrls)>0): # ueberschreibe diese durch presentation informationen 
  428:             # presentation url ergiebt sich ersetzen von index.meta in der url der fŸr die Metadaten
  429:             # durch den relativen Pfad auf die presentation infos
  430:            presentationUrl=url.replace('index.meta',getTextFromNode(presentationUrls[0]))
  431:            docinfo = self.getBibinfoFromTextToolPresentation(presentationUrl,docinfo=docinfo,dom=dom)
  432: 
  433:        docinfo = self.getAuthinfoFromIndexMeta(url,docinfo=docinfo,dom=dom)   # get access info
  434:        return docinfo
  435:    
  436:    
  437:     def getBibinfoFromTextToolPresentation(self,url,docinfo=None,dom=None):
  438:         """gets the bibliographical information from the preseantion entry in texttools
  439:         """
  440:         dom=self.getPresentationInfoXML(url)
  441:         docinfo['author']=getTextFromNode(dom.xpath("//author")[0])
  442:         docinfo['title']=getTextFromNode(dom.xpath("//title")[0])
  443:         docinfo['year']=getTextFromNode(dom.xpath("//date")[0])
  444:         return docinfo
  445:     
  446:     def getDocinfoFromImagePath(self,path,docinfo=None):
  447:         """path ist the path to the images it assumes that the index.meta file is one level higher."""
  448:         logger("documentViewer (getdocinfofromimagepath)", logging.INFO,"path: %s"%(path))
  449:         if docinfo is None:
  450:             docinfo = {}
  451:         path=path.replace("/mpiwg/online","")
  452:         docinfo['imagePath'] = path
  453:         docinfo=self.getDirinfoFromDigilib(path,docinfo=docinfo)
  454:         imageUrl=self.digilibBaseUrl+"/servlet/Scaler?fn="+path
  455:         docinfo['imageURL'] = imageUrl
  456:         
  457:         docinfo = self.getBibinfoFromIndexMeta(path,docinfo=docinfo)
  458:         docinfo = self.getAuthinfoFromIndexMeta(path,docinfo=docinfo)
  459:         return docinfo
  460:     
  461:     
  462:     def getDocinfo(self, mode, url):
  463:         """returns docinfo depending on mode"""
  464:         logger("documentViewer (getdocinfo)", logging.INFO,"mode: %s, url: %s"%(mode,url))
  465:         # look for cached docinfo in session
  466:         if self.REQUEST.SESSION.has_key('docinfo'):
  467:             docinfo = self.REQUEST.SESSION['docinfo']
  468:             # check if its still current
  469:             if docinfo is not None and docinfo.get('mode') == mode and docinfo.get('url') == url:
  470:                 logger("documentViewer (getdocinfo)", logging.INFO,"docinfo in session: %s"%docinfo)
  471:                 return docinfo
  472:         # new docinfo
  473:         docinfo = {'mode': mode, 'url': url}
  474:         if mode=="texttool": #index.meta with texttool information
  475:             docinfo = self.getDocinfoFromTextTool(url, docinfo=docinfo)
  476:         elif mode=="imagepath":
  477:             docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo)
  478:         else:
  479:             logger("documentViewer (getdocinfo)", logging.ERROR,"unknown mode!")
  480:             raise ValueError("Unknown mode %s"%(mode))
  481:                         
  482:         logger("documentViewer (getdocinfo)", logging.INFO,"docinfo: %s"%docinfo)
  483:         self.REQUEST.SESSION['docinfo'] = docinfo
  484:         return docinfo
  485:         
  486:         
  487:     def getPageinfo(self, current, start=None, rows=None, cols=None, docinfo=None):
  488:         """returns pageinfo with the given parameters"""
  489:         pageinfo = {}
  490:         current = getInt(current)
  491:         pageinfo['current'] = current
  492:         rows = int(rows or self.thumbrows)
  493:         pageinfo['rows'] = rows
  494:         cols = int(cols or self.thumbcols)
  495:         pageinfo['cols'] = cols
  496:         grpsize = cols * rows
  497:         pageinfo['groupsize'] = grpsize
  498:         start = getInt(start, default=(int(current / grpsize) * grpsize +1))
  499:         pageinfo['start'] = start
  500:         pageinfo['end'] = start + grpsize
  501:         if docinfo is not None:
  502:             np = int(docinfo['numPages'])
  503:             pageinfo['end'] = min(pageinfo['end'], np)
  504:             pageinfo['numgroups'] = int(np / grpsize)
  505:             if np % grpsize > 0:
  506:                 pageinfo['numgroups'] += 1
  507:                 
  508:         return pageinfo
  509:                 
  510:     def text(self,mode,url,pn):
  511:         """give text"""
  512:         if mode=="texttool": #index.meta with texttool information
  513:             (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
  514:         
  515:         #print textpath
  516:         try:
  517:             dom = NonvalidatingReader.parseUri(textpath)
  518:         except:
  519:             return None
  520:     
  521:         list=[]
  522:         nodes=dom.xpath("//pb")
  523: 
  524:         node=nodes[int(pn)-1]
  525:         
  526:         p=node
  527:         
  528:         while p.tagName!="p":
  529:             p=p.parentNode
  530:         
  531:         
  532:         endNode=nodes[int(pn)]
  533:         
  534:         
  535:         e=endNode
  536:         
  537:         while e.tagName!="p":
  538:             e=e.parentNode
  539:         
  540:         
  541:         next=node.parentNode
  542:         
  543:         #sammle s
  544:         while next and (next!=endNode.parentNode):
  545:             list.append(next)    
  546:             next=next.nextSibling    
  547:         list.append(endNode.parentNode)
  548:         
  549:         if p==e:# beide im selben paragraphen
  550:             pass
  551: #    else:
  552: #            next=p
  553: #            while next!=e:
  554: #                print next,e
  555: #                list.append(next)
  556: #                next=next.nextSibling
  557: #            
  558: #        for x in list:
  559: #            PrettyPrint(x)
  560: #
  561: #        return list
  562: #
  563: 
  564:     def findDigilibUrl(self):
  565:         """try to get the digilib URL from zogilib"""
  566:         url = self.imageViewerUrl[:-1] + "/getScalerUrl"
  567:         #print urlparse.urlparse(url)[0]
  568:         #print urlparse.urljoin(self.absolute_url(),url)
  569:         logging.info("finddigiliburl: %s"%urlparse.urlparse(url)[0])
  570:         logging.info("finddigiliburl: %s"%urlparse.urljoin(self.absolute_url(),url))
  571:         
  572:         try:
  573:             if urlparse.urlparse(url)[0]=='': #relative path
  574:                 url=urlparse.urljoin(self.absolute_url()+"/",url)
  575:                 
  576:             scaler = urlopen(url).read()
  577:             return scaler.replace("/servlet/Scaler?", "")
  578:         except:
  579:             return None
  580:     
  581:     def changeDocumentViewer(self,imageViewerUrl,textViewerUrl,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=10,authgroups='mpiwg',RESPONSE=None):
  582:         """init document viewer"""
  583:         self.title=title
  584:         self.imageViewerUrl=imageViewerUrl
  585:         self.textViewerUrl=textViewerUrl
  586:         self.digilibBaseUrl = digilibBaseUrl
  587:         self.thumbrows = thumbrows
  588:         self.thumbcols = thumbcols
  589:         self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
  590:         if RESPONSE is not None:
  591:             RESPONSE.redirect('manage_main')
  592:     
  593:     
  594:         
  595:         
  596: #    security.declareProtected('View management screens','renameImageForm')
  597: 
  598: def manage_AddDocumentViewerForm(self):
  599:     """add the viewer form"""
  600:     pt=PageTemplateFile('zpt/addDocumentViewer', globals()).__of__(self)
  601:     return pt()
  602:   
  603: def manage_AddDocumentViewer(self,id,imageViewerUrl="",textViewerUrl="",title="",RESPONSE=None):
  604:     """add the viewer"""
  605:     newObj=documentViewer(id,imageViewerUrl,title=title,textViewerUrl=textViewerUrl)
  606:     self._setObject(id,newObj)
  607:     
  608:     if RESPONSE is not None:
  609:         RESPONSE.redirect('manage_main')
  610: 
  611: 
  612: ##
  613: ## DocumentViewerTemplate class
  614: ##
  615: class DocumentViewerTemplate(ZopePageTemplate):
  616:     """Template for document viewer"""
  617:     meta_type="DocumentViewer Template"
  618: 
  619: 
  620: def manage_addDocumentViewerTemplateForm(self):
  621:     """Form for adding"""
  622:     pt=PageTemplateFile('zpt/addDocumentViewerTemplate', globals()).__of__(self)
  623:     return pt()
  624: 
  625: def manage_addDocumentViewerTemplate(self, id='viewer_main', title=None, text=None,
  626:                            REQUEST=None, submit=None):
  627:     "Add a Page Template with optional file content."
  628: 
  629:     self._setObject(id, DocumentViewerTemplate(id))
  630:     ob = getattr(self, id)
  631:     txt=file(os.path.join(package_home(globals()),'zpt/viewer_main.zpt'),'r').read()
  632:     logging.info("txt %s:"%txt)
  633:     ob.pt_edit(txt,"text/html")
  634:     if title:
  635:         ob.pt_setTitle(title)
  636:     try:
  637:         u = self.DestinationURL()
  638:     except AttributeError:
  639:         u = REQUEST['URL1']
  640:         
  641:     u = "%s/%s" % (u, urllib.quote(id))
  642:     REQUEST.RESPONSE.redirect(u+'/manage_main')
  643:     return ''
  644: 
  645: 
  646:     

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