source: ZMS/trunk/_globals.py @ 1772

Revision 1772, 32.6 KB checked in by zmsdev, 8 weeks ago (diff)

applied minor performance-fixes (5): zms_log

Line 
1################################################################################
2# _globals.py
3#
4# This program is free software; you can redistribute it and/or
5# modify it under the terms of the GNU General Public License
6# as published by the Free Software Foundation; either version 2
7# of the License, or (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program; if not, write to the Free Software
16# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17################################################################################
18
19# Imports.
20from App.Common import package_home
21from DateTime.DateTime import DateTime
22from httplib import HTTP
23from types import StringTypes
24from traceback import format_exception
25try: # >= Zope-2.10
26  from zope.contenttype import guess_content_type
27except: # < Zope-2.10
28  from zope.app.content_types import guess_content_type
29import cgi
30import copy
31import fnmatch
32import logging
33import operator
34import os
35import re
36import sys
37import time
38import urllib
39import zExceptions
40
41
42""" Globals. """
43
44# Datatypes.
45DT_UNKNOWN = 0
46DT_BOOLEAN = 1
47DT_DATE = 2
48DT_DATETIME = 3
49DT_DICT = 4
50DT_FILE = 5
51DT_FLOAT = 6
52DT_IMAGE = 7
53DT_INT = 8
54DT_LIST = 9
55DT_PASSWORD = 10
56DT_STRING = 11
57DT_TEXT = 12
58DT_TIME = 13
59DT_URL = 14
60DT_ID = 15
61DT_XML = 16
62DT_AMOUNT = 17
63DT_COLOR = 18
64DT_TEXTS = [ DT_STRING, DT_TEXT ]
65DT_STRINGS = [ DT_STRING, DT_TEXT, DT_URL, DT_PASSWORD, DT_XML, DT_COLOR ]
66DT_BLOBS = [ DT_IMAGE, DT_FILE ]
67DT_INTS = [ DT_INT, DT_BOOLEAN ]
68DT_NUMBERS = [ DT_INT, DT_FLOAT, DT_AMOUNT ]
69DT_DATETIMES = [ DT_DATE, DT_TIME, DT_DATETIME ]
70
71dtMapping = [
72  [ 'unknown',''],
73  [ 'boolean',0],
74  [ 'date',None],
75  [ 'datetime',None],
76  [ 'dictionary',{}],
77  [ 'file',None],
78  [ 'float',0.0],
79  [ 'image',None],
80  [ 'int',0],
81  [ 'list',[]],
82  [ 'password',''],
83  [ 'string',''],
84  [ 'text',''],
85  [ 'time',None],
86  [ 'url',''],
87  [ 'identifier',''],
88  [ 'xml',''],
89  [ 'amount',0.0],
90  [ 'color',''],
91]
92
93"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
94German umlaute.
95"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
96umlautMapping = {
97        unicode('\xe4','latin-1').encode('utf-8'):'ae',
98        unicode('\xf6','latin-1').encode('utf-8'):'oe',
99        unicode('\xfc','latin-1').encode('utf-8'):'ue',
100        unicode('\xc4','latin-1').encode('utf-8'):'Ae',
101        unicode('\xd6','latin-1').encode('utf-8'):'Oe',
102        unicode('\xdc','latin-1').encode('utf-8'):'Ue',
103        unicode('\xdf','latin-1').encode('utf-8'):'ss',
104}
105
106
107"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
108_globals.umlaut_quote:
109"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
110def umlaut_quote(s, mapping={}):
111  map( lambda x: operator.setitem( mapping, x, umlautMapping[x]), umlautMapping.keys())
112  for key in mapping.keys():
113    s = s.replace(key,mapping[key])
114  return s
115
116
117"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
118_globals.datatype_key:
119"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
120def datatype_key(datatype):
121  for dtIndex in range(len(dtMapping)):
122    if dtMapping[dtIndex][0] == datatype:
123      return dtIndex
124  else:
125    return DT_UNKNOWN
126
127
128"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
129_globals.url_encode:
130
131All unsafe characters must always be encoded within a URL.
132@see: http://www.ietf.org/rfc/rfc1738.txt
133"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
134def url_encode(url):
135  for ch in ['[',']',' ','(',')']:
136    url = url.replace(ch,'%'+bin2hex(ch).upper())
137  return url
138
139"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
140_globals.guess_contenttype:
141"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
142def guess_contenttype(filename, data):
143  mt, enc  = guess_content_type( filename, data)
144  return mt, enc
145
146"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
147_globals.format_sort_id:
148"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
149def format_sort_id(i_sort_id):
150  sort_id = '0000%i'%i_sort_id
151  sort_id = 's' + sort_id[-4:]
152  return sort_id
153
154
155"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
156_globals.html_quote:
157"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
158def html_quote(v, name='(Unknown name)', md={}):
159  return cgi.escape(str(v), 1)
160
161
162"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
163_globals.bin2hex:
164"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
165def bin2hex(m):
166  return ''.join(map(lambda x: hex(ord(x)/16)[-1]+hex(ord(x)%16)[-1],m))
167
168
169"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
170_globals.hex2bin:
171"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
172def hex2bin(m):
173  return ''.join(map(lambda x: chr(16*int('0x%s'%m[x*2],0)+int('0x%s'%m[x*2+1],0)),range(len(m)/2)))
174
175
176"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
177_globals.unencode:
178
179Unencodes given parameter.
180"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
181def unencode( p, enc='utf-8'):
182  if type( p) is dict:
183    for key in p.keys():
184      if type( p[ key]) is unicode:
185        p[ key] = p[ key].encode( enc)
186  elif type( p) is list:
187    l = []
188    for i in p:
189      if type( i) is unicode:
190        l.append( i.encode( enc))
191      else:
192        l.append( i)
193    p = l
194  elif type( p) is unicode:
195    p = p.encode( enc)
196  return p
197
198
199"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
200_globals.id_quote:
201"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
202def id_quote(s, mapping={
203                '\x20':'_',
204                '-':'_',
205                '/':'_',
206}):
207  s = umlaut_quote(s,mapping)
208  valid = map( lambda x: ord(x[0]), mapping.values()) + [ord('_')] + range(ord('0'),ord('9')+1) + range(ord('A'),ord('Z')+1) + range(ord('a'),ord('z')+1)
209  s = filter( lambda x: ord(x) in valid, s)
210  while len(s) > 0 and s[0] == '_':
211    s = s[1:]
212  s = s.lower()
213  return s
214
215
216"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
217_globals.strip_int:
218
219Strips numeric part from string.
220"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
221def strip_int(s):
222  i = 0
223  while i < len(s) and ord(s[i]) in range(ord('0'),ord('9')+1):
224    i = i + 1
225  return i
226
227
228"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
229_globals.id_prefix:
230
231Strips non-numeric part from string.
232"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
233def id_prefix(s):
234  i = len(s)
235  while i > 0 and ord(s[i-1]) in range(ord('0'),ord('9')+1):
236    i = i - 1
237  return s[:i]
238
239
240"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
241_globals.map_key_vals:
242
243Maps list of keys and list of values to new dictionary.
244"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
245def map_key_vals(keys, vals):
246  d = {}
247  map(operator.setitem, [d]*len(keys), keys, vals)
248  return d
249
250
251"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
252_globals.objectTree:
253"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
254def objectTree(self, clients=False):
255  rtn = [ self]
256  try:
257    for ob in self.objectValues( self.dGlobalAttrs.keys()):
258      rtn.extend( objectTree( ob))
259  except:
260    writeError( self, '[objectTree]')
261  if clients:
262    for ob in self.getPortalClients():
263      rtn.extend( objectTree( ob, clients))
264  return rtn
265
266
267"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
268_globals.dt_html:
269
270Process dtml.
271"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
272def dt_html(self, value, REQUEST):
273  import DocumentTemplate.DT_HTML
274  i = 0
275  while True:
276    i = value.find( '<dtml-', i)
277    if i < 0:
278      break
279    j = value.find( '>', i)
280    if j < 0:
281      break
282    if value[ j-1] == '/':
283      value = value[ :j-1] + value[ j:]
284    i = j
285  value = re.sub( '</dtml-var>', '', value)
286  dtml = DocumentTemplate.DT_HTML.HTML(value)
287  value = dtml( self, REQUEST)
288  return value
289
290
291"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
292_globals.dt_parse:
293
294Parse and validate dtml.
295"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
296def dt_parse(self, value):
297  message = ''
298  try:
299    import DocumentTemplate.DT_HTML
300    dtml = DocumentTemplate.DT_HTML.HTML(value)
301    dtml.cook()
302  except:
303    writeError( self, '[dt_parse]')
304    message += str(sys.exc_value)
305  return message
306
307
308"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
309_globals.form_quote
310
311Remove <form>-tags for Management Interface.
312"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
313def form_quote(text, REQUEST):
314  rtn = text
315  if isManagementInterface(REQUEST):
316    rtn = re.sub( '<form(.*?)>', '<noform\\1>', rtn)
317    rtn = re.sub( ' name="lang"', ' name="_lang"', rtn)
318    rtn = re.sub( '</form(.*?)>', '</noform\\1>', rtn)
319  return rtn
320
321 
322"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
323_globals.qs_append:
324
325Append to Query-String.
326"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
327def qs_append(qs, p, v):
328  if len(qs) == 0:
329    qs += '?'
330  else:
331    qs += '&amp;'
332  qs += p + '=' + urllib.quote(v)
333  return qs
334
335
336"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
337_globals.nvl:
338"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
339def nvl(a1, a2, n=None):
340  """
341  Returns its first argument if it is not equal to third argument (None),
342  otherwise it returns its second argument.
343  @param a1: 1st argument
344  @type a1: C{any}
345  @param a2: 2nd argument
346  @type a2: C{any}
347  @rtype: C{any}
348  """
349  if (n is None and a1 is not None) or (type(n) is str and a1 != n) or (type(n) is list and a1 not in n):
350    return a1
351  else:
352    return a2
353
354
355"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
356_globals.get_session:
357"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
358def get_session(self):
359  return getattr(self, 'session_data_manager', None) and \
360    self.session_data_manager.getSessionData(create=0)
361
362
363"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
364_globals.triggerEvent:
365
366Hook for trigger of custom event (if there is one)
367"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
368def triggerEvent(self, name, preview=False, REQUEST=None):
369  l = []
370  if preview:
371    if REQUEST is not None:
372      try: REQUEST.set('preview','preview')
373      except: REQUEST['preview'] = 'preview'
374  metaObj = self.getMetaobj( self.meta_id)
375  if metaObj:
376    metaObjAttr = self.getMetaobjAttr( self.meta_id, name)
377    if metaObjAttr is not None:
378      v = self.getObjProperty(name,REQUEST)
379      l.append( v)
380    ob = self
381    ob_ids = []
382    while ob is not None:
383      for ob_id in ob.getHome().objectIds():
384        if ob_id not in ob_ids and ob_id.find( name) == 0:
385          v = getattr(self,ob_id)(context=self,REQUEST=REQUEST)
386          l.append( v)
387          ob_ids.append(ob_id)
388      ob = ob.getPortalMaster()
389  return l
390
391
392"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
393_globals.isManagementInterface
394
395Returns true if current context is management-interface, false else.
396"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
397def isManagementInterface(REQUEST):
398  return REQUEST is not None and \
399         REQUEST.get('URL','').find('/manage') >= 0 and \
400         isPreviewRequest(REQUEST)
401     
402
403"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
404_globals.isPreviewRequest:
405
406Returns true if current context is preview-request, false else.
407"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
408def isPreviewRequest(REQUEST):
409  return REQUEST is not None and \
410         REQUEST.get('preview','') == 'preview'
411
412
413"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
414_globals.getPageWithElements:
415"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
416def getPageWithElements(self, REQUEST):
417  obs = self.getChildNodes(REQUEST)
418  for ob in obs:
419    if ob.isVisible(REQUEST):
420      if ob.isPageElement():
421        return self
422      elif ob.isPage():
423        return getPageWithElements(ob,REQUEST)
424  return self
425
426
427
428"""
429################################################################################
430#
431#  Http
432#
433################################################################################
434"""
435
436"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
437_globals.unescape:
438"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
439def unescape(s):
440  while True:
441    i = s.find('%')
442    if i < 0: break
443    if s[i+1] == 'u':
444      old = s[i:i+6]
445      if old == '%u21B5':
446        new = '&crarr;'
447      else:
448        new = ''
449    else:
450      old = s[i:i+3]
451      new = chr(int('0x'+s[i+1:i+3],0))
452    s = s.replace(old,new)
453  return s
454
455
456"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
457_globals.authtobasic:
458
459Basic Authentication
460"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
461def authtobasic(auth, h):
462 """Converts basic auth data into an HTTP header."""
463 import base64
464 if auth is not None:
465   userpass = auth['username']+':'+auth['password']
466   userpass = base64.encodestring(urllib.unquote(userpass)).strip()
467   h.putheader('Authorization', 'Basic '+userpass)
468
469
470"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
471_globals.http_import:
472"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
473def http_import(self, url, method='GET', auth=None, parse_qs=0, timeout=5):
474 
475  HTTP_PREFIX = 'http://'
476 
477  # Get Query-String.
478  qs = ''
479  i = url.find('?')
480  if i > 0:
481    qs = url[i+1:]
482    url = url[:i]
483 
484  # Get Host.
485  host = ''
486  servername = url
487  if servername.startswith(HTTP_PREFIX):
488    servername = servername[len(HTTP_PREFIX):]
489  if servername.find('/') > 0:
490    servername = servername[:servername.find('/')]
491  useproxy = True
492  noproxy = ['localhost','127.0.0.1']+filter(lambda x: len(x)>0,map(lambda x: x.strip(),self.getConfProperty('HTTP.noproxy','').split(',')))
493  for noproxyurl in noproxy:
494    if fnmatch.fnmatch(servername,noproxyurl):
495      useproxy = False
496      break
497  if useproxy:
498    host = self.getConfProperty('HTTP.proxy',host)
499 
500  if len( host) == 0:
501    # Remove HTTP-Prefix.
502    if url.startswith( HTTP_PREFIX):
503      url = url[ len( HTTP_PREFIX):]
504     
505    i = url.find('/')
506    if i > 0:
507      host = url[:i]
508      url = url[i:]
509    else:
510      host = url
511      url = '/'
512
513  # Get Port.
514  i = host.find(':',max(0,host.find('@')))
515  port = 80
516  if i > 0:
517    port = int(host[i+1:])
518    host = host[:i]
519 
520  # Open HTTP connection.
521  writeLog( self, "[http_import.%s]: %s:%i --> %s?%s"%(method,host,port,url,qs))
522  req = HTTP(host,port)
523 
524  # Set request-headers.
525  if method.upper() == 'GET':
526    if len( qs) > 0:
527      qs = '?' + qs
528    req.putrequest( method, url + qs)
529    req.putheader('Host', host)
530    authtobasic(auth,req)
531    req.putheader('Accept', '*/*')
532    req.endheaders()
533  elif method.upper() == 'POST':
534    req.putrequest(method,url)
535    req.putheader('Host', host)
536    authtobasic(auth,req)
537    req.putheader('Accept', '*/*')
538    req.putheader('Content-type', 'application/x-www-form-urlencoded')
539    req.putheader('Content-length', '%d' % len(qs))
540    req.endheaders()
541    # Send query string
542    req.send(qs)
543 
544  # Send request.
545  reply_code, message, headers = req.getreply()
546 
547  #### get parameter from content
548  if reply_code == 404 or reply_code >= 500:
549    error = "[%i]: %s at %s [%s]"%(reply_code,message,url,method)
550    writeLog( self, "[http_import.error]: %s"%error)
551    raise zExceptions.InternalError(error)
552  elif reply_code==200:
553    # get content
554    f = req.getfile()
555    content = f.read()
556    f.close()
557    rtn = None
558    if parse_qs:
559      try:
560        # return dictionary of value lists
561        rtn = cgi.parse_qs(content, keep_blank_values=1, strict_parsing=1)
562      except:
563        # return string
564        rtn = content
565    else:
566      # return string
567      rtn = content
568      if port != 80:
569        rtn = rtn.replace( '%s%s/'%(HTTP_PREFIX,host), '%s%s:%i/'%(HTTP_PREFIX,host,port))
570    return rtn
571  else:
572    result = '['+str(reply_code)+']: '+str(message)
573    writeLog( self, "[http_import.result]: %s"%result)
574    return result
575
576
577"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
578_globals.get_size:
579"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
580def get_size(v):
581  size = 0
582  if v is not None:
583    if type(v) in StringTypes:
584      size = size + len(v)
585    elif type(v) is list:
586      size = sum( map( lambda x: get_size(x), v))
587    elif type(v) is dict:
588      size = sum( map( lambda x: get_size(x) + get_size(v[x]), v.keys()))
589    elif type(v) is int or type(v) is float:
590      size = size + 4
591    elif hasattr(v,'get_real_size') and callable(getattr(v,'get_real_size')):
592      try:
593        size = size + v.get_real_size()
594      except:
595        pass
596    elif hasattr(v,'get_size') and callable(getattr(v,'get_size')):
597      try:
598        size = size + v.get_size()
599      except:
600        pass
601  return size
602
603
604"""
605################################################################################
606#
607#  Logging
608#
609################################################################################
610"""
611
612"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
613_globals.debug:
614"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
615def debug(self):
616  b = False
617  try:
618    zms_log = self.zms_log
619    severity = logging.DEBUG
620    b = zms_log.hasSeverity(severity)
621  except:
622    pass
623  return b
624
625"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
626_globals.writeLog:
627"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
628def writeLog(self, info):
629  try:
630    zms_log = self.zms_log
631    severity = logging.DEBUG
632    if zms_log.hasSeverity(severity):
633      info = "[%s@%s]"%(self.meta_id,self.absolute_url()[len(self.REQUEST['SERVER_URL']):]) + info
634      zms_log.LOG( severity, info)
635  except:
636    pass
637
638"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
639_globals.writeBlock:
640"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
641def writeBlock(self, info):
642  try:
643    zms_log = self.zms_log
644    severity = logging.INFO
645    if zms_log.hasSeverity(severity):
646      info = "[%s@%s]"%(self.meta_id,self.absolute_url()[len(self.REQUEST['SERVER_URL']):]) + info
647      zms_log.LOG( severity, info)
648  except:
649    pass
650
651"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
652_globals.writeError:
653"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
654def writeError(self, info):
655  try:
656    t,v,tb = sys.exc_info()
657    v = str(v)
658    # Strip HTML tags from the error value
659    for pattern in [r"<[^<>]*>", r"&[A-Za-z]+;"]:
660      v = re_sub(self, pattern,' ', v)
661    if info:
662      info += '\n'
663    severity = logging.ERROR
664    info += ''.join(format_exception(t, v, tb))
665    info = "[%s@%s]"%(self.meta_id,self.absolute_url()[len(self.REQUEST['SERVER_URL']):]) + info
666    zms_log = self.zms_log
667    if zms_log.hasSeverity(severity):
668      zms_log.LOG( severity, info)
669  except:
670    pass
671  return info
672
673"""
674################################################################################
675#
676#( Regular Expressions
677#
678################################################################################
679"""
680
681"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
682_globals.re_sub:
683"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
684def re_sub( self, pattern, replacement, subject, ignorecase=False):
685  """
686  Performs a search-and-replace across subject, replacing all matches of
687  regex in subject with replacement. The result is returned by the sub()
688  function. The subject string you pass is not modified.
689  @rtype: C{string}
690  """
691  if ignorecase:
692    return re.compile( pattern, re.IGNORECASE).sub( replacement, subject)
693  else:
694    return re.compile( pattern).sub( replacement, subject)
695
696"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
697_globals.re_search:
698"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
699def re_search( self, pattern, subject, ignorecase=False):
700  """
701  Scan through string looking for a location where the regular expression
702  pattern produces a match, and return a corresponding MatchObject
703  instance. Return None if no position in the string matches the pattern;
704  note that this is different from finding a zero-length match at some
705  point in the string.
706  """
707  if ignorecase:
708    s = re.compile( pattern, re.IGNORECASE).split( subject)
709  else:
710    s = re.compile( pattern).split( subject)
711  return map( lambda x: s[x*2+1], range(len(s)/2))
712
713#)
714
715
716"""
717################################################################################
718#
719#{ DateTime
720#
721################################################################################
722"""
723
724"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
725Index  Field  Values 
7260  year (for example, 1993)
7271  month range [1,12]
7282  day range [1,31]
7293  hour range [0,23]
7304  minute range [0,59]
7315  second range [0,61]; see (1) in strftime() description
7326  weekday range [0,6], Monday is 0
7337  Julian day range [1,366]
7348  daylight savings flag 0, 1 or -1; see below
735"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
736
737"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
738_globals.getDateTime:
739
740Bei Python 2.2 ist der Typ der Objekte des Moduls "time" nicht
741mehr "tuple", sondern "time.struct_time". Es verhaelt sich aber weiterhin
742abwaertskompatibel zu einem tuple.
743This is no problem for Zope since Zope uses its own, more flexible, type
744DateTime. Nevertheless ZMS relies on the datatype "tuple" as DateTime has
745the limitation that no date prior to 1970-01-01 can be used!
746"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
747def getDateTime(t):
748  if t is not None:
749    try:
750      if isinstance( t, DateTime):
751        f = '%Y/%m/%d %H:%M:%S'
752        st = str(t)
753        if st.rfind(' ')>0:
754          st = st[:st.rfind(' ')]
755        else:
756          f = f[:f.rfind(' ')]
757        if st.rfind('.')>0:
758          st = st[:st.rfind('.')]
759        t = time.strptime( st, f)
760      if type(t) is tuple:
761        t = time.mktime( t)
762      if type(t) is not time.struct_time:
763        t = time.localtime( t)
764    except:
765      pass
766  return t
767
768"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
769_globals.stripDateTime:
770
771Strips time portion from date-time and returns date.
772"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
773def stripDateTime(t):
774  d = None
775  if t is not None:
776    t = getDateTime(t)
777    d = (t[0],t[1],t[2],0,0,0,t[6],t[7],t[8])
778  return d
779
780"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
781_globals.daysBetween:
782"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
783def daysBetween(t0, t1):
784  t0 = time.mktime(stripDateTime(getDateTime(t0)))
785  t1 = time.mktime(stripDateTime(getDateTime(t1)))
786  d = 24.0*60.0*60.0
787  return int((t1-t0)/d)
788
789"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
790_globals.compareDate:
791
792Compares two dates and returns result.
793 +1: t0 < t1
794  0: t0 == t1
795 -1: t0 > t1
796"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
797def compareDate(t0, t1):
798  mt0 = time.mktime(stripDateTime(getDateTime(t0)))
799  mt1 = time.mktime(stripDateTime(getDateTime(t1)))
800  if mt1 > mt0:
801    return +1
802  elif mt1 < mt0:
803    return -1
804  else:
805    return 0
806
807"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
808_globals.parseLangFmtDate:
809"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
810def parseLangFmtDate(s):
811  value = None
812  for fmt in ['%d.%m.%Y %H:%M:%S','%Y/%m/%d %H:%M:%S','%Y-%m-%d %H:%M:%S','%H:%M:%S']:
813    if value is None:
814      try:
815        if isinstance(s,DateTime):
816          s = s.strftime( fmt)
817        if s is not None and len(str(s)) > 0:
818          dctTime = {'Y':0,'m':0,'d':0,'H':0,'M':0,'S':0}
819          v = str(s)
820          while True:
821            i = fmt.find('%')+1
822            if i == 0:
823              break
824            dirkey = fmt[i]
825            fmt = fmt[i+1:]
826            j = strip_int(v)
827            if j == 0:
828              break
829            dirval = int(v[:j])
830            v = v[j:]
831            dctTime[dirkey] = dirval
832            if len(v) == 0:
833              break
834            if fmt[0] != v[0]:
835              raise zExceptions.InternalError
836            fmt = fmt[1:]
837            v = v[1:]
838          if dctTime['Y'] + dctTime['m'] + dctTime['d'] == 0:
839            dctTime['Y'] = 1980
840            dctTime['m'] = 1
841            dctTime['d'] = 1
842          if dctTime['Y'] in range( 0, 50):
843            dctTime['Y'] = dctTime['Y'] + 2000
844          if dctTime['Y'] in range( 50, 100):
845            dctTime['Y'] = dctTime['Y'] + 1900
846          if len(v.strip())>0 or \
847             (dctTime['Y']+dctTime['m']+dctTime['d']!=0 and dctTime['Y']-1 not in range(1900,2100)) or \
848             (dctTime['Y']+dctTime['m']+dctTime['d']!=0 and dctTime['m']-1 not in range(12)) or \
849             (dctTime['Y']+dctTime['m']+dctTime['d']!=0 and dctTime['d']-1 not in range(31)) or \
850             (dctTime['H']!=0 and dctTime['H']-1 not in range(24)) or \
851             (dctTime['M']!=0 and dctTime['M']-1 not in range(60)) or \
852             (dctTime['S']!=0 and dctTime['S']-1 not in range(60)):
853            raise zExceptions.InternalError
854          value = getDateTime((dctTime['Y'],dctTime['m'],dctTime['d'],dctTime['H'],dctTime['M'],dctTime['S'],0,1,-1))
855      except:
856        pass
857  return value
858
859#)
860
861
862################################################################################
863# Define the initialize() util.
864################################################################################
865class initutil:
866
867  def __init__(self):
868    self.__attr_conf_dict__ = {}
869
870  def setConfProperty(self, key, value):
871    self.__attr_conf_dict__[key] = value
872
873  def getConfProperty(self, key, default=None):
874    return self.__attr_conf_dict__.get(key,default)
875
876  def import_instance_home(self, this, url):
877    path = this.Control_Panel.getINSTANCE_HOME()+'/etc/zms/'+url
878    mode = 'b'
879    if os.path.exists(path):
880      f = None
881      try:
882        f = open( path, 'r'+mode)
883        data = f.read()
884      finally:
885        if f is not None:
886          f.close()
887      return data
888    return None
889
890  def http_import(self, url, method='GET', auth=None, parse_qs=0):
891    return http_import( self, url, method, auth, parse_qs)
892
893  def re_sub( self, pattern, replacement, subject, ignorecase=False):
894    return re_sub( self, pattern, replacement, subject, ignorecase=False)
895
896  def re_search( self, pattern, subject, ignorecase=False):
897    return re_search( self, pattern, subject, ignorecase)
898
899
900################################################################################
901# Define MyClass.
902################################################################################
903class MyClass:
904
905  # ----------------------------------------------------------------------------
906  #  MyClass.keys:
907  # ----------------------------------------------------------------------------
908  def keys(self):
909    return self.__dict__.keys()
910
911
912################################################################################
913# Define MySectionizer.
914################################################################################
915class MySectionizer:
916
917    # --------------------------------------------------------------------------
918    #  MySectionizer.__init__:
919    #
920    #  Constructor.
921    # --------------------------------------------------------------------------
922    def __init__(self, levelnfc='0'):
923      self.levelnfc = levelnfc
924      self.sections = []
925
926    # --------------------------------------------------------------------------
927    #  MySectionizer.__str__:
928    #
929    #  Returns a string representation of the object.
930    # --------------------------------------------------------------------------
931    def __str__(self):
932      s = ''
933      for i in range(len(self.sections)):
934        if self.levelnfc == '0':
935          s += str(self.sections[i]) + '.'
936        elif self.levelnfc == '1':
937          s += chr(self.sections[i] - 1 + ord('A')) + '.'
938        elif self.levelnfc == '2':
939          s += chr(self.sections[i] - 1 + ord('a')) + '.'
940      return s
941
942    # --------------------------------------------------------------------------
943    #  MySectionizer.clone:
944    #
945    #  Creates and returns a copy of this object.
946    # --------------------------------------------------------------------------
947    def clone(self):
948      ob = MySectionizer(self.levelnfc)
949      ob.sections = copy.deepcopy(self.sections)
950      return ob
951
952    # --------------------------------------------------------------------------
953    #  MySectionizer.getLevel:
954    # --------------------------------------------------------------------------
955    def getLevel(self):
956      return len(self.sections)
957
958    # --------------------------------------------------------------------------
959    #  MySectionizer.processLevel:
960    # --------------------------------------------------------------------------
961    def processLevel(self, level):
962      # Increase section counter on this level.
963      if level > 0:
964        if level == len(self.sections):
965          self.sections[level-1] = self.sections[level-1] + 1
966        elif level > len(self.sections):
967          for i in range(len(self.sections),level):
968            self.sections.append(1)
969        elif level < len(self.sections):
970          for i in range(level,len(self.sections)):
971            del self.sections[len(self.sections)-1]
972          self.sections[level-1] = self.sections[level-1] + 1
973
974
975################################################################################
976# Define MyStack.
977################################################################################
978class MyStack:
979
980    # --------------------------------------------------------------------------
981    #  MyStack.__init__:
982    #
983    #  Constructor.
984    # --------------------------------------------------------------------------
985    def __init__(self):
986      self.clear()
987       
988    # --------------------------------------------------------------------------
989    #  MyStack.__str__:
990    #
991    #  Returns a string representation of the object.
992    # --------------------------------------------------------------------------
993    def __str__(self):
994      s = ''
995      for el in self._stack:
996        s += str(el) + ';'
997      return s[:-1]
998
999    def size(self):
1000      return len(self._stack)
1001
1002    def clear(self):
1003      self._stack = []
1004
1005    def push(self, x):
1006      self._stack.append(x)
1007
1008    def pop(self):
1009      if len(self._stack) > 0:
1010        return self._stack.pop()
1011      else:
1012        return None
1013
1014    def get(self, i=0):
1015      if len(self._stack) > 0 and abs(i) < len(self._stack):
1016        if i < 0:
1017          return self._stack[len(self._stack)+i-1]
1018        else:
1019          return self._stack[i]
1020      else:
1021        return None
1022
1023    def top(self):
1024      if len(self._stack) > 0:
1025        return self._stack[len(self._stack)-1]
1026      else:
1027        return None
1028
1029################################################################################
Note: See TracBrowser for help on using the repository browser.