Annotation of zogiLib/zogiLib.py, revision 1.32
1.1 dwinter 1: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
2: from Products.PageTemplates.PageTemplate import PageTemplate
3: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
1.4 dwinter 4: from OFS.Image import Image
5: from webdav.common import rfc1123_date
1.1 dwinter 6:
7: import xml.dom.minidom
8: from OFS.Folder import Folder
1.32 ! dwinter 9: from xml_helpers import getUniqueElementText,getText
1.1 dwinter 10: import os
11: import re
12: import string
13: import urllib
1.24 casties 14: import types
1.1 dwinter 15: from Globals import package_home
16:
1.30 casties 17: ZOGIVERSION = "0.9.5 ROC:25.6.2004"
18:
19: def cropf(f):
20: """returns a float with reduced precision"""
21: return float(int(f * 10000)/10000.0)
22:
1.28 casties 23:
1.15 casties 24: def sendFile(self, filename, type):
1.17 casties 25: """sends an object or a local file (in the product) as response"""
26: paths = filename.split('/')
27: object = self
28: # look for an object called filename
29: for path in paths:
30: if hasattr(object, path):
31: object = getattr(object, path)
32: else:
33: object = None
34: break
35: if object:
1.18 casties 36: # if the object exists then send it
37: return object.index_html(self.REQUEST.REQUEST, self.REQUEST.RESPONSE)
1.17 casties 38: else:
39: # send a local file with the given content-type
40: fn = os.path.join(package_home(globals()), filename)
41: self.REQUEST.RESPONSE.setHeader("Content-Type", type)
42: self.REQUEST.RESPONSE.write(file(fn).read())
1.15 casties 43: return
44:
1.26 casties 45: def browserCheck(self):
1.18 casties 46: """check the browsers request to find out the browser type"""
1.26 casties 47: bt = {}
48: ua = self.REQUEST.get_header("HTTP_USER_AGENT")
49: bt['ua'] = ua
50: bt['isIE'] = string.find(ua, 'MSIE') > -1
51: bt['isN4'] = (string.find(ua, 'Mozilla/4.') > -1) and not bt['isIE']
52: nav = ua[string.find(ua, '('):]
53: ie = string.split(nav, "; ")[1]
54: if string.find(ie, "MSIE") > -1:
55: bt['versIE'] = string.split(ie, " ")[1]
56: bt['isMac'] = string.find(ua, 'Macintosh') > -1
57: bt['isWin'] = string.find(ua, 'Windows') > -1
58: bt['isIEWin'] = bt['isIE'] and bt['isWin']
59: bt['isIEMac'] = bt['isIE'] and bt['isMac']
60: bt['staticHTML'] = False
1.5 dwinter 61:
1.26 casties 62: return bt
1.5 dwinter 63:
1.1 dwinter 64:
1.4 dwinter 65: class zogiImage(Image):
66: """einzelnes Image"""
67: meta_type="zogiImage"
68:
1.18 casties 69: manage_options=ZopePageTemplate.manage_options+(
70: {'label':'Main config','action':'changeZogiImageForm'},
71: )
1.4 dwinter 72:
73:
74: def __init__(self,id,title,baseUrl,queryString,content_type='',precondition=''):
75: """init"""
76: self.id=id
77: self.title=title
78: self.baseUrl=baseUrl
79: self.queryString=queryString
80: self.content_type=content_type
81: self.precondition=precondition
82:
83: def getData(self):
84: """getUrlData"""
85: return urllib.urlopen(self.baseUrl+self.queryString)
86:
87: def changeZogiImageForm(self):
88: """Main configuration"""
1.18 casties 89: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/changeZogiImageForm.zpt')).__of__(self)
1.4 dwinter 90: return pt()
91:
92: def changeZogiImage(self,title,baseUrl, queryString,RESPONSE=None):
93: """change it"""
94: self.title=title
95: self.baseUrl=baseUrl
96: self.queryString=queryString
97:
98: if RESPONSE is not None:
99: RESPONSE.redirect('manage_main')
100:
101:
102: def index_html(self, REQUEST, RESPONSE):
103: """
104: Modified version of OFS/Image.py
1.1 dwinter 105:
1.4 dwinter 106: The default view of the contents of a File or Image.
107:
108: Returns the contents of the file or image. Also, sets the
109: Content-Type HTTP header to the objects content type.
110: """
111:
112: # HTTP If-Modified-Since header handling.
113: header=REQUEST.get_header('If-Modified-Since', None)
114: if header is not None:
115: header=header.split( ';')[0]
116: # Some proxies seem to send invalid date strings for this
117: # header. If the date string is not valid, we ignore it
118: # rather than raise an error to be generally consistent
119: # with common servers such as Apache (which can usually
120: # understand the screwy date string as a lucky side effect
121: # of the way they parse it).
122: # This happens to be what RFC2616 tells us to do in the face of an
123: # invalid date.
124: try: mod_since=long(DateTime(header).timeTime())
125: except: mod_since=None
126: if mod_since is not None:
127: if self._p_mtime:
128: last_mod = long(self._p_mtime)
129: else:
130: last_mod = long(0)
131: if last_mod > 0 and last_mod <= mod_since:
132: # Set header values since apache caching will return Content-Length
133: # of 0 in response if size is not set here
134: RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime))
135: RESPONSE.setHeader('Content-Type', self.content_type)
136: RESPONSE.setHeader('Content-Length', self.size)
137: RESPONSE.setHeader('Accept-Ranges', 'bytes')
138: self.ZCacheable_set(None)
139: RESPONSE.setStatus(304)
140: return ''
141:
142: if self.precondition and hasattr(self,self.precondition):
143: # Grab whatever precondition was defined and then
144: # execute it. The precondition will raise an exception
145: # if something violates its terms.
146: c=getattr(self,self.precondition)
147: if hasattr(c,'isDocTemp') and c.isDocTemp:
148: c(REQUEST['PARENTS'][1],REQUEST)
149: else:
150: c()
151:
152: # HTTP Range header handling
153: range = REQUEST.get_header('Range', None)
154: request_range = REQUEST.get_header('Request-Range', None)
155: if request_range is not None:
156: # Netscape 2 through 4 and MSIE 3 implement a draft version
157: # Later on, we need to serve a different mime-type as well.
158: range = request_range
159: if_range = REQUEST.get_header('If-Range', None)
160: if range is not None:
161: ranges = HTTPRangeSupport.parseRange(range)
162:
163: if if_range is not None:
164: # Only send ranges if the data isn't modified, otherwise send
165: # the whole object. Support both ETags and Last-Modified dates!
166: if len(if_range) > 1 and if_range[:2] == 'ts':
167: # ETag:
168: if if_range != self.http__etag():
169: # Modified, so send a normal response. We delete
170: # the ranges, which causes us to skip to the 200
171: # response.
172: ranges = None
173: else:
174: # Date
175: date = if_range.split( ';')[0]
176: try: mod_since=long(DateTime(date).timeTime())
177: except: mod_since=None
178: if mod_since is not None:
179: if self._p_mtime:
180: last_mod = long(self._p_mtime)
181: else:
182: last_mod = long(0)
183: if last_mod > mod_since:
184: # Modified, so send a normal response. We delete
185: # the ranges, which causes us to skip to the 200
186: # response.
187: ranges = None
188:
189: if ranges:
190: # Search for satisfiable ranges.
191: satisfiable = 0
192: for start, end in ranges:
193: if start < self.size:
194: satisfiable = 1
195: break
196:
197: if not satisfiable:
198: RESPONSE.setHeader('Content-Range',
199: 'bytes */%d' % self.size)
200: RESPONSE.setHeader('Accept-Ranges', 'bytes')
201: RESPONSE.setHeader('Last-Modified',
202: rfc1123_date(self._p_mtime))
203: RESPONSE.setHeader('Content-Type', self.content_type)
204: RESPONSE.setHeader('Content-Length', self.size)
205: RESPONSE.setStatus(416)
206: return ''
207:
208: ranges = HTTPRangeSupport.expandRanges(ranges, self.size)
209:
210: if len(ranges) == 1:
211: # Easy case, set extra header and return partial set.
212: start, end = ranges[0]
213: size = end - start
214:
215: RESPONSE.setHeader('Last-Modified',
216: rfc1123_date(self._p_mtime))
217: RESPONSE.setHeader('Content-Type', self.content_type)
218: RESPONSE.setHeader('Content-Length', size)
219: RESPONSE.setHeader('Accept-Ranges', 'bytes')
220: RESPONSE.setHeader('Content-Range',
221: 'bytes %d-%d/%d' % (start, end - 1, self.size))
222: RESPONSE.setStatus(206) # Partial content
223:
224: data = urllib.urlopen(self.baseUrl+self.queryString).read()
225: if type(data) is StringType:
226: return data[start:end]
227:
228: # Linked Pdata objects. Urgh.
229: pos = 0
230: while data is not None:
231: l = len(data.data)
232: pos = pos + l
233: if pos > start:
234: # We are within the range
235: lstart = l - (pos - start)
236:
237: if lstart < 0: lstart = 0
238:
239: # find the endpoint
240: if end <= pos:
241: lend = l - (pos - end)
242:
243: # Send and end transmission
244: RESPONSE.write(data[lstart:lend])
245: break
246:
247: # Not yet at the end, transmit what we have.
248: RESPONSE.write(data[lstart:])
249:
250: data = data.next
251:
252: return ''
253:
254: else:
255: boundary = choose_boundary()
256:
257: # Calculate the content length
258: size = (8 + len(boundary) + # End marker length
259: len(ranges) * ( # Constant lenght per set
260: 49 + len(boundary) + len(self.content_type) +
261: len('%d' % self.size)))
262: for start, end in ranges:
263: # Variable length per set
264: size = (size + len('%d%d' % (start, end - 1)) +
265: end - start)
266:
267:
268: # Some clients implement an earlier draft of the spec, they
269: # will only accept x-byteranges.
270: draftprefix = (request_range is not None) and 'x-' or ''
271:
272: RESPONSE.setHeader('Content-Length', size)
273: RESPONSE.setHeader('Accept-Ranges', 'bytes')
274: RESPONSE.setHeader('Last-Modified',
275: rfc1123_date(self._p_mtime))
276: RESPONSE.setHeader('Content-Type',
277: 'multipart/%sbyteranges; boundary=%s' % (
278: draftprefix, boundary))
279: RESPONSE.setStatus(206) # Partial content
280:
281: data = urllib.urlopen(self.baseUrl+self.queryString).read()
282: # The Pdata map allows us to jump into the Pdata chain
283: # arbitrarily during out-of-order range searching.
284: pdata_map = {}
285: pdata_map[0] = data
286:
287: for start, end in ranges:
288: RESPONSE.write('\r\n--%s\r\n' % boundary)
289: RESPONSE.write('Content-Type: %s\r\n' %
290: self.content_type)
291: RESPONSE.write(
292: 'Content-Range: bytes %d-%d/%d\r\n\r\n' % (
293: start, end - 1, self.size))
294:
295: if type(data) is StringType:
296: RESPONSE.write(data[start:end])
297:
298: else:
299: # Yippee. Linked Pdata objects. The following
300: # calculations allow us to fast-forward through the
301: # Pdata chain without a lot of dereferencing if we
302: # did the work already.
303: first_size = len(pdata_map[0].data)
304: if start < first_size:
305: closest_pos = 0
306: else:
307: closest_pos = (
308: ((start - first_size) >> 16 << 16) +
309: first_size)
310: pos = min(closest_pos, max(pdata_map.keys()))
311: data = pdata_map[pos]
312:
313: while data is not None:
314: l = len(data.data)
315: pos = pos + l
316: if pos > start:
317: # We are within the range
318: lstart = l - (pos - start)
319:
320: if lstart < 0: lstart = 0
321:
322: # find the endpoint
323: if end <= pos:
324: lend = l - (pos - end)
325:
326: # Send and loop to next range
327: RESPONSE.write(data[lstart:lend])
328: break
329:
330: # Not yet at the end, transmit what we have.
331: RESPONSE.write(data[lstart:])
332:
333: data = data.next
334: # Store a reference to a Pdata chain link so we
335: # don't have to deref during this request again.
336: pdata_map[pos] = data
337:
338: # Do not keep the link references around.
339: del pdata_map
340:
341: RESPONSE.write('\r\n--%s--\r\n' % boundary)
342: return ''
343:
344: RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime))
345: RESPONSE.setHeader('Content-Type', self.content_type)
346: RESPONSE.setHeader('Content-Length', self.size)
347: RESPONSE.setHeader('Accept-Ranges', 'bytes')
348:
349: # Don't cache the data itself, but provide an opportunity
350: # for a cache manager to set response headers.
351: self.ZCacheable_set(None)
352:
353: data=urllib.urlopen(self.baseUrl+self.queryString).read()
354:
355: if type(data) is type(''):
356: RESPONSE.setBase(None)
357: return data
358:
359: while data is not None:
360: RESPONSE.write(data.data)
361: data=data.next
362:
363: return ''
364:
365:
366: def manage_addZogiImageForm(self):
367: """Form for adding"""
1.18 casties 368: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/addZogiImage.zpt')).__of__(self)
1.4 dwinter 369: return pt()
370:
371:
372: def manage_addZogiImage(self,id,title,baseUrl, queryString,RESPONSE=None):
373: """add dgilib"""
374: newObj=zogiImage(id,title,baseUrl, queryString)
375: self.Destination()._setObject(id,newObj)
376: if RESPONSE is not None:
377: RESPONSE.redirect('manage_main')
378:
379:
380:
1.1 dwinter 381: class zogiLib(Folder):
382: """StandardElement"""
383:
384: meta_type="zogiLib"
1.32 ! dwinter 385: #xxxx
1.1 dwinter 386:
1.18 casties 387: manage_options = Folder.manage_options+(
388: {'label':'Main Config','action':'changeZogiLibForm'},
389: )
1.1 dwinter 390:
1.32 ! dwinter 391: def __init__(self, id, title, digilibBaseUrl,localFileBase, version="book", basePath="", dlTarget=None):
1.1 dwinter 392: """init"""
393:
394: self.id=id
395: self.title=title
1.2 dwinter 396: self.digilibBaseUrl=digilibBaseUrl
1.32 ! dwinter 397:
1.1 dwinter 398: self.localFileBase=localFileBase
1.21 casties 399: self.basePath=basePath
1.18 casties 400: self.layout=version
1.27 casties 401: if dlTarget:
402: self.dlTarget = dlTarget
403: else:
404: self.dlTarget = "digilib"
1.1 dwinter 405:
1.28 casties 406: def version(self):
407: """version information"""
408: return ZOGIVERSION
409:
1.32 ! dwinter 410: def getContextStatic(self):
! 411: """get all the contexts which go to static pages"""
! 412:
! 413:
! 414: dom=xml.dom.minidom.parse(urllib.urlopen(self.getMetaFileName()))
! 415: contexts=dom.getElementsByTagName("context")
! 416:
! 417: ret=[]
! 418: for context in contexts:
! 419: name=getUniqueElementText(context.getElementsByTagName("name"))
! 420:
! 421: link=getUniqueElementText(context.getElementsByTagName("link"))
! 422: if name or link:
! 423: ret.append((name,link))
! 424: return ret
! 425:
! 426: def getContextDatabases(self):
! 427: """get all dynamic contexts"""
! 428: dom=xml.dom.minidom.parse(urllib.urlopen(self.getMetaFileName()))
! 429: contexts=dom.getElementsByTagName("context")
! 430: ret=[]
! 431: for context in contexts:
! 432: metaDataLinks=context.getElementsByTagName("meta-datalink")
! 433: for metaDataLink in metaDataLinks:
! 434: db=metaDataLink.getAttribute("db")
! 435: link=self.REQUEST['URL1']+"/dl_db?db=%s"%db
! 436: if db:
! 437: ret.append((db,link))
! 438: metaDataLinks=context.getElementsByTagName("meta-baselink")
! 439:
! 440: for metaDataLink in metaDataLinks:
! 441: db=metaDataLink.getAttribute("db")
! 442: link=self.REQUEST['URL1']+"/dl_db?db=%s"%db
! 443: if db:
! 444: ret.append((db,link))
! 445:
! 446: return ret
! 447:
! 448: def formatHTML(self,url,label=None,viewUrl=None):
! 449:
! 450:
! 451: sets=xml.dom.minidom.parse(urllib.urlopen(url)).getElementsByTagName('dataset')
! 452: ret=""
! 453: print label
! 454: if label:
! 455: ret+="""<a href="%s">%s</a>"""%(viewUrl,label)
! 456: for set in sets:
! 457: ret+="<table>"
! 458: for node in set.childNodes:
! 459: if hasattr(node,'tagName'):
! 460: tag=node.tagName
! 461: label=node.getAttribute("label")
! 462: if not label:
! 463: label=tag
! 464: text=getText(node.childNodes)
! 465: ret+="""<tr><td><b>%s:</b></td><td>%s</td></tr>"""%(label,text)
! 466: ret+="</table>"
! 467: return ret
! 468:
! 469: def getMetaData(self):
! 470: """getMetaData"""
! 471: dom=xml.dom.minidom.parse(urllib.urlopen(self.getMetaFileName()))
! 472: contexts=dom.getElementsByTagName("context")
! 473: ret=[]
! 474: db=self.getDLParam("db")
! 475: ob=self.getDLParam("object")
! 476:
! 477: fn=self.getDLParam("fn")
! 478: pn=self.getDLParam("pn")
! 479: if not fn:
! 480: fn=""
! 481: if not pn:
! 482: pn=""
! 483: if not ob:
! 484: ob=""
! 485:
! 486: for context in contexts:
! 487: metaDataLinks=context.getElementsByTagName("meta-datalink")
! 488: for metaDataLink in metaDataLinks:
! 489:
! 490: if (db==metaDataLink.getAttribute("db")) or (len(metaDataLinks)==1):
! 491:
! 492: link=getUniqueElementText(metaDataLink.getElementsByTagName("metadata-url"))
! 493: label=getUniqueElementText(metaDataLink.getElementsByTagName("label"))
! 494: url=getUniqueElementText(metaDataLink.getElementsByTagName("url"))
! 495:
! 496: return self.formatHTML(link,label,url)
! 497:
! 498: metaDataLinks=context.getElementsByTagName("meta-baselink")
! 499:
! 500: for metaDataLink in metaDataLinks:
! 501:
! 502: if db==metaDataLink.getAttribute("db") or (len(metaDataLinks)==1):
! 503:
! 504: link=getUniqueElementText(metaDataLink.getElementsByTagName("metadata-url"))
! 505: label=getUniqueElementText(metaDataLink.getElementsByTagName("label"))
! 506: url=getUniqueElementText(metaDataLink.getElementsByTagName("url"))
! 507:
! 508: return self.formatHTML(link+'fn=%s&pn=%s&object=%s'%(fn,pn,ob),label,url)
! 509: return ret
! 510:
1.18 casties 511: def getDLInfo(self):
512: """get DLInfo from digilib server"""
513: paramH={}
514: baseUrl=re.sub("servlet/Scaler","dlInfo-xml.jsp",self.digilibBaseUrl)
515: try:
516: url=urllib.urlopen(baseUrl+self.REQUEST['QUERY_STRING'])
517: dom=xml.dom.minidom.parse(url)
518: params=dom.getElementsByTagName('parameter')
519: for param in params:
520: paramH[param.getAttribute('name')]=param.getAttribute('value')
521: return paramH
522: except:
523: return null
524:
1.1 dwinter 525:
1.18 casties 526: def createHeadJS(self):
1.19 casties 527: """generate all javascript tags for head"""
1.26 casties 528: self.checkQuery()
529: bt = self.REQUEST.SESSION['browserType']
530: if bt['staticHTML']:
531: return
532:
1.18 casties 533: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/zogilib_head_js')).__of__(self)
534: return pt()
1.19 casties 535:
536: def createParamJS(self):
537: """generate javascript for parameters only"""
1.26 casties 538: self.checkQuery()
539: bt = self.REQUEST.SESSION['browserType']
540: if bt['staticHTML']:
541: return
542:
1.19 casties 543: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/zogilib_param_js')).__of__(self)
544: return pt()
545:
1.3 dwinter 546:
1.26 casties 547: def createScalerImg(self, requestString=None, bottom=0, side=0, width=500, height=500):
1.18 casties 548: """generate Scaler IMG Tag"""
1.20 casties 549: self.checkQuery()
550: bt = self.REQUEST.SESSION['browserType']
1.24 casties 551: # override with parameters from session
552: if self.REQUEST.SESSION.has_key('scalerDiv'):
1.26 casties 553: (requestString, bottom, side, width, height) = self.REQUEST.SESSION['scalerDiv']
1.24 casties 554: # if not explicitly defined take normal request
1.18 casties 555: if not requestString:
1.21 casties 556: requestString = self.getAllDLParams()
1.18 casties 557: url = self.digilibBaseUrl+requestString
1.24 casties 558: # construct bottom and side insets
559: b_par = ""
560: s_par = ""
561: if (bottom != 0) or (side != 0):
562: b_par = "-" + str(int(bottom))
563: s_par = "-" + str(int(side))
1.18 casties 564: tag = ""
1.26 casties 565: if bt['staticHTML']:
566: tag += '<div id="scaler"><img id="pic" src="%s&dw=%i&dh=%i" /></div>'%(url, int(width-side), int(height-bottom))
1.18 casties 567: else:
1.26 casties 568: if bt['isN4']:
569: # N4 needs layers
570: tag += '<ilayer id="scaler">'
571: else:
572: tag += '<div id="scaler">'
573: tag += '<script type="text/javascript">'
574: tag += "var ps = bestPicSize(getElement('scaler'));"
575: # write img tag with javascript
576: tag += 'document.write(\'<img id="pic" src="%s&dw=\'+(ps.width%s)+\'&dh=\'+(ps.height%s)+\'" />\');'%(url, s_par, b_par)
577: tag += '</script>'
578: if bt['isN4']:
579: tag += '</ilayer>'
580: else:
581: tag += '</div>'
1.18 casties 582: return tag
1.1 dwinter 583:
1.26 casties 584: def createScalerDiv(self, requestString = None, bottom = 0, side = 0, width=500, height=500):
1.23 casties 585: """generate scaler img and table with navigation arrows"""
586: self.checkQuery()
1.24 casties 587: if requestString != None or bottom != 0 or side != 0:
1.26 casties 588: self.REQUEST.SESSION['scalerDiv'] = (requestString, bottom, side, width, height)
1.24 casties 589: else:
590: if self.REQUEST.SESSION.has_key('scalerDiv'):
1.26 casties 591: # make shure to remove unused parameter
1.24 casties 592: del self.REQUEST.SESSION['scalerDiv']
1.26 casties 593:
1.23 casties 594: pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt/zogilib_img_div')).__of__(self)
595: return pt()
596:
1.18 casties 597: def createAuxDiv(self):
598: """generate other divs"""
1.20 casties 599: self.checkQuery()
600: bt = self.REQUEST.SESSION['browserType']
1.26 casties 601: if bt['staticHTML']:
602: return
603: if bt['isN4']:
1.18 casties 604: f = 'zpt/zogilib_divsN4.zpt'
605: else:
606: f = 'zpt/zogilib_divs.zpt'
607: pt=PageTemplateFile(os.path.join(package_home(globals()),f)).__of__(self)
608: return pt()
1.3 dwinter 609:
1.9 dwinter 610:
1.18 casties 611: def option_js(self):
1.28 casties 612: """javascript"""
613: return sendFile(self, 'js/option.js', 'text/plain')
1.1 dwinter 614:
1.18 casties 615: def dl_lib_js(self):
616: """javascript"""
617: return sendFile(self, 'js/dl_lib.js', 'text/plain')
618:
619: def js_lib_js(self):
620: """javascript"""
621: return sendFile(self, 'js/js_lib.js', 'text/plain')
1.1 dwinter 622:
1.18 casties 623: def optionwindow(self):
624: """showoptions"""
1.26 casties 625: self.checkQuery()
626: bt = self.REQUEST.SESSION['browserType']
627: if bt['staticHTML']:
628: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/optionwindow_static.zpt')).__of__(self)
629: else:
1.31 dwinter 630: finds=self.ZopeFind(self,obj_ids=['viewingTools.zpt'])
631: if finds:
632:
633: return finds[0][1]()
634: else:
635: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/optionwindow.zpt')).__of__(self)
636: return pt()
1.13 casties 637:
638: def mark1(self):
639: """mark image"""
1.18 casties 640: return sendFile(self, 'images/mark1.gif', 'image/gif')
1.13 casties 641:
642: def mark2(self):
643: """mark image"""
1.18 casties 644: return sendFile(self, 'images/mark2.gif', 'image/gif')
1.13 casties 645:
646: def mark3(self):
647: """mark image"""
1.18 casties 648: return sendFile(self, 'images/mark3.gif', 'image/gif')
1.13 casties 649:
650: def mark4(self):
651: """mark image"""
1.18 casties 652: return sendFile(self, 'images/mark4.gif', 'image/gif')
1.13 casties 653:
654: def mark5(self):
655: """mark image"""
1.18 casties 656: return sendFile(self, 'images/mark5.gif', 'image/gif')
1.13 casties 657:
658: def mark6(self):
659: """mark image"""
1.18 casties 660: return sendFile(self, 'images/mark6.gif', 'image/gif')
1.13 casties 661:
662: def mark7(self):
663: """mark image"""
1.18 casties 664: return sendFile(self, 'images/mark7.gif', 'image/gif')
1.13 casties 665:
666: def mark8(self):
667: """mark image"""
1.18 casties 668: return sendFile(self, 'images/mark8.gif', 'image/gif')
1.13 casties 669:
670: def corner1(self):
671: """mark image"""
1.18 casties 672: return sendFile(self, 'images/olinks.gif', 'image/gif')
1.13 casties 673:
674: def corner2(self):
675: """mark image"""
1.18 casties 676: return sendFile(self, 'images/orechts.gif', 'image/gif')
1.13 casties 677:
678: def corner3(self):
679: """mark image"""
1.18 casties 680: return sendFile(self, 'images/ulinks.gif', 'image/gif')
1.13 casties 681:
682: def corner4(self):
683: """mark image"""
1.18 casties 684: return sendFile(self, 'images/urechts.gif', 'image/gif')
1.13 casties 685:
1.22 casties 686: def up_img(self):
687: """mark image"""
688: return sendFile(self, 'images/up.gif', 'image/gif')
689:
690: def down_img(self):
691: """mark image"""
692: return sendFile(self, 'images/down.gif', 'image/gif')
693:
694: def left_img(self):
695: """mark image"""
696: return sendFile(self, 'images/left.gif', 'image/gif')
697:
698: def right_img(self):
699: """mark image"""
700: return sendFile(self, 'images/right.gif', 'image/gif')
1.13 casties 701:
702:
1.1 dwinter 703:
704: def index_html(self):
705: """main action"""
1.26 casties 706: self.checkQuery()
707: bt = self.REQUEST.SESSION['browserType']
1.18 casties 708: tp = "zogiLibMainTemplate"
1.32 ! dwinter 709:
1.18 casties 710: if hasattr(self, tp):
711: pt = getattr(self, tp)
712: else:
1.26 casties 713: tpt = self.layout
1.32 ! dwinter 714:
1.26 casties 715: if bt['staticHTML']:
716: tpt = "static"
717:
718: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/zogiLibMain_%s'%tpt)).__of__(self)
719:
1.18 casties 720: return pt()
721:
1.1 dwinter 722:
723:
1.21 casties 724: def storeQuery(self, more = None):
1.1 dwinter 725: """storeQuery in session"""
1.18 casties 726: dlParams = {}
1.1 dwinter 727: for fm in self.REQUEST.form.keys():
1.18 casties 728: dlParams[fm] = self.REQUEST.form[fm]
1.21 casties 729: # look for more
730: if more:
731: for fm in more.split('&'):
732: try:
733: pv = fm.split('=')
734: dlParams[pv[0]] = pv[1]
735: except:
1.26 casties 736: pass
737:
1.21 casties 738: # parse digilib mode parameter
1.18 casties 739: if 'mo' in dlParams:
740: if len(dlParams['mo']) > 0:
741: modes=dlParams['mo'].split(',')
742: else:
743: modes=[]
744:
745: self.REQUEST.SESSION['query'] = dlParams
746: self.REQUEST.SESSION['dlModes'] = modes
747: self.REQUEST.SESSION['dlInfo'] = self.getDLInfo()
1.26 casties 748: if not self.REQUEST.SESSION.has_key('browserType'):
749: self.REQUEST.SESSION['browserType'] = browserCheck(self)
750:
751: return
1.1 dwinter 752:
1.20 casties 753: def checkQuery(self):
754: """check if the query has been stored"""
1.26 casties 755: if not (self.REQUEST.SESSION and self.REQUEST.SESSION.has_key('query')) :
1.20 casties 756: print "ZOGILIB: have to store query!!"
1.26 casties 757: self.storeQuery()
1.24 casties 758: return
1.23 casties 759:
1.24 casties 760: def zogilibPath(self, otherbase=None):
1.23 casties 761: """returns an URL to the zogiLib instance"""
762: url = self.REQUEST['URL1']
1.24 casties 763: # should end with "/"
764: if len(url) > 0 and url[-1] != '/':
765: url += '/'
766: if type(otherbase) is str:
767: url += otherbase
768: else:
769: url += self.basePath
1.23 casties 770: # should end with "/"
771: if len(url) > 0 and url[-1] != '/':
772: url += '/'
773: return url
1.3 dwinter 774:
1.22 casties 775: def getDLParam(self, param):
1.18 casties 776: """returns parameter"""
1.3 dwinter 777: try:
778: return self.REQUEST.SESSION['query'][param]
779: except:
1.24 casties 780: return
1.3 dwinter 781:
1.18 casties 782: def setDLParam(self, param, value):
783: """sets parameter"""
784: self.REQUEST.SESSION['query'][param] = value
785: return
786:
787: def getAllDLParams(self):
788: """parameter string for digilib"""
789: dlParams = self.REQUEST.SESSION['query']
790: # save modes
791: modes = self.REQUEST.SESSION['dlModes']
792: dlParams['mo'] = string.join(modes, ',')
793: # assemble query string
794: ret = ""
795: for param in dlParams.keys():
1.29 casties 796: if dlParams[param] is None: continue
1.18 casties 797: val = str(dlParams[param])
798: if val != "":
799: ret += param + "=" + val + "&"
1.28 casties 800:
1.18 casties 801: # omit trailing "&"
802: return ret.rstrip('&')
803:
804:
805: def setDLParams(self,pn=None,ws=None,rot=None,brgt=None,cont=None):
806: """setze Parameter"""
807:
1.23 casties 808: self.setDLParam('brgt', brgt)
809: self.setDLParam('cont', cont)
810: self.setDLParam('ws', ws)
811: self.setDLParam('rot', rot)
1.18 casties 812:
813: if pn:
1.21 casties 814: # unmark
815: self.setDLParam('mk', None)
1.18 casties 816: self.setDLParam('pn', pn)
817:
818: return self.display()
819:
820:
821: def display(self):
822: """(re)display page"""
823: params = self.getAllDLParams()
1.21 casties 824: if self.basePath:
825: self.REQUEST.RESPONSE.redirect(self.REQUEST['URL2']+'?'+params)
826: else:
827: self.REQUEST.RESPONSE.redirect(self.REQUEST['URL1']+'?'+params)
1.18 casties 828:
1.32 ! dwinter 829: def getMetaFileName(self):
! 830: urlbase=re.sub('/servlet/Scaler','/dlContext-xml.jsp',self.digilibBaseUrl)
! 831:
! 832:
! 833: return urlbase+self.getAllDLParams()
! 834:
1.26 casties 835:
1.32 ! dwinter 836:
1.30 casties 837: def getDLTarget(self):
838: """returns dlTarget"""
839: self.checkQuery()
840: s = self.dlTarget
841: # s = 'dl'
842: # if self.getDLParam('fn'):
843: # s += "_" + self.getDLParam('fn')
844: # if self.getDLParam('pn'):
845: # s += "_" + self.getDLParam('pn')
846: return s
847:
1.26 casties 848: def setStaticHTML(self, static=True):
849: """sets the preference to static HTML"""
850: self.checkQuery()
851: self.REQUEST.SESSION['browserType']['staticHTML'] = static
852: return
853:
854: def isStaticHTML(self):
855: """returns if the page is using static HTML only"""
856: self.checkQuery()
857: return self.REQUEST.SESSION['browserType']['staticHTML']
858:
1.18 casties 859: def getPT(self):
860: """pagenums"""
861: di = self.REQUEST.SESSION['dlInfo']
862: if di:
863: return int(di['pt'])
864: else:
865: return 1
866:
867: def getPN(self):
868: """Pagenum"""
869: pn = self.getDLParam('pn')
1.25 casties 870: try:
1.18 casties 871: return int(pn)
1.25 casties 872: except:
1.3 dwinter 873: return 1
874:
1.18 casties 875: def getBiggerWS(self):
1.3 dwinter 876: """ws+1"""
1.23 casties 877: ws = self.getDLParam('ws')
1.25 casties 878: try:
1.26 casties 879: return float(ws)+0.5
1.25 casties 880: except:
1.26 casties 881: return 1.5
1.3 dwinter 882:
1.18 casties 883: def getSmallerWS(self):
884: """ws-1"""
885: ws=self.getDLParam('ws')
1.25 casties 886: try:
1.26 casties 887: return max(float(ws)-0.5, 1)
1.25 casties 888: except:
1.3 dwinter 889: return 1
1.1 dwinter 890:
1.18 casties 891: def hasMode(self, mode):
892: """returns if mode is in the diglib mo parameter"""
893: return (mode in self.REQUEST.SESSION['dlModes'])
894:
895: def hasNextPage(self):
896: """returns if there is a next page"""
897: pn = self.getPN()
898: pt = self.getPT()
899: return (pn < pt)
900:
901: def hasPrevPage(self):
902: """returns if there is a previous page"""
903: pn = self.getPN()
904: return (pn > 1)
1.1 dwinter 905:
1.22 casties 906: def canMoveLeft(self):
907: """returns if its possible to move left"""
908: wx = float(self.getDLParam('wx') or 0)
909: return (wx > 0)
910:
911: def canMoveRight(self):
912: """returns if its possible to move right"""
913: wx = float(self.getDLParam('wx') or 0)
914: ww = float(self.getDLParam('ww') or 1)
915: return (wx + ww < 1)
916:
917: def canMoveUp(self):
918: """returns if its possible to move up"""
919: wy = float(self.getDLParam('wy') or 0)
920: return (wy > 0)
921:
922: def canMoveDown(self):
923: """returns if its possible to move down"""
924: wy = float(self.getDLParam('wy') or 0)
925: wh = float(self.getDLParam('wh') or 1)
926: return (wy + wh < 1)
927:
1.26 casties 928:
929: def dl_StaticHTML(self):
930: """set rendering to static HTML"""
931: self.checkQuery()
932: self.REQUEST.SESSION['browserType']['staticHTML'] = True
933: return self.display()
934:
935: def dl_DynamicHTML(self):
936: """set rendering to dynamic HTML"""
937: self.checkQuery()
938: self.REQUEST.SESSION['browserType']['staticHTML'] = False
939: return self.display()
1.1 dwinter 940:
1.18 casties 941: def dl_HMirror(self):
942: """mirror action"""
943: modes = self.REQUEST.SESSION['dlModes']
944: if 'hmir' in modes:
945: modes.remove('hmir')
946: else:
947: modes.append('hmir')
1.1 dwinter 948:
1.18 casties 949: return self.display()
950:
951: def dl_VMirror(self):
952: """mirror action"""
953: modes = self.REQUEST.SESSION['dlModes']
954: if 'vmir' in modes:
955: modes.remove('vmir')
956: else:
957: modes.append('vmir')
1.1 dwinter 958:
1.18 casties 959: return self.display()
1.1 dwinter 960:
1.22 casties 961: def dl_Zoom(self, z):
962: """general zoom action"""
963: ww1 = float(self.getDLParam('ww') or 1)
964: wh1 = float(self.getDLParam('wh') or 1)
965: wx = float(self.getDLParam('wx') or 0)
966: wy = float(self.getDLParam('wy') or 0)
967: ww2 = ww1 * z
968: wh2 = wh1 * z
969: wx += (ww1 - ww2) / 2
970: wy += (wh1 - wh2) / 2
971: ww2 = max(min(ww2, 1), 0)
972: wh2 = max(min(wh2, 1), 0)
973: wx = max(min(wx, 1), 0)
974: wy = max(min(wy, 1), 0)
1.30 casties 975: self.setDLParam('ww', cropf(ww2))
976: self.setDLParam('wh', cropf(wh2))
977: self.setDLParam('wx', cropf(wx))
978: self.setDLParam('wy', cropf(wy))
1.22 casties 979: return self.display()
980:
981: def dl_ZoomIn(self):
982: """zoom in action"""
983: z = 0.7071
984: return self.dl_Zoom(z)
985:
986: def dl_ZoomOut(self):
987: """zoom out action"""
988: z = 1.4142
989: return self.dl_Zoom(z)
990:
991: def dl_Move(self, dx, dy):
992: """general move action"""
993: ww = float(self.getDLParam('ww') or 1)
994: wh = float(self.getDLParam('wh') or 1)
995: wx = float(self.getDLParam('wx') or 0)
996: wy = float(self.getDLParam('wy') or 0)
997: wx += dx * 0.5 * ww
998: wy += dy * 0.5 * wh
999: wx = max(min(wx, 1), 0)
1000: wy = max(min(wy, 1), 0)
1.30 casties 1001: self.setDLParam('wx', cropf(wx))
1002: self.setDLParam('wy', cropf(wy))
1.22 casties 1003: return self.display()
1004:
1005: def dl_MoveLeft(self):
1006: """move left action"""
1007: return self.dl_Move(-1, 0)
1008:
1009: def dl_MoveRight(self):
1010: """move left action"""
1011: return self.dl_Move(1, 0)
1012:
1013: def dl_MoveUp(self):
1014: """move left action"""
1015: return self.dl_Move(0, -1)
1016:
1017: def dl_MoveDown(self):
1018: """move left action"""
1019: return self.dl_Move(0, 1)
1020:
1.18 casties 1021: def dl_WholePage(self):
1022: """zoom out action"""
1023: self.setDLParam('ww', 1)
1024: self.setDLParam('wh', 1)
1025: self.setDLParam('wx', 0)
1026: self.setDLParam('wy', 0)
1027: return self.display()
1028:
1029: def dl_PrevPage(self):
1030: """next page action"""
1031: pn = self.getPN() - 1
1032: if pn < 1:
1033: pn = 1
1034: self.setDLParam('pn', pn)
1035: # unmark
1036: self.setDLParam('mk', None)
1037: return self.display()
1038:
1039: def dl_NextPage(self):
1040: """next page action"""
1041: pn = self.getPN() + 1
1042: pt = self.getPT()
1043: if pn > pt:
1044: pn = pt
1045: self.setDLParam('pn', pn)
1046: # unmark
1047: self.setDLParam('mk', None)
1048: return self.display()
1049:
1050: def dl_FirstPage(self):
1051: """first page action"""
1052: self.setDLParam('pn', 1)
1053: # unmark
1054: self.setDLParam('mk', None)
1055: return self.display()
1056:
1057: def dl_LastPage(self):
1058: """last page action"""
1059: self.setDLParam('pn', self.getPT())
1060: # unmark
1061: self.setDLParam('mk', None)
1062: return self.display()
1063:
1064: def dl_Unmark(self):
1065: """action to remove last mark"""
1066: mk = self.getDLParam('mk')
1067: if mk:
1068: marks = mk.split(',')
1069: marks.pop()
1070: mk = string.join(marks, ',')
1071: self.setDLParam('mk', mk)
1072: return self.display()
1.1 dwinter 1073:
1.32 ! dwinter 1074: def dl_db(self,db):
! 1075: """set db"""
! 1076: self.setDLParam('db',db)
! 1077: self.display()
1.1 dwinter 1078:
1.18 casties 1079: def changeZogiLibForm(self):
1080: """Main configuration"""
1081: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/changeZogiLibForm.zpt')).__of__(self)
1082: return pt()
1.1 dwinter 1083:
1.27 casties 1084: def changeZogiLib(self,title,digilibBaseUrl, localFileBase, version, basePath, dlTarget, RESPONSE=None):
1.18 casties 1085: """change it"""
1086: self.title=title
1087: self.digilibBaseUrl=digilibBaseUrl
1088: self.localFileBase=localFileBase
1.21 casties 1089: self.basePath = basePath
1.18 casties 1090: self.layout=version
1.27 casties 1091: if dlTarget:
1092: self.dlTarget = dlTarget
1093: else:
1094: self.dlTarget = "digilib"
1.3 dwinter 1095:
1.18 casties 1096: if RESPONSE is not None:
1097: RESPONSE.redirect('manage_main')
1.8 dwinter 1098:
1099:
1.1 dwinter 1100: def manage_addZogiLibForm(self):
1101: """interface for adding zogilib"""
1.18 casties 1102: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/addZogiLibForm')).__of__(self)
1.1 dwinter 1103: return pt()
1104:
1.27 casties 1105: def manage_addZogiLib(self,id,title,digilibBaseUrl, localFileBase,version="book",basePath="",dlTarget="digilib",RESPONSE=None):
1.1 dwinter 1106: """add dgilib"""
1.27 casties 1107: newObj=zogiLib(id,title,digilibBaseUrl, localFileBase, version, basePath, dlTarget)
1.1 dwinter 1108: self.Destination()._setObject(id,newObj)
1109: if RESPONSE is not None:
1110: RESPONSE.redirect('manage_main')
1.29 casties 1111:
1112:
1113: class zogiLibPageTemplate(ZopePageTemplate):
1114: """pageTemplate Objekt"""
1115: meta_type="zogiLib_pageTemplate"
1116:
1117:
1118: ## def __init__(self, id, text=None, contentType=None):
1119: ## self.id = str(id)
1120: ## self.ZBindings_edit(self._default_bindings)
1121: ## if text is None:
1122: ## text = open(self._default_cont).read()
1123: ## self.pt_edit(text, contentType)
1124:
1125: def manage_addZogiLibPageTemplateForm(self):
1126: """Form for adding"""
1127: pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/addZogiLibPageTemplateForm')).__of__(self)
1128: return pt()
1129:
1130: def manage_addZogiLibPageTemplate(self, id='zogiLibMainTemplate', title=None, layout=None, text=None,
1131: REQUEST=None, submit=None):
1132: "Add a Page Template with optional file content."
1133:
1134: id = str(id)
1135: self._setObject(id, zogiLibPageTemplate(id))
1136: ob = getattr(self, id)
1137: if not layout: layout = "book"
1138: ob.pt_edit(open(os.path.join(package_home(globals()),'zpt/zogiLibMain_%s.zpt'%layout)).read(),None)
1139: if title:
1140: ob.pt_setTitle(title)
1141: try:
1142: u = self.DestinationURL()
1143: except AttributeError:
1144: u = REQUEST['URL1']
1145:
1146: u = "%s/%s" % (u, urllib.quote(id))
1147: REQUEST.RESPONSE.redirect(u+'/manage_main')
1148: return ''
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>