CatalogTool.py 57.6 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
#
# 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.
#
##############################################################################

29
import sys
30
from copy import deepcopy
31
from collections import defaultdict
32
from math import ceil
Jean-Paul Smets's avatar
Jean-Paul Smets committed
33 34
from Products.CMFCore.CatalogTool import CatalogTool as CMFCoreCatalogTool
from Products.ZSQLCatalog.ZSQLCatalog import ZCatalog
35
from Products.ZSQLCatalog.SQLCatalog import ComplexQuery, SimpleQuery
36
from Products.ERP5Type import Permissions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37
from AccessControl import ClassSecurityInfo, getSecurityManager
38
from AccessControl.User import system as system_user
Aurel's avatar
Aurel committed
39 40
from Products.CMFCore.utils import UniqueObject, _getAuthenticatedUser, getToolByName
from Products.ERP5Type.Globals import InitializeClass, DTMLFile
41
from Acquisition import aq_base, aq_inner, aq_parent, ImplicitAcquisitionWrapper
42
from Products.CMFActivity.ActiveObject import ActiveObject
43
from Products.CMFActivity.ActivityTool import GroupedMessage
44
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Jean-Paul Smets's avatar
Jean-Paul Smets committed
45 46 47

from AccessControl.PermissionRole import rolesForPermissionOn

48
from MethodObject import Method
Jean-Paul Smets's avatar
Jean-Paul Smets committed
49

50
from Products.ERP5Security import mergedLocalRoles
51
from Products import ERP5Security
52
from Products.ZSQLCatalog.Utils import sqlquote
53

Aurel's avatar
Aurel committed
54
import warnings
55
from zLOG import LOG, PROBLEM, WARNING, INFO
Jean-Paul Smets's avatar
Jean-Paul Smets committed
56

57
ACQUIRE_PERMISSION_VALUE = []
58
DYNAMIC_METHOD_NAME = 'z_related_'
59
DYNAMIC_METHOD_NAME_LEN = len(DYNAMIC_METHOD_NAME)
60 61
STRICT_METHOD_NAME = 'strict_'
STRICT_METHOD_NAME_LEN = len(STRICT_METHOD_NAME)
62 63
PARENT_METHOD_NAME = 'parent_'
PARENT_METHOD_NAME_LEN = len(PARENT_METHOD_NAME)
64
RELATED_DYNAMIC_METHOD_NAME = '_related'
65 66
# Negative as it's used as a slice end offset
RELATED_DYNAMIC_METHOD_NAME_LEN = -len(RELATED_DYNAMIC_METHOD_NAME)
67
ZOPE_SECURITY_SUFFIX = '__roles__'
68
IGNORE_BASE_CATEGORY_UID = 'any'
Aurel's avatar
Aurel committed
69

70 71
SECURITY_QUERY_ARGUMENT_NAME = 'ERP5Catalog_security_query'

72 73
DYNAMIC_RELATED_KEY_FLAG_PARENT    = 1 << 0
DYNAMIC_RELATED_KEY_FLAG_STRICT    = 1 << 1
74
DYNAMIC_RELATED_KEY_FLAG_PREDICATE = 1 << 2
75 76 77 78 79
# Note: parsing flags backward as "pop()" is O(1), so this list contains flags
# in right to left order.
DYNAMIC_RELATED_KEY_FLAG_LIST = (
  ('parent', DYNAMIC_RELATED_KEY_FLAG_PARENT),
  ('strict', DYNAMIC_RELATED_KEY_FLAG_STRICT),
80
  ('predicate', DYNAMIC_RELATED_KEY_FLAG_PREDICATE),
81
)
82
EMPTY_SET = ()
83

84
class IndexableObjectWrapper(object):
85 86
    __security_parameter_cache = None
    __local_role_cache = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
87

88
    def __init__(self, ob, user_set, role_dict):
89
        self.__ob = ob
90 91
        self.__user_set = user_set
        self.__role_dict = role_dict
92

93 94 95 96
    def __getattr__(self, name):
        return getattr(self.__ob, name)

    # We need to update the uid during the cataloging process
97
    uid = property(lambda self: self.__ob.getUid(),
98
                   lambda self, value: setattr(self.__ob, 'uid', value))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
99

100 101 102
    def __getLocalRoleDict(self):
      local_role_dict = self.__local_role_cache
      if local_role_dict is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
103
        ob = self.__ob
104 105 106 107 108
        # 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'
109
        local_role_dict = {}
110
        skip_role_set = set()
111 112
        skip_role = skip_role_set.add
        clear_skip_role = skip_role_set.clear
113
        for key, role_list in mergedLocalRoles(ob).iteritems():
114 115 116 117 118 119 120 121
          new_role_list = []
          new_role = new_role_list.append
          clear_skip_role()
          for role in role_list:
            if role[:1] == '-':
              skip_role(role[1:])
            elif role not in skip_role_set:
              new_role(role)
122
          if new_role_list:
123 124 125
            local_role_dict[key] = [new_role_list, False]
        self.__local_role_cache = local_role_dict
      return local_role_dict
126

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    def _getSecurityGroupIdList(self):
      """
      Return the list of security group identifiers this document is
      interested in. They may be actual user identifiers or not.
      Supposed to be accessed by CatalogTool.
      """
      return self.__getLocalRoleDict().keys()

    def _getSecurityParameterList(self):
      result = self.__security_parameter_cache
      if result is None:
        ob = self.__ob
        local_role_dict = self.__getLocalRoleDict()

        role_dict = self.__role_dict
        user_set = self.__user_set
        for security_group_id, security_group_data in local_role_dict.iteritems():
          security_group_data[1] = security_group_id in user_set
145

146
        allowed_dict = {}
147

148 149 150 151 152 153
        # For each local role of a user:
        #   If the local role grants View permission, add it.
        # Every addition implies 2 lines:
        #   user:<user_id>
        #   user:<user_id>:<role_id>
        # A line must not be present twice in final result.
154
        allowed_role_set = set(rolesForPermissionOn('View', ob))
155 156 157 158 159
        # XXX the permission name is included by default for verbose
        # logging of security errors, but the catalog does not need to
        # index it. Unfortunately, rolesForPermissionOn does not have
        # an option to disable this behavior at calling time, so
        # discard it explicitly.
160
        allowed_role_set.discard('_View_Permission')
161 162
        # XXX Owner is hardcoded, in order to prevent searching for user on the
        # site root.
163 164 165
        allowed_role_set.discard('Owner')

        # XXX make this a method of base ?
166
        local_roles_group_id_dict = deepcopy(getattr(ob,
167
          '__ac_local_roles_group_id_dict__', {}))
168 169 170 171 172 173 174 175 176 177

        # If we acquire a permission, then we also want to acquire the local
        # roles group ids
        local_roles_container = ob
        while getattr(local_roles_container, 'isRADContent', 0):
          if local_roles_container._getAcquireLocalRoles():
            local_roles_container = local_roles_container.aq_parent
            for role_definition_group, user_and_role_list in \
                getattr(local_roles_container,
                        '__ac_local_roles_group_id_dict__',
178
                        {}).items():
179
              local_roles_group_id_dict.setdefault(role_definition_group, set()
180 181 182
                ).update(user_and_role_list)
          else:
            break
183

184
        allowed_by_local_roles_group_id = {}
