File:  [Repository] / documentViewer / documentViewer.py
Revision 1.26: download - view: text, annotated - select for diffs - revision graph
Fri May 4 13:17:02 2007 UTC (17 years, 2 months ago) by casties
Branches: MAIN
CVS tags: HEAD
added getInfo_xml method

    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:         logger("documentViewer (getbibinfofromindexmeta)", logging.INFO,"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:         metaData=self.metadata.main.meta.bib
  321:         bibtype=dom.xpath("//bib/@type")
  322:         if bibtype and (len(bibtype)>0):
  323:             bibtype=bibtype[0].value
  324:         else:
  325:             bibtype="generic"
  326:         bibtype=bibtype.replace("-"," ") # wrong typesiin index meta "-" instead of " " (not wrong! ROC)
  327:         bibmap=metaData.generateMappingForType(bibtype)
  328:         #print "bibmap: ", bibmap, " for: ", bibtype
  329:         # if there is no mapping bibmap is empty (mapping sometimes has empty fields)
  330:         if len(bibmap) > 0 and len(bibmap['author'][0]) > 0:
  331:             docinfo['author']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['author'][0])[0])
  332:             docinfo['title']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['title'][0])[0])
  333:             docinfo['year']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['year'][0])[0])
  334:             
  335:             logging.info("bla")
  336:             try:
  337:                 docinfo['lang']=getTextFromNode(dom.xpath("//bib/lang")[0])
  338:             except:
  339:                 docinfo['lang']=''
  340:         return docinfo
  341: 
  342:         
  343:     def getDocinfoFromTextTool(self,url,dom=None,docinfo=None):
  344:        """parse texttool tag in index meta"""
  345:        logger("documentViewer (getdocinfofromtexttool)", logging.INFO,"url: %s"%(url))
  346:        if docinfo is None:
  347:            docinfo = {}
  348:            
  349:        if docinfo.get('lang',None) is None:
  350:            docinfo['lang']='' # default keine Sprache gesetzt
  351:        if dom is None:
  352:            dom = self.getIndexMeta(url)
  353:        
  354:        archivePath = None
  355:        archiveName = None
  356: 
  357:        archiveNames=dom.xpath("//resource/name")
  358:        if archiveNames and (len(archiveNames)>0):
  359:            archiveName=getTextFromNode(archiveNames[0])
  360:        else:
  361:            logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/name missing in: %s"%(url))
  362:        
  363:        archivePaths=dom.xpath("//resource/archive-path")
  364:        if archivePaths and (len(archivePaths)>0):
  365:            archivePath=getTextFromNode(archivePaths[0])
  366:            # clean up archive path
  367:            if archivePath[0] != '/':
  368:                archivePath = '/' + archivePath
  369:            if archiveName and (not archivePath.endswith(archiveName)):
  370:                archivePath += "/" + archiveName
  371:        else:
  372:            # try to get archive-path from url
  373:            logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/archive-path missing in: %s"%(url))
  374:            if (not url.startswith('http')):
  375:                archivePath = url.replace('index.meta', '')
  376:                
  377:        if archivePath is None:
  378:            # we balk without archive-path
  379:            raise IOError("Missing archive-path (for text-tool) in %s"%(url))
  380:        
  381:        imageDirs=dom.xpath("//texttool/image")
  382:        if imageDirs and (len(imageDirs)>0):
  383:            imageDir=getTextFromNode(imageDirs[0])
  384:        else:
  385:            # we balk with no image tag / not necessary anymore because textmode is now standard
  386:            #raise IOError("No text-tool info in %s"%(url))
  387:            imageDir=""
  388:            docinfo['numPages']=1 # im moment einfach auf eins setzen, navigation ueber die thumbs geht natuerlich nicht
  389:        
  390:            docinfo['imagePath'] = "" # keine Bilder
  391:            docinfo['imageURL'] = ""
  392: 
  393:        if imageDir and archivePath:
  394:            #print "image: ", imageDir, " archivepath: ", archivePath
  395:            imageDir=os.path.join(archivePath,imageDir)
  396:            imageDir=imageDir.replace("/mpiwg/online",'')
  397:            docinfo=self.getDirinfoFromDigilib(imageDir,docinfo=docinfo)
  398:            docinfo['imagePath'] = imageDir
  399:            docinfo['imageURL'] = self.digilibBaseUrl+"/servlet/Scaler?fn="+imageDir
  400:            
  401:        viewerUrls=dom.xpath("//texttool/digiliburlprefix")
  402:        if viewerUrls and (len(viewerUrls)>0):
  403:            viewerUrl=getTextFromNode(viewerUrls[0])
  404:            docinfo['viewerURL'] = viewerUrl
  405:                   
  406:        textUrls=dom.xpath("//texttool/text")
  407:        if textUrls and (len(textUrls)>0):
  408:            textUrl=getTextFromNode(textUrls[0])
  409:            if urlparse.urlparse(textUrl)[0]=="": #keine url
  410:                textUrl=os.path.join(archivePath,textUrl) 
  411: 
  412:            docinfo['textURL'] = textUrl
  413:    
  414:        presentationUrls=dom.xpath("//texttool/presentation")
  415:        docinfo = self.getBibinfoFromIndexMeta(url,docinfo=docinfo,dom=dom)   # get info von bib tag
  416:        
  417:        if presentationUrls and (len(presentationUrls)>0): # ueberschreibe diese durch presentation informationen 
  418:             # presentation url ergiebt sich ersetzen von index.meta in der url der fŸr die Metadaten
  419:             # durch den relativen Pfad auf die presentation infos
  420:            presentationUrl=url.replace('index.meta',getTextFromNode(presentationUrls[0]))
  421:            docinfo = self.getBibinfoFromTextToolPresentation(presentationUrl,docinfo=docinfo,dom=dom)
  422: 
  423:        docinfo = self.getAuthinfoFromIndexMeta(url,docinfo=docinfo,dom=dom)   # get access info
  424:        return docinfo
  425:    
  426:    
  427:     def getBibinfoFromTextToolPresentation(self,url,docinfo=None,dom=None):
  428:         """gets the bibliographical information from the preseantion entry in texttools
  429:         """
  430:         dom=self.getPresentationInfoXML(url)
  431:         docinfo['author']=getTextFromNode(dom.xpath("//author")[0])
  432:         docinfo['title']=getTextFromNode(dom.xpath("//title")[0])
  433:         docinfo['year']=getTextFromNode(dom.xpath("//date")[0])
  434:         return docinfo
  435:     
  436:     def getDocinfoFromImagePath(self,path,docinfo=None):
  437:         """path ist the path to the images it assumes that the index.meta file is one level higher."""
  438:         logger("documentViewer (getdocinfofromimagepath)", logging.INFO,"path: %s"%(path))
  439:         if docinfo is None:
  440:             docinfo = {}
  441:         path=path.replace("/mpiwg/online","")
  442:         docinfo['imagePath'] = path
  443:         docinfo=self.getDirinfoFromDigilib(path,docinfo=docinfo)
  444:         imageUrl=self.digilibBaseUrl+"/servlet/Scaler?fn="+path
  445:         docinfo['imageURL'] = imageUrl
  446:         
  447:         docinfo = self.getBibinfoFromIndexMeta(path,docinfo=docinfo)
  448:         docinfo = self.getAuthinfoFromIndexMeta(path,docinfo=docinfo)
  449:         return docinfo
  450:     
  451:     
  452:     def getDocinfo(self, mode, url):
  453:         """returns docinfo depending on mode"""
  454:         logger("documentViewer (getdocinfo)", logging.INFO,"mode: %s, url: %s"%(mode,url))
  455:         # look for cached docinfo in session
  456:         if self.REQUEST.SESSION.has_key('docinfo'):
  457:             docinfo = self.REQUEST.SESSION['docinfo']
  458:             # check if its still current
  459:             if docinfo is not None and docinfo.get('mode') == mode and docinfo.get('url') == url:
  460:                 logger("documentViewer (getdocinfo)", logging.INFO,"docinfo in session: %s"%docinfo)
  461:                 return docinfo
  462:         # new docinfo
  463:         docinfo = {'mode': mode, 'url': url}
  464:         if mode=="texttool": #index.meta with texttool information
  465:             docinfo = self.getDocinfoFromTextTool(url, docinfo=docinfo)
  466:         elif mode=="imagepath":
  467:             docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo)
  468:         else:
  469:             logger("documentViewer (getdocinfo)", logging.ERROR,"unknown mode!")
  470:             raise ValueError("Unknown mode %s"%(mode))
  471:                         
  472:         logger("documentViewer (getdocinfo)", logging.INFO,"docinfo: %s"%docinfo)
  473:         self.REQUEST.SESSION['docinfo'] = docinfo
  474:         return docinfo
  475:         
  476:         
  477:     def getPageinfo(self, current, start=None, rows=None, cols=None, docinfo=None):
  478:         """returns pageinfo with the given parameters"""
  479:         pageinfo = {}
  480:         current = getInt(current)
  481:         pageinfo['current'] = current
  482:         rows = int(rows or self.thumbrows)
  483:         pageinfo['rows'] = rows
  484:         cols = int(cols or self.thumbcols)
  485:         pageinfo['cols'] = cols
  486:         grpsize = cols * rows
  487:         pageinfo['groupsize'] = grpsize
  488:         start = getInt(start, default=(int(current / grpsize) * grpsize +1))
  489:         pageinfo['start'] = start
  490:         pageinfo['end'] = start + grpsize
  491:         if docinfo is not None:
  492:             np = int(docinfo['numPages'])
  493:             pageinfo['end'] = min(pageinfo['end'], np)
  494:             pageinfo['numgroups'] = int(np / grpsize)
  495:             if np % grpsize > 0:
  496:                 pageinfo['numgroups'] += 1
  497:                 
  498:         return pageinfo
  499:                 
  500:     def text(self,mode,url,pn):
  501:         """give text"""
  502:         if mode=="texttool": #index.meta with texttool information
  503:             (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
  504:         
  505:         #print textpath
  506:         try:
  507:             dom = NonvalidatingReader.parseUri(textpath)
  508:         except:
  509:             return None
  510:     
  511:         list=[]
  512:         nodes=dom.xpath("//pb")
  513: 
  514:         node=nodes[int(pn)-1]
  515:         
  516:         p=node
  517:         
  518:         while p.tagName!="p":
  519:             p=p.parentNode
  520:         
  521:         
  522:         endNode=nodes[int(pn)]
  523:         
  524:         
  525:         e=endNode
  526:         
  527:         while e.tagName!="p":
  528:             e=e.parentNode
  529:         
  530:         
  531:         next=node.parentNode
  532:         
  533:         #sammle s
  534:         while next and (next!=endNode.parentNode):
  535:             list.append(next)    
  536:             next=next.nextSibling    
  537:         list.append(endNode.parentNode)
  538:         
  539:         if p==e:# beide im selben paragraphen
  540:             pass
  541: #    else:
  542: #            next=p
  543: #            while next!=e:
  544: #                print next,e
  545: #                list.append(next)
  546: #                next=next.nextSibling
  547: #            
  548: #        for x in list:
  549: #            PrettyPrint(x)
  550: #
  551: #        return list
  552: #
  553: 
  554:     def findDigilibUrl(self):
  555:         """try to get the digilib URL from zogilib"""
  556:         url = self.imageViewerUrl[:-1] + "/getScalerUrl"
  557:         #print urlparse.urlparse(url)[0]
  558:         #print urlparse.urljoin(self.absolute_url(),url)
  559:         logging.info("finddigiliburl: %s"%urlparse.urlparse(url)[0])
  560:         logging.info("finddigiliburl: %s"%urlparse.urljoin(self.absolute_url(),url))
  561:         
  562:         try:
  563:             if urlparse.urlparse(url)[0]=='': #relative path
  564:                 url=urlparse.urljoin(self.absolute_url()+"/",url)
  565:                 
  566:             scaler = urlopen(url).read()
  567:             return scaler.replace("/servlet/Scaler?", "")
  568:         except:
  569:             return None
  570:     
  571:     def changeDocumentViewer(self,imageViewerUrl,textViewerUrl,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=10,authgroups='mpiwg',RESPONSE=None):
  572:         """init document viewer"""
  573:         self.title=title
  574:         self.imageViewerUrl=imageViewerUrl
  575:         self.textViewerUrl=textViewerUrl
  576:         self.digilibBaseUrl = digilibBaseUrl
  577:         self.thumbrows = thumbrows
  578:         self.thumbcols = thumbcols
  579:         self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
  580:         if RESPONSE is not None:
  581:             RESPONSE.redirect('manage_main')
  582:     
  583:     
  584:         
  585:         
  586: #    security.declareProtected('View management screens','renameImageForm')
  587: 
  588: def manage_AddDocumentViewerForm(self):
  589:     """add the viewer form"""
  590:     pt=PageTemplateFile('zpt/addDocumentViewer', globals()).__of__(self)
  591:     return pt()
  592:   
  593: def manage_AddDocumentViewer(self,id,imageViewerUrl="",textViewerUrl="",title="",RESPONSE=None):
  594:     """add the viewer"""
  595:     newObj=documentViewer(id,imageViewerUrl,title=title,textViewerUrl=textViewerUrl)
  596:     self._setObject(id,newObj)
  597:     
  598:     if RESPONSE is not None:
  599:         RESPONSE.redirect('manage_main')
  600: 
  601: 
  602: ##
  603: ## DocumentViewerTemplate class
  604: ##
  605: class DocumentViewerTemplate(ZopePageTemplate):
  606:     """Template for document viewer"""
  607:     meta_type="DocumentViewer Template"
  608: 
  609: 
  610: def manage_addDocumentViewerTemplateForm(self):
  611:     """Form for adding"""
  612:     pt=PageTemplateFile('zpt/addDocumentViewerTemplate', globals()).__of__(self)
  613:     return pt()
  614: 
  615: def manage_addDocumentViewerTemplate(self, id='viewer_main', title=None, text=None,
  616:                            REQUEST=None, submit=None):
  617:     "Add a Page Template with optional file content."
  618: 
  619:     self._setObject(id, DocumentViewerTemplate(id))
  620:     ob = getattr(self, id)
  621:     txt=file(os.path.join(package_home(globals()),'zpt/viewer_main.zpt'),'r').read()
  622:     logging.info("txt %s:"%txt)
  623:     ob.pt_edit(txt,"text/html")
  624:     if title:
  625:         ob.pt_setTitle(title)
  626:     try:
  627:         u = self.DestinationURL()
  628:     except AttributeError:
  629:         u = REQUEST['URL1']
  630:         
  631:     u = "%s/%s" % (u, urllib.quote(id))
  632:     REQUEST.RESPONSE.redirect(u+'/manage_main')
  633:     return ''
  634: 
  635: 
  636:     

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