Diff for /zogiLib/zogiLib.py between versions 1.48 and 1.57

version 1.48, 2004/10/12 16:58:14 version 1.57, 2005/06/09 06:46:12
Line 1 Line 1
   from OFS.SimpleItem import SimpleItem
 from Products.PageTemplates.PageTemplateFile import PageTemplateFile  from Products.PageTemplates.PageTemplateFile import PageTemplateFile
 from Products.PageTemplates.PageTemplate import PageTemplate  from Products.PageTemplates.PageTemplate import PageTemplate
 from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate  from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
 from OFS.Image import Image  from OFS.Image import Image
 from webdav.common import rfc1123_date  from AccessControl import ClassSecurityInfo
   
 import xml.dom.minidom  import xml.dom.minidom
 from OFS.Folder import Folder  from OFS.Folder import Folder
 from xml_helpers import getUniqueElementText,getText  from xml_helpers import getUniqueElementText,getText
Line 11  import os Line 11  import os
 import re  import re
 import string  import string
 import urllib  import urllib
 import types  from types import *
 import random  import random
   import cgi
 from Globals import package_home  from Globals import package_home
   
 ZOGIVERSION = "0.9.10b ROC:12.10.2004"  ZOGIVERSION = "0.9.15b DW:22.2.2005"
   
 def cropf(f):  def cropf(f):
     """returns a float with reduced precision"""      """returns a float with reduced precision"""
Line 48  def browserCheck(self): Line 49  def browserCheck(self):
     bt = {}      bt = {}
     ua = self.REQUEST.get_header("HTTP_USER_AGENT")      ua = self.REQUEST.get_header("HTTP_USER_AGENT")
     bt['ua'] = ua      bt['ua'] = ua
     bt['isIE'] = string.find(ua, 'MSIE') > -1      bt['isIE'] = False
     bt['isN4'] = (string.find(ua, 'Mozilla/4.') > -1) and not bt['isIE']      bt['isN4'] = False
       if string.find(ua, 'MSIE') > -1:
           bt['isIE'] = True
       else:
           bt['isN4'] = (string.find(ua, 'Mozilla/4.') > -1)
           
       try:
     nav = ua[string.find(ua, '('):]      nav = ua[string.find(ua, '('):]
     ie = string.split(nav, "; ")[1]      ie = string.split(nav, "; ")[1]
     if string.find(ie, "MSIE") > -1:      if string.find(ie, "MSIE") > -1:
         bt['versIE'] = string.split(ie, " ")[1]          bt['versIE'] = string.split(ie, " ")[1]
       except: pass
       
     bt['isMac'] = string.find(ua, 'Macintosh') > -1      bt['isMac'] = string.find(ua, 'Macintosh') > -1
     bt['isWin'] = string.find(ua, 'Windows') > -1      bt['isWin'] = string.find(ua, 'Windows') > -1
     bt['isIEWin'] = bt['isIE'] and bt['isWin']      bt['isIEWin'] = bt['isIE'] and bt['isWin']
Line 63  def browserCheck(self): Line 72  def browserCheck(self):
     return bt      return bt
   
           
 class zogiImage(Image):  class zogiImage(SimpleItem):
     """einzelnes Image"""      """einzelnes Image"""
     meta_type="zogiImage"      meta_type="zogiImage"
   
     manage_options=ZopePageTemplate.manage_options+(      manage_options=SimpleItem.manage_options+(
         {'label':'Main config','action':'changeZogiImageForm'},          {'label':'Main config','action':'changeZogiImageForm'},
        )         )
           
Line 85  class zogiImage(Image): Line 94  class zogiImage(Image):
         self.content_type=content_type          self.content_type=content_type
         self.precondition=precondition          self.precondition=precondition
   
     def getData(self):      #def getData(self):
         """getUrlData"""      #    """getUrlData"""
         return urllib.urlopen(self.baseUrl+self.queryString)      #    return urllib.urlopen(self.baseUrl+self.queryString)
   
     def changeZogiImageForm(self):      def changeZogiImageForm(self):
         """Main configuration"""          """Main configuration"""
