CatalogTool.py 23.2 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# 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.
#
##############################################################################

from Products.CMFCore.CatalogTool import CatalogTool as CMFCoreCatalogTool
from Products.ZSQLCatalog.ZSQLCatalog import ZCatalog
from Products.CMFCore import CMFCorePermissions
from AccessControl import ClassSecurityInfo, getSecurityManager
from Products.CMFCore.CatalogTool import IndexableObjectWrapper as CMFCoreIndexableObjectWrapper
34
from Products.CMFCore.utils import UniqueObject, _checkPermission, _getAuthenticatedUser, getToolByName
35
from Products.CMFCore.utils import _mergedLocalRoles
36
from Globals import InitializeClass, DTMLFile, package_home
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37 38
from Acquisition import aq_base, aq_inner, aq_parent
from DateTime.DateTime import DateTime
39
from Products.CMFActivity.ActiveObject import ActiveObject
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40 41 42 43 44 45

from AccessControl.PermissionRole import rolesForPermissionOn

from Products.PageTemplates.Expressions import SecureModuleImporter
from Products.CMFCore.Expression import Expression
from Products.PageTemplates.Expressions import getEngine
46
from MethodObject import Method
Jean-Paul Smets's avatar
Jean-Paul Smets committed
47

48
import os, time, urllib
Jean-Paul Smets's avatar
Jean-Paul Smets committed
49 50
from zLOG import LOG

51 52 53 54 55 56 57 58 59
  # Security uses ERP5Security by default
try:
  from Products.ERP5Security import ERP5UserManager
  withnuxgroups = 0
except ImportError:
  ERP5UserManager = None
  # If NuxUserGroups is installed and ERP5Security is not installed, we use NuxUserGroups groups
  try:
    from Products.NuxUserGroups.CatalogToolWithGroups import mergedLocalRoles
60
    from Products.NuxUserGroups.CatalogToolWithGroups import _getAllowedRolesAndUsers
61
    withnuxgroups = 1
62
  except ImportError:
63 64
    withnuxgroups = 0
    
Jean-Paul Smets's avatar
Jean-Paul Smets committed
65 66 67 68 69 70 71 72 73 74 75
class IndexableObjectWrapper(CMFCoreIndexableObjectWrapper):

    def __setattr__(self, name, value):
      # We need to update the uid during the cataloging process
      if name == 'uid':
        setattr(self.__ob, name, value)
      else:
        self.__dict__[name] = value

    def allowedRolesAndUsers(self):
        """
76 77
        Return a list of roles and users with Access contents
        information permission.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
78 79 80 81
        Used by PortalCatalog to filter out items you're not allowed to see.
        """
        ob = self.__ob
        allowed = {}
Romain Courteaud's avatar
Romain Courteaud committed
82
        for r in rolesForPermissionOn('Access contents information', ob):
83
          allowed[r] = 1
84
        if withnuxgroups:
85 86 87 88
          localroles = mergedLocalRoles(ob, withgroups=1)
        else:
          # CMF
          localroles = _mergedLocalRoles(ob)
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        # For each group or user, we have a list of roles, this list
        # give in this order : [roles on object, roles acquired on the parent,
        # roles acquired on the parent of the parent....]
        # So if we have ['-Author','Author'] we should remove the role 'Author'
        # but if we have ['Author','-Author'] we have to keep the role 'Author'
        new_dict = {}
        for key in localroles.keys():
          new_list = []
          remove_list = []
          for role in localroles[key]:
            if role.startswith('-'):
              if not role[1:] in new_list and not role[1:] in remove_list:
                remove_list.append(role[1:])
            elif not role in remove_list:
              new_list.append(role)
          if len(new_list)>0:
            new_dict[key] = new_list
        localroles = new_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
107
        for user, roles in localroles.items():
108 109 110 111 112 113 114 115 116 117 118 119
          for role in roles:
            if allowed.has_key(role):
              if withnuxgroups:
                allowed[user] = 1
              else:
                allowed['user:' + user] = 1
            # Added for ERP5 project by JP Smets
            if role != 'Owner':
              if withnuxgroups:
                allowed[user + ':' + role] = 1
              else:
                allowed['user:' + user + ':' + role] = 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
