def getMetaCmds(self, context=None, stereotype='', sort=True):
   stereotypes = {'insert':'manage_add','tab':'manage_tab','repository':'manage_repository','zcatalog':'manage_zcatalog'}
   metaCmds = []
   portalMasterMetaCmds = None
   for metaCmd in [x for x in self.commands if x['id'].startswith(stereotypes.get(stereotype, ''))]:
     # Acquire from parent.
     if metaCmd.get('acquired', 0)==1:
       if portalMasterMetaCmds is None:
         portalMaster = self.getPortalMaster()
         portalMasterMetaCmds = portalMaster.getMetaCmds(stereotype=stereotype)
       l = [x for x in portalMasterMetaCmds if x['id']==metaCmd['id']]
       if len(l) > 0:
         metaCmd = l[0]
         metaCmd['acquired'] = 1
     else:
       metaCmd = metaCmd.copy()
       metaCmd['home'] = self.aq_parent
       metaCmd['stereotype'] = ' '.join([x for x in stereotypes if metaCmd['id'].startswith(stereotypes[x])])
       metaCmd['action'] = '%smanage_executeMetacmd?id='+metaCmd['id']
       if metaCmd.get('execution') == 2:
         metaCmd['action'] = 'javascript:%%s'+metaCmd['id']
         
     metaCmds.append(metaCmd)
   if context is not None:
     request = context.REQUEST
     auth_user = request['AUTHENTICATED_USER']
     user_roles = context.getUserRoles(auth_user)
     absolute_url = '/'.join(list(context.getPhysicalPath())+[''])
     l = []
     for metaCmd in metaCmds:
       canExecute = True
       if canExecute:
         meta_types = metaCmd.get('meta_types',[])
         hasMetaType = False
         hasMetaType = hasMetaType or '*' in meta_types
         hasMetaType = hasMetaType or context.meta_id in meta_types
         hasMetaType = hasMetaType or 'type(%s)'%context.getType() in meta_types
         canExecute = canExecute and hasMetaType
       if canExecute:
         roles = metaCmd.get('roles',[])
         hasRole = False
         hasRole = hasRole or '*' in roles
         hasRole = hasRole or len(standard.intersection_list(user_roles,roles)) > 0
         hasRole = hasRole or auth_user.has_role('Manager')
         canExecute = canExecute and hasRole
       if canExecute:
         nodes = standard.string_list(metaCmd.get('nodes', '{$}'))
         sl = []
         sl.extend([(context.getHome().id+'/content/'+x[2:-1]+'/').replace('//', '/') for x in [x for x in nodes if x.find('@')<0]])
         sl.extend([(x[2:-1].replace('@', '/content/')+'/').replace('//', '/') for x in [x for x in nodes if x.find('@')>0]])
         hasNode = len([x for x in sl if absolute_url.find(x)>=0]) > 0
         canExecute = canExecute and hasNode
       if canExecute:
         l.append(metaCmd)
     metaCmds = l
   return metaCmds
Example #2
0
    def manage_changeWorkflow(self, lang, key='', btn='', REQUEST=None, RESPONSE=None):
      """ ZMSWorkflowProvider.manage_changeWorkflow """
      message = ''
      
      # Active.
      # -------
      if key == 'custom' and btn == 'BTN_SAVE':
        # Autocommit & Nodes.
        old_autocommit = getattr(self, 'autocommit', 1)
        new_autocommit = REQUEST.get('workflow', 0) == 0
        self.autocommit = new_autocommit
        self.nodes = standard.string_list(REQUEST.get('nodes', ''))
        if old_autocommit == 0 and new_autocommit == 1:
          self.doAutocommit(lang, REQUEST)
        message = self.getZMILangStr('MSG_CHANGED')
      
      # Return with message.
      message = standard.url_quote(message)
      return RESPONSE.redirect('manage_main?lang=%s&manage_tabs_message=%s#_%s'%(lang, message, key))