185 186
        allowed_by_local_roles_group_id[''] = allowed_role_set

187
        optimized_role_set = set()
188
        for role_definition_group, user_and_role_list in local_roles_group_id_dict.iteritems():
189 190
          group_allowed_set = allowed_by_local_roles_group_id.setdefault(
            role_definition_group, set())
191
          for user, role in user_and_role_list:
192 193 194 195
            if role in allowed_role_set:
              prefix = 'user:' + user
              group_allowed_set.update((prefix, '%s:%s' % (prefix, role)))
              optimized_role_set.add((user, role))
196 197
        user_role_dict = {}
        user_view_permission_role_dict = {}
198
        for user, (roles, user_exists) in local_role_dict.iteritems():
199
          prefix = 'user:' + user
200
          for role in roles:
201
            is_not_in_optimised_role_set = (user, role) not in optimized_role_set
202
            if user_exists and role in role_dict:
203 204 205 206
              # User is a user (= not a group) and role is configured as
              # monovalued.
              if is_not_in_optimised_role_set:
                user_role_dict[role] = user
207
              if role in allowed_role_set:
208
                # ...and local role grants view permission.
209 210
                user_view_permission_role_dict[role] = user
            elif role in allowed_role_set:
211 212
              # User is a group and local role grants view permission.
              for group in local_roles_group_id_dict.get(user, ('', )):
213 214
                group_allowed_set = allowed_by_local_roles_group_id.setdefault(
                  group, set())
215 216 217
                if is_not_in_optimised_role_set:
                  group_allowed_set.add(prefix)
                  group_allowed_set.add('%s:%s' % (prefix, role))
218

219
        # sort `allowed` principals
220
        sorted_allowed_by_local_roles_group_id = {}
221
        for local_roles_group_id, allowed in \
222
                allowed_by_local_roles_group_id.iteritems():
223 224 225
          sorted_allowed_by_local_roles_group_id[local_roles_group_id] = tuple(
            sorted(allowed))

226 227 228 229 230
        self.__security_parameter_cache = result = (
          sorted_allowed_by_local_roles_group_id,
          user_role_dict,
          user_view_permission_role_dict,
        )
231
      return result
232