120
        if allowed.has_key('Owner'):
121
          del allowed['Owner']
122
        #LOG("allowedRolesAndUsers",0,str(allowed.keys()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
123 124
        return list(allowed.keys())

125
class RelatedBaseCategory(Method):
126 127
    """A Dynamic Method to act as a related key.
    """
128 129 130 131
    def __init__(self, id):
      self._id = id

    def __call__(self, instance, table_0, table_1, query_table='catalog',**kw):
132
      """Create the sql code for this related key."""
133 134 135 136 137 138 139 140
      base_category_uid = instance.portal_categories._getOb(self._id).getUid()
      expression_list = []
      append = expression_list.append
      append('%s.uid = %s.category_uid' % (table_1,table_0))
      append('AND %s.base_category_uid = %s' % (table_0,base_category_uid))
      append('AND %s.uid = %s.uid' % (table_0,query_table))
      return ' '.join(expression_list)

141
class CatalogTool (UniqueObject, ZCatalog, CMFCoreCatalogTool, ActiveObject):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    """
    This is a ZSQLCatalog that filters catalog queries.
    It is based on ZSQLCatalog
    """
    id = 'portal_catalog'
    meta_type = 'ERP5 Catalog'
    security = ClassSecurityInfo()

    manage_options = ( { 'label' : 'Overview', 'action' : 'manage_overview' },
                     ) + ZCatalog.manage_options


    def __init__(self):
        ZCatalog.__init__(self, self.getId())

    # Explicite Inheritance
    __url = CMFCoreCatalogTool.__url
    manage_catalogFind = CMFCoreCatalogTool.manage_catalogFind

Jean-Paul Smets's avatar
Jean-Paul Smets committed
161 162 163 164
    security.declareProtected( CMFCorePermissions.ManagePortal
                , 'manage_schema' )
    manage_schema = DTMLFile( 'dtml/manageSchema', globals() )

165
    security.declareProtected( 'Import/Export objects', 'addDefaultSQLMethods' )
166
    def addDefaultSQLMethods(self, config_id='erp5'):
167 168 169
      """
        Add default SQL methods for a given configuration.
      """
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
      # For compatibility.
      if config_id.lower() == 'erp5':
        config_id = 'erp5_mysql'
      elif config_id.lower() == 'cps3':
        config_id = 'cps3_mysql'

      addSQLCatalog = self.manage_addProduct['ZSQLCatalog'].manage_addSQLCatalog
      if config_id not in self.objectIds():
        addSQLCatalog(config_id, '')

      catalog = self.getSQLCatalog(config_id)
      addSQLMethod = catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod
      product_path = package_home(globals())
      zsql_dirs = []

      # Common methods
      if config_id.lower() == 'erp5_mysql':
187
        zsql_dirs.append(os.path.join(product_path, 'sql', 'common_mysql'))
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        zsql_dirs.append(os.path.join(product_path, 'sql', 'erp5_mysql'))
      elif config_id.lower() == 'cps3_mysql':
        zsql_dirs.append(os.path.join(product_path, 'sql', 'common_mysql'))
        zsql_dirs.append(os.path.join(product_path, 'sql', 'cps3_mysql'))
      # XXX TODO : add other cases

      # Iterate over the sql directory. Add all sql methods in that directory.
      for directory in zsql_dirs:
        for entry in os.listdir(directory):
          if entry.endswith('.zsql'):
            id = entry[:-5]
            # Create an empty SQL method first.
            addSQLMethod(id = id, title = '', connection_id = '', arguments = '', template = '')
            #LOG('addDefaultSQLMethods', 0, 'catalog = %r' % (catalog.objectIds(),))
            sql_method = getattr(catalog, id)
            # Set parameters of the SQL method from the contents of a .zsql file.
            sql_method.fromFile(os.path.join(directory, entry))
          elif entry == 'properties.xml':
            # This sets up the attributes. The file should be generated by manage_exportProperties.
            catalog.manage_importProperties(os.path.join(directory, entry))

      # Make this the default.
      self.default_sql_catalog_id = config_id
