-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZMSMetaobjManager.py
1316 lines (1223 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
# -*- coding: utf-8 -*-
################################################################################
# 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 cStringIO import StringIO
from DateTime import DateTime
from distutils.version import LooseVersion
import ZPublisher.HTTPRequest
import collections
import copy
import os
import sys
import time
import zExceptions
import zope.interface
# Product Imports.
import IZMSRepositoryProvider
import standard
import zopeutil
import _blobfields
import _fileutil
import _globals
import _ziputil
# ------------------------------------------------------------------------------
# Synchronize type.
# ------------------------------------------------------------------------------
def syncZopeMetaobjAttr( self, metaObj, attr):
id = metaObj['id']
attr_id = attr['id']
try:
artefact = None
if attr['type'] in self.valid_zopeattrs:
artefact = getattr(self,id+'.'+attr_id,None)
if attr['type'] in self.valid_zopetypes:
container = self.getHome()
for artefact_id in attr_id.split('/')[:-1]:
container = getattr( container, artefact_id)
artefact_id = attr['id'].split('/')[-1]
artefact = getattr(container,artefact_id,None)
if artefact is None and attr['type'] in ['External Method']:
class MissingArtefactProxy:
def __init__(self,id,meta_type):
self.id=id
self.meta_type=meta_type
icon__roles__=None
def icon(self):
return {'External Method':'/misc_/ExternalMethod/extmethod.gif'}.get(self.meta_type,'/misc_/OFSP/File_icon.gif')
absolute_url__roles__=None
def absolute_url(self):
return '#'
def bobobase_modification_time(self):
return DateTime()
artefact = MissingArtefactProxy(attr['id'],attr['type'])
if artefact is not None:
attr['ob'] = artefact
except:
standard.writeError(self,"[syncZopeMetaobjAttr]: %s.%s"%(id,attr_id))
# ------------------------------------------------------------------------------
# Effective ids.
# ------------------------------------------------------------------------------
def effective_ids(self, ids):
l = []
keys = self.model.keys()
if ids:
for id in filter(lambda x:x in keys,ids):
metaObj = self.getMetaobj( id)
l.append(id)
if metaObj['type'] == 'ZMSPackage':
for pkgMetaObjId in self.getMetaobjIds():
pkgMetaObj = self.getMetaobj( pkgMetaObjId)
if pkgMetaObj[ 'package'] == metaObj[ 'id']:
l.append( pkgMetaObjId)
else:
l = keys
l.sort()
return l
################################################################################
################################################################################
###
### 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_zopeattrs = ['method','py','zpt','interface','resource']
valid_xtypes = ['constant','delimiter','hint']+valid_zopeattrs
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', 'File', 'Folder', 'Image', 'Page Template', 'Script (Python)', 'Z SQL Method']
deprecated_types = [] # 'DTML Method', 'DTML Document', 'method']
############################################################################
#
# IRepositoryProvider
#
############################################################################
"""
@see IRepositoryProvider
"""
def provideRepositoryModel(self, r, ids=None):
self.writeBlock("[provideRepositoryModel]: ids=%s"%str(ids))
valid_ids = self.getMetaobjIds()
if ids is None:
ids = valid_ids
for id in filter(lambda x:x in valid_ids, ids):
o = self.getMetaobj(id)
if o and not o.get('acquired',0):
d = copy.deepcopy(o)
attrs = d.get('attrs',[])
package = d.get('package','')
mandatory_keys = ['access','enabled','id','name','package','revision','type']
for key in d.keys():
if not key in mandatory_keys:
del d[key]
package = o.get('package','')
d['__filename__'] = [[],[package]][len(package)>0]+[id,'__init__.py']
for attr in attrs:
syncZopeMetaobjAttr(self,d,attr)
mandatory_keys = ['id','name','type','default','keys','mandatory','multilang','ob','repetitive']
if attr['type']=='interface':
attr['name'] = attr['id']
if o['type'] == 'ZMSRecordSet' or attr['type'] == 'constant':
mandatory_keys += ['custom']
for key in attr.keys():
if not key in mandatory_keys:
del attr[key]
d['Attrs'] = attrs
r[id] = d
"""
@see IRepositoryProvider
"""
def updateRepositoryModel(self, r):
id = r['id']
if not id.startswith('__') and not id.endswith('__'):
self.writeBlock("[updateRepositoryModel]: id=%s"%id)
r['attrs'] = r.get('Attrs',[])
if r.has_key('Attrs'): del r['Attrs']
self.delMetaobj(id)
self.setMetaobj(r)
for attr in r['attrs']:
if attr['type'] in self.valid_zopeattrs+self.valid_zopetypes:
oldId = attr['id']
newId = attr['id']
newName = attr['name']
newMandatory = attr.get('mandatory',0)
newMultilang = attr.get('multilang',0)
newRepetitive = attr.get('repetitive',0)
newType = attr['type']
newKeys = attr.get('keys',[])
newCustom = attr.get('data','')
newDefault = attr.get('default','')
if newType in ['resource']:
newCustom = _blobfields.createBlobField( self,_blobfields.MyFile, {'data':newCustom,'filename':newId})
self.setMetaobjAttr(id,oldId,newId,newName,newMandatory,newMultilang,newRepetitive,newType,newKeys,newCustom,newDefault)
self.synchronizeObjAttrs(id)
return id
############################################################################
#
# XML IM/EXPORT
#
############################################################################
# --------------------------------------------------------------------------
# ZMSMetaobjManager.importMetaobjXml
# --------------------------------------------------------------------------
def _importMetaobjXml(self, item, createIfNotExists=1, createIdsFilter=None):
ids = []
id = item['key']
meta_types = self.model.keys()
if (createIfNotExists == 1) 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'])
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))
# Delete Object.
oldAttrs = None
if id in ids:
self.delMetaobj( id)
# Set Object.
self.setMetaobj( newValue)
# Set Attributes.
attr_ids = []
for attr in newAttrs:
# Mandatory.
attr_id = attr['id']
newName = attr['name']
newMandatory = attr.get('mandatory',0)
newMultilang = attr.get('multilang',0)
newRepetitive = attr.get('repetitive',0)
newType = attr.get('meta_type','')
if not newType:
newType = attr['type']
# Optional.
newKeys = attr.get('keys',[])
newCustom = attr.get('custom','')
newDefault = attr.get('default','')
# Backwards compatibility: map interface.name to interface.custom.
if newType == 'interface' and newName and not newCustom:
newCustom = newName
newName = ''
# 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'])
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)
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)
standard.writeBlock( self, '[ZMSMetaobjManager._importMetaobjXml]: id=%s'%str(id))
return id
def importMetaobjXml(self, xml, createIfNotExists=1, createIdsFilter=None):
self.REQUEST.set( '__get_metaobjs__', True)
ids = []
v = self.parseXmlString(xml)
if not type(v) is list:
v = [v]
for item in v:
id = self._importMetaobjXml(item,createIfNotExists,createIdsFilter)
ids.append( id)
if len( ids) == 1:
ids = ids[ 0]
standard.writeBlock( self, '[ZMSMetaobjManager.importMetaobjXml]: ids=%s'%str(ids))
return ids
def exportMetaobjXml(self, ids, REQUEST=None, RESPONSE=None):
value = []
revision = '0.0.0'
for id in effective_ids(self,ids):
ob = None
context = self
while ob is None:
ob = context.__get_metaobj__(id)
if ob.get('acquired',0):
ob = None
context = context.getPortalMaster().metaobj_manager
ob = copy.deepcopy(ob)
revision = self.getMetaobjRevision(id)
attrs = []
for attr_id in map(lambda x:x['id'],ob['attrs']):
attr = self.getMetaobjAttr(id, attr_id)
mandatory_keys = ['id','name','type','meta_type','default','keys','mandatory','multilang','ob','repetitive']
if attr['type']=='interface':
attr['name'] = attr['id']
if ob['type'] == 'ZMSRecordSet' or attr['type'] == 'constant':
mandatory_keys += ['custom']
for key in attr.keys():
if (not attr[key] and REQUEST is None) or \
(not key in mandatory_keys):
del attr[key]
if attr.has_key('ob'):
attr['custom'] = attr['ob']
del attr['ob']
attrs.append( attr)
ob['__obj_attrs__'] = attrs
for key in ['attrs','acquired']:
if ob.has_key(key):
del ob[key]
# Value.
value.append({'key':id,'value':ob})
if len(value)==1:
value = value[0]
# XML.
if len(ids)==1:
filename = '%s-%s.metaobj.xml'%(ids[0],revision)
else:
filename = 'export.metaobj.xml'
content_type = 'text/xml; charset=utf-8'
processing_instruction = '<?zms version=\'%s\'?>'%(context.zms_version())
export = self.getXmlHeader() + processing_instruction + standard.toXmlString(self,value,xhtml=True)
if RESPONSE:
RESPONSE.setHeader('Content-Type',content_type)
RESPONSE.setHeader('Content-Disposition','attachment;filename="%s"'%filename)
return export
# --------------------------------------------------------------------------
# ZMSMetaobjManager.importTheme
#
# Import theme.
# --------------------------------------------------------------------------
def importTheme(self, id):
home = self.getHome()
def traverse(context, container_id):
for childNode in context.objectValues():
if childNode.meta_type in ['Folder', 'Filesystem Directory View']:
traverse(childNode, container_id)
elif childNode.meta_type in ['DTML Document', 'DTML Method', 'External Method', 'Image', 'File', 'Filesystem File', 'Filesystem Image', 'Filesystem Page Template', 'Filesystem Script (Python)', 'Page Template', 'Script (Python)']:
newIds = childNode.getPhysicalPath()
newIds = [container_id+'~'] + list(newIds[newIds.index(container_id)+1:])
newId = '/'.join(newIds)
newName = childNode.title_or_id()
newType = childNode.meta_type
newType = {'Filesystem File':'File', 'Filesystem Image':'Image', 'Filesystem Page Template':'Page Template'}.get(newType,newType)
newCustom = zopeutil.readData(childNode)
self.setMetaobjAttr(id,None,newId=newId,newName=newName,newType=newType,newCustom=newCustom)
if id in self.model.keys():
del self.model[id]
container = getattr(home,id)
self.setMetaobj({'id':id,'name':container.title_or_id(),'type':'ZMSLibrary'})
traverse(container,id)
############################################################################
#
# OBJECTS
#
############################################################################
# --------------------------------------------------------------------------
# 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 = 'ZMSMetaobjManager.__get_metaobjs__'
try: return self.fetchReqBuff(reqBuffId)
except: pass
# Get value.
obs = {}
m = self.model
aq_obs = None
for id in m.keys():
ob = m[id]
# handle acquisition
if ob.get('acquired',0) == 1:
acquired = 1
subobjects = ob.get('subobjects',1)
if aq_obs is None:
portalMaster = self.getPortalMaster()
if portalMaster is not None:
aq_obs = portalMaster.metaobj_manager.__get_metaobjs__()
if aq_obs is not None:
if aq_obs.has_key(id):
ob = aq_obs[id].copy()
else:
ob = {'id':id,'type':'ZMSUnknown'}
ob['acquired'] = acquired
ob['subobjects'] = subobjects
obs[id] = ob
if ob['type'] == 'ZMSPackage' and ob['subobjects'] == 1:
for aq_id in aq_obs.keys():
ob = aq_obs[aq_id].copy()
if ob.get( 'package') == id:
ob['acquired'] = 1
obs[aq_id] = ob
else:
obs[id] = ob
#-- [ReqBuff]: Returns value and stores it in buffer of Http-Request.
return self.storeReqBuff( reqBuffId, obs)
# --------------------------------------------------------------------------
# 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.getMetaobjIds:
#
# Returns list of all meta-ids in model.
# --------------------------------------------------------------------------
def getMetaobjIds(self, sort=False, excl_ids=[]):
obs = self.__get_metaobjs__()
ids = map(lambda x:obs[x]['id'],obs.keys())
# exclude ids
if excl_ids:
ids = filter(lambda x: x not in excl_ids,ids)
# sort
if sort:
mapping = map(lambda x: (self.display_type(self.REQUEST,x),x),ids)
mapping.sort()
ids = map(lambda x: x[1],mapping)
return list(ids)
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobj:
#
# Returns meta-object specified by id.
# --------------------------------------------------------------------------
def getMetaobj(self, id, aq_attrs=[]):
ob = standard.nvl( self.__get_metaobj__(id), {'id':id, 'attrs':[], })
if ob.get('acquired'):
for k in aq_attrs:
v = self.get_conf_property('%s.%s'%(id,k),None)
if v is not None:
ob[k] = v
return ob
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobjRevision:
#
# Returns meta-object-revision specified by id.
# --------------------------------------------------------------------------
def getMetaobjRevision(self, id):
ob = self.getMetaobj(id)
if ob is not None and ob.get('type') == 'ZMSPackage':
metaobjs = [x for x in self.__get_metaobjs__().values() if x.get('package') == ob['id']]
# https://stackoverflow.com/questions/11887762/how-do-i-compare-version-numbers-in-python
revisions = sorted(['0.0.0'] + map(lambda x: standard.nvl(x.get('revision'), '0.0.0'), metaobjs),
key=lambda v: LooseVersion(v))
if LooseVersion(revisions[-1]) > LooseVersion(ob.get('revision','0.0.0')):
ob['revision'] = revisions[-1]
return ob.get('revision', '0.0.0')
# --------------------------------------------------------------------------
# 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):
self.clearReqBuff('ZMSMetaobjManager')
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)
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):
self.clearReqBuff('ZMSMetaobjManager')
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, acquire=True)
self.delMetaobj( id, acquire=True)
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, acquire=False):
self.clearReqBuff('ZMSMetaobjManager')
# 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, acquire)
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 and ''.join(keys).find('##') < 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.get('custom',None), 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 len( types) > 0:
attrs = filter( lambda x: x['type'] in types, attrs)
return attrs
# --------------------------------------------------------------------------
# ZMSMetaobjManager.evalMetaobjAttr
# --------------------------------------------------------------------------
def evalMetaobjAttr(self, id, attr_id, zmscontext=None, options={}):
value = None
# Find meta-object attributes by given id.
metaObjAttrs = []
# all meta-objects:
if id == '*':
metaObjs = self.__get_metaobjs__()
for metaObjId in metaObjs.keys():
metaObj = metaObjs[metaObjId]
for metaObjAttr in filter(lambda x:x['id']==attr_id, metaObj.get('attrs',[])):
metaObjAttrs.append(self.getMetaobjAttr( metaObjId, attr_id))
# single meta-object:
else:
metaObjAttrs.append(self.getMetaobjAttr( id, attr_id))
metaObjAttrs = filter(lambda x: x is not None, metaObjAttrs)
# Process meta-object attributes.
for metaObjAttr in metaObjAttrs:
if metaObjAttr['type'] == 'constant':
value = metaObjAttr.get('custom','')
elif metaObjAttr['type'] == 'resource':
value = metaObjAttr.get('ob',None)
elif metaObjAttr['type'] in self.valid_zopeattrs:
ob = metaObjAttr.get('ob',None)
if ob:
value = zopeutil.callObject(ob,zmscontext,options)
# Return value.
return value
# --------------------------------------------------------------------------
# ZMSMetaobjManager.getMetaobjAttr:
#
# Get attribute for meta-object specified by attribute-id.
# --------------------------------------------------------------------------
def getMetaobjAttr(self, id, attr_id, sync=True):
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, sync)
return attr
meta_obj = self.getMetaobj(id)
attrs = meta_obj.get('attrs',meta_obj.get('__obj_attrs__',[]))
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 sync:
syncZopeMetaobjAttr( self, meta_obj, 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=''):
self.writeBlock("[setMetaobjAttr]: %s %s %s"%(str(id),str(oldId),str(newId)))
self.clearReqBuff('ZMSMetaobjManager')
ob = self.__get_metaobj__(id)
if ob is None: return
attrs = copy.copy(ob['attrs'])
# Set Attributes.
if newType in ['delimiter','hint']:
newCustom = ''
if newType in ['resource'] and (type(newCustom) is str or type(newCustom) is int):
newCustom = None
if newType not in ['*','autocomplete','color','multiautocomplete','multiselect','recordset','select']:
newKeys = []
if newType in self.getMetadictAttrs():
newId = newType
if newType in self.getMetaobjIds()+['*']:
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,options=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 += 'p = []\n'
newCustom += 'p.append("This is the Python Script %s" % script.getId())\n'
newCustom += 'p.append("in %s" % container.absolute_url())\n'
newCustom += 'return "\\n".join(p)\n'
newCustom += '\n'
newCustom += '# --// /'+ newId + ' //--\n'
elif newType in [ 'Z SQL Method']:
newCustom = ''
newCustom += '<connection>%s</connection>\n'%self.SQLConnectionIDs()[0][1]
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.MyBlob):
if oldId is not None and id+'.'+oldId in self.objectIds():
self.manage_delObjects(ids=[id+'.'+oldId])
zopeutil.addObject(self,'File',id+'.'+newId,newCustom.getFilename(),newCustom.getData())
elif oldId is not None and oldId != newId and id+'.'+oldId in self.objectIds():
self.manage_renameObject(id=id+'.'+oldId,new_id=id+'.'+newId)
if not ob['type'] == 'ZMSRecordSet':
newCustom = ''
attr = {}
attr['id'] = newId
attr['name'] = newName
attr['mandatory'] = newMandatory
attr['multilang'] = newMultilang
attr['repetitive'] = newRepetitive
attr['type'] = newType
attr['keys'] = newKeys
attr['custom'] = newCustom if type(newCustom) in (int,str,unicode) else None
attr['default'] = newDefault
# Handle special methods and interfaces.
mapTypes = {'method':'DTML Method','py':'Script (Python)','zpt':'Page Template'}
message = ''
if newType in ['interface']:
newType = standard.dt_executable(self,newCustom)
if not newType:
newType = 'method'
newName = '%s: %s'%(newId,newType)
if newType in mapTypes.keys():
oldObId = '%s.%s'%(id,oldId)
newObId = '%s.%s'%(id,newId)
# Remove Zope-Object (if exists)
zopeutil.removeObject(self, oldObId)
zopeutil.removeObject(self, newObId)
# Insert Zope-Object.
if isinstance(newCustom,_blobfields.MyBlob): newCustom = newCustom.getData()
if _globals.is_str_type(newCustom): newCustom = newCustom.replace('\r','')
zopeutil.addObject(self, mapTypes[newType], newObId, newName, newCustom)
del attr['custom']
# Replace
ids = map( lambda x: x['id'], attrs)
if oldId in ids:
i = ids.index(oldId)
attrs[i] = attr
elif newId in ids:
i = ids.index(newId)
attrs[i] = attr
# Always append new methods at the end.
elif 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]
zopeutil.removeObject(container, newObId)
# Get container (old).
if oldId is not None:
oldContainer = self.getHome()
for ob_id in oldId.split('/')[:-1]:
if oldContainer is not None:
oldContainer = getattr(oldContainer,ob_id,None)
if oldContainer is not None:
oldObId = oldId.split('/')[-1]
zopeutil.removeObject(oldContainer, oldObId)
# Insert Zope-Object.
if isinstance(newCustom,_blobfields.MyBlob): newCustom = newCustom.getData()
if _globals.is_str_type(newCustom): newCustom = newCustom.replace('\r','')
try:
zopeutil.addObject(container, newType, newObId, newName, newCustom)
artefact = zopeutil.getObject(container, newObId)
del attr['custom']
except:
standard.writeError(self,'can\'t insert zope-object: %s (%s)'%(newObId,newType))
# Change Zope-Object (special).
newOb = zopeutil.getObject(container, newObId)
if newType == 'Folder':
if isinstance( newCustom, _blobfields.MyFile) and len(newCustom.getData()) > 0:
newOb.manage_delObjects(ids=newOb.objectIds())
_ziputil.importZip2Zodb( newOb, newCustom.getData())
# Assign attributes to meta-object.
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, acquire=False):
ob = self.__get_metaobj__(id)
attrs = copy.copy(ob.get('attrs',[]))
# Delete Attribute.
cp = []
for attr in attrs:
if attr['id'] == attr_id:
if id+'.'+attr['id'] in self.objectIds():
ob_id = id+'.'+attr['id']
zopeutil.removeObject(self, ob_id, removeFile=True)
if not acquire and attr['type'] in self.valid_zopetypes:
# Get container.
container = self.getHome()
ids = attr['id'].split('/')
for ob_id in ids[:-1]:
container = getattr(container,ob_id,None)
if container is None:
break
if container is not None:
zopeutil.removeObject(container, ids[-1], removeFile=True)
else:
cp.append(attr)
ob['attrs'] = cp
# Assign Attributes to Meta-Object.
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, RESPONSE=None):
""" MetaobjManager.manage_ajaxChangeProperties """
xml = self.getXmlHeader()
xml += '<result '
xml += ' id="%s"'%id