-
Notifications
You must be signed in to change notification settings - Fork 0
/
_objattrs.py
1508 lines (1352 loc) · 59.9 KB
/
_objattrs.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
################################################################################
# _objattrs.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.
################################################################################
# Imports.
from DateTime.DateTime import DateTime
from types import StringTypes
import ZPublisher.HTTPRequest
import datetime
import string
import time
import urllib
import zExceptions
# Product Imports.
import _blobfields
import _globals
import ZMSMetaobjManager
# ------------------------------------------------------------------------------
# _objattrs.utf8:
# ------------------------------------------------------------------------------
def utf8(v, encoding = 'latin-1'):
if type( v) in StringTypes:
cp1252_map = {
"\x80" : "\xe2\x82\xac", # /* EURO SIGN */
"\x82" : "\xe2\x80\x9a", # /* SINGLE LOW-9 QUOTATION MARK */
"\x83" : "\xc6\x92", # /* LATIN SMALL LETTER F WITH HOOK */
"\x84" : "\xe2\x80\x9e", # /* DOUBLE LOW-9 QUOTATION MARK */
"\x85" : "\xe2\x80\xa6", # /* HORIZONTAL ELLIPSIS */
"\x86" : "\xe2\x80\xa0", # /* DAGGER */
"\x87" : "\xe2\x80\xa1", # /* DOUBLE DAGGER */
"\x88" : "\xcb\x86", # /* MODIFIER LETTER CIRCUMFLEX ACCENT */
"\x89" : "\xe2\x80\xb0", # /* PER MILLE SIGN */
"\x8a" : "\xc5\xa0", # /* LATIN CAPITAL LETTER S WITH CARON */
"\x8b" : "\xe2\x80\xb9", # /* SINGLE LEFT-POINTING ANGLE QUOTATION */
"\x8c" : "\xc5\x92", # /* LATIN CAPITAL LIGATURE OE */
"\x8e" : "\xc5\xbd", # /* LATIN CAPITAL LETTER Z WITH CARON */
"\x91" : "\xe2\x80\x98", # /* LEFT SINGLE QUOTATION MARK */
"\x92" : "\xe2\x80\x99", # /* RIGHT SINGLE QUOTATION MARK */
"\x93" : "\xe2\x80\x9c", # /* LEFT DOUBLE QUOTATION MARK */
"\x94" : "\xe2\x80\x9d", # /* RIGHT DOUBLE QUOTATION MARK */
"\x95" : "\xe2\x80\xa2", # /* BULLET */
"\x96" : "\xe2\x80\x93", # /* EN DASH */
"\x97" : "\xe2\x80\x94", # /* EM DASH */
"\x98" : "\xcb\x9c", # /* SMALL TILDE */
"\x99" : "\xe2\x84\xa2", # /* TRADE MARK SIGN */
"\x9a" : "\xc5\xa1", # /* LATIN SMALL LETTER S WITH CARON */
"\x9b" : "\xe2\x80\xba", # /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
"\x9c" : "\xc5\x93", # /* LATIN SMALL LIGATURE OE */
"\x9e" : "\xc5\xbe", # /* LATIN SMALL LETTER Z WITH CARON */
"\x9f" : "\xc5\xb8" # /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
}
if encoding == 'latin-1':
n = ''
for i in v:
if i in cp1252_map.keys():
c = '&#%i;'%ord( i)
n += c
else:
n += i
v = n
v = unicode( v, encoding).encode( 'utf-8')
if encoding == 'latin-1':
for i in cp1252_map.keys():
c = '&#%i;'%ord( i)
j = 0
while j >= 0:
j = v.find( c)
if j >= 0:
v = v[:j] + cp1252_map[ i] + v[j+len(c):]
return v
elif type( v) is list:
return map(lambda x: utf8( x, encoding), v)
elif type( v) is tuple:
return tuple(map(lambda x: utf8( x, encoding), list(v)))
elif type( v) is dict:
keys = v.keys()
vals = map(lambda x: utf8(v[x],encoding), keys)
return _globals.map_key_vals(keys, vals)
else:
return v
# ------------------------------------------------------------------------------
# _objattrs.setutf8attr:
# ------------------------------------------------------------------------------
def setutf8attr(self, obj_vers, obj_attr, langId):
charset = self.getLang(langId).get('charset','')
if len(charset) == 0:
charset = 'latin-1'
key = self.getObjAttrName(obj_attr,langId)
v = getattr(obj_vers,key,None)
v = utf8(v,charset)
setattr(obj_vers,key,v)
# ------------------------------------------------------------------------------
# _objattrs.getobjattr:
# ------------------------------------------------------------------------------
def getobjattr(self, obj, obj_attr, lang):
key = self.getObjAttrName(obj_attr,lang)
v = None
if key in obj.__dict__.keys():
v = getattr(obj,key)
# Default value.
if v is None:
datatype = obj_attr['datatype_key']
default = obj_attr.get('default',_globals.dtMapping[datatype][1])
# Default inactive in untranslated languages.
if obj_attr['id'] == 'active' and len(self.getLangIds()) > 1 and not self.isTranslated(lang,self.REQUEST):
default = 0
if default is not None:
if datatype in _globals.DT_DATETIMES and default == '{now}':
default = time.time()
elif type(default) is list or type(default) is tuple:
v = self.copy_list(default)
elif type(default) is dict:
v = default.copy()
else:
if type( default) is str and len( default) > 0:
default = _globals.dt_html( self, str( default), self.REQUEST)
v = default
return v
# ------------------------------------------------------------------------------
# _objattrs.setobjattr:
# ------------------------------------------------------------------------------
def setobjattr(self, obj, obj_attr, value, lang):
key = self.getObjAttrName(obj_attr,lang)
# Assign value.
setattr(obj,key,value)
# ------------------------------------------------------------------------------
# _objattrs.cloneobjattr:
# ------------------------------------------------------------------------------
def cloneobjattr(self, src, dst, obj_attr, lang):
_globals.writeLog( self, "[cloneobjattr]: Clone object-attributes from '%s' to '%s'"%(str(src),str(dst)))
# Fetch value.
v = getobjattr(self,src,obj_attr,lang)
# Clone value.
if v is not None:
datatype = obj_attr['datatype_key']
if datatype in _globals.DT_BLOBS:
try:
v = v._getCopy()
except:
e = "[cloneobjattr]: Can't clone object-attribute: obj_attr=%s, lang=%s, v=%s!"%(str(obj_attr), str(lang), str(v))
_globals.writeError( self, e)
raise zExceptions.InternalError(e)
elif type(v) is list or type(v) is tuple:
v = self.copy_list(v)
elif type(v) is dict:
v = v.copy()
# Assign value.
setobjattr(self,dst,obj_attr,v,lang)
################################################################################
################################################################################
###
### Object Attributes
###
################################################################################
################################################################################
class ObjAttrs:
# --------------------------------------------------------------------------
# ObjAttrs.ajaxGetObjOptions:
# --------------------------------------------------------------------------
def ajaxGetObjOptions(self, key, meta_id, fmt=None, REQUEST=None):
""" ObjAttrs.ajaxGetObjOptions """
RESPONSE = REQUEST.RESPONSE
content_type = 'text/plain; charset=utf-8'
filename = 'ajaxGetObjOptions.txt'
RESPONSE.setHeader('Content-Type',content_type)
RESPONSE.setHeader('Content-Disposition','inline;filename="%s"'%filename)
RESPONSE.setHeader('Cache-Control', 'no-cache')
RESPONSE.setHeader('Pragma', 'no-cache')
obj_attr = self.getObjAttr( key, meta_id)
l = map( lambda x: x[1], self.getObjOptions( obj_attr, REQUEST))
q = REQUEST.get( 'q', '').upper()
if q:
l = filter( lambda x: x.upper().find( q) >= 0, l)
limit = int(REQUEST.get('limit',self.getConfProperty('ZMS.input.autocomplete.limit',15)))
if len(l) > limit:
l = l[:limit]
if fmt == 'json':
return self.str_json(l)
return '\n'.join(l)
# --------------------------------------------------------------------------
# ObjAttrs.ajaxGetObjAttrs:
# --------------------------------------------------------------------------
def ajaxGetObjAttrs(self, meta_id, REQUEST):
""" ObjAttrs.ajaxGetObjAttrs """
RESPONSE = REQUEST.RESPONSE
content_type = 'text/xml; charset=utf-8'
filename = 'ajaxGetObjAttrs.xml'
RESPONSE.setHeader('Content-Type',content_type)
RESPONSE.setHeader('Content-Disposition','inline;filename="%s"'%filename)
RESPONSE.setHeader('Cache-Control', 'no-cache')
RESPONSE.setHeader('Pragma', 'no-cache')
return self.getXmlHeader() + self.toXmlString( self.getObjAttrs( meta_id))
# --------------------------------------------------------------------------
# ObjAttrs.getObjAttrs:
#
# Returns object-attributes and resolves meta-dictionaries.
# --------------------------------------------------------------------------
def getObjAttrs(self, meta_id=None):
meta_id = _globals.nvl( meta_id, self.meta_id)
obj_attrs = getattr( self, 'dObjAttrs', {})
return obj_attrs.get(meta_id,{})
# --------------------------------------------------------------------------
# ObjAttrs.getObjAttr:
# --------------------------------------------------------------------------
def getObjAttr(self, key, meta_id=None):
obj_attrs = self.getObjAttrs( meta_id)
return obj_attrs.get(key,{'id':key,'key':key,'xml':False,'multilang':False,'lang_inherit':False,'name':'UNKNOWN','datatype':'string','datatype_key':_globals.DT_UNKNOWN})
# --------------------------------------------------------------------------
# ObjAttrs.getObjAttrLabel:
# --------------------------------------------------------------------------
def getObjAttrLabel(self, obj_attr):
lang = self.REQUEST['lang']
for key in [ 'name', 'id']:
if obj_attr.has_key( key):
name = obj_attr.get( key)
lang_key = name
lang_str = self.getLangStr( lang_key, lang)
if lang_key != lang_str:
return lang_str
lang_key = name.upper()
lang_str = self.getLangStr( lang_key, lang)
if lang_key != lang_str:
return lang_str
lang_key = ('attr_'+name).upper()
lang_str = self.getLangStr( lang_key, lang)
if lang_key != lang_str:
return lang_str
return obj_attr.get('name',obj_attr['id'].capitalize())
# --------------------------------------------------------------------------
# ObjAttrs.getObjOptions:
# --------------------------------------------------------------------------
def getObjOptions(self, obj_attr, REQUEST):
optpl = []
if obj_attr.has_key('options'):
opts = []
obj_attropts = obj_attr['options']
if type(obj_attropts) is list:
dtml = ''.join(map(lambda x: str(obj_attropts[x*2]),range(len(obj_attropts)/2)))
if len(obj_attropts)==2 and self.getLinkObj(obj_attropts[0],REQUEST):
ob = self.getLinkObj(obj_attropts[0],REQUEST)
metaObj = self.getMetaobj(ob.meta_id)
res = ob.getObjProperty(metaObj['attrs'][0]['id'],REQUEST)
res = map(lambda x: {'key':x['key'],'value':x.get('value',x.get('value_%s'%REQUEST['lang']))},res)
res = self.sort_list(res,'value','asc')
opts = map(lambda x: [x['key'],x['value']],res)
elif dtml.find('<dtml')>=0:
try:
opts = _globals.dt_html(self,dtml,REQUEST)
except:
opts = _globals.writeError(self,'[getObjOptions]: key=%s'%obj_attr['id'])
else:
for i in range(len(obj_attropts)/2):
opts.append([obj_attropts[i*2],obj_attropts[i*2+1]])
elif type(obj_attropts) is dict:
for k in obj_attropts.keys():
opts.append([k,obj_attropts[k]])
for opt in opts:
lang_attr = 'OPT_'
for skey in obj_attr['id'].split('_'):
lang_attr += skey[0]
lang_attr += '_' + str(opt[1]).replace(' ','')
lang_attr = lang_attr.upper()
lang_str = self.getZMILangStr(lang_attr)
value = str(opt[0])
display = str(opt[1])
if lang_attr != lang_str:
display = lang_str
optpl.append([value,display])
return optpl
# --------------------------------------------------------------------------
# ObjAttrs.getObjAttrName:
# --------------------------------------------------------------------------
def getObjAttrName(self, obj_attr, lang=None):
attr = obj_attr['id']
if obj_attr['multilang']:
if lang is None:
lang = self.getPrimaryLanguage()
attr = '%s_%s'%(attr,lang)
return attr
# --------------------------------------------------------------------------
# ObjAttrs.isDisabledAttr:
# --------------------------------------------------------------------------
def isDisabledAttr(self, obj_attr, REQUEST):
lang = REQUEST.get('lang',self.getPrimaryLanguage())
return REQUEST.get(obj_attr['id']+'-disabled',False) or not (obj_attr['multilang'] or REQUEST.get('ZMS_INSERT',None) is not None or self.getDCCoverage(REQUEST).find('.'+lang)>0)
############################################################################
#
# INPUT-FIELDS
#
############################################################################
# --------------------------------------------------------------------------
# ObjAttrs.getObjAttrInput:
# --------------------------------------------------------------------------
def getObjAttrInput(self, fmName, obj_attr, value, REQUEST):
#-- DATATYPE
datatype = obj_attr['datatype_key']
#-- NAME
lang = REQUEST['lang']
attr = self.getObjAttrName(obj_attr,lang)
elName = self.REQUEST.get('objAttrNamePrefix','') + attr
#-- INPUTTYPE
inputtype = obj_attr.get('type','string')
#-- ENABLED / DISABLED
enabled = not self.isDisabledAttr(obj_attr,REQUEST)
disabled = obj_attr['id'].find('_')==0
#-- Meta-Object
meta_id = REQUEST.get( 'ZMS_INSERT', self.meta_id)
metaObj = self.getMetaobj( meta_id)
#-- Label
lang_str = self.getObjAttrLabel(obj_attr)
#-- Mandatory
mandatory = obj_attr.get('mandatory',0)
#-- Repetitive-Fields.
if obj_attr.get('repetitive',0):
return self.f_selectRepetitive(self,ob=self,fmName=fmName,elName=elName,value=value,obj_attr=obj_attr,REQUEST=REQUEST)
#-- ID-Fields.
if inputtype == 'identifier':
if value == '': value = 'e%i'%self.getSequence().nextVal()
return '<div class="form-element"><code><input type="hidden" name="%s" value="%s">%s</code></div>'%(elName,value,value)
#-- Richtext-Fields.
elif inputtype == 'richtext':
REQUEST.set('data',value)
form_fixed = False
css = 'form-element'
wrap = 'virtual'
filteredMetaObjAttrs = filter( lambda x: x['id']=='format', metaObj['attrs'])
if len(filteredMetaObjAttrs) == 1:
if REQUEST.get('ZMS_INSERT'):
default = _globals.dt_html( self, str( filteredMetaObjAttrs[0].get('default','')), REQUEST)
if default:
fmt = default
else:
fmt = self.getTextFormatDefault()
data = ''
else:
fmt = self.getObjProperty('format',REQUEST)
txt = self.getObjProperty('text',REQUEST)
data = self.renderText(None,'text',txt,REQUEST)
REQUEST.set('format',fmt)
REQUEST.set('data',data)
text_fmt = self.getTextFormat(fmt,REQUEST)
form_fixed = form_fixed or ( text_fmt is not None and not text_fmt.getTag() and not text_fmt.getSubTag())
ltxt = str(value).lower()
form_fixed = form_fixed or ( ltxt.find( '<form') >= 0 or ltxt.find( '<input') >= 0 or ltxt.find( '<script') >= 0)
if form_fixed:
css = 'form-fixed'
wrap = 'off'
if disabled:
css += '-disabled'
return self.f_selectRichtext(self,ob=self,fmName=fmName,elName=elName,cols=50,rows=15,value=value,key=obj_attr['id'],metaObj=metaObj,enabled=enabled,lang=lang,lang_str=lang_str,REQUEST=REQUEST,css=css,wrap=wrap)
#-- Color-Fields.
elif inputtype == 'color':
return self.f_selectColor(self,ob=self,fmName=fmName,elName=elName,value=value,key=obj_attr['id'],lang_str=lang_str,mandatory=mandatory,REQUEST=REQUEST)
#-- Image-Fields.
elif inputtype == 'image':
return self.f_selectImage(self,ob=self,fmName=fmName,elName=elName,value=value,key=obj_attr['id'],metaObj=metaObj,lang=lang,REQUEST=REQUEST)
#-- File-Fields.
elif inputtype == 'file':
return self.f_selectFile(self,ob=self,fmName=fmName,elName=elName,value=value,key=obj_attr['id'],metaObj=metaObj,lang=lang,REQUEST=REQUEST)
#-- Password-Fields.
if inputtype == 'password':
return self.getPasswordInput(fmName=fmName,elName=elName,value=value)
#-- Dictionary/List-Fields.
elif inputtype in [ 'dictionary', 'list']:
css = 'form-fixed'
wrap = 'virtual'
if disabled:
css += '-disabled'
cols = 35
rows = 1
inp = []
inp.append(self.getTextArea(fmName,elName,cols,rows,self.toXmlString(value),enabled,REQUEST,css,wrap))
return ''.join(inp)
#-- Text-Fields.
elif inputtype in [ 'text', 'xml']:
css = 'form-element'
wrap = 'virtual'
if inputtype in ['xml']:
css = 'form-fixed'
wrap = 'off'
if disabled:
css += '-disabled'
cols = None
rows = 5
extra = ' onselect="storeCaret(this)"'
return self.getTextArea(fmName,elName,cols,rows,value,enabled,REQUEST,css,wrap,extra)
#-- Boolean-Fields.
elif inputtype == 'boolean':
return self.getCheckbox(fmName=fmName,elName=elName,elId=obj_attr['id'],value=value,enabled=enabled,hidden=False,REQUEST=REQUEST)
#-- Autocomplete-Fields.
elif inputtype in ['autocomplete','multiautocomplete']:
css = 'form-element'
if disabled: css += '-disabled'
return self.f_selectAutocomplete(self,fmName=fmName,elName=elName,value=value,type=inputtype,key=obj_attr['id'],lang_str=lang_str,enabled=enabled,css=css,REQUEST=REQUEST)
#-- Select-Fields.
elif inputtype in ['multiselect','select']:
css = 'form-element'
if disabled: css += '-disabled'
optpl = self.getObjOptions(obj_attr,REQUEST)
return self.getSelect(fmName,elName,value,inputtype,lang_str,mandatory,optpl,enabled,REQUEST,css)
#-- Input-Fields.
else:
css = 'form-element'
if disabled: css += '-disabled'
if datatype in _globals.DT_DATETIMES:
size = 12
fmt_str = 'DATETIME_FMT'
if datatype == _globals.DT_DATE:
size = 8
fmt_str = 'DATE_FMT'
elif datatype == _globals.DT_TIME:
size = 8
fmt_str = 'TIME_FMT'
return self.getDateTimeInput(fmName,elName,size,value,enabled,fmt_str,REQUEST,css)
elif datatype == _globals.DT_URL:
size = 22
elTextName = ''
return self.getUrlInput( fmName, elName, elTextName, size, value, enabled, REQUEST, css )
else:
size = None
extra = ''
if obj_attr.has_key('size'):
size = obj_attr['size']
elif datatype in [_globals.DT_INT]:
size = 5
elif datatype in [_globals.DT_FLOAT]:
size = 8
elif datatype in [_globals.DT_AMOUNT]:
size = 8
extra = 'style="text-align: right;"'
if value is not None:
try:
value = '%1.2f'%float(value)
except:
pass
inp = []
inp.append(self.getTextInput( fmName, elName, size, value, 'text', enabled, REQUEST, css, extra ))
if datatype in [_globals.DT_AMOUNT]:
inp.append(' '+self.getConfProperty('ZMS.locale.amount.unit','EUR'))
return ''.join(inp)
# --------------------------------------------------------------------------
# ObjAttrs.getObjInput:
# --------------------------------------------------------------------------
def getObjInput(self, key, REQUEST):
id = self.id
fmName = REQUEST.get( 'fmName' ,REQUEST.get('fmName','form0_%s'%id))
meta_id = REQUEST.get( 'ZMS_INSERT', None)
obj_attr = self.getObjAttr( key, _globals.nvl( meta_id, self.meta_id))
if meta_id is None:
value = self.getObjAttrValue( obj_attr, REQUEST)
else:
default = ''
datatype = obj_attr['datatype_key']
if datatype == _globals.DT_BOOLEAN:
default = 0
value = REQUEST.get( '%s_value'%key, obj_attr.get( 'default', default))
return self.getObjAttrInput( fmName, obj_attr, value, REQUEST)
# --------------------------------------------------------------------------
# ObjAttrs.hasObjProperty:
#
# Checks if object has specified property.
# --------------------------------------------------------------------------
def hasObjProperty(self, key, REQUEST):
#-- REQUEST
lang = REQUEST.get('lang',self.getPrimaryLanguage())
#-- DEFINITION
obj_attr = self.getObjAttr(key)
#-- OBJECT (Live / Work).
ob = self.getObjVersion(REQUEST)
#-- ATTR
attr = self.getObjAttrName(obj_attr,lang)
#-- Return true if object has specified property, false else.
return ob.__dict__.get(attr,None) is not None
"""
############################################################################
#
# Get
#
############################################################################
"""
# --------------------------------------------------------------------------
# ObjAttrs._getObjAttrValue:
# --------------------------------------------------------------------------
def _getObjAttrValue(self, obj_attr, obj_vers, lang):
datatype = obj_attr['datatype_key']
set, value = False, getobjattr(self,obj_vers,obj_attr,lang)
obj_default = _globals.dtMapping[datatype][1]
#-- Blob-Fields
if datatype in _globals.DT_BLOBS:
if type(value) in StringTypes:
set, value = True, None
elif value is not None:
value = value._createCopy( self, obj_attr['id'])
value.lang = lang
#-- DateTime-Fields.
elif datatype in _globals.DT_DATETIMES:
if value is not None:
if type(value) in StringTypes:
fmt_str = 'DATETIME_FMT'
if datatype == _globals.DT_DATE:
fmt_str = 'DATE_FMT'
elif datatype == _globals.DT_TIME:
fmt_str = 'TIME_FMT'
_globals.writeLog( self, "[_getObjAttrValue]: type(value) is type(string) - parseLangFmtDate(%s)"%(str(value)))
set, value = True, self.parseLangFmtDate(value)
elif type(value) is not time.struct_time:
_globals.writeLog( self, "[_getObjAttrValue]: type(value) is not time.struct_time - getDateTime(%s)"%(str(value)))
set, value = True, _globals.getDateTime(value)
#-- List-Fields.
elif datatype == _globals.DT_LIST:
if not type(value) is type(obj_default):
set, value = True, [value]
#-- Integer-Fields.
elif datatype in _globals.DT_INTS and not type(value) is type(obj_default):
try:
set, value = type( value) is not int, int(value)
except:
value = obj_default
#-- Float-Fields.
elif datatype == _globals.DT_FLOAT and not type(value) is type(obj_default):
try:
set, value = type( value) is not float, float( value)
except:
value = obj_default
#-- Url-Fields
elif datatype == _globals.DT_URL and value.startswith('{$') and not value.startswith('{$__') and self.getConfProperty('ZMS.InternalLinks.autocorrection',0)==1:
try:
old = value
value = self.validateLinkObj(value)
set = old != value
except:
_globals.writeError(self,'[_getObjAttrValue]: Unexpected Exception when processing Url-Fields: value=%s!'%str(value))
#-- SET?
if set:
attr = self.getObjAttrName( obj_attr, lang)
_globals.writeLog( self, "[_getObjAttrValue]: setattr(%s,%s)"%(attr,str(value)))
setattr(obj_vers,attr,value)
# Return value.
return value
# --------------------------------------------------------------------------
# ObjAttrs.getObjAttrValue:
# --------------------------------------------------------------------------
def getObjAttrValue(self, obj_attr, REQUEST):
datatype = obj_attr['datatype_key']
obj_vers = self.getObjVersion(REQUEST)
lang = REQUEST.get('lang',self.getPrimaryLanguage())
while True:
value = self._getObjAttrValue(obj_attr,obj_vers,lang)
empty = False
if obj_attr['multilang'] and \
obj_attr['lang_inherit']:
lang = self.getParentLanguage(lang)
if lang is not None:
empty = empty or (value is None)
empty = empty or (datatype in _globals.DT_NUMBERS and value==0)
empty = empty or (datatype in _globals.DT_STRINGS and value=='')
empty = empty or (datatype == _globals.DT_LIST and value==[])
if not empty: break
return value
# --------------------------------------------------------------------------
# ObjAttrs.getObjProperty:
#
# Retrieves value for specified property.
#
# @deprecated: use attr(key) instead!
# --------------------------------------------------------------------------
def getObjProperty(self, key, REQUEST={}, par=None):
#-- [ReqBuff]: Fetch buffered value from Http-Request.
reqBuffId = '%s_%s'%('getObjProperty',key)
try:
if ( type( par) is dict and par.get( 'fetchReqBuff') in [ 0, False]) or \
( REQUEST.get( 'ZMS_VERSION_%s'%self.id) is not None):
raise zExceptions.InternalError('ReqBuff set inactive!')
forced = type( par) is dict and par.get( 'fetchReqBuff') in [ 1, True]
value = self.fetchReqBuff( reqBuffId, REQUEST, forced)
return value
except:
meta_id = REQUEST.get('ZMS_INSERT',self.meta_id)
objAttrs = self.getObjAttrs()
metaObjAttr = None
try:
if key not in objAttrs.keys():
if key.find('.')>0:
meta_id = key[:key.find('.')]
key = key[key.find('.')+1:]
metaObjAttr = self.getMetaobjAttr( meta_id, key, syncTypes=['*'])
except:
_globals.writeError( self, "[getObjProperty]: Can't get attribute from meta-objects: %s.%s"%(self.meta_id,key))
#-- Special attributes.
if metaObjAttr is not None and metaObjAttr['type'] == 'interface':
try:
if metaObjAttr.get('py') is not None:
value = metaObjAttr['py'](zmscontext=self)
elif metaObjAttr.get('zpt') is not None:
value = metaObjAttr['zpt'](zmscontext=self)
value = unicode(value).encode('utf-8')
else:
value = _globals.dt_html(self,metaObjAttr.get('name',''),REQUEST)
except:
value = _globals.writeError(self,'[getObjProperty]: key=%s[%s]'%(key,metaObjAttr['type']))
elif metaObjAttr is not None and metaObjAttr['type'] == 'method':
try:
value = _globals.dt_html(self,metaObjAttr.get('custom',''),REQUEST)
except:
value = _globals.writeError(self,'[getObjProperty]: key=%s[%s]'%(key,metaObjAttr['type']))
elif metaObjAttr is not None and metaObjAttr['type'] == 'py':
try:
value = metaObjAttr['py'](zmscontext=self)
except:
value = _globals.writeError(self,'[getObjProperty]: key=%s[%s]'%(key,metaObjAttr['type']))
elif metaObjAttr is not None and metaObjAttr['type'] == 'zpt':
try:
value = metaObjAttr['zpt'](zmscontext=self)
value = unicode(value).encode('utf-8')
except:
value = _globals.writeError(self,'[getObjProperty]: key=%s[%s]'%(key,metaObjAttr['type']))
elif metaObjAttr is not None and metaObjAttr['type'] == 'constant':
value = metaObjAttr.get('custom','')
elif metaObjAttr is not None and metaObjAttr['type'] == 'resource':
value = _blobfields.MyBlobWrapper(metaObjAttr.get('custom',None))
#-- Standard attributes.
elif key in objAttrs.keys():
objAttr = objAttrs[key]
datatype = objAttr['datatype_key']
value = self.getObjAttrValue( objAttr, REQUEST)
if datatype == _globals.DT_TEXT and type(value) in StringTypes and value.find('<dtml-') >= 0:
try:
value = _globals.re_sub(self,'<dtml-sendmail(.*?)>(\r\n|\n)','<dtml-sendmail\\1>',value)
value = _globals.dt_html(self,value,REQUEST)
except:
value = _globals.writeError(self,'[getObjProperty]: key=%s'%key)
#-- Undefined attributes.
else:
value = ''
#-- [ReqBuff]: Returns value and stores it in buffer of Http-Request.
return self.storeReqBuff( reqBuffId, value, REQUEST)
# --------------------------------------------------------------------------
# ObjAttrs.attr:
#
# Get one or set one or more attributes.
#
# attr(key) -> getObjProperty(key,REQUEST)
# attr(key,value) -> setObjProperty(key,value)
# attr({key0:value0,...,keyN:valueN}) -> setObjProperty(key0,value0),...
# --------------------------------------------------------------------------
def attr(self, *args, **kwargs):
request = self.REQUEST
if len(args) == 1 and type(args[0]) is str:
return self.getObjProperty( args[0], request, kwargs)
elif len(args) == 2:
self.setObjProperty( args[0], args[1], request.get('lang'))
elif len(args) == 1 and type(args[0]) is dict:
for key in args[0].keys():
self.setObjProperty( key, args[0][key], request.get('lang'))
"""
############################################################################
###
### Active
###
############################################################################
"""
# --------------------------------------------------------------------------
# ObjAttrs.isActive:
# --------------------------------------------------------------------------
def isActive(self, REQUEST):
b = True
if self.getType()=='ZMSRecordSet':
return b
v = self.attr('active')
if type(v) is bool:
return v
v = self.attr('isActive')
if type(v) is bool:
b = b and v
obj_vers = self.getObjVersion(REQUEST)
obj_attrs = self.getObjAttrs()
for key in ['active','attr_active_start','attr_active_end']:
if obj_attrs.has_key(key):
obj_attr = obj_attrs[key]
lang = REQUEST.get('lang',self.getPrimaryLanguage())
while True:
value = self._getObjAttrValue(obj_attr,obj_vers,lang)
empty = False
lang = self.getParentLanguage(lang)
if lang is not None:
empty = value is None
if not empty:
break
# Toggle.
if key == 'active':
b = b and value
# Start time.
elif key == 'attr_active_start':
if value is not None:
try:
dt = DateTime(time.mktime(value))
b = b and dt.isPast()
except:
# todo: consistent replacement of time by datetime
dtValue = datetime.datetime(value[0],value[1],value[2],value[3],value[4],value[5],value[6])
b = b and datetime.datetime.now() > dtValue
# End time.
elif key == 'attr_active_end':
if value is not None:
try:
dt = DateTime(time.mktime(value))
b = b and (dt.isFuture() or (dt.equalTo(dt.earliestTime()) and dt.latestTime().isFuture()))
except:
# todo: consistent replacement of time by datetime
dtValue = datetime.datetime(value[0],value[1],value[2],value[3],value[4],value[5],value[6])
b = b and dtValue < datetime.datetime.now()
if not b: break
return b
"""
############################################################################
#
# Set
#
############################################################################
"""
# --------------------------------------------------------------------------
# ObjAttrs.formatObjAttrValue:
# --------------------------------------------------------------------------
def formatObjAttrValue(self, obj_attr, v, lang=None):
#-- DATATYPE
datatype = obj_attr.get('datatype_key',_globals.DT_UNKNOWN)
#-- VALUE
if type(v) in StringTypes:
chars = ''.join(filter(lambda x: x!='\t',string.whitespace))
v = v.strip(chars)
# Retrieve v from options.
if obj_attr.has_key('options'):
options = obj_attr['options']
try:
i = options.index(int(v))
if i%2==1: v = options[i-1]
except:
try:
i = options.index(str(v))
if i%2==1: v = options[i-1]
except:
pass
#-- Blob-Fields
if datatype in _globals.DT_BLOBS:
if self.getType()=='ZMSRecordSet' and \
str(v) == str(_blobfields.createBlobField(self,datatype)):
l = self.getObjProperty(self.getMetaobj(self.meta_id)['attrs'][0]['id'],self.REQUEST)
r = filter(lambda x: v.equals(x.get(obj_attr['id'],None)),l)
if len( r) == 0:
v = None
else:
v = v._getCopy()
v.aq_parent = self
v.key = '%s:%i'%(obj_attr['id'],l.index(r[0]))
v.lang = lang
if isinstance(v,ZPublisher.HTTPRequest.FileUpload):
if len(getattr(v,'filename',''))==0:
v = None
else:
v = _blobfields.createBlobField(self,datatype,v)
if type(v) is dict:
if len(v.get('filename',''))==0:
v = None
else:
v = _blobfields.createBlobField(self,datatype,v)
#-- DateTime-Fields.
elif datatype in _globals.DT_DATETIMES:
if type(v) in StringTypes:
fmt_str = 'DATETIME_FMT'
if datatype == _globals.DT_DATE:
fmt_str = 'DATE_FMT'
elif datatype == _globals.DT_TIME:
fmt_str = 'TIME_FMT'
v = self.parseLangFmtDate(v)
elif type(v) is not time.struct_time:
v = _globals.getDateTime(v)
#-- Dictionary-Fields
elif datatype == _globals.DT_DICT:
if v is None:
v = {}
if type(v) in StringTypes:
try:
v = self.parseXmlString(self.getXmlHeader() + v)
except:
_globals.writeError( self, "[formatObjAttrValue]: can't parse dict from xml - exception ignored!")
pass
if type(v) is dict:
v = v.copy()
#-- List-Fields
elif datatype == _globals.DT_LIST:
if obj_attr['repetitive'] and not type(v) is list:
if obj_attr['type'] in ['file','image']:
l = self.getObjProperty(obj_attr['id'],self.REQUEST)
r = filter(lambda x: v is not None and v.equals(x),l)
if len( r) == 0:
v = None
else:
v = v._getCopy()
v.aq_parent = self
v.key = '%s:%i'%(obj_attr['id'],l.index(r[0]))
v.lang = lang
else:
if v is None:
v = []
if type(v) in StringTypes:
try:
l = self.parseXmlString(self.getXmlHeader() + v)
except:
_globals.writeError( self, "[formatObjAttrValue]: can't parse list from xml - exception ignored!")
l = None
if l is not None:
v = l
else:
v = [v.strip()]
if type(v) is list or type(v) is tuple:
v = self.copy_list(v)
#-- Integer-Fields
elif datatype in _globals.DT_INTS:
if type(v) in StringTypes and len(v) > 0:
if v[-1] == '.':
v = v[:-1]
v = int(v)
#-- Float-Fields
elif datatype == _globals.DT_FLOAT:
if type(v) in StringTypes and len(v) > 0:
v = float(v)
#-- String-Fields.
elif datatype in _globals.DT_STRINGS:
if v is None:
v = ''
#-- Text-Fields
if datatype == _globals.DT_TEXT:
# Inline-links: getLinkUrl (deprecated!)
i = -1
start = '{$'
end = '}'
while True:
i = v.find( start, i + 1)
j = v.find( end, i + 1)
if i < 0 or j < 0:
break
ref_url = v[i:j+1]
ref_obj = self.getLinkObj(ref_url)
if ref_obj is not None:
# Repair link.
ref_url = self.getRefObjPath(ref_obj)
v = v[:i] + ref_url + v[j+1:]
elif ref_url.find('{$') == 0 and ref_url.find('{$__') < 0:
# Broken link.
ref_url = '{$__' + ref_url[2:-1] + '__}'
v = v[:i] + ref_url + v[j+1:]
#-- Url-Fields
if datatype == _globals.DT_URL and v.startswith('{$') and not v.startswith('{$__') and self.getConfProperty('ZMS.InternalLinks.autocorrection',0)==1:
v = self.validateLinkObj(v)
# Hook for custom formatting.
name = 'formatCustomObjAttrValue'
if hasattr(self,name):
v = getattr(self,name)( context=self, obj_attr=obj_attr, v=v)
return v
# --------------------------------------------------------------------------
# ObjAttrs.setReqProperty:
#
# Assigns value to specified property from Request-Object.
# --------------------------------------------------------------------------
def setReqProperty(self, key, REQUEST, forced=0):
#-- REQUEST
lang = REQUEST['lang']
#-- DEFINTION
obj_attr = self.getObjAttr(key)
attr = self.getObjAttrName(obj_attr,lang)
elName = self.REQUEST.get('objAttrNamePrefix','') + attr
#-- ENABLED
enabled = not self.isDisabledAttr(obj_attr,REQUEST)
#-- DATATYPE
datatype = obj_attr['datatype_key']
#-- RETURN
if ( not enabled) or \
( not obj_attr['xml']) or \
( obj_attr['id'].find('_') == 0 and not REQUEST.form.has_key(elName)) or \
( datatype == _globals.DT_UNKNOWN):
if not forced:
return