211 212
      
    security.declareProtected( 'Import/Export objects', 'exportSQLMethods' )
213
    def exportSQLMethods(self, sql_catalog_id=None, config_id='erp5'):
214 215 216 217 218 219 220 221
      """
        Export SQL methods for a given configuration.
      """
      # For compatibility.
      if config_id.lower() == 'erp5':
        config_id = 'erp5_mysql'
      elif config_id.lower() == 'cps3':
        config_id = 'cps3_mysql'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
222

223
      catalog = self.getSQLCatalog(sql_catalog_id)
224 225 226
      product_path = package_home(globals())
      common_sql_dir = os.path.join(product_path, 'sql', 'common_mysql')
      config_sql_dir = os.path.join(product_path, 'sql', config_id)
227 228 229 230 231
      common_sql_list = ('z0_drop_record', 'z_read_recorded_object_list', 'z_catalog_paths',
                         'z_record_catalog_object', 'z_clear_reserved', 'z_record_uncatalog_object',
                         'z_create_record', 'z_related_security', 'z_delete_recorded_object_list',
                         'z_reserve_uid', 'z_getitem_by_path', 'z_show_columns', 'z_getitem_by_path',
                         'z_show_tables', 'z_getitem_by_uid', 'z_unique_values', 'z_produce_reserved_uid_list',)
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    
      msg = ''
      for id in catalog.objectIds(spec=('Z SQL Method',)):
        if id in common_sql_list:
          d = common_sql_dir
        else:
          d = config_sql_dir
        sql = catalog._getOb(id)
        # First convert the skin to text
        text = sql.manage_FTPget()
        name = os.path.join(d, '%s.zsql' % (id,))
        msg += 'Writing %s\n' % (name,)
        f = open(name, 'w')
        try:
          f.write(text)
        finally:
          f.close()
249 250 251 252 253 254 255 256 257 258
          
      properties = self.manage_catalogExportProperties(sql_catalog_id=sql_catalog_id)
      name = os.path.join(config_sql_dir, 'properties.xml')
      msg += 'Writing %s\n' % (name,)
      f = open(name, 'w')
      try:
        f.write(properties)
      finally:
        f.close()
        
259 260
      return msg
        
261
    def _listAllowedRolesAndUsers(self, user):
262 263 264 265 266 267
      if ERP5UserManager is not None:
        # We use ERP5Security PAS based authentication
        result = CMFCoreCatalogTool._listAllowedRolesAndUsers(self, user)
        # deal with groups
        getGroups = getattr(user, 'getGroups', None)
        if getGroups is not None:
268
            groups = list(user.getGroups())
269 270 271 272 273 274
            groups.append('role:Anonymous')
            if 'Authenticated' in result:
                groups.append('role:Authenticated')
            for group in groups:
                result.append('user:%s' % group)
        # end groups
275 276
        return result
      elif withnuxgroups:
277
        return _getAllowedRolesAndUsers(user)
278
      else:
279
        return CMFCoreCatalogTool._listAllowedRolesAndUsers(self, user)
280

Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
    # Schema Management
    def editColumn(self, column_id, sql_definition, method_id, default_value, REQUEST=None, RESPONSE=None):
      """
        Modifies a schema column of the catalog
      """
      new_schema = []
      for c in self.getIndexList():
        if c.id == index_id:
          new_c = {'id': index_id, 'sql_definition': sql_definition, 'method_id': method_id, 'default_value': default_value}
        else:
          new_c = c
        new_schema.append(new_c)
      self.setColumnList(new_schema)

    def setColumnList(self, column_list):
      """
      """
      self._sql_schema = column_list

    def getColumnList(self):
      """
      """
      if not hasattr(self, '_sql_schema'): self._sql_schema = []
      return self._sql_schema

    def getColumn(self, column_id):
      """
      """
      for c in self.getColumnList():
        if c.id == column_id:
          return c
      return None

    def editIndex(self, index_id, sql_definition, REQUEST=None, RESPONSE=None):
      """
        Modifies the schema of the catalog
      """
      new_index = []
      for c in self.getIndexList():
        if c.id == index_id:
          new_c = {'id': index_id, 'sql_definition': sql_definition}
        else:
          new_c = c
        new_index.append(new_c)
      self.setIndexList(new_index)

    def setIndexList(self, index_list):
      """
      """
      self._sql_index = index_list

    def getIndexList(self):
      """
      """
      if not hasattr(self, '_sql_index'): self._sql_index = []
      return self._sql_index

    def getIndex(self, index_id):
      """
      """
      for c in self.getIndexList():
        if c.id == index_id:
          return c
      return None


