-
Notifications
You must be signed in to change notification settings - Fork 0
/
standard.py
2156 lines (1948 loc) · 61.5 KB
/
standard.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
# standard.py
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
################################################################################
"""ZMS standard utility module
This module provides helpful functions and classes for use in Python
Scripts. It can be accessed from Python with the statement
"import Products.zms.standard"
"""
# Imports.
from AccessControl.SecurityInfo import ModuleSecurityInfo
from AccessControl import AuthEncoding
from App.Common import package_home
from App.config import getConfiguration
from DateTime.DateTime import DateTime
from OFS.CopySupport import absattr
from cStringIO import StringIO
from traceback import format_exception
from zope.event import notify
from zope.lifecycleevent import ObjectModifiedEvent
import base64
import cgi
import copy
import fnmatch
import inspect
import logging
import operator
import os
import re
import sys
import time
import urllib
import zExceptions
# Product Imports.
import _globals
import _fileutil
import _mimetypes
import _xmllib
security = ModuleSecurityInfo('Products.zms.standard')
"""
@group PIL (Python Imaging Library): pil_img_*
@group Local File-System: localfs_*
@group Logging: writeBlock, writeLog
@group Mappings: *_list
@group Operators: operator_*
@group Styles / CSS: parse_stylesheet, get_colormap
@group Regular Expressions: re_*
@group: XML: getXmlHeader, toXmlString, parseXmlString, xslProcess, processData, xmlParse, xmlNodeSet
"""
security.declarePublic('getPRODUCT_HOME')
def getPRODUCT_HOME():
"""
Returns home-folder of this Product.
@rtype: C{str}
"""
PRODUCT_HOME = os.path.dirname(os.path.abspath(__file__))
return PRODUCT_HOME
security.declarePublic('getPACKAGE_HOME')
def getPACKAGE_HOME():
"""
Returns path to lib/site-packages.
@rtype: C{str}
"""
from distutils.sysconfig import get_python_lib
return get_python_lib()
security.declarePublic('getINSTANCE_HOME')
def getINSTANCE_HOME():
"""
Returns path to Instance
@rtype: C{str}
"""
return getConfiguration().instancehome
security.declarePublic('FileFromData')
def FileFromData( context, data, filename='', content_type=None):
"""
Creates a new instance of a file from given data.
@param data: File-data (binary)
@type data: C{string}
@param filename: Filename
@type filename: C{string}
@return: New instance of file.
@rtype: L{MyFile}
"""
return context.FileFromData(data, filename, content_type)
security.declarePublic('ImageFromData')
def ImageFromData( context, data, filename='', content_type=None):
"""
Creates a new instance of an image from given data.
@param data: Image-data (binary)
@type data: C{string}
@param filename: Filename
@type filename: C{string}
@return: New instance of image.
@rtype: L{MyImage}
"""
return context.ImageFromData(data, filename, content_type)
security.declarePublic('set_response_headers')
def set_response_headers(fn, mt='application/octet-stream', size=None, request=None):
"""
Set content-type and -disposition to response-headers.
"""
RESPONSE = request.RESPONSE
RESPONSE.setHeader('Content-Type', mt)
content_disposition = '; filename="%s"'%_fileutil.extractFilename(fn)
content_disposition = request.get('ZMS_ADDITIONAL_CONTENT_DISPOSITION','inline;') + content_disposition
RESPONSE.setHeader('Content-Disposition',content_disposition)
if size:
RESPONSE.setHeader('Content-Length',size)
RESPONSE.setHeader('Accept-Ranges','bytes')
security.declarePublic('set_response_headers_cache')
def set_response_headers_cache(context, request=None, cache_max_age=24*3600):
"""
Set default and dynamic cache response headers according to ZMS_CACHE_EXPIRE_DATETIME
which is determined in ObjAttrs.isActive for each page element as the earliest time for invalidation.
@see: http://nginx.org/en/docs/http/ngx_http_headers_module.html#expires
@see: https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/
@return: Tuple of expires date time in GMT as ISO8601 string and the seconds until expiration
USAGE: Add to standard_html master template, e.g.
<tal:block tal:define="
standard modules/Products.zms/standard;
cache_expire python:standard.set_response_headers_cache(this, request, cache_max_age=6*3600)">
</tal:block>
"""
if request is not None:
is_preview = request.get('preview', '') == 'preview'
is_restricted = len([ob for ob in context.breadcrumbs_obj_path(portalMaster=False)
if ob.attr('attr_dc_accessrights_restricted') in [1, True]]) > 0
if is_restricted or is_preview:
request.RESPONSE.setHeader('Cache-Control', 'no-cache')
request.RESPONSE.setHeader('Expires', '-1')
request.RESPONSE.setHeader('Pragma', 'no-cache')
else:
request.RESPONSE.setHeader('Cache-Control',
'max-age={}, public, must-revalidate, proxy-revalidate'.format(cache_max_age))
now = time.time()
expire_datetime = DateTime(request.get('ZMS_CACHE_EXPIRE_DATETIME', now + cache_max_age))
t1 = expire_datetime.millis()
t0 = DateTime(now).millis()
expire_in_secs = int((t1-t0)/1000)
expire_datetime_gmt = expire_datetime.toZone('GMT')
if t1 > t0 and cache_max_age > expire_in_secs:
request.RESPONSE.setHeader('Expires', expire_datetime_gmt.asdatetime().strftime('%a, %d %b %Y %H:%M:%S %Z'))
request.RESPONSE.setHeader('X-Accel-Expires', expire_in_secs)
return expire_datetime_gmt.ISO8601(), expire_in_secs
return None
security.declarePublic('umlaut_quote')
def umlaut_quote(s, mapping={}):
"""
Replace umlauts in s using given mapping.
@param s: String
@type s: C{str}
@param mapping: Mapping
@type mapping: C{dict}
@return: Quoted string
@rtype: C{str}
"""
if type(s) is not unicode:
s = unicode(s,'utf-8',errors='ignore')
map( lambda x: operator.setitem( mapping, x, _globals.umlaut_map[x]), _globals.umlaut_map.keys())
for key in mapping.keys():
s = s.replace(key,mapping[key])
s = s.encode('utf-8')
return s
security.declarePublic('url_append_params')
def url_append_params(url, dict, sep='&'):
"""
Append params from dict to given url.
@param url: Url
@type url: C{str}
@param dict: dictionary of params (key/value pairs)
@type dict: C{dict}
@return: New url
@rtype: C{str}
"""
anchor = ''
i = url.rfind('#')
if i > 0:
anchor = url[i:]
url = url[:i]
targetdef = ''
i = url.find('#')
if i >= 0:
targetdef = url[i:]
url = url[:i]
qs = '?'
i = url.find(qs)
if i >= 0:
qs = sep
for key in dict.keys():
value = dict[key]
if type(value) is list:
for item in value:
qi = key + ':list=' + urllib.quote(str(item))
url += qs + qi
qs = sep
else:
qi = key + '=' + urllib.quote(str(value))
if url.find( '?' + qi) < 0 and url.find( '&' + qi) < 0 and url.find( '&' + qi) < 0:
url += qs + qi
qs = sep
url += targetdef
return url+anchor
security.declarePublic('url_inherit_params')
def url_inherit_params(url, REQUEST, exclude=[], sep='&'):
"""
Inerits params from request to given url.
@param url: Url
@type url: C{str}
@param REQUEST: the triggering request
@type REQUEST: C{ZPublisher.HTTPRequest}
@return: New url
@rtype: C{str}
"""
anchor = ''
i = url.rfind('#')
if i > 0:
anchor = url[i:]
url = url[:i]
if REQUEST.form:
for key in REQUEST.form.keys():
if not key in exclude:
v = REQUEST.form.get( key, None )
if key is not None:
if url.find('?') < 0:
url += '?'
else:
url += sep
if type(v) is int:
url += urllib.quote(key+':int') + '=' + urllib.quote(str(v))
elif type(v) is float:
url += urllib.quote(key+':float') + '=' + urllib.quote(str(v))
elif type(v) is list:
c = 0
for i in v:
if c > 0:
url += sep
url += urllib.quote(key+':list') + '=' + urllib.quote(str(i))
c = c + 1
else:
url += key + '=' + urllib.quote(str(v))
return url+anchor
security.declarePublic('string_maxlen')
def string_maxlen(s, maxlen=20, etc='...', encoding=None):
"""
Returns string with specified maximum-length. If original string exceeds
maximum-length '...' is appended at the end.
@param s: String
@type s: C{str}
@param maxlen: Maximum-length
@type maxlen: C{int}
@param etc: Characters to be appended if maximum-length is exceeded
@type etc: C{str}
@param encoding: Encoding
@type encoding: C{str}
@rtype: C{str}
"""
if encoding is not None:
s = unicode( s, encoding)
# remove all tags.
s = re.sub( '<!--(.*?)-->', '', s)
s = re.sub( '<script((.|\n|\r|\t)*?)>((.|\n|\r|\t)*?)</script>', '', s)
s = re.sub( '<style((.|\n|\r|\t)*?)>((.|\n|\r|\t)*?)</style>', '', s)
s = re.sub( '<((.|\n|\r|\t)*?)>', '', s)
if len(s) > maxlen:
if s[:maxlen].rfind('&') >= 0 and not s[:maxlen].rfind('&') < s[:maxlen].rfind(';') and \
s[maxlen:].find(';') >= 0 and not s[maxlen:].find(';') > s[maxlen:].find('&'):
maxlen = maxlen + s[maxlen:].find(';')
try:
if s[:maxlen].endswith(chr(195)) and maxlen < len(s):
maxlen += 1
except:
pass
s = s[:maxlen] + etc
return s
security.declarePublic('url_encode')
def url_encode(url):
"""
All unsafe characters must always be encoded within a URL.
@see: http://www.ietf.org/rfc/rfc1738.txt
@param url: Url
@type s: C{str}
@return: Encoded string
@rtype: C{str}
"""
for ch in ['[',']',' ','(',')']:
url = url.replace(ch,'%'+bin2hex(ch).upper())
return url
security.declarePublic('guess_content_type')
def guess_content_type(filename, data):
"""
Guess the type of a file based on its filename and the data.
@param filename: Filename
@type filename: C{str}
@param data: Data
@type data: C{str}
@return: Tuple of MIME-type and encoding.
@rtype: C{tuple}
"""
import zope.contenttype
mt, enc = zope.contenttype.guess_content_type( filename, data)
return mt, enc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
html_quote:
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
def html_quote(v, name='(Unknown name)', md={}):
if not _globals.is_str_type(v):
v = str(v)
return cgi.escape(v, 1)
def bin2hex(m):
"""
Returns a string with the hexadecimal representation of integer m.
@param m: Binary
@type m: C{int}
@return: String
@rtype: C{str}
"""
return ''.join(map(lambda x: hex(ord(x)/16)[-1]+hex(ord(x)%16)[-1],m))
def hex2bin(m):
"""
Converts a hexadecimal-string m to an integer.
@param m: Hexadecimal.
@type m: C{str}
@return: Integer
@rtype: C{str}
"""
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)))
security.declarePublic('encrypt_schemes')
def encrypt_schemes():
"""
Available encryption-schemes.
@return: list of encryption-scheme ids
@rtype: C{list}
"""
ids = []
for id, prefix, scheme in AuthEncoding._schemes:
ids.append( id)
return ids
security.declarePublic('encrypt_password')
def encrypt_password(pw, algorithm='md5', hex=False):
"""
Encrypts given password.
@param pw: Password
@type pw: C{str}
@param algorithm: Encryption-algorithm (md5, sha-1, etc.)
@type algorithm: C{str}
@param hex: Hexlify
@type hex: C{bool}
@return: Encrypted password
@rtype: C{str}
"""
enc = None
if algorithm.upper() == 'SHA-1':
import sha
enc = sha.new(pw)
if hex:
enc = enc.hexdigest()
else:
enc = enc.digest()
else:
for id, prefix, scheme in AuthEncoding._schemes:
if algorithm.upper() == id:
enc = scheme.encrypt(pw)
return enc
security.declarePublic('encrypt_ordtype')
def encrypt_ordtype(s):
"""
Encrypts given string with entities by random algorithm.
@param s: String
@type s: C{str}
@return: Encrypted string
@rtype: C{str}
"""
from binascii import hexlify
new = ''
for ch in s:
whichCode=rand_int(2)
if whichCode==0:
new += ch
elif whichCode==1:
new += '&#%d;'%ord(ch)
else:
new += '&#x%s;'%str(hexlify(ch))
return new
security.declarePublic('rand_int')
def rand_int(n):
"""
Random integer in given range.
@param n: Range
@type n: C{int}
@return: Random integer
@rtype: C{int}
"""
from random import randint
return randint(0,n)
security.declarePublic('getDataSizeStr')
def getDataSizeStr(len):
"""
Returns display string for file-size (KB).
@param len: length (bytes)
@type len: C{int}
@rtype: C{str}
"""
return _fileutil.getDataSizeStr(len)
security.declarePublic('getMimeTypeIconSrc')
def getMimeTypeIconSrc(mt):
"""
Returns the absolute-url of an icon representing the specified MIME-type.
@param mt: MIME-Type (e.g. image/gif, text/xml).
@type mt: C{str}
@rtype: C{str}
"""
return'/++resource++zms_/img/%s'%_mimetypes.dctMimeType.get( mt, _mimetypes.content_unknown)
security.declarePublic('unencode')
def unencode( p, enc='utf-8'):
"""
Unencodes given parameter.
"""
if type( p) is dict:
for key in p.keys():
if type( p[ key]) is unicode:
p[ key] = p[ key].encode( enc)
elif type( p) is list:
l = []
for i in p:
if type( i) is unicode:
l.append( i.encode( enc))
else:
l.append( i)
p = l
elif type( p) is unicode:
p = p.encode( enc)
return p
security.declarePublic('id_prefix')
def id_prefix(s):
"""
Returns prefix from identifier (which is the non-numeric part at the beginning).
@param s: Identifier
@type s: C{str}
@return: Id-prefix
@rtype: C{str}
"""
return re.findall('^(\\D*)',s)[0]
security.declarePublic('id_quote')
def id_quote(s, mapping={
'\x20':'_',
'-':'_',
'/':'_',
}):
"""
Converts given string to identifier (removes special-characters and
replaces German umlauts).
@param s: String
@type s: C{str}
@return: Identifier
@rtype: C{str}
"""
s = umlaut_quote(s, mapping)
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)
s = filter( lambda x: ord(x) in valid, s)
while len(s) > 0 and s[0] == '_':
s = s[1:]
s = s.lower()
return s
security.declarePublic('form_quote')
def form_quote(text, REQUEST):
"""
Remove <form>-tags for Management Interface.
"""
rtn = text
if isManagementInterface(REQUEST):
rtn = re.sub( '<form(.*?)>', '<noform\\1>', rtn)
rtn = re.sub( ' name="lang"', ' name="_lang"', rtn)
rtn = re.sub( '</form(.*?)>', '</noform\\1>', rtn)
return rtn
def qs_append(qs, p, v):
"""
Append to query-string.
"""
if len(qs) == 0:
qs += '?'
else:
qs += '&'
qs += p + '=' + urllib.quote(v)
return qs
security.declarePublic('nvl')
def nvl(a1, a2, n=None):
"""
Returns its first argument if it is not equal to third argument (None),
otherwise it returns its second argument.
@param a1: 1st argument
@type a1: C{any}
@param a2: 2nd argument
@type a2: C{any}
@rtype: C{any}
"""
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):
return a1
else:
return a2
def get_session(context):
"""
Get http-session.
"""
return getattr(context, 'session_data_manager', None) and \
context.session_data_manager.getSessionData(create=0)
security.declarePublic('get_session_value')
def get_session_value(context, key, defaultValue=None):
"""
Get http-session-value.
"""
session = get_session(context)
if session is not None:
return session.get(key,defaultValue)
return None
security.declarePublic('set_session_value')
def set_session_value(context, key, value):
"""
Set http-session-value.
"""
session = get_session(context)
if session is not None:
session.set(key,value)
return value
return None
def triggerEvent(context, *args, **kwargs):
"""
Hook for trigger of custom event (if there is one)
"""
l = []
name = args[0]
# Always call local trigger for global triggers.
if name.startswith('*.'):
triggerEvent(context,name[2:]+'Local')
# Pass custom event to zope ObjectModifiedEvent event.
notify(ObjectModifiedEvent(context, name))
metaObj = context.getMetaobj( context.meta_id)
if metaObj:
# Process meta-object-triggers.
context = context
v = context.evalMetaobjAttr(name,kwargs)
writeLog( context, "[triggerEvent]: %s=%s"%(name,str(v)))
if v is not None:
l.append(v)
# Process zope-triggers.
m = getattr(context,name,None)
if m is not None:
m(context=context,REQUEST=context.REQUEST)
return l
security.declarePublic('isManagementInterface')
def isManagementInterface(REQUEST):
"""
Returns true if current context is management-interface, false else.
@rtype: C{Bool}
"""
return REQUEST is not None and \
REQUEST.get('URL','').find('/manage') >= 0 and \
isPreviewRequest(REQUEST)
security.declarePublic('isPreviewRequest')
def isPreviewRequest(REQUEST):
"""
Returns true if current context is preview-request, false else.
@rtype: C{Bool}
"""
return REQUEST is not None and \
REQUEST.get('preview','') == 'preview'
"""
################################################################################
#
# Http
#
################################################################################
"""
security.declarePublic('unescape')
def unescape(s):
"""
Unescape
@rtype: C{str}
"""
while True:
i = s.find('%')
if i < 0: break
if s[i+1] == 'u':
old = s[i:i+6]
if old == '%u21B5':
new = '↵'
else:
new = ''
else:
old = s[i:i+3]
new = chr(int('0x'+s[i+1:i+3],0))
s = s.replace(old,new)
return s
security.declarePublic('http_import')
def http_import(context, url, method='GET', auth=None, parse_qs=0, timeout=10, headers={'Accept':'*/*'}):
"""
Send Http-Request and return Response-Body.
@param url: Remote-URL
@type url: C{str}
@param method: Method
@type method: C{str}, values are GET or POST
@param auth: Authentication
@type auth: C{str}
@param parse_qs: Parse Query-String
@type parse_qs: C{int}, values are 0 or 1
@param timeout: Time-Out [s]
@type timeout: C{int}, values in seconds
@param headers: Request-Headers
@type headers: C{dict}
@return: Response-Body
@rtype: C{str}
"""
# Parse URL.
import urlparse
u = urlparse.urlparse(url)
writeLog( context, "[http_import.%s]: %s"%(method,str(u)))
scheme = u[0]
netloc = u[1]
path = u[2]
query = u[4]
# Get Proxy.
useproxy = True
noproxy = ['localhost','127.0.0.1']+filter(lambda x: len(x)>0,map(lambda x: x.strip(),context.getConfProperty('%s.noproxy'%scheme.upper(),'').split(',')))
for noproxyurl in noproxy:
if fnmatch.fnmatch(netloc,noproxyurl):
useproxy = False
break
if useproxy:
proxy = context.getConfProperty('%s.proxy'%scheme.upper(),'')
if len(proxy) > 0:
path = '%s://%s%s'%(scheme,netloc,path)
netloc = proxy
# Open HTTP connection.
import httplib
writeLog( context, "[http_import.%s]: %sConnection(%s) -> %s"%(method,scheme,netloc,path))
if scheme == 'http':
conn = httplib.HTTPConnection(netloc,timeout=timeout)
else:
conn = httplib.HTTPSConnection(netloc,timeout=timeout)
# Set request-headers.
if auth is not None:
userpass = auth['username']+':'+auth['password']
userpass = base64.encodestring(urllib.unquote(userpass)).strip()
headers['Authorization'] = 'Basic '+userpass
if method == 'GET' and query:
path += '?' + query
query = ''
conn.request(method, path, query, headers)
response = conn.getresponse()
reply_code = response.status
message = response.reason
#### get parameter from content
if reply_code == 404 or reply_code >= 500:
error = "[%i]: %s at %s [%s]"%(reply_code,message,url,method)
writeLog( context, "[http_import.error]: %s"%error)
raise zExceptions.InternalError(error)
elif reply_code==200:
# get content
data = response.read()
rtn = None
if parse_qs:
try:
# return dictionary of value lists
data = cgi.parse_qs(data, keep_blank_values=1, strict_parsing=1)
except:
writeError(context,'[http_import]: can\'t parse_qs')
return data
else:
result = '['+str(reply_code)+']: '+str(message)
writeLog( context, "[http_import.result]: %s"%result)
return result
################################################################################
#
#{ Logging
#
################################################################################
def getLog(context):
"""
Get zms_log.
"""
request = context.REQUEST
if request.has_key('ZMSLOG'):
zms_log = request.get('ZMSLOG')
else:
zms_log = getattr(context,'zms_log',None)
if zms_log is None:
zms_log = getattr(context.getPortalMaster(),'zms_log',None)
request.set('ZMSLOG',zms_log)
return zms_log
security.declarePublic('writeStdout')
def writeStdout(context, info):
"""
Write to standard-out (only allowed for development-purposes!).
@param info: Object
@type info: C{any}
@rtype: C{str}
"""
print(info)
return info
security.declarePublic('writeLog')
def writeLog(context, info):
"""
Log debug-information.
@param info: Debug-information
@type info: C{any}
@rtype: C{str}
"""
try:
zms_log = getLog(context)
severity = logging.DEBUG
if zms_log.hasSeverity(severity):
info = "[%s@%s] "%(context.meta_id,'/'.join(context.getPhysicalPath())) + info
zms_log.LOG( severity, info)
except:
pass
return info
security.declarePublic('writeBlock')
def writeBlock(context, info):
"""
Log information.
@param info: Information
@type info: C{any}
@rtype: C{str}
"""
try:
zms_log = getLog(context)
severity = logging.INFO
if zms_log.hasSeverity(severity):
info = "[%s@%s] "%(context.meta_id,'/'.join(context.getPhysicalPath())) + info
zms_log.LOG( severity, info)
except:
pass
return info
security.declarePublic('writeError')
def writeError(context, info):
"""
Log error.
@param info: Information
@type info: C{any}
@rtype: C{str}
"""
t,v='?','?'
try:
t,v,tb = sys.exc_info()
if t is not None:
v = str(v)
# Strip HTML tags from the error value
for pattern in [r"<[^<>]*>", r"&[A-Za-z]+;"]:
v = re_sub(pattern,' ', v)
if info:
info += '\n'
info += ''.join(format_exception(t, v, tb))
info = "[%s@%s] "%(context.meta_id,'/'.join(context.getPhysicalPath())) + info
zms_log = getLog(context)
severity = logging.ERROR
if zms_log.hasSeverity(severity):
zms_log.LOG( severity, info)
t = t.__name__.upper()
except:
pass
rtn = '%s: %s <!-- %s -->'%(t,v,info)
request = getattr(context,'REQUEST',None)
if request:
request.set('ZMS_MESSAGES',request.get('ZMS_MESSAGES',[])+[('ERROR',rtn)])
return rtn
#)
################################################################################
#
#( Regular Expressions
#
################################################################################
security.declarePublic('re_sub')
def re_sub( pattern, replacement, subject, ignorecase=False):
"""
Performs a search-and-replace across subject, replacing all matches of
regex in subject with replacement. The result is returned by the sub()
function. The subject string you pass is not modified.
@rtype: C{str}
"""
if ignorecase:
return re.compile( pattern, re.IGNORECASE).sub( replacement, subject)
else:
return re.compile( pattern).sub( replacement, subject)
security.declarePublic('re_search')
def re_search( pattern, subject, ignorecase=False):
"""
Scan through string looking for a location where the regular expression
pattern produces a match, and return a corresponding MatchObject
instance. Return None if no position in the string matches the pattern;
note that this is different from finding a zero-length match at some
point in the string.
@rtype: C{str}
"""
if ignorecase:
s = re.compile( pattern, re.IGNORECASE).split( subject)
else:
s = re.compile( pattern).split( subject)
return map( lambda x: s[x*2+1], range(len(s)/2))
security.declarePublic('re_findall')
def re_findall( pattern, text, ignorecase=False):
"""
Return all non-overlapping matches of pattern in string, as a list of strings.
The string is scanned left-to-right, and matches are returned in the order found.
If one or more groups are present in the pattern, return a list of groups;
this will be a list of tuples if the pattern has more than one group.
Empty matches are included in the result unless they touch the beginning of another match
@rtype: C{str}
"""
if ignorecase:
r = re.compile( pattern, re.IGNORECASE)
else:
r = re.compile( pattern)
return r.findall(text)
#)
############################################################################
#
# DATE TIME
#
############################################################################
# ==========================================================================
# Index Field Values
# 0 year (for example, 1993)
# 1 month range [1,12]
# 2 day range [1,31]
# 3 hour range [0,23]
# 4 minute range [0,59]
# 5 second range [0,61]; see (1) in strftime() description
# 6 weekday range [0,6], Monday is 0
# 7 Julian day range [1,366]
# 8 daylight savings flag 0, 1 or -1; see below
# ==========================================================================
security.declarePublic('format_datetime_iso')
def format_datetime_iso(t):
# DST is Daylight Saving Time, an adjustment of the timezone by
# (usually) one hour during part of the year. DST rules are magic
# (determined by local law) and can change from year to year.
#
# DST in t[8] ! -1 (unknown), 0 (off), 1 (on)
if t[8] == 1:
tz = time.altzone
elif t[8] == 0:
tz = time.timezone
else:
tz = 0
# The offset of the local (non-DST) timezone, in seconds west of UTC
# (negative in most of Western Europe, positive in the US, zero in the
# UK).
#
# ==> quite the opposite to the usual definition as eg in RFC 822.
tch = '-'
if tz < 0:
tch = '+'
tz = abs(tz)
tzh = tz/60/60
tzm = (tz-tzh*60*60)/60
return time.strftime('%Y-%m-%dT%H:%M:%S',t)+tch+('00%d'%tzh)[-2:]+':'+('00%d'%tzm)[-2:]
def getLangFmtDate(context, t, lang=None, fmt_str='SHORTDATETIME_FMT'):
"""
Formats date in locale-format
@param t: Datetime
@type t: C{struct_time}
@param lang: Locale
@type lang: C{str}
@param fmt_str: Format-String, possible values SHORTDATETIME_FMT (default),
SHORTDATE_FMT, DATETIME_FMT, DATE_FMT, DateTime, Day, Month, ISO8601, RFC2822
"""
try:
if lang is None:
lang = context.get_manage_lang()
# Convert to struct_time
t = getDateTime(t)
# Return ModificationTime
if fmt_str == 'BOBOBASE_MODIFICATION_FMT':
sdtf = context.getLangFmtDate(t, lang, fmt_str='SHORTDATETIME_FMT')
if context.daysBetween(t,DateTime()) > context.getConfProperty('ZMS.shortDateFormat.daysBetween',5):
sdf = context.getLangFmtDate(t, lang, fmt_str='SHORTDATE_FMT')