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