source: ZMS/trunk/ZMSMetadictManager.py @ 1557

Revision 1557, 14.8 KB checked in by zmsdev, 11 months ago (diff)

removed old zms artefacts

Line 
1################################################################################
2# ZMSMetadictManager.py
3#
4# This program is free software; you can redistribute it and/or
5# modify it under the terms of the GNU General Public License
6# as published by the Free Software Foundation; either version 2
7# of the License, or (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program; if not, write to the Free Software
16# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17################################################################################
18
19# Imports.
20import copy
21import sys
22import time
23# Product Imports.
24import _globals
25
26
27################################################################################
28################################################################################
29###
30###   Class
31###
32################################################################################
33################################################################################
34class ZMSMetadictManager:
35
36
37    ############################################################################
38    #
39    #  XML IM/EXPORT
40    #
41    ############################################################################
42
43    # --------------------------------------------------------------------------
44    #  ZMSMetadictManager.importMetadictXml
45    # --------------------------------------------------------------------------
46
47    def _importMetadictXml(self, item, zms_system=0, createIfNotExists=1):
48      id = item['id']
49      metaDicts = self.dict_list(self.metas)
50      ids = metaDicts.keys()
51      ids = filter(lambda x: metaDicts[x].get('zms_system',0)==1,metaDicts.keys())
52      if createIfNotExists == 1 or id in ids:
53        newId = id
54        newAcquired = 0
55        newName = item['name']
56        newType = item['type']
57        newMandatory = item.get('mandatory',0)
58        newMultilang = item.get('multilang',1)
59        newRepetitive = item.get('repetitive',0)
60        newKeys = item.get('keys',[])
61        newCustom = item.get('custom','')
62        self.setMetadictAttr( None, newId, newAcquired, newName, newType, \
63          newMandatory, newMultilang, newRepetitive, newCustom, newKeys, \
64          zms_system)
65        for meta_id in item.get('dst_meta_types',[]):
66          metaObj = self.getMetaobj( meta_id)
67          if metaObj is not None  and id not in self.getMetadictAttrs(meta_id):
68            self.setMetaobjAttr(meta_id,None,newId=id,newType=id)
69
70    def importMetadictXml(self, xml, REQUEST=None, zms_system=0, createIfNotExists=1):
71      v = self.parseXmlString(xml)
72      if type(v) is list:
73        for item in v:
74          self._importMetadictXml(item,zms_system,createIfNotExists)
75      else:
76        self._importMetadictXml(v,zms_system,createIfNotExists)
77
78
79    # --------------------------------------------------------------------------
80    #  ZMSMetadictManager.getMetadictAttrs:
81    #
82    #  Returns list of attributes of DC.Metadictionaries.
83    # --------------------------------------------------------------------------
84    def getMetadictAttrs(self, meta_type=None):
85      obs = self.metas
86      if meta_type is not None:
87        attrs = []
88        metaObj = self.getMetaobj( meta_type)
89        for attr in metaObj.get('attrs',[]):
90          if attr['type'] in obs:
91            attrs.append(attr['type'])
92      else:
93       attrs = map( lambda x: obs[x*2], range(len(obs)/2))
94      # Return attributes.
95      return attrs
96
97
98    # --------------------------------------------------------------------------
99    #  ZMSMetadictManager.getMetadictAttr:
100    #
101    #  Get Attribute for Meta-Dictionary specified by key.
102    # --------------------------------------------------------------------------
103    def getMetadictAttr(self, key):
104      obs = self.metas
105      if key in obs:
106        ob = obs[obs.index(key)+1].copy()
107      # Not found!
108      else:
109        return None
110      # Acquire from parent.
111      if ob.get('acquired',0)==1:
112        portalMaster = self.getPortalMaster()
113        if portalMaster is not None:
114          portalMasterOb = portalMaster.metaobj_manager.getMetadictAttr(key)
115          if portalMasterOb is not None:
116            ob = portalMasterOb
117            ob = ob.copy()
118            ob['acquired'] = 1
119          else:
120            ob = ob.copy()
121            ob['errors'] = 'Not found in master!'
122      ob['mandatory'] = ob.get('mandatory',0)
123      ob['multilang'] = ob.get('multilang',1)
124      ob['repetitive'] = ob.get('repetitive',0)
125      ob['keys'] = ob.get('keys',[])
126      ob['custom'] = ob.get('custom','')
127      ob['errors'] = ob.get('errors','')
128      return ob
129
130
131    # --------------------------------------------------------------------------
132    #  ZMSMetadictManager.delMetadictAttr:
133    #
134    #  Delete Meta-Attribute specified by ID.
135    # --------------------------------------------------------------------------
136    def delMetadictAttr(self, id):
137      # Delete.
138      obs = self.metas
139      i = obs.index(id)
140      # Update attribute.
141      del obs[i]
142      del obs[i]
143      # Make persistent.
144      self.metas = copy.deepcopy(self.metas)
145      # Return with empty ID.
146      return ''
147
148
149    # --------------------------------------------------------------------------
150    #  ZMSMetadictManager.setMetadictAttr:
151    # --------------------------------------------------------------------------
152    def setMetadictAttr(self, oldId, newId, newAcquired, newName='', newType='', \
153          newMandatory=0, newMultilang=1, newRepetitive=0, newCustom='', \
154          newKeys=[], zms_system=0):
155      """
156      Set/add meta-attribute with specified values.
157      @param oldId: Old id
158      @type oldId: C{string}
159      @param newId: New id
160      @type newId: C{string}
161      @param newAcquired: Acquired
162      @type newAcquired: C{int}: 0 or 1
163      @param newName: (Display-)Name
164      @type newName: C{string}
165      @param newType: Type
166      @type newType: C{string}
167      @return: New id
168      @rtype: C{string}
169      """
170      obs = self.metas
171      # Remove exisiting entry.
172      if oldId is None:
173        oldId = newId
174      if oldId in obs:
175        i = obs.index(oldId)
176        del obs[i]
177        del obs[i]
178      else:
179        i = len(obs)
180      # Values.
181      newValues = {}
182      newValues['id'] = newId
183      newValues['acquired'] = newAcquired
184      newValues['name'] = newName
185      newValues['type'] = newType
186      newValues['mandatory'] = newMandatory
187      newValues['multilang'] = newMultilang
188      newValues['repetitive'] = newRepetitive
189      newValues['keys'] = newKeys
190      newValues['custom'] = newCustom
191      newValues['zms_system'] = zms_system
192      # Update attribute.
193      obs.insert(i,newValues)
194      obs.insert(i,newId)
195      # Make persistent.
196      self.metas = copy.deepcopy(self.metas)
197      # Return with new attr.
198      return newId
199
200
201    # --------------------------------------------------------------------------
202    #  ZMSMetadictManager.moveMetadictAttr:
203    #
204    #  Moves Meta-Attribute specified by given attr to specified position.
205    # --------------------------------------------------------------------------
206    def moveMetadictAttr(self, attr, pos):
207      # Move.
208      obs = self.metas
209      i = obs.index(attr)
210      attr = obs[i]
211      values = obs[i+1]
212      del obs[i]
213      del obs[i]
214      obs.insert(pos*2, values)
215      obs.insert(pos*2, attr)
216      # Make persistent.
217      self.metas = copy.deepcopy(self.metas)
218      # Return with empty attr.
219      return ''
220
221
222    ############################################################################
223    #  ZMSMetadictManager.manage_changeMetaProperties:
224    #
225    #  Change Meta-Attributes.
226    ############################################################################
227    def manage_changeMetaProperties(self, btn, lang, REQUEST, RESPONSE=None):
228        """ MetadictManager.manage_changeMetaProperties """
229        message = ''
230        extra = {}
231        t0 = time.time()
232        id = REQUEST.get('id','')
233        target = 'manage_metas'
234       
235        try:
236         
237          # Acquire.
238          # --------
239          if btn == self.getZMILangStr('BTN_ACQUIRE'):
240            ids = REQUEST.get('aq_ids',[])
241            for newId in ids:
242              newAcquired = 1
243              id = self.setMetadictAttr( None, newId, newAcquired)
244            message = self.getZMILangStr('MSG_INSERTED')%str(len(ids))
245         
246          # Change.
247          # -------
248          elif btn == self.getZMILangStr('BTN_SAVE'):
249            for oldId in REQUEST.get('old_ids',[]):
250              if REQUEST.has_key('attr_id_%s'%oldId):
251                newId = REQUEST['attr_id_%s'%oldId].strip()
252                newAcquired = 0
253                newName = REQUEST['attr_name_%s'%oldId].strip()
254                newType = REQUEST['attr_type_%s'%oldId].strip()
255                newMandatory = REQUEST.get('attr_mandatory_%s'%oldId, 0)
256                newMultilang = REQUEST.get('attr_multilang_%s'%oldId, 0)
257                newRepetitive = REQUEST.get('attr_repetitive_%s'%oldId, 0)
258                newKeys = self.string_list(REQUEST.get('attr_keys_%s'%oldId,''), '\n')
259                newCustom = REQUEST.get('attr_custom_%s'%oldId, '')
260                self.setMetadictAttr( oldId, newId, newAcquired, newName, newType, newMandatory, newMultilang, newRepetitive, newCustom, newKeys)
261            message = self.getZMILangStr('MSG_CHANGED')
262         
263          # Copy.
264          # -----
265          elif btn == self.getZMILangStr('BTN_COPY'):
266            metaOb = self.getMetadictAttr(id)
267            if metaOb.get('acquired',0) == 1:
268              masterRoot = getattr(self,self.getConfProperty('Portal.Master'))
269              masterDocElmnt = masterRoot.content
270              REQUEST.set('ids',[id])
271              xml =  masterDocElmnt.manage_changeMetaProperties(self.getZMILangStr('BTN_EXPORT'), lang, REQUEST, RESPONSE)
272              self.importMetadictXml(xml=xml)
273              message = self.getZMILangStr('MSG_IMPORTED')%('<i>%s</i>'%id)
274         
275          # Delete.
276          # -------
277          elif btn in ['delete',self.getZMILangStr('BTN_DELETE')]:
278            oldId = id
279            self.delMetadictAttr( oldId)
280            for portalClient in self.getPortalClients():
281              pcmm = portalClient.metaobj_manager
282              if oldId in pcmm.getMetadictAttrs() and pcmm.getMetadictAttr(oldId).get('acquired',0)==1:
283                pcmm.delMetadictAttr( oldId)
284            message = self.getZMILangStr('MSG_DELETED')%int(1)
285         
286          # Export.
287          # -------
288          elif btn == self.getZMILangStr('BTN_EXPORT'):
289            value = []
290            ids = REQUEST.get('ids',[])
291            metadicts = self.metas
292            for i in range(len(metadicts)/2):
293              id = metadicts[i*2]
294              dict = metadicts[i*2+1].copy()
295              if id in ids or len(ids) == 0:
296                if dict.has_key('zms_system'):
297                    del dict['zms_system']
298                dst_meta_types = []
299                for meta_id in self.getMetaobjIds():
300                  if id in self.getMetadictAttrs( meta_id):
301                    dst_meta_types.append( meta_id)
302                dict['dst_meta_types'] = dst_meta_types
303                value.append(dict)
304            if len(value) == 1:
305              value = value[0]
306            content_type = 'text/xml; charset=utf-8'
307            filename = 'export.metadict.xml'
308            export = self.getXmlHeader() + self.toXmlString(value,1)
309            RESPONSE.setHeader('Content-Type',content_type)
310            RESPONSE.setHeader('Content-Disposition','inline;filename="%s"'%filename)
311            return export
312         
313          # Import.
314          # -------
315          elif btn == self.getZMILangStr('BTN_IMPORT'):
316            f = REQUEST['file']
317            if f:
318              filename = f.filename
319              self.importMetadictXml(xml=f)
320            else:
321              filename = REQUEST['init']
322              createIfNotExists = 1
323              self.importConf(filename, REQUEST, createIfNotExists)
324            message = self.getZMILangStr('MSG_IMPORTED')%('<i>%s</i>'%filename)
325         
326          # Insert.
327          # -------
328          elif btn == self.getZMILangStr('BTN_INSERT'):
329            newId = REQUEST['_id'].strip()
330            newAcquired = 0
331            newName = REQUEST['_name'].strip()
332            newType = REQUEST['_type'].strip()
333            newMandatory = REQUEST.get('_mandatory',0)
334            newMultilang = REQUEST.get('_multilang',0)
335            newRepetitive = REQUEST.get('_repetitive',0)
336            newCustom = ''
337            if newType == 'method':
338              newCustom += '<dtml-comment>--// BO '+ newId + ' //--</dtml-comment>\n'
339              newCustom += '\n'
340              newCustom += '<dtml-comment>--// EO '+ newId + ' //--</dtml-comment>\n'
341            id = self.setMetadictAttr( None, newId, newAcquired, newName, newType, newMandatory, newMultilang, newRepetitive, newCustom)
342            message = self.getZMILangStr('MSG_INSERTED')%id
343         
344          # Move to.
345          # --------
346          elif btn == 'move_to':
347            pos = REQUEST['pos']
348            oldId = id
349            id = self.moveMetadictAttr( oldId, pos)
350            message = self.getZMILangStr('MSG_MOVEDOBJTOPOS')%(("<i>%s</i>"%oldId),(pos+1))
351         
352          ##### Page-Extension ####
353          if id == 'attr_pageext':
354            for langId in self.getLangIds():
355              self.setLangMethods( langId)
356           
357          ##### SYNCHRONIZE ####
358          self.synchronizeObjAttrs()
359       
360        # Handle exception.
361        except:
362          _globals.writeError(self,"[manage_changeMetaProperties]")
363          error = str( sys.exc_type)
364          if sys.exc_value:
365            error += ': ' + str( sys.exc_value)
366          target = self.url_append_params( target, { 'manage_tabs_error_message':error})
367       
368        # Return with message.
369        target = self.url_append_params( target, { 'lang':lang, 'id':id})
370        target = self.url_append_params( target, extra)
371        if len( message) > 0:
372          message += ' (in '+str(int((time.time()-t0)*100.0)/100.0)+' secs.)'
373          target = self.url_append_params( target, { 'manage_tabs_message':message})
374        return RESPONSE.redirect( target)
375
376################################################################################
Note: See TracBrowser for help on using the repository browser.