233 234 235
    def getLocalRolesGroupIdDict(self):
      """Returns a mapping of local roles group id to roles and users with View
      permission.
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
      """
      return self._getSecurityParameterList()[0]

    def getAssignee(self):
      """Returns the user ID of the user with 'Assignee' local role on this
      document.

      If there is more than one Assignee local role, the result is undefined.
      """
      return self._getSecurityParameterList()[1].get('Assignee', None)

    def getViewPermissionAssignee(self):
      """Returns the user ID of the user with 'Assignee' local role on this
      document, if the Assignee role has View permission.

      If there is more than one Assignee local role, the result is undefined.
      """
      return self._getSecurityParameterList()[2].get('Assignee', None)

    def getViewPermissionAssignor(self):
      """Returns the user ID of the user with 'Assignor' local role on this
      document, if the Assignor role has View permission.

      If there is more than one Assignor local role, the result is undefined.
      """
      return self._getSecurityParameterList()[2].get('Assignor', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
262

263 264 265 266 267 268 269 270
    def getViewPermissionAssociate(self):
      """Returns the user ID of the user with 'Associate' local role on this
      document, if the Associate role has View permission.

      If there is more than one Associate local role, the result is undefined.
      """
      return self._getSecurityParameterList()[2].get('Associate', None)

271 272 273 274
    def __repr__(self):
      return '<Products.ERP5Catalog.CatalogTool.IndexableObjectWrapper'\
          ' for %s>' % ('/'.join(self.__ob.getPhysicalPath()), )

275

276
class RelatedBaseCategory(Method):
277 278
    """A Dynamic Method to act as a related key.
    """
279
    def __init__(self, id, strict_membership=0, related=0, query_table_column='uid'):
280
      self._id = id
281 282 283 284
      if self._id == IGNORE_BASE_CATEGORY_UID:
        base_category_sql = ''
      else:
        base_category_sql = "%(category_table)s.base_category_uid = %(base_category_uid)s AND\n"
285
      if strict_membership:
286
        strict = '%(category_table)s.category_strict_membership = 1 AND\n'
287 288 289 290 291
      else:
        strict = ''
      # From the point of view of query_table, we are looking up objects...
      if related:
        # ... which have a relation toward us
Vincent Pelletier's avatar
Vincent Pelletier committed
292 293 294 295
        # query_table's uid = category table's category_uid
        query_table_side = 'category_uid'
        # category table's uid = foreign_table's uid
        foreign_side = 'uid'
296 297
      else:
        # ... toward which we have a relation
Vincent Pelletier's avatar
Vincent Pelletier committed
298 299 300 301
        # query_table's uid = category table's uid
        query_table_side = 'uid'
        # category table's category_uid = foreign_table's uid
        foreign_side = 'category_uid'
302
      self._template = """\
303
%(base_category)s%(strict)s%%(foreign_catalog)s.uid = %%(category_table)s.%(foreign_side)s
304
%%(RELATED_QUERY_SEPARATOR)s
305
%%(category_table)s.%(query_table_side)s = %%(query_table)s.%(query_table_column)s""" % {
306
          'base_category': base_category_sql,
307
          'strict': strict,
Vincent Pelletier's avatar
Vincent Pelletier committed
308 309
          'foreign_side': foreign_side,
          'query_table_side': query_table_side,
310
          'query_table_column': query_table_column
311
      }
312
      self._monotable_template = """\
313 314
%(base_category)s%(strict)s%%(category_table)s.%(query_table_side)s = %%(query_table)s.%(query_table_column)s""" % {
          'base_category': base_category_sql,
315 316
          'strict': strict,
          'query_table_side': query_table_side,
317
          'query_table_column': query_table_column,
318
      }
319

320
    def __call__(self, instance, table_0, table_1=None, query_table='catalog',
321
        RELATED_QUERY_SEPARATOR=' AND ', **kw):
322
      """Create the sql code for this related key."""
323
      format_dict = {
Vincent Pelletier's avatar
Vincent Pelletier committed
324
        'query_table': query_table,
325
        'category_table': table_0,
Vincent Pelletier's avatar
Vincent Pelletier committed
326
        'foreign_catalog': table_1,
327
        'RELATED_QUERY_SEPARATOR': RELATED_QUERY_SEPARATOR,
328
      }
329 330 331 332 333 334 335 336
      if self._id != IGNORE_BASE_CATEGORY_UID:
        # Note: in normal conditions, our category's uid will not change from
        # one invocation to the next.
        format_dict['base_category_uid'] = instance.getPortalObject().portal_categories.\
          _getOb(self._id).getUid()
      return (
        self._monotable_template if table_1 is None else self._template
      ) % format_dict
337

338
class CatalogTool (UniqueObject, ZCatalog, CMFCoreCatalogTool, ActiveObject):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
339 340 341 342 343 344 345
    """
    This is a ZSQLCatalog that filters catalog queries.
    It is based on ZSQLCatalog
    """
    id = 'portal_catalog'
    meta_type = 'ERP5 Catalog'
    security = ClassSecurityInfo()
Aurel's avatar
Aurel committed
346

Mame Coumba Sall's avatar
Mame Coumba Sall committed
347
    default_result_limit = None
348
    default_count_limit = 1
Aurel's avatar
Aurel committed
349

Vincent Pelletier's avatar
Vincent Pelletier committed
350
    manage_options = ({ 'label' : 'Overview', 'action' : 'manage_overview' },
Jean-Paul Smets's avatar
Jean-Paul Smets committed
351 352 353 354 355
                     ) + ZCatalog.manage_options

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

356
    # Explicit Inheritance
Jean-Paul Smets's avatar
Jean-Paul Smets committed
357 358 359
    __url = CMFCoreCatalogTool.__url
    manage_catalogFind = CMFCoreCatalogTool.manage_catalogFind

Vincent Pelletier's avatar
Vincent Pelletier committed
360 361 362
    security.declareProtected(Permissions.ManagePortal
                , 'manage_schema')
    manage_schema = DTMLFile('dtml/manageSchema', globals())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
    def _isBootstrapRequired(self):
      return True

    def _bootstrap(self):
      # Get erp5 site
      parent = self.aq_parent
      portal_types = parent.portal_types
      portal_property_sheets = parent.portal_property_sheets
      from Products.ERP5.ERP5Site import ERP5Generator
      ERP5Generator.bootstrap(portal_types, 'erp5_core', 'PortalTypeTemplateItem', (
        'Catalog',
        'Catalog Tool',
        'SQL Method',
        'Python Script'
      ))
      ERP5Generator.bootstrap(portal_property_sheets, 'erp5_core', 'PropertySheetTemplateItem', (
        'Catalog',
        'CatalogTool',
        'SQLMethod',
        'PythonScript',
        'CatalogFilter'
      ))
      # We need ERP5 Form portal_type to exist during migration we would be
      # indexing some ERP5 Form objects.
      ERP5Generator.bootstrap(portal_types, 'erp5_hal_json_style', 'PortalTypeTemplateItem', (
        'ERP5 Form',
      ))

      import erp5
      from Products.ERP5.Extensions.CheckPortalTypes import changeObjectClass

      # Get all dynamic classes from portal_type
      catalog_tool_class = getattr(erp5.portal_type, 'Catalog Tool')
      catalog_class = getattr(erp5.portal_type, 'Catalog')
      sql_class = getattr(erp5.portal_type, 'SQL Method')
      script_class = getattr(erp5.portal_type, 'Python Script')

      if not catalog_tool_class:
        LOG('OldCatalogTool', WARNING, "Portal Type Catalog Tool doesn't exist")
        return

      # Change classes for all object inside catalog and catalog_tool
      for obj in self.objectValues():
        filter_dict = obj.filter_dict
        for method in obj.objectValues():
          if method.meta_type == 'Z SQL Method':
            new_method = changeObjectClass(obj, method.id, sql_class)
          elif method.meta_type == 'Script (Python)':
            new_method = changeObjectClass(obj, method.id, script_class)
          else:
            LOG('Catalog Migration', WARNING, '''Subobject %s is not of meta_type \
                                          Z SQL Method or Script(Python)'''%method.id)
            return

          # Migrate filter_dict and keep them as properties for the methods
          new_method_id = new_method.id
          if new_method_id in filter_dict:
            filter_ = filter_dict[new_method_id]
            new_method.setFiltered(filter_['filtered'])
            new_method.setTypeList(filter_['type'])
            new_method.setExpressionCacheKeyList(filter_['expression_cache_key'])
            new_method.setExpression(filter_['expression'])
            new_method.setExpressionInstance(filter_['expression_instance'])
        # Delete filter_dict before migration of catalog object(s)
        del obj.filter_dict

        changeObjectClass(self, obj.id, catalog_class)
      changeObjectClass(parent, self.id, catalog_tool_class)

      # Update some required attributes to the portal_catalog object
      parent.portal_catalog.default_erp5_catalog_id = self.default_sql_catalog_id
      del parent.portal_catalog.default_sql_catalog_id

437
    security.declarePublic('getPreferredSQLCatalogId')
Aurel's avatar
Aurel committed
438 439 440 441 442 443 444
    def getPreferredSQLCatalogId(self, id=None):
      """
      Get the SQL Catalog from preference.
      """
      if id is None:
        # Check if we want to use an archive
        #if getattr(aq_base(self.portal_preferences), 'uid', None) is not None:
445
        archive_path = self.portal_preferences.getPreferredArchive(sql_catalog_id=self.getDefaultSqlCatalogId())
Aurel's avatar
Aurel committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459
        if archive_path not in ('', None):
          try:
            archive = self.restrictedTraverse(archive_path)
          except KeyError:
            # Do not fail if archive object has been removed,
            # but preference is not up to date
            return None
          if archive is not None:
            catalog_id = archive.getCatalogId()
            if catalog_id not in ('', None):
              return catalog_id
        return None
      else:
        return id
460

461
    def _listAllowedRolesAndUsers(self, user):
462
        # We use ERP5Security PAS based authentication
463 464 465
        try:
          # check for proxy role in stack
          eo = getSecurityManager()._context.stack[-1]
466
          proxy_roles = getattr(eo, '_proxy_roles',None)
467 468 469 470 471
        except IndexError:
          proxy_roles = None
        if proxy_roles:
          # apply proxy roles
          user = eo.getOwner()
Vincent Pelletier's avatar
Vincent Pelletier committed
472
          result = list(proxy_roles)
473
        else:
Vincent Pelletier's avatar
Vincent Pelletier committed
474 475 476
          result = list(user.getRoles())
        result.append('Anonymous')
        result.append('user:%s' % user.getId())
477 478 479
        # deal with groups
        getGroups = getattr(user, 'getGroups', None)
        if getGroups is not None:
480
            groups = list(user.getGroups())
481 482 483 484 485 486
            groups.append('role:Anonymous')
            if 'Authenticated' in result:
                groups.append('role:Authenticated')
            for group in groups:
                result.append('user:%s' % group)
        # end groups
487
        return result
488

Jean-Paul Smets's avatar
Jean-Paul Smets committed
489
    # Schema Management
490
    security.declareProtected(Permissions.ManagePortal, 'editColumn')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
491 492 493 494 495 496 497 498 499 500 501 502 503
    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)