Line 105  class zogiImage(Image): Line 114  class zogiImage(Image):
   
     def index_html(self, REQUEST, RESPONSE):      def index_html(self, REQUEST, RESPONSE):
         """service the request by redirecting to digilib server"""          """service the request by redirecting to digilib server"""
         print "REDIRECT: ", self.baseUrl+self.queryString  
         RESPONSE.redirect(self.baseUrl+self.queryString)          RESPONSE.redirect(self.baseUrl+self.queryString)
         return ''          return ''
                   
     def index_html2(self, REQUEST, RESPONSE):      def rescale(self,width=None,height=None):
         """          """andere parameter im querystring"""
         Modified version of OFS/Image.py          qs=cgi.parse_qs(self.queryString)
                   for x in qs.keys():
         The default view of the contents of a File or Image.              if type(qs[x]) is ListType:
                   qs[x]=qs[x][0]
         Returns the contents of the file or image.  Also, sets the          
         Content-Type HTTP header to the objects content type.          if width:
         """              qs['dw']=width
           if height:
         # HTTP If-Modified-Since header handling.              qs['dh']=height
         header=REQUEST.get_header('If-Modified-Since', None)  
         if header is not None:          
             header=header.split( ';')[0]          qsneu=urllib.urlencode(qs)
             # Some proxies seem to send invalid date strings for this          self.queryString=qsneu
             # header. If the date string is not valid, we ignore it          return "done"
             # rather than raise an error to be generally consistent  
             # with common servers such as Apache (which can usually  
             # understand the screwy date string as a lucky side effect  
             # of the way they parse it).  
             # This happens to be what RFC2616 tells us to do in the face of an  
             # invalid date.  
             try:    mod_since=long(DateTime(header).timeTime())  
             except: mod_since=None  
             if mod_since is not None:  
                 if self._p_mtime:  
                     last_mod = long(self._p_mtime)  
                 else:  
                     last_mod = long(0)  
                 if last_mod > 0 and last_mod <= mod_since:  
                     # Set header values since apache caching will return Content-Length  
                     # of 0 in response if size is not set here  
                     RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime))  
                     RESPONSE.setHeader('Content-Type', self.content_type)  
                     RESPONSE.setHeader('Content-Length', self.size)  
                     RESPONSE.setHeader('Accept-Ranges', 'bytes')  
                     self.ZCacheable_set(None)  
                     RESPONSE.setStatus(304)  
                     return ''  
   
         if self.precondition and hasattr(self,self.precondition):  
             # Grab whatever precondition was defined and then  
             # execute it.  The precondition will raise an exception  
             # if something violates its terms.  
             c=getattr(self,self.precondition)  
             if hasattr(c,'isDocTemp') and c.isDocTemp:  
                 c(REQUEST['PARENTS'][1],REQUEST)  
             else:  
                 c()  
   
         # HTTP Range header handling  
         range = REQUEST.get_header('Range', None)  
         request_range = REQUEST.get_header('Request-Range', None)  
         if request_range is not None:  
             # Netscape 2 through 4 and MSIE 3 implement a draft version  
             # Later on, we need to serve a different mime-type as well.  
             range = request_range  
         if_range = REQUEST.get_header('If-Range', None)  
         if range is not None:  
             ranges = HTTPRangeSupport.parseRange(range)  
   
             if if_range is not None:  
                 # Only send ranges if the data isn't modified, otherwise send  
                 # the whole object. Support both ETags and Last-Modified dates!  
                 if len(if_range) > 1 and if_range[:2] == 'ts':  
                     # ETag:  
                     if if_range != self.http__etag():  
                         # Modified, so send a normal response. We delete  
                         # the ranges, which causes us to skip to the 200  
                         # response.  
                         ranges = None  
                 else:  
                     # Date  
                     date = if_range.split( ';')[0]  
                     try: mod_since=long(DateTime(date).timeTime())  
                     except: mod_since=None  
                     if mod_since is not None:  
                         if self._p_mtime:  
                             last_mod = long(self._p_mtime)  
                         else:  
                             last_mod = long(0)  
                         if last_mod > mod_since:  
                             # Modified, so send a normal response. We delete  
                             # the ranges, which causes us to skip to the 200  
                             # response.  
                             ranges = None  
   
             if ranges:  
                 # Search for satisfiable ranges.  
                 satisfiable = 0  
                 for start, end in ranges:  
                     if start < self.size:  
                         satisfiable = 1  
                         break  
   
                 if not satisfiable:  
                     RESPONSE.setHeader('Content-Range',  
                         'bytes */%d' % self.size)  
                     RESPONSE.setHeader('Accept-Ranges', 'bytes')  
                     RESPONSE.setHeader('Last-Modified',  
                         rfc1123_date(self._p_mtime))  
                     RESPONSE.setHeader('Content-Type', self.content_type)  
                     RESPONSE.setHeader('Content-Length', self.size)  
                     RESPONSE.setStatus(416)  
                     return ''  
   
                 ranges = HTTPRangeSupport.expandRanges(ranges, self.size)  
                                   
                 if len(ranges) == 1:  
                     # Easy case, set extra header and return partial set.  
                     start, end = ranges[0]  
                     size = end - start  
   
                     RESPONSE.setHeader('Last-Modified',  
                         rfc1123_date(self._p_mtime))  
                     RESPONSE.setHeader('Content-Type', self.content_type)  
                     RESPONSE.setHeader('Content-Length', size)  
                     RESPONSE.setHeader('Accept-Ranges', 'bytes')  
                     RESPONSE.setHeader('Content-Range',  
                         'bytes %d-%d/%d' % (start, end - 1, self.size))  
                     RESPONSE.setStatus(206) # Partial content  
   
                     data = urllib.urlopen(self.baseUrl+self.queryString).read()  
                     if type(data) is StringType:  
                         return data[start:end]  
   
                     # Linked Pdata objects. Urgh.  
                     pos = 0  
                     while data is not None:  
                         l = len(data.data)  
                         pos = pos + l  
                         if pos > start:  
                             # We are within the range  
                             lstart = l - (pos - start)  
   
                             if lstart < 0: lstart = 0  
   
                             # find the endpoint  
                             if end <= pos:  
                                 lend = l - (pos - end)  
   
                                 # Send and end transmission  
                                 RESPONSE.write(data[lstart:lend])  
                                 break  
   
                             # Not yet at the end, transmit what we have.  
                             RESPONSE.write(data[lstart:])  
   
                         data = data.next  
   
                     return ''  
   
                 else:  
                     boundary = choose_boundary()  
   
                     # Calculate the content length  
                     size = (8 + len(boundary) + # End marker length  
                         len(ranges) * (         # Constant lenght per set  
                             49 + len(boundary) + len(self.content_type) +  
                             len('%d' % self.size)))  
                     for start, end in ranges:  
                         # Variable length per set  
                         size = (size + len('%d%d' % (start, end - 1)) +  
                             end - start)  
   
   
                     # Some clients implement an earlier draft of the spec, they  
                     # will only accept x-byteranges.  
                     draftprefix = (request_range is not None) and 'x-' or ''  
   
                     RESPONSE.setHeader('Content-Length', size)  
                     RESPONSE.setHeader('Accept-Ranges', 'bytes')  
                     RESPONSE.setHeader('Last-Modified',  
                         rfc1123_date(self._p_mtime))  
                     RESPONSE.setHeader('Content-Type',  
                         'multipart/%sbyteranges; boundary=%s' % (  
                             draftprefix, boundary))  
                     RESPONSE.setStatus(206) # Partial content  
   
                     data = urllib.urlopen(self.baseUrl+self.queryString).read()  
                     # The Pdata map allows us to jump into the Pdata chain  
                     # arbitrarily during out-of-order range searching.  
                     pdata_map = {}  
                     pdata_map[0] = data  
   
                     for start, end in ranges:  
                         RESPONSE.write('\r\n--%s\r\n' % boundary)  
                         RESPONSE.write('Content-Type: %s\r\n' %  
                             self.content_type)  
                         RESPONSE.write(  
                             'Content-Range: bytes %d-%d/%d\r\n\r\n' % (  
                                 start, end - 1, self.size))  
   
                         if type(data) is StringType:  
                             RESPONSE.write(data[start:end])  
   
                         else:  
                             # Yippee. Linked Pdata objects. The following  
                             # calculations allow us to fast-forward through the  
                             # Pdata chain without a lot of dereferencing if we  
                             # did the work already.  
                             first_size = len(pdata_map[0].data)  
                             if start < first_size:  
                                 closest_pos = 0  
                             else:  
                                 closest_pos = (  
                                     ((start - first_size) >> 16 << 16) +  
                                     first_size)  
                             pos = min(closest_pos, max(pdata_map.keys()))  
                             data = pdata_map[pos]  
   
                             while data is not None:  
                                 l = len(data.data)  
                                 pos = pos + l  
                                 if pos > start:  
                                     # We are within the range  
                                     lstart = l - (pos - start)  
   
                                     if lstart < 0: lstart = 0  
   
                                     # find the endpoint  
                                     if end <= pos:  
                                         lend = l - (pos - end)  
   
                                         # Send and loop to next range  
                                         RESPONSE.write(data[lstart:lend])  
                                         break  
   
                                     # Not yet at the end, transmit what we have.  
                                     RESPONSE.write(data[lstart:])  
   
                                 data = data.next  
                                 # Store a reference to a Pdata chain link so we  
                                 # don't have to deref during this request again.  
                                 pdata_map[pos] = data  
   
                     # Do not keep the link references around.  
                     del pdata_map  
   
                     RESPONSE.write('\r\n--%s--\r\n' % boundary)  
                     return ''  
   
         RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime))  
         RESPONSE.setHeader('Content-Type', self.content_type)  
         RESPONSE.setHeader('Content-Length', self.size)  
         RESPONSE.setHeader('Accept-Ranges', 'bytes')  
   
         # Don't cache the data itself, but provide an opportunity  
         # for a cache manager to set response headers.  
         self.ZCacheable_set(None)  
   
     #return "zogiimage: "+self.baseUrl+self.queryString  
         data=urllib.urlopen(self.baseUrl+self.queryString).read()  
           
         if type(data) is type(''):   
             RESPONSE.setBase(None)  
             return data  
   
         while data is not None:  
             RESPONSE.write(data.data)  
             data=data.next  
   
         return ''  
   
   
 def manage_addZogiImageForm(self):  def manage_addZogiImageForm(self):
     """Form for adding"""      """Form for adding"""
