source: documentViewer/documentViewer.py @ 67:0fa278fb82b5

Last change on this file since 67:0fa278fb82b5 was 65:c048559460a3, checked in by casties, 17 years ago

fix problems with full text paths starting with /mpiwg/online

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