################################################################################
Example #3
0
 def string_list(self, s, sep='\n', trim=True):
     warn(self, 'string_list', 'Products.zms.standard.string_list')
     return standard.string_list(s, sep, trim)
    def manage_changeWorkflow(self,
                              lang,
                              btn='',
                              key='properties',
                              REQUEST=None,
                              RESPONSE=None):
        """ ZMSWorkflowProvider.manage_changeWorkflow """
        message = ''

        # Version Control.
        # -----------
        if key == 'history':
            old_active = self.getConfProperty('ZMS.Version.active', 0)
            new_active = REQUEST.get('active', 0)
            old_nodes = self.getConfProperty('ZMS.Version.nodes', ['{$}'])
            new_nodes = standard.string_list(REQUEST.get('nodes', ''))
            self.setConfProperty('ZMS.Version.active', new_active)
            self.setConfProperty('ZMS.Version.nodes', new_nodes)
            nodes = []
            if old_active == 1 and new_active == 0:
                nodes = old_nodes
            if old_active == 1 and new_active == 1:
                nodes = standard.difference_list(
                    old_nodes,
                    self.getConfProperty('ZMS.Version.nodes', ['{$}']))
            for node in nodes:
                ob = self.getLinkObj(node)
                if ob is not None:
                    try:
                        message += '[%s: %i]' % (node, ob.packHistory())
                    except:
                        message += '[%s: %s]' % (node, 'No history to pack')
            message = self.getZMILangStr('MSG_CHANGED') + message

        # Properties.
        # -----------
        elif key == 'properties':
            # Save.
            # ------
            if btn == 'BTN_SAVE':
                # Autocommit & Nodes.
                old_autocommit = self.autocommit
                new_autocommit = REQUEST.get('workflow', 0) == 0
                self.revision = REQUEST.get('revision', '0.0.0')
                self.autocommit = new_autocommit
                self.nodes = standard.string_list(REQUEST.get('nodes', ''))
                if old_autocommit == 0 and new_autocommit == 1:
                    self.doAutocommit(lang, REQUEST)
                message = self.getZMILangStr('MSG_CHANGED')

            # Clear.
            # ------
            elif btn == 'BTN_CLEAR':
                self.doAutocommit(lang, REQUEST)
                self.autocommit = 1
                self.activities = []
                self.transitions = []
                message = self.getZMILangStr('MSG_CHANGED')

            # Export.
            # -------
            elif btn == 'BTN_EXPORT':
                return exportXml(self, REQUEST, RESPONSE)

            # Import.
            # -------
            elif btn == 'BTN_IMPORT':
                f = REQUEST['file']
                if f:
                    filename = f.filename
                    xml = f
                else:
                    filename = REQUEST.get('init')
                    xml = open(_fileutil.getOSPath(filename), 'rb')
                self.importXml(xml)
                message = self.getZMILangStr('MSG_IMPORTED') % ('<i>%s</i>' %
                                                                filename)

        # Return with message.
        message = standard.url_quote(message)
        return RESPONSE.redirect(
            'manage_main?lang=%s&key=%s&manage_tabs_message=%s#_properties' %
            (lang, key, message))