Line 390  def manage_addZogiImage(self,id,title,ba Line 150  def manage_addZogiImage(self,id,title,ba
   
   
 class zogiLib(Folder):  class zogiLib(Folder):
     """StandardElement"""      """digilib frontend with ZOPE"""
   
     meta_type="zogiLib"      meta_type="zogiLib"
     #xxxx      #xxxx
       security=ClassSecurityInfo()
   
     manage_options = Folder.manage_options+(      manage_options = Folder.manage_options+(
             {'label':'Main Config','action':'changeZogiLibForm'},              {'label':'Main Config','action':'changeZogiLibForm'},
Line 414  class zogiLib(Folder): Line 175  class zogiLib(Folder):
         else:          else:
             self.dlToolbarBaseURL = dlServerURL + "/digimage.jsp?"              self.dlToolbarBaseURL = dlServerURL + "/digimage.jsp?"
   
       security.declareProtected('View','getLayout')
       def getLayout(self):
           """get Layout"""
           return self.layout
   
     def version(self):      def version(self):
         """version information"""          """version information"""
Line 537  class zogiLib(Folder): Line 302  class zogiLib(Folder):
         paramH={}          paramH={}
         baseUrl=self.dlServerURL+"/dlInfo-xml.jsp"          baseUrl=self.dlServerURL+"/dlInfo-xml.jsp"
         try:          try:
             print "querying: ", baseUrl+'?'+self.REQUEST['QUERY_STRING']  
             url=urllib.urlopen(baseUrl+'?'+self.REQUEST['QUERY_STRING'])              url=urllib.urlopen(baseUrl+'?'+self.REQUEST['QUERY_STRING'])
             print "  ok, parsing..."  
             dom=xml.dom.minidom.parse(url)              dom=xml.dom.minidom.parse(url)
             print "  ok"  
             params=dom.getElementsByTagName('parameter')              params=dom.getElementsByTagName('parameter')
             for param in params:              for param in params:
                 print "  param: ", param.getAttribute('name'), " = ", param.getAttribute('value')  
                 paramH[param.getAttribute('name')]=param.getAttribute('value')                  paramH[param.getAttribute('name')]=param.getAttribute('value')
             return paramH              return paramH
         except:          except:
Line 631  class zogiLib(Folder): Line 392  class zogiLib(Folder):
         if bt['isN4']:          if bt['isN4']:
             f = 'zpt/zogilib_divsN4.zpt'              f = 'zpt/zogilib_divsN4.zpt'
         else:          else:
             f = 'zpt/zogilib_divs.zpt'              f = 'zpt/zogiLib_divs.zpt'
         pt=PageTemplateFile(os.path.join(package_home(globals()),f)).__of__(self)          pt=PageTemplateFile(os.path.join(package_home(globals()),f)).__of__(self)
         return pt()          return pt()
   
Line 830  class zogiLib(Folder): Line 591  class zogiLib(Folder):
             print "new WID:", wid              print "new WID:", wid
         return wid          return wid
                   
     def getDLParam(self, param):      def getDLParam(self, param, default=None):
         """returns parameter"""          """returns parameter or default"""
         try:          try:
             return self.getSubSession('dlQuery').get(param)              return self.getSubSession('dlQuery').get(param, default)
         except:          except:
             return              return default
   
     def setDLParam(self, param, value):      def setDLParam(self, param, value):
         """sets parameter"""          """sets parameter"""

Removed from v.1.48  
changed lines
  Added in v.1.57


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