347 348 349 350
    security.declarePublic( 'getAllowedRolesAndUsers' )
    def getAllowedRolesAndUsers(self, **kw):
      """
        Return allowed roles and users.
351

352
        This is supposed to be used with Z SQL Methods to check permissions
353 354 355 356
        when you list up documents. It is also able to take into account
        a parameter named local_roles so that list documents only include
        those documents for which the user (or the group) was
        associated one of the given local roles.
357 358
      """
      user = _getAuthenticatedUser(self)
359
      allowedRolesAndUsers = self._listAllowedRolesAndUsers(user)
360 361 362 363

      # Patch for ERP5 by JP Smets in order
      # to implement worklists and search of local roles
      if kw.has_key('local_roles'):
364
        # XXX user is not enough - we should also include groups of the user
365 366 367
        # Only consider local_roles if it is not empty
        if kw['local_roles'] != '' and  kw['local_roles'] != [] and  kw['local_roles'] is not None:
          local_roles = kw['local_roles']
368
          new_allowedRolesAndUsers = []
369 370 371 372
          # Turn it into a list if necessary according to ';' separator
          if type(local_roles) == type('a'):
            local_roles = local_roles.split(';')
          # Local roles now has precedence (since it comes from a WorkList)
373
          for user_or_group in allowedRolesAndUsers:
374
            for role in local_roles:
375 376
              new_allowedRolesAndUsers.append('%s:%s' % (user_or_group, role))
          allowedRolesAndUsers = new_allowedRolesAndUsers
377 378 379

      return allowedRolesAndUsers

Jean-Paul Smets's avatar
Jean-Paul Smets committed
380 381 382 383 384 385
    # searchResults has inherited security assertions.
    def searchResults(self, REQUEST=None, **kw):
        """
            Calls ZCatalog.searchResults with extra arguments that
            limit the results to what the user is allowed to see.
        """
386 387
        kw[ 'allowedRolesAndUsers' ] = self.getAllowedRolesAndUsers(**kw) # XXX allowedRolesAndUsers naming is wrong

Jean-Paul Smets's avatar
Jean-Paul Smets committed
388 389 390 391 392 393
        if not _checkPermission(
            CMFCorePermissions.AccessInactivePortalContent, self ):
            base = aq_base( self )
            now = DateTime()
            kw[ 'effective' ] = { 'query' : now, 'range' : 'max' }
            kw[ 'expires'   ] = { 'query' : now, 'range' : 'min' }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
394

395 396
        
        if not kw.has_key('limit'):
397
          kw['limit'] = 1000
398

399
        #LOG("search allowedRolesAndUsers",0,str(kw[ 'allowedRolesAndUsers' ]))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
400 401 402 403 404 405 406 407 408
        return apply(ZCatalog.searchResults, (self, REQUEST), kw)

    __call__ = searchResults

    def countResults(self, REQUEST=None, **kw):
        """
            Calls ZCatalog.countResults with extra arguments that
            limit the results to what the user is allowed to see.
        """
409
        kw[ 'allowedRolesAndUsers' ] = self.getAllowedRolesAndUsers(**kw) # XXX allowedRolesAndUsers naming is wrong
410
        
Jean-Paul Smets's avatar
Jean-Paul Smets committed
411
        # Forget about permissions in statistics