Example #5
0
    def manage_changeMetaProperties(self, btn, lang, REQUEST, RESPONSE=None):
        """ MetadictManager.manage_changeMetaProperties """
        message = ''
        extra = {}
        t0 = time.time()
        id = REQUEST.get('id', '')
        target = 'manage_metas'

        try:

            # Acquire.
            # --------
            if btn == 'BTN_ACQUIRE':
                ids = REQUEST.get('aq_ids', [])
                for newId in ids:
                    newAcquired = 1
                    id = self.setMetadictAttr(None, newId, newAcquired)
                message = self.getZMILangStr('MSG_INSERTED') % str(len(ids))

            # Change.
            # -------
            elif btn == 'BTN_SAVE':
                for oldId in REQUEST.get('old_ids', []):
                    if 'attr_id_%s' % oldId in REQUEST:
                        newId = REQUEST['attr_id_%s' % oldId].strip()
                        newAcquired = 0
                        newName = REQUEST['attr_name_%s' % oldId].strip()
                        newType = REQUEST['attr_type_%s' % oldId].strip()
                        newMandatory = REQUEST.get('attr_mandatory_%s' % oldId,
                                                   0)
                        newMultilang = REQUEST.get('attr_multilang_%s' % oldId,
                                                   0)
                        newRepetitive = REQUEST.get(
                            'attr_repetitive_%s' % oldId, 0)
                        newKeys = standard.string_list(
                            REQUEST.get('attr_keys_%s' % oldId, ''), '\n')
                        newCustom = REQUEST.get('attr_custom_%s' % oldId, '')
                        newDefault = REQUEST.get('attr_default_%s' % oldId, '')
                        self.setMetadictAttr(oldId, newId, newAcquired,
                                             newName, newType, newMandatory,
                                             newMultilang, newRepetitive,
                                             newCustom, newKeys, newDefault)
                message += self.getZMILangStr('MSG_CHANGED')
                newId = REQUEST['_id'].strip()
                newAcquired = 0
                newName = REQUEST['_name'].strip()
                newType = REQUEST['_type'].strip()
                newMandatory = REQUEST.get('_mandatory', 0)
                newMultilang = REQUEST.get('_multilang', 0)
                newRepetitive = REQUEST.get('_repetitive', 0)
                newCustom = ''
                if len(newId) > 0 and len(newName) > 0 and len(newType) > 0:
                    if newType == 'method':
                        newCustom += '<dtml-comment>--// BO ' + newId + ' //--</dtml-comment>\n'
                        newCustom += '\n'
                        newCustom += '<dtml-comment>--// EO ' + newId + ' //--</dtml-comment>\n'
                    self.setMetadictAttr(None, newId, newAcquired, newName,
                                         newType, newMandatory, newMultilang,
                                         newRepetitive, newCustom)
                    message += self.getZMILangStr('MSG_INSERTED') % newId

            # Copy.
            # -----
            elif btn == 'BTN_COPY':
                metaOb = self.getMetadictAttr(id)
                if metaOb.get('acquired', 0) == 1:
                    masterRoot = getattr(self,
                                         self.getConfProperty('Portal.Master'))
                    masterDocElmnt = masterRoot.content
                    REQUEST.set('ids', [id])
                    xml = masterDocElmnt.manage_changeMetaProperties(
                        'BTN_EXPORT', lang, REQUEST, RESPONSE)
                    self.importMetadictXml(xml=xml)
                    message = self.getZMILangStr('MSG_IMPORTED') % (
                        '<i>%s</i>' % id)

            # Delete.
            # -------
            elif btn == 'BTN_DELETE':
                oldId = id
                self.delMetadictAttr(oldId)
                for portalClient in self.getPortalClients():
                    pcmm = portalClient.metaobj_manager
                    if oldId in pcmm.getMetadictAttrs(
                    ) and pcmm.getMetadictAttr(oldId).get('acquired', 0) == 1:
                        pcmm.delMetadictAttr(oldId)
                message = self.getZMILangStr('MSG_DELETED') % int(1)

            # Export.
            # -------
            elif btn == 'BTN_EXPORT':
                value = []
                ids = REQUEST.get('ids', [])
                metadicts = self.metas
                for i in range(len(metadicts) // 2):
                    id = metadicts[i * 2]
                    dict = metadicts[i * 2 + 1].copy()
                    if id in ids or len(ids) == 0:
                        dst_meta_types = []
                        for meta_id in self.getMetaobjIds():
                            if id in self.getMetadictAttrs(meta_id):
                                dst_meta_types.append(meta_id)
                        dict['dst_meta_types'] = dst_meta_types
                        value.append(dict)
                if len(value) == 1:
                    value = value[0]
                content_type = 'text/xml; charset=utf-8'
                filename = 'export.metadict.xml'
                export = self.getXmlHeader() + self.toXmlString(value, 1)
                RESPONSE.setHeader('Content-Type', content_type)
                RESPONSE.setHeader('Content-Disposition',
                                   'attachment;filename="%s"' % filename)
                return export

            # Import.
            # -------
            elif btn == 'BTN_IMPORT':
                f = REQUEST['file']
                if f:
                    filename = f.filename
                    self.importMetadictXml(xml=f)
                else:
                    filename = REQUEST['init']
                    self.importConf(filename, createIfNotExists=1)
                message = self.getZMILangStr('MSG_IMPORTED') % ('<i>%s</i>' %
                                                                filename)

            # Move to.
            # --------
            elif btn == 'move_to':
                pos = REQUEST['pos']
                oldId = id
                id = self.moveMetadictAttr(oldId, pos)
                message = self.getZMILangStr('MSG_MOVEDOBJTOPOS') % (
                    ("<i>%s</i>" % oldId), (pos + 1))

            ##### SYNCHRONIZE ####
            self.synchronizeObjAttrs()

        # Handle exception.
        except:
            standard.writeError(self, "[manage_changeMetaProperties]")
            error = str(sys.exc_info()[0])
            if sys.exc_info()[1]:
                error += ': ' + str(sys.exc_info()[1])
            target = self.url_append_params(
                target, {'manage_tabs_error_message': error})

        # Return with message.
        target = self.url_append_params(target, {'lang': lang, 'id': id})
        target = self.url_append_params(target, extra)
        if len(message) > 0:
            message += ' (in ' + str(int(
                (time.time() - t0) * 100.0) / 100.0) + ' secs.)'
            target = self.url_append_params(target,
                                            {'manage_tabs_message': message})
        return RESPONSE.redirect(target)
Example #6
0
def zmi_insert_actions(container, context, objAttr, objChildren, objPath=''):
    """
  Returns sorted list of insert actions. 
  """
    actions = []
    if not objAttr:
        return actions

    REQUEST = container.REQUEST
    auth_user = REQUEST['AUTHENTICATED_USER']
    absolute_url = '/'.join(list(container.getPhysicalPath()) + [''])
    userdef_roles = list(
        container.getRootElement().aq_parent.userdefined_roles()) + list(
            container.getRootElement().userdefined_roles())
    user_roles = [
        x for x in container.getUserRoles(auth_user, resolve=False)
        if x in userdef_roles
    ]

    repetitive = objAttr.get('repetitive', 0) == 1
    mandatory = objAttr.get('mandatory', 0) == 1

    #-- Objects.
    if repetitive or len(container.getObjChildren(objAttr['id'],
                                                  REQUEST)) == 0:
        metaObjIds = container.getMetaobjIds(sort=True)
        meta_ids = []
        if objAttr['type'] == '*':
            # get types
            meta_keys = objAttr['keys']
            # dynamic list of types
            if standard.dt_executable(container, '\n'.join(meta_keys)):
                meta_keys = standard.dt_exec(container, '\n'.join(meta_keys))
            # iterate types
            metaobj_manager = container.getMetaobjManager()
            for meta_id in meta_keys:
                if meta_id.startswith('type(') and meta_id.endswith(')'):
                    for metaObjId in metaObjIds:
                        metaObj = metaobj_manager.getMetaobj(
                            metaObjId, aq_attrs=['enabled'])
                        if metaObj['type'] == meta_id[5:-1] and metaObj[
                                'enabled'] == 1:
                            meta_ids.append(metaObj['id'])
                elif meta_id in metaObjIds:
                    meta_ids.append(meta_id)
                else:
                    container.writeError(
                        '[zmi_insert_actions]: %s.%s contains invalid meta_id \'%s\''
                        % (container.meta_id, objAttr['id'], meta_id))
        else:
            meta_ids.append(objAttr['type'])
        for meta_id in meta_ids:
            metaObj = container.getMetaobj(meta_id)
            ob_access = True
            ob_manage_access = container.getMetaobjAttr(
                meta_id, 'manage_access')
            if ob_manage_access is not None:
                try:
                    ob_access = standard.dt_exec(container,
                                                 ob_manage_access['custom'])
                except:
                    standard.writeError(
                        container,
                        '[zmi_insert_actions]: can\'t get manage_access from %s'
                        % meta_id)
            can_insert = True
            if objAttr['type'] == '*':
                can_insert = can_insert and (
                    (not isinstance(ob_access, dict)) or
                    (ob_access.get('insert') is None) or (len(
                        standard.intersection_list(ob_access.get('insert'),
                                                   user_roles)) > 0))
                mo_access = metaObj.get('access', {})
                mo_access_deny = mo_access.get('insert_deny', [])
                can_insert = can_insert and len(
                    [x for x in user_roles if x not in mo_access_deny]) > 0
                can_insert = can_insert or auth_user.has_role('Manager')
                mo_access_insert_nodes = standard.string_list(
                    mo_access.get('insert_custom', '{$}'))
                sl = []
                for x in mo_access_insert_nodes:
                    if x.find('@') < 0:
                        si = (container.getHome().id + '/content/' + x[2:-1] +
                              '/').replace('//', '/')
                    else:
                        si = (x[2:-1].replace('@', '/content/') + '/').replace(
                            '//', '/')
                    sl.append(si)
                can_insert = can_insert and len(
                    [x for x in sl if absolute_url.find(x) >= 0]) > 0
            if can_insert:
                if meta_id in container.dGlobalAttrs and 'constructor' in container.dGlobalAttrs[
                        meta_id]:
                    value = 'manage_addProduct/zms/%s' % container.dGlobalAttrs[
                        meta_id]['constructor']
                elif metaObj['type'] == 'ZMSModule':
                    value = 'manage_addZMSModule'
                elif objAttr['type'] in meta_ids and repetitive and objAttr.get(
                        'custom'):
                    value = 'manage_addZMSCustomDefault'
                else:
                    value = 'manage_addProduct/zms/manage_addzmscustomform'
                action = (container.display_type(REQUEST, meta_id), value,
                          container.display_icon(REQUEST, meta_id))
                if action not in actions:
                    actions.append(action)

    #-- Insert Commands.
    actions.extend(zmi_command_actions(container, stereotype='insert'))

    #-- Sort.
    actions.sort()

    #-- Headline.
    if len(actions) > 0:
        actions.insert(
            0, ('----- %s -----' % container.getZMILangStr('CAPTION_INSERT') %
                container.getZMILangStr('ATTR_CONTENT'), 'insert-action'))

    # Return action list.
    return actions