504
    security.declareProtected(Permissions.ManagePortal, 'setColumnList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
505 506 507 508 509
    def setColumnList(self, column_list):
      """
      """
      self._sql_schema = column_list

510
    security.declarePublic('getColumnList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
511 512 513 514 515 516
    def getColumnList(self):
      """
      """
      if not hasattr(self, '_sql_schema'): self._sql_schema = []
      return self._sql_schema

517
    security.declarePublic('getColumn')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
518 519 520 521 522 523 524 525
    def getColumn(self, column_id):
      """
      """
      for c in self.getColumnList():
        if c.id == column_id:
          return c
      return None

526
    security.declareProtected(Permissions.ManagePortal, 'editIndex')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
527 528 529 530 531 532 533 534 535 536 537 538 539
    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)

540
    security.declareProtected(Permissions.ManagePortal, 'setIndexList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
541 542 543 544 545
    def setIndexList(self, index_list):
      """
      """
      self._sql_index = index_list

546
    security.declarePublic('getIndexList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
547 548 549 550 551 552
    def getIndexList(self):
      """
      """
      if not hasattr(self, '_sql_index'): self._sql_index = []
      return self._sql_index

553
    security.declarePublic('getIndex')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
554 555 556 557 558 559 560 561 562
    def getIndex(self, index_id):
      """
      """
      for c in self.getIndexList():
        if c.id == index_id:
          return c
      return None


Vincent Pelletier's avatar
Vincent Pelletier committed
563
    security.declarePublic('getAllowedRolesAndUsers')
564
    def getAllowedRolesAndUsers(self, sql_catalog_id=None, local_roles=None):
565 566
      """
        Return allowed roles and users.
567

568
        This is supposed to be used with Z SQL Methods to check permissions
569
        when you list up documents. It is also able to take into account
570
        a parameter named local_roles so that listed documents only include
571 572
        those documents for which the user (or the group) was
        associated one of the given local roles.
Aurel's avatar
Aurel committed
573

574 575
        The use of getAllowedRolesAndUsers is deprecated, you should use
        getSecurityQuery instead
576 577
      """
      user = _getAuthenticatedUser(self)
578
      user_str = user.getIdOrUserName()
579
      user_is_superuser = (user == system_user) or (user_str == ERP5Security.SUPER_USER)
580
      allowedRolesAndUsers = self._listAllowedRolesAndUsers(user)
581
      role_column_dict = {}
582 583 584
      local_role_column_dict = {}
      catalog = self.getSQLCatalog(sql_catalog_id)
      column_map = catalog.getColumnMap()
585

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
      # We only consider here the Owner role (since it was not indexed)
      # since some objects may only be visible by their owner
      # which was not indexed
      for role, column_id in catalog.getSQLCatalogRoleKeysList():
        # XXX This should be a list
        if not user_is_superuser:
          try:
            # if called by an executable with proxy roles, we don't use
            # owner, but only roles from the proxy.
            eo = getSecurityManager()._context.stack[-1]
            proxy_roles = getattr(eo, '_proxy_roles', None)
            if not proxy_roles:
              role_column_dict[column_id] = user_str
          except IndexError:
            role_column_dict[column_id] = user_str

602 603
      # Patch for ERP5 by JP Smets in order
      # to implement worklists and search of local roles
604
      if local_roles:
605 606
        local_role_dict = dict(catalog.getSQLCatalogLocalRoleKeysList())
        role_dict = dict(catalog.getSQLCatalogRoleKeysList())
607
        # XXX user is not enough - we should also include groups of the user
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        new_allowedRolesAndUsers = []
        new_role_column_dict = {}
        # Turn it into a list if necessary according to ';' separator
        if isinstance(local_roles, str):
          local_roles = local_roles.split(';')
        # Local roles now has precedence (since it comes from a WorkList)
        for user_or_group in allowedRolesAndUsers:
          for role in local_roles:
            # Performance optimisation
            if local_role_dict.has_key(role):
              # XXX This should be a list
              # If a given role exists as a column in the catalog,
              # then it is considered as single valued and indexed
              # through the catalog.
              if not user_is_superuser:
623
                # XXX This should be a list
624 625 626 627 628 629 630 631 632
                # which also includes all user groups
                column_id = local_role_dict[role]
                local_role_column_dict[column_id] = user_str
            if role_dict.has_key(role):
              # XXX This should be a list
              # If a given role exists as a column in the catalog,
              # then it is considered as single valued and indexed
              # through the catalog.
              if not user_is_superuser:
633
                # XXX This should be a list
634 635 636 637 638 639 640
                # which also includes all user groups
                column_id = role_dict[role]
                new_role_column_dict[column_id] = user_str
            new_allowedRolesAndUsers.append('%s:%s' % (user_or_group, role))
        if local_role_column_dict == {}:
          allowedRolesAndUsers = new_allowedRolesAndUsers
          role_column_dict = new_role_column_dict
641 642

      return allowedRolesAndUsers, role_column_dict, local_role_column_dict
643

644
    security.declarePublic('getSecurityUidDictAndRoleColumnDict')
645
    def getSecurityUidDictAndRoleColumnDict(self, sql_catalog_id=None, local_roles=None):
646
      """
647 648
        Return a dict of local_roles_group_id -> security Uids and a
        dictionnary containing available role columns.
649 650 651 652

        XXX: This method always uses default catalog. This should not break a
        site as long as security uids are considered consistent among all
        catalogs.
653
      """
654
      allowedRolesAndUsers, role_column_dict, local_role_column_dict = \
655 656 657 658
          self.getAllowedRolesAndUsers(
            sql_catalog_id=sql_catalog_id,
            local_roles=local_roles,
          )
Aurel's avatar
Aurel committed
659
      catalog = self.getSQLCatalog(sql_catalog_id)
660
      method = getattr(catalog, catalog.sql_search_security, None)
661
      if allowedRolesAndUsers:
662
        allowedRolesAndUsers.sort()
663
        cache_key = tuple(allowedRolesAndUsers)
664
        tv = getTransactionalVariable()
665
        try:
666
          security_uid_cache = tv['getSecurityUidDictAndRoleColumnDict']
667
        except KeyError:
668
          security_uid_cache = tv['getSecurityUidDictAndRoleColumnDict'] = {}
669
        try:
670
          security_uid_dict = security_uid_cache[cache_key]
671
        except KeyError:
672 673 674 675
          if method is None:
            warnings.warn("The usage of allowedRolesAndUsers is "\
                          "deprecated. Please update your catalog "\
                          "business template.", DeprecationWarning)
676
            security_uid_dict = {None: [x.security_uid for x in \
677 678
              self.unrestrictedSearchResults(
                allowedRolesAndUsers=allowedRolesAndUsers,
679 680
                select_list=["security_uid"],
                group_by=["security_uid"])] }
681 682
          else:
            # XXX: What with this string transformation ?! Souldn't it be done in
683
            # dtml instead ? ... yes, but how to be bw compatible ?
684
            allowedRolesAndUsers = [sqlquote(role) for role in allowedRolesAndUsers]
685

686
            security_uid_dict = defaultdict(list)
687
            for brain in method(security_roles_list=allowedRolesAndUsers):
688 689
              security_uid_dict[getattr(brain, 'local_roles_group_id', '')
                ].append(brain.uid)
690 691

          security_uid_cache[cache_key] = security_uid_dict
692
      else:
693 694
        security_uid_dict = []
      return security_uid_dict, role_column_dict, local_role_column_dict
695

Vincent Pelletier's avatar
Vincent Pelletier committed
696
    security.declarePublic('getSecurityQuery')
697
    def getSecurityQuery(self, sql_catalog_id=None, local_roles=None, **kw):
698
      """
699 700 701
        Build a query based on allowed roles or on a list of security_uid
        values. The query takes into account the fact that some roles are
        catalogued with columns.
702
      """
703
      user = _getAuthenticatedUser(self)
704
      user_str = user.getIdOrUserName()
705
      user_is_superuser = (user == system_user) or (user_str == ERP5Security.SUPER_USER)
706 707
      if user_is_superuser:
        # We need no security check for super user.
708
        return
709
      security_uid_dict, role_column_dict, local_role_column_dict = \
710 711 712 713
          self.getSecurityUidDictAndRoleColumnDict(
            sql_catalog_id=sql_catalog_id,
            local_roles=local_roles,
          )
714 715 716 717
      query_list = []
      append = query_list.append
      for key, value in role_column_dict.iteritems():
        append(SimpleQuery(**{key : value}))
718
      if security_uid_dict:
719 720
        catalog_security_uid_groups_columns_dict = self.getSQLCatalog().getSQLCatalogSecurityUidGroupsColumnsDict()
        for local_roles_group_id, security_uid_list in security_uid_dict.iteritems():
721
          assert security_uid_list
722 723 724 725 726 727 728 729 730 731 732 733 734
          append(SimpleQuery(
            **{catalog_security_uid_groups_columns_dict[local_roles_group_id]: security_uid_list}
          ))
      if query_list:
        query = ComplexQuery(query_list, logical_operator='OR')
        if local_role_column_dict:
          query = ComplexQuery(
            [
              SimpleQuery(**{key : value})
              for key, value in local_role_column_dict.items()
            ] + [query],
            logical_operator='AND',
          )
735
      else:
Aurel's avatar
Aurel committed
736
        # XXX A false query has to be generated.
737 738 739 740 741
        # As it is not possible to use SQLKey for now, pass impossible value
        # on uid (which will be detected as False by MySQL, as it is not in the
        # column range)
        # Do not pass security_uid_list as empty in order to prevent useless
        # overhead
742
        query = SimpleQuery(uid=-1)
743
      return query
744

Jean-Paul Smets's avatar
Jean-Paul Smets committed
745
    # searchResults has inherited security assertions.
746
    def searchResults(self, sql_catalog_id=None, local_roles=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
747
        """
748 749
        Calls ZCatalog.searchResults with extra arguments that
        limit the results to what the user is allowed to see.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
750
        """
751 752 753 754 755
        #if not _checkPermission(
        #    Permissions.AccessInactivePortalContent, self):
        #    now = DateTime()
        #    kw[ 'effective' ] = { 'query' : now, 'range' : 'max' }
        #    kw[ 'expires'   ] = { 'query' : now, 'range' : 'min' }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
756

757 758 759 760 761
        catalog_id = self.getPreferredSQLCatalogId(sql_catalog_id)
        query = self.getSecurityQuery(
          sql_catalog_id=catalog_id,
          local_roles=local_roles,
        )
762 763 764 765 766
        if SECURITY_QUERY_ARGUMENT_NAME in kw:
          # Note: we must *not* create a ComplexQuery on behalf of caller.
          # ComplexQueries bypass SearchKey mechanism, which would make passed
          # "security_query" argument behave differently from arbitrary names.
          raise ValueError('%r is a reserved argument.' % SECURITY_QUERY_ARGUMENT_NAME)
767
        if query is not None:
768
          kw[SECURITY_QUERY_ARGUMENT_NAME] = query
769
        kw.setdefault('limit', self.default_result_limit)
770
        return ZCatalog.searchResults(self, sql_catalog_id=catalog_id, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
771 772 773

    __call__ = searchResults

774
    security.declarePrivate('unrestrictedSearchResults')
775
    def unrestrictedSearchResults(self, **kw):
776 777
        """Calls ZSQLCatalog.searchResults directly without restrictions.
        """
778
        kw.setdefault('limit', self.default_result_limit)
779
        return ZCatalog.searchResults(self, **kw)
780

781 782
    # We use a string for permissions here due to circular reference in import
    # from ERP5Type.Permissions
783
    security.declareProtected('Search ZCatalog', 'getResultValue')
784
    def getResultValue(self, **kw):
785 786 787 788
        """
        A method to factor common code used to search a single
        object in the database.
        """
789
        kw.setdefault('limit', 1)
790
        result = self.searchResults(**kw)
791 792 793 794
        try:
          return result[0].getObject()
        except IndexError:
          return None
795 796

    security.declarePrivate('unrestrictedGetResultValue')
797
    def unrestrictedGetResultValue(self, **kw):
798 799 800 801 802
        """
        A method to factor common code used to search a single
        object in the database. Same as getResultValue but without
        taking into account security.
        """
803
        kw.setdefault('limit', 1)
804
        result = self.unrestrictedSearchResults(**kw)
805 806 807 808 809
        try:
          return result[0].getObject()
        except IndexError:
          return None

810
    def countResults(self, sql_catalog_id=None, local_roles=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
811 812 813 814
        """
            Calls ZCatalog.countResults with extra arguments that
            limit the results to what the user is allowed to see.
        """
815
        # XXX This needs to be set again
816
        #if not _checkPermission(
Vincent Pelletier's avatar
Vincent Pelletier committed
817 818
        #    Permissions.AccessInactivePortalContent, self):
        #    base = aq_base(self)
819 820 821
        #    now = DateTime()
        #    #kw[ 'effective' ] = { 'query' : now, 'range' : 'max' }
        #    #kw[ 'expires'   ] = { 'query' : now, 'range' : 'min' }
822 823 824 825 826
        catalog_id = self.getPreferredSQLCatalogId(sql_catalog_id)
        query = self.getSecurityQuery(
          sql_catalog_id=catalog_id,
          local_roles=local_roles,
        )
827 828 829 830 831
        if SECURITY_QUERY_ARGUMENT_NAME in kw:
          # Note: we must *not* create a ComplexQuery on behalf of caller.
          # ComplexQueries bypass SearchKey mechanism, which would make passed
          # "security_query" argument behave differently from arbitrary names.
          raise ValueError('%r is a reserved argument.' % SECURITY_QUERY_ARGUMENT_NAME)
832
        if query is not None:
833
          kw[SECURITY_QUERY_ARGUMENT_NAME] = query
834
        kw.setdefault('limit', self.default_count_limit)
835
        return ZCatalog.countResults(self, sql_catalog_id=catalog_id, **kw)
Aurel's avatar
Aurel committed
836

837 838 839 840 841
    security.declarePrivate('unrestrictedCountResults')
    def unrestrictedCountResults(self, REQUEST=None, **kw):
        """Calls ZSQLCatalog.countResults directly without restrictions.
        """
        return ZCatalog.countResults(self, REQUEST, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
842

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
    def wrapObjectList(self, object_value_list, catalog_value):
      """
        Return a list of wrapped objects for reindexing.
      """
      portal = self.getPortalObject()

      user_set = set()
      role_dict = dict(catalog_value.getSQLCatalogRoleKeysList())
      catalog_security_uid_groups_columns_dict = catalog_value.getSQLCatalogSecurityUidGroupsColumnsDict()
      default_security_uid_column = catalog_security_uid_groups_columns_dict['']
      getPredicatePropertyDict = catalog_value.getPredicatePropertyDict
      security_group_set = set()
      wrapper_list = []
      for object_value in object_value_list:
        document_object = aq_inner(object_value)
        w = IndexableObjectWrapper(document_object, user_set, role_dict)
        w.predicate_property_dict = getPredicatePropertyDict(object_value) or {}
        security_group_set.update(w._getSecurityGroupIdList())
861

862 863 864
        # Find the parent definition for security
        is_acquired = 0
        while getattr(document_object, 'isRADContent', 0):
Aurel's avatar
Aurel committed
865
          # This condition tells which object should acquire
866 867
          # from their parent.
          # XXX Hardcode _View_Permission for a performance point of view
868 869
          if getattr(aq_base(document_object), '_View_Permission', ACQUIRE_PERMISSION_VALUE) == ACQUIRE_PERMISSION_VALUE\
             and document_object._getAcquireLocalRoles():
870
            document_object = document_object.aq_parent
871 872 873 874
            is_acquired = 1
          else:
            break
        if is_acquired:
875 876
          document_w = IndexableObjectWrapper(document_object, user_set, role_dict)
          security_group_set.update(document_w._getSecurityGroupIdList())
877 878
        else:
          document_w = w
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
        wrapper_list.append((document_object, w, document_w))

      # Note: we mutate the set, so all related wrappers get (purposedly)
      # affected by this, which must happen before _getSecurityParameterList
      # is called (which happens when calling getSecurityUidDict below).
      user_set.update(
        x['id'] for x in portal.acl_users.searchUsers(
          id=list(security_group_set),
          exact_match=True,
        )
      )

      getSecurityUidDict = catalog_value.getSecurityUidDict
      getSubjectSetUid = catalog_value.getSubjectSetUid
      wrapped_object_list = []
      for (document_object, w, document_w) in wrapper_list:
        (
          security_uid_dict,
          w.optimised_roles_and_users,
        ) = getSecurityUidDict(document_w)
        for local_roles_group_id, security_uid in security_uid_dict.iteritems():
900
          catalog_column = catalog_security_uid_groups_columns_dict.get(
901 902 903
            local_roles_group_id,
            default_security_uid_column,
          )
904
          setattr(w, catalog_column, security_uid)
905 906 907 908
        (
          w.subject_set_uid,
          w.optimised_subject_list,
        ) = getSubjectSetUid(document_w)
909

910 911
        wrapped_object_list.append(ImplicitAcquisitionWrapper(w, aq_parent(document_object)))
      return wrapped_object_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
912

913 914
    security.declarePrivate('reindexCatalogObject')
    def reindexCatalogObject(self, object, idxs=None, sql_catalog_id=None,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
915 916 917 918
        '''Update catalog after object data has changed.
        The optional idxs argument is a list of specific indexes
        to update (all of them by default).
        '''
919
        if idxs is None: idxs = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
920
        url = self.__url(object)
921
        self.catalog_object(object, url, idxs=idxs, sql_catalog_id=sql_catalog_id,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
922

923 924 925 926
    # Required for compatibilty with ERP5CatalogTool
    security.declarePrivate('reindexObject')
    reindexObject = reindexCatalogObject

927

928 929
    def catalogObjectList(self, object_list, *args, **kw):
        """Catalog a list of objects"""
930
        m = object_list[0]
931 932 933
        if isinstance(m, GroupedMessage):
          tmp_object_list = [x.object for x in object_list]
          super(CatalogTool, self).catalogObjectList(tmp_object_list, **m.kw)
934
          if tmp_object_list:
935 936
            exc_info = sys.exc_info()
          for x in object_list:
937 938
            if x.object in tmp_object_list:
              x.raised(exc_info)
939
            else:
940
              x.result = None
941 942 943
        else:
          super(CatalogTool, self).catalogObjectList(object_list, *args, **kw)

944 945 946
    security.declarePrivate('uncatalogObjectList')
    def uncatalogObjectList(self, message_list):
      """Uncatalog a list of objects"""
947
      # TODO: this is currently only a placeholder for further optimization
948 949
      try:
        for m in message_list:
950
          m.result = self.unindexObject(*m.args, **m.kw)
951
      except Exception:
952
        m.raised()
953

Jean-Paul Smets's avatar
Jean-Paul Smets committed
954
    security.declarePrivate('unindexObject')
955
    def unindexObject(self, object=None, path=None, uid=None,sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
956 957 958
        """
          Remove from catalog.
        """
959
        if path is None and uid is None:
960 961
          if object is None:
            raise TypeError, 'One of uid, path and object parameters must not be None'
962
          path = self.__url(object)
963 964
        if uid is None:
          raise TypeError, "unindexObject supports only uid now"
965
        self.uncatalog_object(path=path, uid=uid, sql_catalog_id=sql_catalog_id)
966

Sebastien Robin's avatar
Sebastien Robin committed
967 968 969 970 971 972 973 974 975
    security.declarePrivate('beforeUnindexObject')
    def beforeUnindexObject(self, object, path=None, uid=None,sql_catalog_id=None):
        """
          Remove from catalog.
        """
        if path is None and uid is None:
          path = self.__url(object)
        self.beforeUncatalogObject(path=path,uid=uid, sql_catalog_id=sql_catalog_id)

976 977 978
    security.declarePrivate('getUrl')
    def getUrl(self, object):
      return self.__url(object)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
979

Jean-Paul Smets's avatar
Jean-Paul Smets committed
980
    security.declarePrivate('moveObject')
981
    def moveObject(self, object, idxs=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
982 983 984 985 986 987
        """
          Reindex in catalog, taking into account
          peculiarities of ERP5Catalog / ZSQLCatalog

          Useless ??? XXX
        """
988
        if idxs is None: idxs = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
989 990
        url = self.__url(object)
        self.catalog_object(object, url, idxs=idxs, is_object_moved=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
991

992 993 994 995 996 997
    security.declarePublic('getPredicatePropertyDict')
    def getPredicatePropertyDict(self, object):
      """
      Construct a dictionnary with a list of properties
      to catalog into the table predicate
      """
998
      if not object.providesIPredicate():
999 1000 1001
        return None
      object = object.asPredicate()
      if object is None:
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        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:
1013
            property_dict['%s_range_min' % property] = min
1014
          if max is not None:
1015
            property_dict['%s_range_max' % property] = max
1016
      property_dict['membership_criterion_category_list'] = object.getMembershipCriterionCategoryList()
1017 1018
      return property_dict

1019
    security.declarePrivate('getDynamicRelatedKeyList')
1020
    def getDynamicRelatedKeyList(self, key_list, sql_catalog_id=None):
1021
      """
1022
      Return the list of dynamic related keys.
1023 1024
      This method will try to automatically generate new related key
      by looking at the category tree.
1025

1026
      Syntax:
1027 1028
        [[predicate_][strict_][parent_]_]<base category id>__[related__]<column id>
      "predicate": Use predicate_category as relation table, otherwise category table.
1029 1030
      "strict": Match only strict relation members, otherwise match non-strict too.
      "parent": Search for documents whose parent have described relation, otherwise search for their immediate relations.
1031
      <base_category_id>: The id of an existing Base Category document, or "any" to not restrict by relation type.
1032
      "related": Search for reverse relationships, otherwise search for direct relationships.
1033
      <column_id>: The name of the column to compare values against.
1034 1035 1036 1037

      Old syntax is supported for backward-compatibility, but will not receive
      further extensions:
        [default_][strict_][parent_]<base category id>_[related_]<column id>
1038
      """
1039
      base_category_id_set = set(
1040 1041
        self.getPortalObject().portal_categories.getBaseCategoryList()
      )
1042
      base_category_id_set.discard('parent')
1043
      column_map = self.getSQLCatalog(sql_catalog_id).getColumnMap()
1044
      related_key_list = []
1045
      for key in key_list:
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
        flag_bitmap = 0
        if '__' in key:
          split_key = key.split('__')
          column_id = split_key.pop()
          if 'catalog' not in column_map.get(column_id, ()):
            continue
          base_category_id = split_key.pop()
          related = base_category_id == 'related'
          if related:
            base_category_id = split_key.pop()
          if split_key:
            flag_string, = split_key
            flag_list = flag_string.split('_')
            pop = flag_list.pop
            for flag_name, flag in DYNAMIC_RELATED_KEY_FLAG_LIST:
              if flag_list[-1] == flag_name:
                flag_bitmap |= flag
                pop()
                if not flag_list:
                  break
            else:
              continue
        else:
          # BBB: legacy related key format
          default_string = 'default_'
          related_string = 'related_'
          prefix = key
          if prefix.startswith(default_string):
            prefix = prefix[len(default_string):]
          if prefix.startswith(STRICT_METHOD_NAME):
            prefix = prefix[len(STRICT_METHOD_NAME):]
            flag_bitmap |= DYNAMIC_RELATED_KEY_FLAG_STRICT
          if prefix.startswith(PARENT_METHOD_NAME):
            prefix = prefix[len(PARENT_METHOD_NAME):]
            flag_bitmap |= DYNAMIC_RELATED_KEY_FLAG_PARENT
          split_key = prefix.split('_')
          for i in xrange(len(split_key) - 1, 0, -1):
            base_category_id = '_'.join(split_key[0:i])
            if base_category_id in base_category_id_set or (
              i == len(split_key) - 1 and base_category_id == IGNORE_BASE_CATEGORY_UID
            ):
              # We have found a base_category
              column_id = '_'.join(split_key[i:])
              related = column_id.startswith(related_string)
              if related:
                column_id = column_id[len(related_string):]
              # XXX: joining with non-catalog tables is not trivial and requires
              # ZSQLCatalog's ColumnMapper cooperation, so only allow catalog
              # columns.
              if 'catalog' in column_map.get(column_id, ()):
                break
          else:
            continue
        is_uid = column_id == 'uid'
        if is_uid:
          column_id = 'uid' if related else 'category_uid'
        related_key_list.append(
          key + ' | ' +
1104
          ('predicate_' if flag_bitmap & DYNAMIC_RELATED_KEY_FLAG_PREDICATE else '') + 'category' +
1105 1106 1107 1108 1109 1110 1111 1112 1113
          ('' if is_uid else ',catalog') +
          '/' +
          column_id +
          '/' + DYNAMIC_METHOD_NAME +
          (STRICT_METHOD_NAME if flag_bitmap & DYNAMIC_RELATED_KEY_FLAG_STRICT else '') +
          (PARENT_METHOD_NAME if flag_bitmap & DYNAMIC_RELATED_KEY_FLAG_PARENT else '') +
          base_category_id +
          (RELATED_DYNAMIC_METHOD_NAME if related else '')
        )
1114 1115
      return related_key_list

1116
    security.declarePublic('getCategoryValueDictParameterDict')
1117
    def getCategoryValueDictParameterDict(self, base_category_dict, category_table='category', strict_membership=True, forward=True, onJoin=lambda x: None):
1118
      """
1119
      From a mapping from base category ids to lists of documents, produce a
1120 1121
      query tree testing (strict or not, forward or reverse relation)
      membership to these documents with their respective base categories.
1122

1123
      base_category_dict (dict with base category ids as keys and document sets
1124 1125
      as values)
        Note: mutated by this method.
1126 1127
      category_table ('category' or 'predicate_category')
        Controls the table to use for membership lookup.
1128 1129 1130 1131 1132 1133
      strict_membership (bool)
        Whether intermediate relation members should be excluded (true) or
        included (false).
      forward (bool)
        Whether document being looked up bears the relation (true) or is its
        target (false).
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
      onJoin(column_name) -> None or query
        Called for each generated query which imply a join. Specifically, this
        will not be called for "parent" relation, as it does not involve a
        join.
        Receives pseudo-column name of the relation as argument.
        If return value is not None, it must be a query tree, OR-ed with
        existing conditions for given pseudo-column.
        This last form should very rarely be needed (ex: when joining with
        predicate_category table as it contains non-standard uid values).

      Return a query tree.
1145 1146
      """
      flag_list = []
1147 1148 1149
      if category_table == 'predicate_category':
        flag_list.append('predicate')
      elif category_table != 'category':
1150 1151 1152 1153 1154
        raise ValueError('Unknown category table %r' % (category_table, ))
      if strict_membership:
        flag_list.append('strict')
      prefix = ('_'.join(flag_list) + '__') if flag_list else ''
      suffix = ('' if forward else '__related') + '__uid'
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
      parent_document_set = base_category_dict.pop('parent', None)
      query_list = []
      for base_category_id, document_set in base_category_dict.iteritems():
        column = prefix + base_category_id + suffix
        category_query = SimpleQuery(**{
          column: {document.getUid() for document in document_set},
        })
        extra_query = onJoin(column)
        if extra_query is not None:
          category_query = ComplexQuery(
            category_query,
            extra_query,
            logical_operator='OR',
          )
        query_list.append(category_query)
      if parent_document_set is not None:
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
        if forward:
          if strict_membership:
            query_list.append(SimpleQuery(
              parent_uid={
                document.getUid()
                for document in parent_document_set
              },
            ))
          else:
            query_list.append(SimpleQuery(
              path={
                x.getPath().replace('_', r'\_').replace('%', r'\%') + '/%'
                for x in parent_document_set
              },
              comparison_operator='like',
            ))
        else:
          parent_uid_set = {
1189 1190
            document.getUid()
            for document in parent_document_set
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
          }
          if not strict_membership:
            for document in parent_document_set:
              while True:
                document = document.getParentValue()
                uid = getattr(document, 'getUid', lambda: None)()
                if uid is None:
                  break
                parent_uid_set.add(uid)
          query_list.append(SimpleQuery(uid=parent_uid_set))
1201
      return ComplexQuery(query_list)
1202

1203 1204 1205
    security.declarePublic('getCategoryParameterDict')
    def getCategoryParameterDict(self, category_list, onMissing=lambda category: True, **kw):
      """
1206 1207 1208
      From a list of categories, produce a query tree testing (strict or not,
      forward or reverse relation) membership to these documents with their
      respective base categories.
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232

      category_list (list of category relative urls with their base categories)
      onMissing (callable)
        Called for each category which does not exist.
        Receives faulty relative url as "category" argument.
        False return value skips the entry.
        True return value causes a None placeholder to be inserted.
        Raised exceptions will propagate.

      Other arguments & return value: see getCategoryValueDictParameterDict.
      """
      base_category_dict = defaultdict(set)
      portal_categories = self.getPortalObject().portal_categories
      getBaseCategoryId = portal_categories.getBaseCategoryId
      getCategoryValue = portal_categories.getCategoryValue
      for relative_url in category_list:
        category_uid = getCategoryValue(relative_url)
        if category_uid is not None or onMissing(category=relative_url):
          base_category_dict[getBaseCategoryId(relative_url)].add(category_uid)
      return self.getCategoryValueDictParameterDict(
        base_category_dict,
        **kw
      )

1233 1234 1235
    def _aq_dynamic(self, name):
      """
      Automatic related key generation.
1236
      Will generate z_related_[base_category_id] if possible
1237
      """
Vincent Pelletier's avatar
Vincent Pelletier committed
1238 1239 1240
      result = None
      if name.startswith(DYNAMIC_METHOD_NAME) and \
          not name.endswith(ZOPE_SECURITY_SUFFIX):
1241
        base_name = name[DYNAMIC_METHOD_NAME_LEN:]
1242
        kw = {}
1243 1244
        if base_name.endswith(RELATED_DYNAMIC_METHOD_NAME):
          base_name = base_name[:RELATED_DYNAMIC_METHOD_NAME_LEN]
1245
          kw['related'] = 1
1246 1247
        if base_name.startswith(STRICT_METHOD_NAME):
          base_name = base_name[STRICT_METHOD_NAME_LEN:]
1248
          kw['strict_membership'] = 1
1249 1250 1251
        if base_name.startswith(PARENT_METHOD_NAME):
          base_name = base_name[PARENT_METHOD_NAME_LEN:]
          kw['query_table_column'] = 'parent_uid'
1252
        method = RelatedBaseCategory(base_name, **kw)
Vincent Pelletier's avatar
Vincent Pelletier committed
1253
        setattr(self.__class__, name, method)
1254 1255 1256 1257 1258 1259
        # This getattr has 2 purposes:
        # - wrap in acquisition context
        #   This alone should be explicitly done rather than through getattr.
        # - wrap (if needed) class attribute on the instance
        #   (for the sake of not relying on current implementation details
        #   "too much")
Vincent Pelletier's avatar
Vincent Pelletier committed
1260 1261
        result = getattr(self, name)
      return result
1262

1263
    def _searchAndActivate(self, method_id, method_args=(), method_kw={},
1264
                           activate_kw={}, min_uid=None, group_kw={}, **kw):
1265 1266
      """Search the catalog and run a script by activity on all found objects

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
      In order to not generate too many activities, this method limits the
      number of rows to fetch from the catalog, and if the catalog would return
      more results, it resumes by calling itself by activity.

      'activate_kw' is for common activate parameters between all generated
      activities and is usually used for priority and dependencies.

      Common usage is to call this method without 'select_method_id'.
      In this case, found objects are processed via a CMFActivity grouping,
      and this can be configured via 'group_kw', for additional parameters to
      pass to CMFActivity (in particular: 'activity' and 'group_method_*').
      A generic grouping method is used if none is given.
      group_method_cost default to 30 objects per packet.

1281 1282 1283 1284
      'select_method_id', if provided, will be called with partial catalog
      results and returned value will be provided to the callable identified by
      'method_id' (which will no longer be invoked in the context of a given
      document returned by catalog) as first positional argument.
1285
      Use 'packet_size' parameter to limit the size of each group (default: 30).
1286

1287 1288 1289 1290 1291
      'activity_count' parameter is deprecated.
      Its value should be hardcoded because CMFActivity can now handle many
      activities efficiently and any tweak should benefit to everyone.
      However, there are still rare cases where one want to limit the number
      of processing nodes, to minimize latency of high-priority activities.
1292
      """
1293
      catalog_kw = kw.copy()
1294
      select_method_id = catalog_kw.pop('select_method_id', None)
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
      if select_method_id:
        packet_size = catalog_kw.pop('packet_size', 30)
        limit = packet_size * catalog_kw.pop('activity_count', 100)
      elif 'packet_size' in catalog_kw: # BBB
        assert not group_kw, (kw, group_kw)
        packet_size = catalog_kw.pop('packet_size')
        group_method_cost = 1. / packet_size
        limit = packet_size * catalog_kw.pop('activity_count', 100)
      else:
        group_method_cost = group_kw.get('group_method_cost', .034) # 30 objects
        limit = catalog_kw.pop('activity_count', None) or \
          100 * int(ceil(1 / group_method_cost))
1307
      if min_uid:
1308 1309
        catalog_kw['min_uid'] = SimpleQuery(uid=min_uid,
                                            comparison_operator='>')
1310 1311 1312 1313 1314 1315 1316 1317
      if catalog_kw.pop('restricted', False):
        search = self
      else:
        search = self.unrestrictedSearchResults
      r = search(sort_on=(('uid','ascending'),), limit=limit, **catalog_kw)
      result_count = len(r)
      if result_count:
        if result_count == limit:
1318 1319
          next_kw = activate_kw.copy()
          next_kw['priority'] = 1 + next_kw.get('priority', 1)
1320
          self.activate(activity='SQLQueue', **next_kw) \
1321
              ._searchAndActivate(method_id,method_args, method_kw,
1322 1323
                                  activate_kw, r[-1].getUid(),
                                  group_kw=group_kw, **kw)
1324 1325 1326 1327
        if select_method_id:
          portal_activities = self.getPortalObject().portal_activities
          active_portal_activities = portal_activities.activate(
            activity='SQLQueue', **activate_kw)
1328 1329
          r = getattr(portal_activities, select_method_id)(r)
          activate = getattr(active_portal_activities, method_id)
1330
          for i in xrange(0, len(r), packet_size):
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
            activate(r[i:i+packet_size], *method_args, **method_kw)
        else:
          kw = activate_kw.copy()
          kw['activity'] = 'SQLQueue'
          if group_method_cost < 1:
            kw['group_method_cost'] = group_method_cost
            kw['group_method_id'] = None
            kw.update(group_kw)
          for r in r:
            getattr(r.activate(**kw), method_id)(*method_args, **method_kw)
1341 1342 1343 1344 1345 1346

    security.declarePublic('searchAndActivate')
    def searchAndActivate(self, *args, **kw):
      """Restricted version of _searchAndActivate"""
      return self._searchAndActivate(restricted=True, *args, **kw)

1347 1348
    security.declareProtected(Permissions.ManagePortal, 'upgradeSchema')
    def upgradeSchema(self, sql_catalog_id=None, src__=0):
1349
      """Upgrade all catalog tables, with ALTER or CREATE queries"""
1350 1351 1352
      catalog = self.getSQLCatalog(sql_catalog_id)
      connection_id = catalog.z_create_catalog.connection_id
      src = []
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
      db = self.getPortalObject()[connection_id]()
      with db.lock():
        for clear_method in catalog.sql_clear_catalog:
          r = catalog[clear_method]._upgradeSchema(
            connection_id, create_if_not_exists=1, src__=1)
          if r:
            src.append(r)
        if not src__:
          for r in src:
            db.query(r)
1363 1364
      return src

1365 1366
    security.declarePublic('getDocumentValueList')
    def getDocumentValueList(self, sql_catalog_id=None,
1367 1368
                             search_context=None, language=None,
                             strict_language=True, all_languages=None,
1369
                             all_versions=None, now=None, **kw):
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
      """
        Return the list of documents which belong to the
        current section. The API is designed to
        support additional parameters so that it is possible
        to group documents by reference, version, language, etc.
        or to implement filtering of documents.

        This method must be implemented through a
        catalog method script :
          SQLCatalog_getDocumentValueList
1380 1381 1382 1383

        Here is the list of arguments :
          * search_context
          * language
1384
          * strict_language
1385 1386 1387 1388 1389 1390 1391 1392 1393
          * all_languages
          * all_versions
          * now

        If you specify search_context, its predicate will be
        respected,
        i.e. web_section.WebSection_getDocumentValueList is
        equivalent to
        portal_catalog.getDocumentValueList(search_context=web_section)
1394
      """
1395 1396 1397 1398
      catalog = self.getSQLCatalog(sql_catalog_id)
      return catalog.SQLCatalog_getDocumentValueList(
          search_context=search_context,
          language=language,
1399
          strict_language=strict_language,
1400 1401 1402 1403
          all_languages=all_languages,
          all_versions=all_versions,
          now=now,
          **kw)
1404

1405
InitializeClass(CatalogTool)