412
        # (we should not count lines more than once with statistic expressions)
413
        if kw.has_key('select_expression'): del kw[ 'allowedRolesAndUsers' ]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
414

415
        # XXX This needs to be set again
416 417 418 419 420 421
        #if not _checkPermission(
        #    CMFCorePermissions.AccessInactivePortalContent, self ):
        #    base = aq_base( self )
        #    now = DateTime()
        #    #kw[ 'effective' ] = { 'query' : now, 'range' : 'max' }
        #    #kw[ 'expires'   ] = { 'query' : now, 'range' : 'min' }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
422 423 424

        return apply(ZCatalog.countResults, (self, REQUEST), kw)

425 426 427 428 429 430 431 432 433 434
    def wrapObject(self, object, sql_catalog_id=None, **kw):
        """
          Return a wrapped object for reindexing.
        """
        catalog = self.getSQLCatalog(sql_catalog_id)
        if catalog is None:
          # Nothing to do.
          LOG('wrapObject', 0, 'Warning: catalog is not available')
          return (None, None)

435
        wf = getToolByName(self, 'portal_workflow')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
436
        if wf is not None:
437
          vars = wf.getCatalogVariablesFor(object)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
438
        else:
439 440
          vars = {}
        #LOG('catalog_object vars', 0, str(vars))
441

Jean-Paul Smets's avatar
Jean-Paul Smets committed
442
        w = IndexableObjectWrapper(vars, object)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

        object_path = object.getPhysicalPath()
        portal_path = object.portal_url.getPortalObject().getPhysicalPath()
        if len(object_path) > len(portal_path) + 2 and getattr(object, 'isRADContent', 0):
          # This only applied to ERP5 Contents (not CPS)
          # We are now in the case of a subobject of a root document
          # We want to return single security information
          document_object = aq_inner(object)
          for i in range(0, len(object_path) - len(portal_path) - 2):
            document_object = document_object.aq_parent
          document_w = IndexableObjectWrapper({}, document_object)
        else:
          document_w = w

        (security_uid, optimised_roles_and_users) = catalog.getSecurityUid(document_w)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
458
        #LOG('catalog_object optimised_roles_and_users', 0, str(optimised_roles_and_users))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
459
        # XXX we should build vars begore building the wrapper
Jean-Paul Smets's avatar
Jean-Paul Smets committed
460 461
        if optimised_roles_and_users is not None:
          vars['optimised_roles_and_users'] = optimised_roles_and_users
462
        else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
463
          vars['optimised_roles_and_users'] = None
464 465 466
        predicate_property_dict = catalog.getPredicatePropertyDict(object)
        if predicate_property_dict is not None:
          vars['predicate_property_dict'] = predicate_property_dict
467
        vars['security_uid'] = security_uid
468 469

        return w
Jean-Paul Smets's avatar
Jean-Paul Smets committed
470 471

    security.declarePrivate('reindexObject')
