-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZMSMetaobjManager.py
1291 lines (1201 loc) · 56.5 KB
/
ZMSMetaobjManager.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
################################################################################
# ZMSMetaobjManager.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 zope.interface import implements
from Products.ExternalMethod import ExternalMethod
from Products.PageTemplates import ZopePageTemplate
from Products.PythonScripts import PythonScript
from cStringIO import StringIO
import ZPublisher.HTTPRequest
import copy
import os
import sys
import time
import zExceptions
# Product Imports.
import _blobfields
import _fileutil
import _globals
import _ziputil
# ------------------------------------------------------------------------------
# Synchronize type.
# ------------------------------------------------------------------------------
syncTypes = ['method','py','zpt','interface','resource']
def syncType( self, id, attr, forced=False):
try:
if attr['type'] not in self.valid_zopetypes+syncTypes:
return
attr_id = attr['id']
if attr['type'] in self.valid_zopetypes:
container = self.getHome()
for ob_id in attr_id.split('/')[:-1]:
container = getattr( container, ob_id)
ob_id = attr['id'].split('/')[-1]
ob = getattr( container, ob_id)
if ob.meta_type in [ 'DTML Method', 'DTML Document']:
attr['custom'] = ob.raw
elif ob.meta_type in [ 'Folder']:
zip = _ziputil.exportZodb2Zip(ob)
blob = _blobfields.createBlobField( self,_globals.DT_FILE, zip, mediadbStorable=False)
attr['custom'] = blob
elif ob.meta_type in [ 'Page Template']:
attr['custom'] = unicode(ob.read()).encode('utf-8')
elif ob.meta_type in [ 'Script (Python)']:
attr['custom'] = ob.read()
elif ob.meta_type in [ 'Z SQL Method']:
connection = ob.connection_id
params = ob.arguments_src
attr['custom'] = '<connection>%s</connection>\n<params>%s</params>\n%s'%(connection,params,ob.src)
else:
ob = getattr(self,id+'.'+attr_id,None)
if ob is not None:
if attr['type'] == 'method':
attr['custom'] = ob.raw
elif attr['type'] == 'py':
attr['py'] = ob
attr['custom'] = ob.read()
elif attr['type'] == 'zpt':
attr['zpt'] = ob
attr['custom'] = unicode(ob.read()).encode('utf-8')
elif attr['type'] == 'interface':
if ob.meta_type in ['Page Template']:
attr['zpt'] = ob
attr['name'] = unicode(ob.read()).encode('utf-8')
elif ob.meta_type in [ 'Script (Python)']:
attr['py'] = ob
attr['name'] = ob.read()
else:
attr['name'] = ob.raw
elif attr['type'] == 'resource':
attr['custom'] = ob
except:
value = _globals.writeError(self,'[syncType]')
################################################################################
################################################################################
###
### Class
###
################################################################################
################################################################################
class ZMSMetaobjManager:
# Globals.
# --------
valid_types = ['amount','autocomplete','boolean','color','date','datetime','dictionary','file','float','identifier','image','int','list','multiautocomplete','multiselect','password','richtext','select','string','text','time','url','xml']
valid_xtypes = ['constant','delimiter','hint','interface','method','py','zpt','resource']
valid_datatypes = valid_types+valid_xtypes
valid_datatypes.sort()
valid_objtypes = [ 'ZMSDocument', 'ZMSObject', 'ZMSTeaserElement', 'ZMSRecordSet', 'ZMSResource', 'ZMSReference', 'ZMSLibrary', 'ZMSPackage', 'ZMSModule']
valid_zopetypes = [ 'DTML Method', 'DTML Document', 'External Method', 'Folder', 'Page Template', 'Script (Python)', 'Z SQL Method']
deprecated_types = [ 'DTML Method', 'DTML Document', 'method']
############################################################################
#
# XML IM/EXPORT
#
############################################################################
# --------------------------------------------------------------------------
# ZMSMetaobjManager.importMetaobjXml
# --------------------------------------------------------------------------
def _importMetaobjXml(self, item, zms_system=0, createIfNotExists=1, createIdsFilter=None):
id = item['key']
meta_types = self.model.keys()
ids = filter( lambda x: self.model[x].get('zms_system',0)==1, meta_types)
if (createIfNotExists == 1 or (id in ids and item.get('value').get('package')==self.model.get(id).get('package'))) and \
(createIdsFilter is None or (id in createIdsFilter)):
# Register Meta Attributes.
metadictAttrs = []
if id in meta_types:
valid_types = self.valid_datatypes+self.valid_zopetypes+meta_types+['*']
metaObj = self.getMetaobj( id)
for metaObjAttr in metaObj['attrs']:
if metaObjAttr['type'] not in valid_types+metadictAttrs:
metadictAttrs.append( metaObjAttr['type'])
newDtml = item.get('dtml')
newValue = item.get('value')
newAttrs = newValue.get('attrs',newValue.get('__obj_attrs__'))
newValue['attrs'] = []
newValue['id'] = id
newValue['enabled'] = newValue.get('enabled',item.get('enabled',1))
newValue['zms_system'] = item.get('zms_system',zms_system)
# Delete Object.
oldAttrs = None
if id in ids:
if zms_system == 1:
oldAttrs = self.getMetaobj( id)['attrs']
self.delMetaobj( id)
# Set Object.
self.setMetaobj( newValue)
# Set Attributes.
attr_ids = []
for attr in newAttrs:
# Mandatory.
attr_id = attr.get('id')
newName = attr.get('name')
newMandatory = attr.get('mandatory')
newMultilang = attr.get('multilang')
newRepetitive = attr.get('repetitive')
newType = attr.get('type')
# Optional.
newKeys = attr.get('keys',[])
newCustom = attr.get('custom','')
newDefault = attr.get('default','')
# Old Attribute.
if type(oldAttrs) is list and len(oldAttrs) > 0:
while len(oldAttrs) > 0 and not (attr_id == oldAttrs[0]['id'] and newType == oldAttrs[0]['type']):
oldAttr = oldAttrs[0]
# Set Attribute.
if oldAttr['id'] not in attr_ids:
self.setMetaobjAttr( id, None, oldAttr['id'], oldAttr['name'], oldAttr['mandatory'], oldAttr['multilang'], oldAttr['repetitive'], oldAttr['type'], oldAttr['keys'], oldAttr['custom'], oldAttr['default'], zms_system)
attr_ids.append(oldAttr['id'])
# Deregister Meta Attribute.
if oldAttr['id'] in metadictAttrs:
metadictAttrs.remove(oldAttr['id'])
oldAttrs.remove( oldAttr)
if len(oldAttrs) > 0:
oldAttrs.remove( oldAttrs[0])
# Set Attribute.
if attr_id not in attr_ids:
self.setMetaobjAttr( id, attr_id, attr_id, newName, newMandatory, newMultilang, newRepetitive, newType, newKeys, newCustom, newDefault, zms_system)
attr_ids.append(attr_id)
# Deregister Meta Attribute.
if attr_id in metadictAttrs:
metadictAttrs.remove(attr_id)
# Set Meta Attributes.
for attr_id in metadictAttrs:
newName = attr_id
newMandatory = 0
newMultilang = 0
newRepetitive = 0
newType = attr_id
newKeys = []
newCustom = ''
newDefault = ''
# Set Attribute.
if attr_id not in attr_ids:
self.setMetaobjAttr( id, None, attr_id, newName, newMandatory, newMultilang, newRepetitive, newType, newKeys, newCustom, newDefault)
attr_ids.append(attr_id)
# Set Template (backwards compatibility).
if newValue['type'] not in [ 'ZMSLibrary', 'ZMSModule', 'ZMSPackage'] and newDtml is not None:
tmpltId = 'standard_html'
tmpltName = 'Template: %s'%newValue['name']
tmpltCustom = newDtml
newType = 'DTML Method'
newKeys = []
newDefault = ''
self.setMetaobjAttr(id,tmpltId,tmpltId,tmpltName,0,0,0, newType, newKeys, tmpltCustom, newDefault, zms_system)
return id
def importMetaobjXml(self, xml, REQUEST=None, zms_system=0, createIfNotExists=1, createIdsFilter=None):
self.REQUEST.set( '__get_metaobjs__', True)
ids = []
v = self.parseXmlString( xml, mediadbStorable=False)
if not type(v) is list:
v = [v]
for item in v:
id = self._importMetaobjXml(item,zms_system,createIfNotExists,createIdsFilter)
ids.append( id)
if len( ids) == 1:
ids = ids[ 0]
return ids
def exportMetaobjXml(self, ids, REQUEST=None, RESPONSE=None):
value = []
for id in ids:
metaObj = self.getMetaobj( id)
if metaObj['type'] == 'ZMSPackage':
for pkgMetaObjId in self.getMetaobjIds():
pkgMetaObj = self.getMetaobj( pkgMetaObjId)
if pkgMetaObj[ 'package'] == metaObj[ 'id']:
ids.append( pkgMetaObjId)
keys = self.model.keys()
keys.sort()
revision = '0.0.0'
for id in keys:
if id in ids or len(ids) == 0:
ob = copy.deepcopy(self.__get_metaobj__(id))
revision = ob.get( 'revision', revision)
attrs = []
for attr in ob['attrs']:
attr_id = attr['id']
syncType( self, id, attr)
for key in ['keys','custom','default']:
if attr.has_key(key) and not attr[key]:
del attr[key]
for key in ['sync','py','zpt']:
if attr.has_key(key):
del attr[key]
attrs.append( attr)
ob['__obj_attrs__'] = attrs
for key in ['attrs','zms_system','acquired']:
if ob.has_key(key):
del ob[key]
# Value.
value.append({'key':id,'value':ob})
# XML.
if len(value)==1:
value = value[0]
filename = '%s-%s.metaobj.xml'%(ids[0],revision)
else:
filename = 'export.metaobj.xml'
content_type = 'text/xml; charset=utf-8'
export = self.getXmlHeader() + self.toXmlString(value,1)
if RESPONSE:
RESPONSE.setHeader('Content-Type',content_type)
RESPONSE.setHeader('Content-Disposition','attachment;filename="%s"'%filename)
return export
############################################################################
#
# OBJECTS
#
############################################################################
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getTemplateId
#
# Returns template-id for meta-object specified by given Id.
# @deprecated
# --------------------------------------------------------------------------
def getTemplateId(self, id):
return "bodyContentZMSCustom_%s"%id
# --------------------------------------------------------------------------
# ZMSMetaobjManager.renderTemplate
#
# Renders template for meta-object.
# --------------------------------------------------------------------------
def renderTemplate(self, obj):
v = ""
id = obj.meta_id
tmpltIds = []
if obj.REQUEST.get("ZMS_SKIN") is not None and obj.REQUEST.get("ZMS_EXT") is not None:
tmpltIds.append("%s_%s"%(obj.REQUEST.get("ZMS_SKIN"),obj.REQUEST.get("ZMS_EXT")))
tmpltIds.append("standard_html")
tmpltIds.append("bodyContentZMSCustom_%s"%id)
for tmpltId in tmpltIds:
if tmpltId in obj.getMetaobjAttrIds(id):
if obj.getMetaobjAttr(id,tmpltId)['type'] in ['method','py','zpt']:
v = obj.attr(tmpltId)
break
elif tmpltId not in ["standard_html"]:
tmpltDtml = getattr(obj,tmpltId,None)
if tmpltDtml is not None:
v = tmpltDtml(obj,obj.REQUEST)
try:
v = v.encode('utf-8')
except UnicodeDecodeError:
v = str(v)
break
return v
# --------------------------------------------------------------------------
# ZMSMetaobjManager.__get_metaobjs__:
#
# Returns all meta-objects (including acquisitions).
# --------------------------------------------------------------------------
def __get_metaobjs__(self):
#-- [ReqBuff]: Fetch buffered value from Http-Request.
reqBuffId = '__get_metaobjs__'
try:
forced = \
not self.REQUEST.get( '__get_metaobjs__', False) and \
not self.REQUEST.get( 'recurse_updateVersionBuild', False)
obs = self.fetchReqBuff( reqBuffId, self.REQUEST, forced)
return obs
except:
obs = {}
raw = self.model
master_obs = None
for ob_id in raw.keys():
ob = raw.get(ob_id)
# Acquire from parent.
if ob.get('acquired',0) == 1:
acquired = 1
subobjects = ob.get('subobjects',1)
if master_obs is None:
portalMaster = self.getPortalMaster()
if portalMaster is not None:
master_obs = portalMaster.metaobj_manager.__get_metaobjs__()
if master_obs is not None:
if master_obs.has_key(ob_id):
ob = master_obs[ob_id].copy()
else:
ob = {'id':ob_id,'type':'ZMSUnknown'}
ob['acquired'] = acquired
ob['subobjects'] = subobjects
obs[ob_id] = ob
if ob['type'] == 'ZMSPackage' and ob['subobjects'] == 1:
package = ob_id
for ob_id in master_obs.keys():
ob = master_obs[ob_id].copy()
if ob.get( 'package') == package:
ob['acquired'] = 1
obs[ob_id] = ob
else:
obs[ob_id] = ob
#-- [ReqBuff]: Returns value and stores it in buffer of Http-Request.
return self.storeReqBuff( reqBuffId, obs, self.REQUEST)
# --------------------------------------------------------------------------
# ZMSMetaobjManager.__get_metaobj__:
#
# Returns meta-object identified by id.
# --------------------------------------------------------------------------
def __get_metaobj__(self, id):
obs = self.__get_metaobjs__()
ob = obs.get( id)
return ob
# --------------------------------------------------------------------------
# ZMSMetaobjManager.__is_page_container__:
# --------------------------------------------------------------------------
def __is_page_container__(self, id):
#-- [ReqBuff]: Fetch buffered value from Http-Request.
reqBuffId = '__%s_is_page_container__'%id
try:
forced = True
return self.fetchReqBuff( reqBuffId, self.REQUEST, forced)
except:
rtnVal = False
ob = self.__get_metaobj__( id)
if type( ob) is dict and (ob.get('type') == 'ZMSDocument' or ob.get('id') == 'ZMSTeaserContainer'):
ids = map( lambda x: x['id'], filter( lambda x: x['type']=='*', ob['attrs']))
rtnVal = ids == ['e']
#-- [ReqBuff]: Returns value and stores it in buffer of Http-Request.
return self.storeReqBuff( reqBuffId, rtnVal, self.REQUEST)
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobjIds:
#
# Returns list of all meta-ids in model.
# --------------------------------------------------------------------------
def getMetaobjIds(self, sort=1, excl_ids=[]):
obs = self.__get_metaobjs__()
ids = obs.keys()
if len( excl_ids) > 0:
excl_types = [ 'ZMSPackage']
ids = filter( lambda x: x not in excl_ids and obs[x]['type'] not in excl_types, ids)
if sort:
mapping = map(lambda x: (self.display_type(self.REQUEST,x),x),ids)
mapping.sort()
ids = map(lambda x: x[1],mapping)
return ids
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobj:
#
# Returns meta-object specified by id.
# --------------------------------------------------------------------------
def getMetaobj(self, id):
return _globals.nvl( self.__get_metaobj__(id), {'id':id, 'attrs':[], })
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobjId:
#
# Returns id of meta-object specified by name.
# --------------------------------------------------------------------------
def getMetaobjId(self, name):
for id in self.getMetaobjIds():
if name == self.display_type(meta_type=id):
return id
return None
# --------------------------------------------------------------------------
# ZMSMetaobjManager.setMetaobj:
#
# Sets meta-object with specified values.
# --------------------------------------------------------------------------
def setMetaobj(self, ob):
obs = self.model
ob = ob.copy()
ob[ 'name'] = ob.get( 'name', '')
ob[ 'revision'] = ob.get( 'revision', '0.0.0')
ob[ 'type'] = ob.get( 'type', '')
ob[ 'package'] = ob.get( 'package', '')
ob[ 'attrs'] = ob.get( 'attrs', ob.get( '__obj_attrs__', []))
ob[ 'acquired'] = ob.get( 'acquired' ,0)
ob[ 'enabled'] = ob.get( 'enabled', 1)
ob[ 'zms_system'] = ob.get( 'zms_system', 0)
if ob.has_key('__obj_attrs__'):
del ob['__obj_attrs__']
obs[ob['id']] = ob
# Make persistent.
self.model = self.model.copy()
# --------------------------------------------------------------------------
# ZMSMetaobjManager.acquireMetaobj:
#
# Acquires meta-object specified by id.
# --------------------------------------------------------------------------
def acquireMetaobj(self, id, subobjects=1):
obs = self.model
ob = self.getMetaobj( id)
if ob is not None and len( ob.keys()) > 0 and subobjects == 1:
if ob.get('type','') == 'ZMSPackage':
pk_obs = filter( lambda x: x.get('package') == id, obs.values())
pk_ids = map( lambda x: x['id'], pk_obs)
for pk_id in pk_ids:
self.delMetaobj( pk_id)
self.delMetaobj( id)
ob = {}
ob['id'] = id
ob['acquired'] = 1
ob['subobjects'] = subobjects
self.setMetaobj( ob)
# Make persistent.
self.model = self.model.copy()
# --------------------------------------------------------------------------
# ZMSMetaobjManager.delMetaobj:
#
# Delete meta-object specified by id.
# --------------------------------------------------------------------------
def delMetaobj(self, id):
# Handle type.
ids = filter( lambda x: x.startswith(id+'.'), self.objectIds())
if ids:
self.manage_delObjects( ids)
# Delete object.
cp = self.model
obs = {}
for key in cp.keys():
if key == id:
# Delete attributes.
attr_ids = map( lambda x: x['id'], cp[key]['attrs'] )
for attr_id in attr_ids:
self.delMetaobjAttr( id, attr_id)
else:
obs[key] = cp[key]
# Make persistent.
self.model = obs.copy()
############################################################################
#
# ATTRIBUTES
#
############################################################################
# --------------------------------------------------------------------------
# ZMSMetaobjManager.notifyMetaobjAttrAboutValue:
#
# Notify attribute for meta-object specified by attribute-id about value.
# --------------------------------------------------------------------------
def notifyMetaobjAttrAboutValue(self, meta_id, key, value):
sync_id = False
attr = self.getMetaobjAttr( meta_id, key)
if attr is not None:
# Self-learning auto-complete attributes.
if attr.get('type') in ['autocomplete','multiautocomplete']:
keys = attr['keys']
if ''.join(keys).find('<dtml') < 0:
if type(value) is not list:
value = [value]
for v in value:
if v not in keys:
keys.append(v)
sync_id = meta_id
if sync_id:
self.setMetaobjAttr( meta_id, key, key, attr['name'], attr['mandatory'], attr['multilang'], attr['repetitive'], attr['type'], keys, attr['custom'], attr['default'])
##### SYNCHRONIZE ####
if sync_id:
self.synchronizeObjAttrs( sync_id)
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobjAttrIdentifierId:
#
# Get attribute-id of identifier for datatable specified by meta-id.
# --------------------------------------------------------------------------
def getMetaobjAttrIdentifierId(self, meta_id):
for attr_id in self.getMetaobjAttrIds( meta_id, types=[ 'identifier', 'string', 'int']):
return attr_id
return None
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobjAttrIds:
#
# Returns list of attribute-ids for meta-object specified by meta-id.
# --------------------------------------------------------------------------
def getMetaobjAttrIds(self, id, types=[]):
return map(lambda x: x['id'], self.getMetaobjAttrs( id, types))
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobjAttrs:
#
# Returns list of attribute-ids for meta-object specified by meta-id.
# --------------------------------------------------------------------------
def getMetaobjAttrs(self, id, types=[]):
attrs = []
ob = self.__get_metaobj__(id)
if ob is not None:
attrs = ob.get('attrs',ob.get('__obj_attrs__'))
if attrs is None:
raise zExceptions.InternalError('Can\'t getMetaobjAttrIds: %s'%(str(id)))
if len( types) > 0:
attrs = filter( lambda x: x['type'] in types, attrs)
return attrs
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobjAttr:
#
# Get attribute for meta-object specified by attribute-id.
# --------------------------------------------------------------------------
def getMetaobjAttr(self, id, attr_id, syncTypes=['resource']):
meta_objs = self.__get_metaobjs__()
if meta_objs.get(id,{}).get('acquired',0) == 1:
portalMaster = self.getPortalMaster()
if portalMaster is not None:
attr = portalMaster.getMetaobjAttr( id, attr_id, syncTypes)
return attr
meta_obj = meta_objs.get(id,{})
attrs = meta_obj.get('attrs',meta_obj.get('__obj_attrs__'))
if attrs is None:
if id == 'ZMSTrashcan':
return {}
raise zExceptions.InternalError('Can\'t getMetaobjAttr %s.%s'%(str(id),str(attr_id)))
for attr in attrs:
valid_datatype = attr['type'] in self.valid_datatypes
if attr_id == attr['type'] and not valid_datatype:
meta_attrs = self.getMetadictAttrs()
if attr['type'] in meta_attrs:
attr_type = attr['type']
attr = self.getMetadictAttr(attr['type'])
attr = attr.copy()
attr['meta_type'] = attr_type
return attr
if attr_id == attr['id']:
attr = attr.copy()
attr['datatype_key'] = _globals.datatype_key(attr['type'])
attr['mandatory'] = attr.get('mandatory',0)
attr['multilang'] = attr.get('multilang',1)
attr['errors'] = attr.get('errors','')
attr['meta_type'] = ['','?'][int(attr['type']==attr['id'] and not valid_datatype)]
if '*' in syncTypes or attr['type'] in syncTypes: syncType( self, id, attr)
return attr
return None
# --------------------------------------------------------------------------
# ZMSMetaobjManager.setMetaobjAttr:
#
# Set/add meta-object attribute with specified values.
# --------------------------------------------------------------------------
def setMetaobjAttr(self, id, oldId, newId, newName='', newMandatory=0, newMultilang=1, newRepetitive=0, newType='string', newKeys=[], newCustom='', newDefault='', zms_system=0):
ob = self.__get_metaobj__(id)
if ob is None: return
attrs = copy.copy(ob['attrs'])
# Set Attributes.
if newType in ['delimiter','hint','interface']:
newCustom = ''
if newType in ['resource'] and (type(newCustom) is str or type(newCustom) is int):
newCustom = None
if newType not in ['*','autocomplete','multiautocomplete','multiselect','recordset','select']:
newKeys = []
if newType in self.getMetaobjIds(sort=0)+['*']:
newMultilang = 0
# Defaults for Insert
method_types = [ 'method','py','zpt'] + self.valid_zopetypes
if oldId is None and \
newType in method_types and \
(newCustom == '' or type(newCustom) is not str):
if newType in [ 'method', 'DTML Method', 'DTML Document']:
newCustom = ''
newCustom += '<!-- '+ newId + ' -->\n'
newCustom += '\n'
newCustom += '<!-- /'+ newId + ' -->\n'
elif newType in [ 'External Method']:
newCustom = ''
newCustom += '# Example code:\n'
newCustom += '\n'
newCustom += 'def ' + newId + '( self):\n'
newCustom += ' return "This is the external method ' + newId + '"\n'
elif newType in [ 'zpt', 'Page Template']:
newCustom = ''
newCustom += '<span tal:replace="here/title_or_id">content title or id</span>'
newCustom += '<span tal:condition="template/title" tal:replace="template/title">optional template title</span>'
elif newType in [ 'py', 'Script (Python)']:
newCustom = '## Script (Python) ""\n'
newCustom += '##bind container=container\n'
newCustom += '##bind context=context\n'
newCustom += '##bind namespace=\n'
newCustom += '##bind script=script\n'
newCustom += '##bind subpath=traverse_subpath\n'
newCustom += '##parameters='
if newType in ['py']: newCustom += 'zmscontext=None'
newCustom += '\n'
newCustom += '##title='
if newType in ['py']: newCustom += newType+': '
newCustom += newName
newCustom += '\n'
newCustom += '##\n'
newCustom += '# --// '+ newId + ' //--\n'
newCustom += '# Example code:\n'
newCustom += '\n'
newCustom += '# Import a standard function, and get the HTML request and response objects.\n'
newCustom += 'from Products.PythonScripts.standard import html_quote\n'
newCustom += 'request = container.REQUEST\n'
newCustom += 'RESPONSE = request.RESPONSE\n'
newCustom += '\n'
newCustom += '# Return a string identifying this script.\n'
newCustom += 'print "This is the", script.meta_type, \'"%s"\' % script.getId(),\n'
newCustom += 'if script.title:\n'
newCustom += ' print "(%s)" % html_quote(script.title),\n'
newCustom += 'print "in", container.absolute_url()\n'
newCustom += 'return printed\n'
newCustom += '\n'
newCustom += '# --// /'+ newId + ' //--\n'
elif newType in [ 'Z SQL Method']:
newCustom = ''
newCustom += '<connection>%s</connection>\n'%self.SQLConnectionIDs()[0][0]
newCustom += '<params></params>\n'
newCustom += 'SELECT * FROM tablename\n'
# Handle resources.
if (newType in ['resource']) or \
(newMandatory and newType in self.getMetaobjIds()) or \
(newRepetitive and newType in self.getMetaobjIds()):
if not newCustom:
if oldId is not None and id+'.'+oldId in self.objectIds():
self.manage_delObjects(ids=[id+'.'+oldId])
elif isinstance( newCustom, _blobfields.MyFile):
if oldId is not None and id+'.'+oldId in self.objectIds():
self.manage_delObjects(ids=[id+'.'+oldId])
self.manage_addFile( id=id+'.'+newId, file=newCustom.getData(),title=newCustom.getFilename(),content_type=newCustom.getContentType())
elif oldId is not None and oldId != newId and id+'.'+oldId in self.objectIds():
self.manage_renameObject(id=id+'.'+oldId,new_id=id+'.'+newId)
newCustom = ''
attr = {}
attr['sync'] = False
attr['id'] = newId
attr['name'] = newName
attr['mandatory'] = newMandatory
attr['multilang'] = newMultilang
attr['repetitive'] = newRepetitive
attr['type'] = newType
attr['keys'] = newKeys
attr['custom'] = newCustom
attr['default'] = newDefault
# Parse Dtml for Errors.
newOb = None
message = ''
if newType in [ 'delimiter', 'hint', 'interface']:
newCustom = newName
if newCustom.find('<tal:') >= 0:
newType = 'zpt'
else:
newType = 'method'
if newType in [ 'DTML Method', 'DTML Document', 'method', 'py', 'zpt']:
newCustom = newCustom.replace('\r','')
if type(newCustom) is str and len(newCustom) > 0:
message = _globals.dt_parse( self, newCustom)
if len( message) > 0:
attr['errors'] = message
message = '<div class="ui-state-error ui-corner-all">DTML-Error in '+newId+'<br>'+message+'</div>'
# Handle methods and interfaces.
if newType in ['method']:
if oldId is not None and id+'.'+oldId in self.objectIds():
self.manage_delObjects(ids=[id+'.'+oldId])
self.manage_addDTMLMethod( id+'.'+newId, newType, newCustom)
newOb = getattr( self, id+'.'+newId)
roles=[ 'Manager']
newOb._proxy_roles=tuple(roles)
# Handle py.
if newType in ['py']:
if oldId is not None and id+'.'+oldId in self.objectIds():
self.manage_delObjects(ids=[id+'.'+oldId])
PythonScript.manage_addPythonScript( self, id+'.'+newId)
newOb = getattr( self, id+'.'+newId)
newOb.write(newCustom)
roles=[ 'Manager']
newOb._proxy_roles=tuple(roles)
# Handle zpt.
elif newType in ['zpt']:
if oldId is not None and id+'.'+oldId in self.objectIds():
self.manage_delObjects(ids=[id+'.'+oldId])
ZopePageTemplate.manage_addPageTemplate( self, id+'.'+newId, title=newType, text=newCustom)
newOb = getattr(self,id+'.'+newId)
newOb.output_encoding = 'utf-8'
# Restrict access.
if newOb is not None:
newOb.manage_acquiredPermissions([])
permissions = map(lambda x: x['name'],newOb.permissionsOfRole('Manager'))
for role_to_manage in [ 'ZMSAuthor', 'ZMSEditor', 'ZMSAdministrator']:
newOb.manage_role(role_to_manage=role_to_manage,permissions=permissions)
# Replace
ids = map( lambda x: x['id'], attrs) # self.getMetaobjAttrIds(id)
if oldId in ids:
i = ids.index(oldId)
attrs[i] = attr
else:
# Always append new methods at the end.
if oldId == newId or newType in method_types:
attrs.append( attr)
# Insert new attributes before methods
else:
i = len( attrs)
while i > 0 and attrs[ i - 1][ 'type'] in method_types:
i -= 1
if i < len(attrs):
attrs.insert( i, attr)
else:
attrs.append( attr)
ob['attrs'] = attrs
# Handle native Zope-Objects.
if newType in self.valid_zopetypes:
# Get container.
container = self.getHome()
for ob_id in newId.split('/')[:-1]:
if ob_id not in container.objectIds():
container.manage_addFolder(id=ob_id,title='Folder: %s'%id)
container = getattr( container, ob_id)
newObId = newId.split('/')[-1]
# Get container (old).
if oldId is not None:
oldContainer = self.getHome()
for ob_id in oldId.split('/')[:-1]:
oldContainer = getattr(oldContainer,ob_id,None)
oldObId = oldId.split('/')[-1]
# External Method.
if newType == 'External Method':
try:
_fileutil.remove( INSTANCE_HOME+'/Extensions/'+oldObId+'.py')
except:
pass
newExternalMethod = INSTANCE_HOME+'/Extensions/'+newObId+'.py'
_fileutil.exportObj( newCustom, newExternalMethod)
# Insert Zope-Object.
if oldId is None or oldId == newId:
# Delete existing Zope-Object.
if newObId in container.objectIds():
if newType in ['External Method', 'Page Template'] or \
newType not in self.valid_zopetypes:
container.manage_delObjects( ids=[ newObId])
# Delete old Zope-Object if type is incompatible.
if newObId in container.objectIds() and getattr(container,newObId).meta_type != newType:
container.manage_delObjects( ids=[ newObId])
# Add new Zope-Object.
if newObId not in container.objectIds():
if newType == 'DTML Method':
container.manage_addDTMLMethod( newObId, newName, newCustom)
elif newType == 'DTML Document':
container.manage_addDTMLDocument( newObId, newName, newCustom)
elif newType == 'External Method':
ExternalMethod.manage_addExternalMethod( container, newObId, newName, newId, newId)
elif newType == 'Folder':
container.manage_addFolder(id=newObId,title=newName)
elif newType == 'Page Template':
ZopePageTemplate.manage_addPageTemplate( container, newObId, title=newName, text=newCustom)
newOb = getattr( container, newObId)
newOb.output_encoding = 'utf-8'
elif newType == 'Script (Python)':
PythonScript.manage_addPythonScript( container, newObId)
elif newType == 'Z SQL Method':
try:
from Products.ZSQLMethods import SQL
connection_id = self.SQLConnectionIDs()[0][0]
arguments = ''
template = ''
SQL.manage_addZSQLMethod( container, newObId, newName, connection_id, arguments, template)
except:
pass
# Rename Zope-Object.
elif oldId != newId:
if oldContainer != container:
cb_copy_data = oldContainer.manage_cutObjects( ids=[oldObId])
container.manage_pasteObjects( cb_copy_data)
if oldObId != newObId:
container.manage_renameObject( id=oldObId, new_id=newObId)
# Change Zope-Object.
newOb = getattr( container, newObId)
if newType in [ 'DTML Method', 'DTML Document']:
newOb.manage_edit( title=newName, data=newCustom)
roles=[ 'Manager']
newOb._proxy_roles=tuple(roles)
if newId.find( 'manage_') >= 0:
newOb.manage_role(role_to_manage='Authenticated',permissions=['View'])
newOb.manage_acquiredPermissions([])
elif newType == 'Folder':
if isinstance( newCustom, _blobfields.MyFile) and len(newCustom.getData()) > 0:
newOb.manage_delObjects(ids=newOb.objectIds())
_ziputil.importZip2Zodb( newOb, newCustom.getData())
attr['custom'] = ''
elif newType == 'Script (Python)':
newOb.write(newCustom)
roles=[ 'Manager']
newOb._proxy_roles=tuple(roles)
if newId.find( 'manage_') >= 0:
newOb.manage_role(role_to_manage='Authenticated',permissions=['View'])
newOb.manage_acquiredPermissions([])
elif newType == 'Z SQL Method':
connection = newCustom
connection = connection[connection.find('<connection>'):connection.find('</connection>')]
connection = connection[connection.find('>')+1:]
arguments = newCustom
arguments = arguments[arguments.find('<params>'):arguments.find('</params>')]
arguments = arguments[arguments.find('>')+1:]
template = newCustom
template = template[template.find('</params>'):]
template = template[template.find('>')+1:]
template = '\n'.join(filter( lambda x: len(x) > 0, template.split('\n')))
newOb.manage_edit(title=newName,connection_id=connection,arguments=arguments,template=template)
# Assign Attributes to Meta-Object.
ob['zms_system'] = int( ob['zms_system'] and (oldId is None or zms_system))
self.model[id] = ob
# Make persistent.
self.model = self.model.copy()
# Return with message.
return message
# --------------------------------------------------------------------------
# ZMSMetaobjManager.delMetaobjAttr:
#
# Delete attribute from meta-object specified by id.
# --------------------------------------------------------------------------
def delMetaobjAttr(self, id, attr_id):
ob = self.__get_metaobj__(id)
attrs = copy.copy(ob['attrs'])
# Delete Attribute.
cp = []
for attr in attrs:
if attr['id'] == attr_id:
if id+'.'+attr['id'] in self.objectIds():
self.manage_delObjects(ids=[id+'.'+attr['id']])
if attr['type'] in self.valid_zopetypes:
# Get container.
container = self.getHome()
for ob_id in attr['id'].split('/')[:-1]:
container = getattr( container, ob_id)
ob_id = attr['id'].split('/')[-1]
if ob_id in container.objectIds([attr['type']]):
container.manage_delObjects(ids=[ob_id])
if attr['type'] == 'External Method':
try:
_fileutil.remove( INSTANCE_HOME+'/Extensions/'+ob_id+'.py')
except:
pass
else:
cp.append(attr)
ob['attrs'] = cp
# Assign Attributes to Meta-Object.
ob['zms_system'] = 0
self.model[id] = ob
# Make persistent.
self.model = self.model.copy()
# --------------------------------------------------------------------------
# ZMSMetaobjManager.moveMetaobjAttr:
#
# Move meta-object attribute to specified position.
# --------------------------------------------------------------------------
def moveMetaobjAttr(self, id, attr_id, pos):
ob = self.__get_metaobj__(id)
attrs = copy.copy(ob['attrs'])
# Move Attribute.
ids = self.getMetaobjAttrIds(id)
i = ids.index(attr_id)
attr = attrs[i]
attrs.remove(attr)
attrs.insert(pos,attr)
ob['attrs'] = attrs
# Assign Attributes to Meta-Object.
self.model[id] = ob
# Make persistent.
self.model = self.model.copy()
############################################################################
# ZMSMetaobjManager.manage_ajaxChangeProperties:
#
# Change properties.
############################################################################
def manage_ajaxChangeProperties(self, id, REQUEST=None, RESPONSE=None):
""" MetaobjManager.manage_ajaxChangeProperties """
ob = self.__get_metaobj__(id)
RESPONSE = REQUEST.RESPONSE
content_type = 'text/xml; charset=utf-8'
filename = 'manage_ajaxChangeProperties.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')
xml = self.getXmlHeader()
xml += '<result '
xml += ' id="%s"'%id
for key in REQUEST.form.keys():
if key.find('set') == 0:
k = key[3:].lower()
v = REQUEST.form.get(key)
if k in ob.keys():
ob[k] = v
xml += ' %s="%s"'%(k,str(v))
xml += '/>'
# Assign Attributes to Meta-Object.
self.model[id] = ob
# Make persistent.
self.model = self.model.copy()
return xml
############################################################################