472
    def reindexObject(self, object, idxs=None, sql_catalog_id=None,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
473 474 475 476
        '''Update catalog after object data has changed.
        The optional idxs argument is a list of specific indexes
        to update (all of them by default).
        '''
477
        if idxs is None: idxs = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
478
        url = self.__url(object)
479
        self.catalog_object(object, url, idxs=idxs, sql_catalog_id=sql_catalog_id,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
480

481

Jean-Paul Smets's avatar
Jean-Paul Smets committed
482
    security.declarePrivate('unindexObject')
483
    def unindexObject(self, object, path=None, sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
484 485 486 487 488 489 490
        """
          Remove from catalog.
        """
        if path is None:
          url = self.__url(object)
        else:
          url = path
491
        self.uncatalog_object(url, sql_catalog_id=sql_catalog_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
492

Jean-Paul Smets's avatar
Jean-Paul Smets committed
493
    security.declarePrivate('moveObject')
494
    def moveObject(self, object, idxs=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
495 496 497 498 499 500
        """
          Reindex in catalog, taking into account
          peculiarities of ERP5Catalog / ZSQLCatalog

          Useless ??? XXX
        """
501
        if idxs is None: idxs = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
502 503
        url = self.__url(object)
        self.catalog_object(object, url, idxs=idxs, is_object_moved=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
504

505 506 507 508 509 510
    security.declarePublic('getPredicatePropertyDict')
    def getPredicatePropertyDict(self, object):
      """
      Construct a dictionnary with a list of properties
      to catalog into the table predicate
      """
511 512 513 514
      if not getattr(object,'isPredicate',None):
        return None
      object = object.asPredicate()
      if object is None:
515 516 517 518 519 520 521 522 523 524 525
        return None
      property_dict = {}
      identity_criterion = getattr(object,'_identity_criterion',None)
      range_criterion = getattr(object,'_range_criterion',None)
      if identity_criterion is not None:
        for property, value in identity_criterion.items():
          if value is not None:
            property_dict[property] = value
      if range_criterion is not None:
        for property, (min, max) in range_criterion.items():
          if min is not None:
526
            property_dict['%s_range_min' % property] = min
527
          if max is not None:
528
            property_dict['%s_range_max' % property] = max
529
      property_dict['membership_criterion_category_list'] = object.getMembershipCriterionCategoryList()
530 531
      return property_dict

532
    security.declarePrivate('getDynamicRelatedKeyList')
533
    def getDynamicRelatedKeyList(self, sql_catalog_id=None, **kw):
534
      """
535
      Return the list of dynamic related keys.
536 537
      This method will try to automatically generate new related key
      by looking at the category tree.
538 539 540 541

      For exemple it will generate:
      destination_title | category,catalog/title/z_related_destination
      default_destination_title | category,catalog/title/z_related_destination
542 543 544
      """
      related_key_list = []
      base_cat_id_list = self.portal_categories.getBaseCategoryList()
545
      default_string = 'default_'
546
      for key in kw.keys():
547 548 549 550
        prefix = ''
        if key.startswith(default_string):
          key = key[len(default_string):]
          prefix = default_string
551
        splitted_key = key.split('_')
552 553
        # look from the end of the key from the beginning if we
        # can find 'title', or 'portal_type'...
554 555
        for i in range(1,len(splitted_key))[::-1]:
          expected_base_cat_id = '_'.join(splitted_key[0:i])
556
          if expected_base_cat_id != 'parent' and \
557 558 559
             expected_base_cat_id in base_cat_id_list:
            # We have found a base_category
            end_key = '_'.join(splitted_key[i:])
560
            # accept only some catalog columns
561 562 563 564 565
            if end_key in ('title', 'uid', 'description',
                           'relative_url', 'id', 'portal_type'):
              related_key_list.append(
                      '%s%s | category,catalog/%s/z_related_%s' %
                      (prefix, key, end_key, expected_base_cat_id))
566 567 568 569 570 571

      return related_key_list

    def _aq_dynamic(self, name):
      """
      Automatic related key generation.
572
      Will generate z_related_[base_category_id] if possible
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
      """
      aq_base_name = getattr(aq_base(self), name, None)
      if aq_base_name == None:
        DYNAMIC_METHOD_NAME = 'z_related_'
        method_name_length = len(DYNAMIC_METHOD_NAME)
        zope_security = '__roles__'
        if (name.startswith(DYNAMIC_METHOD_NAME) and \
          (not name.endswith(zope_security))):
          base_category_id = name[len(DYNAMIC_METHOD_NAME):]
          method = RelatedBaseCategory(base_category_id)
          setattr(self.__class__, name, 
                  method)
          klass = aq_base(self).__class__
          if hasattr(klass, 'security'):
            from Products.ERP5Type import Permissions as ERP5Permissions
            klass.security.declareProtected(ERP5Permissions.View, name)
          else:
            # XXX security declaration always failed....
            LOG('WARNING ERP5Form SelectionTool, security not defined on',
                0, klass.__name__)
          return getattr(self, name)
        else:
          return aq_base_name
      return aq_base_name
597 598 599



600
InitializeClass(CatalogTool)