CatalogTool.py 40.3 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
from ZODB.POSException import ConflictError
Jean-Paul Smets's avatar
Jean-Paul Smets committed
30 31
from Products.CMFCore.CatalogTool import CatalogTool as CMFCoreCatalogTool
from Products.ZSQLCatalog.ZSQLCatalog import ZCatalog
32
from Products.ZSQLCatalog.SQLCatalog import Query, ComplexQuery
33
from Products.ERP5Type import Permissions
34
from Products.ERP5Type.Cache import CachingMethod
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35
from AccessControl import ClassSecurityInfo, getSecurityManager
36
from Products.CMFCore.utils import UniqueObject, _checkPermission, _getAuthenticatedUser, getToolByName
37
from Products.ERP5Type.Globals import InitializeClass, DTMLFile, package_home
38
from Acquisition import aq_base, aq_inner, aq_parent, ImplicitAcquisitionWrapper
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39
from DateTime.DateTime import DateTime
40
from Products.CMFActivity.ActiveObject import ActiveObject
41
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42 43 44 45 46 47

from AccessControl.PermissionRole import rolesForPermissionOn

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

50
from Products.ERP5Security import mergedLocalRoles
51
from Products.ERP5Security.ERP5UserManager import SUPER_USER
52
from Products.ERP5Type.Utils import sqlquote
53

54
import os, time, urllib, warnings
55
import sys
56
from zLOG import LOG, PROBLEM, WARNING, INFO
Jean-Paul Smets's avatar
Jean-Paul Smets committed
57

58 59
ACQUIRE_PERMISSION_VALUE = []

Aurel's avatar
Aurel committed
60
from Persistence import Persistent
61
from Acquisition import Implicit
Aurel's avatar
Aurel committed
62

63
DYNAMIC_METHOD_NAME = 'z_related_'
64
DYNAMIC_METHOD_NAME_LEN = len(DYNAMIC_METHOD_NAME)
65
STRICT_DYNAMIC_METHOD_NAME = DYNAMIC_METHOD_NAME + 'strict_'
66
STRICT_DYNAMIC_METHOD_NAME_LEN = len(STRICT_DYNAMIC_METHOD_NAME)
67
RELATED_DYNAMIC_METHOD_NAME = '_related'
68 69
# Negative as it's used as a slice end offset
RELATED_DYNAMIC_METHOD_NAME_LEN = -len(RELATED_DYNAMIC_METHOD_NAME)
70
ZOPE_SECURITY_SUFFIX = '__roles__'
Aurel's avatar
Aurel committed
71

72
class IndexableObjectWrapper(object):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
73

74
    def __init__(self, ob):
75 76
        self.__ob = ob

77 78 79 80
    def __getattr__(self, name):
        return getattr(self.__ob, name)

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

84
    def _getSecurityParameterList(self):
85 86
      result = self.__dict__.get('_cache_result', None)
      if result is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
87
        ob = self.__ob
88 89 90 91 92
        # 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'
93 94
        localroles = {}
        skip_role_set = set()
95 96
        skip_role = skip_role_set.add
        clear_skip_role = skip_role_set.clear
97
        for key, role_list in mergedLocalRoles(ob).iteritems():
98 99 100 101 102 103 104 105 106
          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)
          if len(new_role_list)>0:
107
            localroles[key] = new_role_list
108

109
        portal = ob.getPortalObject()
110 111 112 113
        role_dict = dict(portal.portal_catalog.getSQLCatalog().\
                                              getSQLCatalogRoleKeysList())
        getUserById = portal.acl_users.getUserById

114 115 116 117 118 119
        # 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.
120
        allowed = set(rolesForPermissionOn('View', ob))
121 122 123 124 125 126
        # 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.
        allowed.discard('_View_Permission')
127 128
        # XXX Owner is hardcoded, in order to prevent searching for user on the
        # site root.
129 130
        allowed.discard('Owner')
        add = allowed.add
131 132
        user_role_dict = {}
        user_view_permission_role_dict = {}
133
        for user, roles in localroles.iteritems():
134
          prefix = 'user:' + user
135
          for role in roles:
136
            if (role in role_dict) and (getUserById(user) is not None):
137 138 139 140 141 142
              # If role is monovalued, check if key is a user.
              # If not, continue to index it in roles_and_users table.
              user_role_dict[role] = user
              if role in allowed:
                user_view_permission_role_dict[role] = user
            elif role in allowed:
143 144
              add(prefix)
              add(prefix + ':' + role)
145

146 147 148
        self._cache_result = result = (sorted(allowed), user_role_dict,
                                       user_view_permission_role_dict)
      return result
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

    def allowedRolesAndUsers(self):
      """
      Return a list of roles and users with View permission.
      Used by Portal Catalog to filter out items you're not allowed to see.

      WARNING (XXX): some user base local role association is currently
      being stored (ex. to be determined). This should be prevented or it will
      make the table explode. To analyse the symptoms, look at the
      user_and_roles table. You will find some user:foo values
      which are not necessary.
      """
      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
186

187 188 189 190
    def __repr__(self):
      return '<Products.ERP5Catalog.CatalogTool.IndexableObjectWrapper'\
          ' for %s>' % ('/'.join(self.__ob.getPhysicalPath()), )

191

192
class RelatedBaseCategory(Method):
193 194
    """A Dynamic Method to act as a related key.
    """
195
    def __init__(self, id, strict_membership=0, related=0):
196
      self._id = id
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
      if strict_membership:
        strict = 'AND %(category_table)s.category_strict_membership = 1\n'
      else:
        strict = ''
      # From the point of view of query_table, we are looking up objects...
      if related:
        # ... which have a relation toward us
        from_table = 'related'
        to_table = 'relation_holder'
      else:
        # ... toward which we have a relation
        from_table = 'relation_holder'
        to_table = 'related'
      self._template = """\
%%(category_table)s.base_category_uid = %%(base_category_uid)s
%(strict)sAND %%(%(to_table)s)s.uid = %%(category_table)s.category_uid
AND %%(category_table)s.uid = %%(%(from_table)s)s.uid""" % {
          'strict': strict,
          'from_table': from_table,
          'to_table': to_table,
      }
218

219
    def __call__(self, instance, table_0, table_1, query_table='catalog', **kw):
220
      """Create the sql code for this related key."""
221 222 223 224 225 226 227 228 229
      # Note: in normal conditions, our category's uid will not change from
      # one invocation to the next.
      return self._template % {
        'base_category_uid': instance.getPortalObject().portal_categories.\
          _getOb(self._id).getUid(),
        'category_table': table_0,
        'relation_holder': query_table,
        'related': table_1,
      }
230

231
class CatalogTool (UniqueObject, ZCatalog, CMFCoreCatalogTool, ActiveObject):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
232 233 234 235 236 237 238
    """
    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
239

Mame Coumba Sall's avatar
Mame Coumba Sall committed
240
    default_result_limit = None
241
    default_count_limit = 1
242
    
Vincent Pelletier's avatar
Vincent Pelletier committed
243
    manage_options = ({ 'label' : 'Overview', 'action' : 'manage_overview' },
Jean-Paul Smets's avatar
Jean-Paul Smets committed
244 245 246 247 248
                     ) + ZCatalog.manage_options

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

249
    # Explicit Inheritance
Jean-Paul Smets's avatar
Jean-Paul Smets committed
250 251 252
    __url = CMFCoreCatalogTool.__url
    manage_catalogFind = CMFCoreCatalogTool.manage_catalogFind

Vincent Pelletier's avatar
Vincent Pelletier committed
253 254 255
    security.declareProtected(Permissions.ManagePortal
                , 'manage_schema')
    manage_schema = DTMLFile('dtml/manageSchema', globals())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
256

Aurel's avatar
Aurel committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    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:
        archive_path = self.portal_preferences.getPreferredArchive(sql_catalog_id=self.default_sql_catalog_id)
        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
      
Vincent Pelletier's avatar
Vincent Pelletier committed
280
    security.declareProtected('Import/Export objects', 'addDefaultSQLMethods')
281
    def addDefaultSQLMethods(self, config_id='erp5'):
282 283 284
      """
        Add default SQL methods for a given configuration.
      """
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
      # 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 = []

300 301
      # Common methods - for backward compatibility
      # SQL code distribution is supposed to be business template based nowadays
302
      if config_id.lower() == 'erp5_mysql':
303
        zsql_dirs.append(os.path.join(product_path, 'sql', 'common_mysql'))
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
        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'))

      # 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
326
     
Vincent Pelletier's avatar
Vincent Pelletier committed
327
    security.declareProtected('Import/Export objects', 'exportSQLMethods')
328
    def exportSQLMethods(self, sql_catalog_id=None, config_id='erp5'):
329 330 331 332 333 334 335 336
      """
        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
337

338
      catalog = self.getSQLCatalog(sql_catalog_id)
339 340 341
      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)
342 343
      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',
344
                         'z_create_record', 'z_delete_recorded_object_list',
345 346
                         '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',)
347
    
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
      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()
364
          
365 366 367 368 369 370 371 372
      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()
373
        
374
      return msg
375
        
376
    def _listAllowedRolesAndUsers(self, user):
377
        # We use ERP5Security PAS based authentication
378 379 380
        try:
          # check for proxy role in stack
          eo = getSecurityManager()._context.stack[-1]
381
          proxy_roles = getattr(eo, '_proxy_roles',None)
382 383 384 385 386
        except IndexError:
          proxy_roles = None
        if proxy_roles:
          # apply proxy roles
          user = eo.getOwner()
Vincent Pelletier's avatar
Vincent Pelletier committed
387
          result = list(proxy_roles)
388
        else:
Vincent Pelletier's avatar
Vincent Pelletier committed
389 390 391
          result = list(user.getRoles())
        result.append('Anonymous')
        result.append('user:%s' % user.getId())
392 393 394
        # deal with groups
        getGroups = getattr(user, 'getGroups', None)
        if getGroups is not None:
395
            groups = list(user.getGroups())
396 397 398 399 400 401
            groups.append('role:Anonymous')
            if 'Authenticated' in result:
                groups.append('role:Authenticated')
            for group in groups:
                result.append('user:%s' % group)
        # end groups
402
        return result
403

Jean-Paul Smets's avatar
Jean-Paul Smets committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
    # 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


Vincent Pelletier's avatar
Vincent Pelletier committed
470
    security.declarePublic('getAllowedRolesAndUsers')
Aurel's avatar
Aurel committed
471
    def getAllowedRolesAndUsers(self, sql_catalog_id=None, **kw):
472 473
      """
        Return allowed roles and users.
474

475
        This is supposed to be used with Z SQL Methods to check permissions
476
        when you list up documents. It is also able to take into account
477
        a parameter named local_roles so that listed documents only include
478 479
        those documents for which the user (or the group) was
        associated one of the given local roles.
480 481 482
      
        The use of getAllowedRolesAndUsers is deprecated, you should use
        getSecurityQuery instead
483 484
      """
      user = _getAuthenticatedUser(self)
485
      user_str = str(user)
486
      user_is_superuser = (user_str == SUPER_USER)
487
      allowedRolesAndUsers = self._listAllowedRolesAndUsers(user)
488
      role_column_dict = {}
489 490 491
      local_role_column_dict = {}
      catalog = self.getSQLCatalog(sql_catalog_id)
      column_map = catalog.getColumnMap()
492

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
      # 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

509 510
      # Patch for ERP5 by JP Smets in order
      # to implement worklists and search of local roles
511 512
      local_roles = kw.get('local_roles', None)
      if local_roles:
513 514
        local_role_dict = dict(catalog.getSQLCatalogLocalRoleKeysList())
        role_dict = dict(catalog.getSQLCatalogRoleKeysList())
515
        # XXX user is not enough - we should also include groups of the user
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        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:
531
                # XXX This should be a list
532 533 534 535 536 537 538 539 540
                # 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:
541
                # XXX This should be a list
542 543 544 545 546 547 548
                # 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
549

550

551
      return allowedRolesAndUsers, role_column_dict, local_role_column_dict
552

Aurel's avatar
Aurel committed
553
    def getSecurityUidListAndRoleColumnDict(self, sql_catalog_id=None, **kw):
554
      """
555 556
        Return a list of security Uids and a dictionnary containing available
        role columns.
557 558 559 560

        XXX: This method always uses default catalog. This should not break a
        site as long as security uids are considered consistent among all
        catalogs.
561
      """
562 563
      allowedRolesAndUsers, role_column_dict, local_role_column_dict = \
          self.getAllowedRolesAndUsers(**kw)
Aurel's avatar
Aurel committed
564
      catalog = self.getSQLCatalog(sql_catalog_id)
565
      method = getattr(catalog, catalog.sql_search_security, None)
566
      if allowedRolesAndUsers:
567
        allowedRolesAndUsers.sort()
568
        cache_key = tuple(allowedRolesAndUsers)
569
        tv = getTransactionalVariable()
570 571 572 573 574 575 576
        try:
          security_uid_cache = tv['getSecurityUidListAndRoleColumnDict']
        except KeyError:
          security_uid_cache = tv['getSecurityUidListAndRoleColumnDict'] = {}
        try:
          security_uid_list = security_uid_cache[cache_key]
        except KeyError:
577 578 579 580 581 582 583 584 585 586 587 588
          if method is None:
            warnings.warn("The usage of allowedRolesAndUsers is "\
                          "deprecated. Please update your catalog "\
                          "business template.", DeprecationWarning)
            security_uid_list = [x.security_uid for x in \
              self.unrestrictedSearchResults(
                allowedRolesAndUsers=allowedRolesAndUsers,
                select_expression="security_uid",
                group_by_expression="security_uid")]
          else:
            # XXX: What with this string transformation ?! Souldn't it be done in
            # dtml instead ?
589
            allowedRolesAndUsers = [sqlquote(role) for role in allowedRolesAndUsers]
590
            security_uid_list = [x.uid for x in method(security_roles_list = allowedRolesAndUsers)]
591
          security_uid_cache[cache_key] = security_uid_list
592 593
      else:
        security_uid_list = []
594
      return security_uid_list, role_column_dict, local_role_column_dict
595

Vincent Pelletier's avatar
Vincent Pelletier committed
596
    security.declarePublic('getSecurityQuery')
Aurel's avatar
Aurel committed
597
    def getSecurityQuery(self, query=None, sql_catalog_id=None, **kw):
598
      """
599 600 601
        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.
602
      """
603
      original_query = query
604 605 606
      security_uid_list, role_column_dict, local_role_column_dict = \
          self.getSecurityUidListAndRoleColumnDict(
              sql_catalog_id=sql_catalog_id, **kw)
607 608 609 610 611
      if role_column_dict:
        query_list = []
        for key, value in role_column_dict.items():
          new_query = Query(**{key : value})
          query_list.append(new_query)
612
        operator_kw = {'operator': 'OR'}
613 614 615 616 617 618 619
        query = ComplexQuery(*query_list, **operator_kw)
        # If security_uid_list is empty, adding it to criterions will only
        # result in "false or [...]", so avoid useless overhead by not
        # adding it at all.
        if security_uid_list:
          query = ComplexQuery(Query(security_uid=security_uid_list, operator='IN'),
                               query, operator='OR')
620
      elif security_uid_list:
621
        query = Query(security_uid=security_uid_list, operator='IN')
622 623 624 625 626 627 628 629
      else:
        # XXX A false query has to be generated. 
        # 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
        query = Query(uid=-1)
630 631 632 633 634 635 636 637 638 639

      if local_role_column_dict:
        query_list = []
        for key, value in local_role_column_dict.items():
          new_query = Query(**{key : value})
          query_list.append(new_query)
        operator_kw = {'operator': 'AND'}
        local_role_query = ComplexQuery(*query_list, **operator_kw)
        query = ComplexQuery(query, local_role_query, operator='AND')

640 641 642
      if original_query is not None:
        query = ComplexQuery(query, original_query, operator='AND')
      return query
643

Jean-Paul Smets's avatar
Jean-Paul Smets committed
644
    # searchResults has inherited security assertions.
645
    def searchResults(self, query=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
646
        """
647 648
        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
649
        """
650 651 652 653 654
        #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
655

Aurel's avatar
Aurel committed
656 657
        catalog_id = self.getPreferredSQLCatalogId(kw.pop("sql_catalog_id", None))
        query = self.getSecurityQuery(query=query, sql_catalog_id=catalog_id, **kw)
658
        kw.setdefault('limit', self.default_result_limit)
Aurel's avatar
Aurel committed
659 660 661 662
        # get catalog from preference
        #LOG("searchResult", INFO, catalog_id)
        #         LOG("searchResult", INFO, ZCatalog.searchResults(self, query=query, sql_catalog_id=catalog_id, src__=1, **kw))
        return ZCatalog.searchResults(self, query=query, sql_catalog_id=catalog_id, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
663 664 665

    __call__ = searchResults

666 667 668 669
    security.declarePrivate('unrestrictedSearchResults')
    def unrestrictedSearchResults(self, REQUEST=None, **kw):
        """Calls ZSQLCatalog.searchResults directly without restrictions.
        """
670
        kw.setdefault('limit', self.default_result_limit)
671 672
        return ZCatalog.searchResults(self, REQUEST, **kw)

673 674
    # We use a string for permissions here due to circular reference in import
    # from ERP5Type.Permissions
675 676
    security.declareProtected('Search ZCatalog', 'getResultValue')
    def getResultValue(self, query=None, **kw):
677 678 679 680
        """
        A method to factor common code used to search a single
        object in the database.
        """
681
        kw.setdefault('limit', 1)
682 683 684 685 686
        result = self.searchResults(query=query, **kw)
        try:
          return result[0].getObject()
        except IndexError:
          return None
687 688 689 690 691 692 693 694

    security.declarePrivate('unrestrictedGetResultValue')
    def unrestrictedGetResultValue(self, query=None, **kw):
        """
        A method to factor common code used to search a single
        object in the database. Same as getResultValue but without
        taking into account security.
        """
695
        kw.setdefault('limit', 1)
696 697 698 699 700 701
        result = self.unrestrictedSearchResults(query=query, **kw)
        try:
          return result[0].getObject()
        except IndexError:
          return None

702
    def countResults(self, query=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
703 704 705 706
        """
            Calls ZCatalog.countResults with extra arguments that
            limit the results to what the user is allowed to see.
        """
707
        # XXX This needs to be set again
708
        #if not _checkPermission(
Vincent Pelletier's avatar
Vincent Pelletier committed
709 710
        #    Permissions.AccessInactivePortalContent, self):
        #    base = aq_base(self)
711 712 713
        #    now = DateTime()
        #    #kw[ 'effective' ] = { 'query' : now, 'range' : 'max' }
        #    #kw[ 'expires'   ] = { 'query' : now, 'range' : 'min' }
Aurel's avatar
Aurel committed
714 715
        catalog_id = self.getPreferredSQLCatalogId(kw.pop("sql_catalog_id", None))        
        query = self.getSecurityQuery(query=query, sql_catalog_id=catalog_id, **kw)
716
        kw.setdefault('limit', self.default_count_limit)
Aurel's avatar
Aurel committed
717 718
        # get catalog from preference
        return ZCatalog.countResults(self, query=query, sql_catalog_id=catalog_id, **kw)
719
    
720 721 722 723 724
    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
725

726 727 728 729 730 731 732 733 734 735
    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)

736 737 738
        document_object = aq_inner(object)
        w = IndexableObjectWrapper(document_object)

739
        wf = getToolByName(self, 'portal_workflow')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
740
        if wf is not None:
741
          w.__dict__.update(wf.getCatalogVariablesFor(object))
742

743 744 745
        # Find the parent definition for security
        is_acquired = 0
        while getattr(document_object, 'isRADContent', 0):
746 747 748
          # This condition tells which object should acquire 
          # from their parent.
          # XXX Hardcode _View_Permission for a performance point of view
749 750
          if getattr(aq_base(document_object), '_View_Permission', ACQUIRE_PERMISSION_VALUE) == ACQUIRE_PERMISSION_VALUE\
             and document_object._getAcquireLocalRoles():
751
            document_object = document_object.aq_parent
752 753 754 755
            is_acquired = 1
          else:
            break
        if is_acquired:
756
          document_w = IndexableObjectWrapper(document_object)
757 758 759 760
        else:
          document_w = w

        (security_uid, optimised_roles_and_users) = catalog.getSecurityUid(document_w)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
761
        #LOG('catalog_object optimised_roles_and_users', 0, str(optimised_roles_and_users))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
762
        # XXX we should build vars begore building the wrapper
763
        w.optimised_roles_and_users = optimised_roles_and_users
764 765
        predicate_property_dict = catalog.getPredicatePropertyDict(object)
        if predicate_property_dict is not None:
766 767
          w.predicate_property_dict = predicate_property_dict
        w.security_uid = security_uid
768 769 770
        (subject_set_uid, optimised_subject_list) = catalog.getSubjectSetUid(document_w)
        w.optimised_subject_list = optimised_subject_list
        w.subject_set_uid = subject_set_uid
771 772

        return ImplicitAcquisitionWrapper(w, aq_parent(document_object))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
773 774

    security.declarePrivate('reindexObject')
775
    def reindexObject(self, object, idxs=None, sql_catalog_id=None,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
776 777 778 779
        '''Update catalog after object data has changed.
        The optional idxs argument is a list of specific indexes
        to update (all of them by default).
        '''
780
        if idxs is None: idxs = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
781
        url = self.__url(object)
782
        self.catalog_object(object, url, idxs=idxs, sql_catalog_id=sql_catalog_id,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
783

784

785 786 787 788 789 790 791 792 793 794
    def catalogObjectList(self, object_list, *args, **kw):
        """Catalog a list of objects"""
        if type(object_list[0]) is tuple:
          tmp_object_list = [x[0] for x in object_list]
          super(CatalogTool, self).catalogObjectList(tmp_object_list, **x[2])
          # keep failed objects in 'object_list'
          object_list[:] = [x for x in object_list if x[0] in tmp_object_list]
        else:
          super(CatalogTool, self).catalogObjectList(object_list, *args, **kw)

795 796 797 798 799 800 801
    security.declarePrivate('uncatalogObjectList')
    def uncatalogObjectList(self, message_list):
      """Uncatalog a list of objects"""
      for obj, args, kw in message_list:
        self.unindexObject(*args, **kw)
      del message_list[:]

Jean-Paul Smets's avatar
Jean-Paul Smets committed
802
    security.declarePrivate('unindexObject')
803
    def unindexObject(self, object=None, path=None, uid=None,sql_catalog_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
804 805 806
        """
          Remove from catalog.
        """
807
        if path is None and uid is None:
808 809
          if object is None:
            raise TypeError, 'One of uid, path and object parameters must not be None'
810
          path = self.__url(object)
811 812
        if uid is None:
          raise TypeError, "unindexObject supports only uid now"
813
        self.uncatalog_object(path=path, uid=uid, sql_catalog_id=sql_catalog_id)
814

Sebastien Robin's avatar
Sebastien Robin committed
815 816 817 818 819 820 821 822 823
    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)

824 825 826
    security.declarePrivate('getUrl')
    def getUrl(self, object):
      return self.__url(object)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
827

Jean-Paul Smets's avatar
Jean-Paul Smets committed
828
    security.declarePrivate('moveObject')
829
    def moveObject(self, object, idxs=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
830 831 832 833 834 835
        """
          Reindex in catalog, taking into account
          peculiarities of ERP5Catalog / ZSQLCatalog

          Useless ??? XXX
        """
836
        if idxs is None: idxs = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
837 838
        url = self.__url(object)
        self.catalog_object(object, url, idxs=idxs, is_object_moved=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
839

840 841 842 843 844 845
    security.declarePublic('getPredicatePropertyDict')
    def getPredicatePropertyDict(self, object):
      """
      Construct a dictionnary with a list of properties
      to catalog into the table predicate
      """
846
      if not object.providesIPredicate():
847 848 849
        return None
      object = object.asPredicate()
      if object is None:
850 851 852 853 854 855 856 857 858 859 860
        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:
861
            property_dict['%s_range_min' % property] = min
862
          if max is not None:
863
            property_dict['%s_range_max' % property] = max
864
      property_dict['membership_criterion_category_list'] = object.getMembershipCriterionCategoryList()
865 866
      return property_dict

867
    security.declarePrivate('getDynamicRelatedKeyList')
868
    def getDynamicRelatedKeyList(self, key_list, sql_catalog_id=None):
869
      """
870
      Return the list of dynamic related keys.
871 872
      This method will try to automatically generate new related key
      by looking at the category tree.
873 874 875 876

      For exemple it will generate:
      destination_title | category,catalog/title/z_related_destination
      default_destination_title | category,catalog/title/z_related_destination
877 878 879 880
      strict_destination_title | category,catalog/title/z_related_strict_destination

      strict_ related keys only returns documents which are strictly member of
      the category.
881 882
      """
      related_key_list = []
883
      base_cat_id_list = self.portal_categories.getBaseCategoryDict()
884
      default_string = 'default_'
885
      strict_string = 'strict_'
886
      for key in key_list:
887
        prefix = ''
888
        strict = 0
889 890 891
        if key.startswith(default_string):
          key = key[len(default_string):]
          prefix = default_string
892 893 894 895
        if key.startswith(strict_string):
          strict = 1
          key = key[len(strict_string):]
          prefix = prefix + strict_string
896
        splitted_key = key.split('_')
897 898
        # look from the end of the key from the beginning if we
        # can find 'title', or 'portal_type'...
899 900
        for i in range(1,len(splitted_key))[::-1]:
          expected_base_cat_id = '_'.join(splitted_key[0:i])
901
          if expected_base_cat_id != 'parent' and \
902 903 904
             expected_base_cat_id in base_cat_id_list:
            # We have found a base_category
            end_key = '_'.join(splitted_key[i:])
905 906 907

            if end_key.startswith('related_'):
              end_key = end_key[len('related_'):]
908
              suffix = '_related'
909
            else:
910 911 912 913 914 915 916 917 918 919 920
              suffix = ''
            # accept only some catalog columns
            if end_key in ('title', 'uid', 'description', 'reference',
                           'relative_url', 'id', 'portal_type',
                           'simulation_state'):
              if strict:
                pattern = '%s%s | category,catalog/%s/z_related_strict_%s%s'
              else:
                pattern = '%s%s | category,catalog/%s/z_related_%s%s'
              related_key_list.append(pattern %
                (prefix, key, end_key, expected_base_cat_id, suffix))
921 922 923 924 925 926

      return related_key_list

    def _aq_dynamic(self, name):
      """
      Automatic related key generation.
927
      Will generate z_related_[base_category_id] if possible
928
      """
Vincent Pelletier's avatar
Vincent Pelletier committed
929 930 931
      result = None
      if name.startswith(DYNAMIC_METHOD_NAME) and \
          not name.endswith(ZOPE_SECURITY_SUFFIX):
932
        kw = {}
Vincent Pelletier's avatar
Vincent Pelletier committed
933
        if name.endswith(RELATED_DYNAMIC_METHOD_NAME):
934 935
          end_offset = RELATED_DYNAMIC_METHOD_NAME_LEN
          kw['related'] = 1
936
        else:
937 938 939 940 941 942 943
          end_offset = None
        if name.startswith(STRICT_DYNAMIC_METHOD_NAME):
          start_offset = STRICT_DYNAMIC_METHOD_NAME_LEN
          kw['strict_membership'] = 1
        else:
          start_offset = DYNAMIC_METHOD_NAME_LEN
        method = RelatedBaseCategory(name[start_offset:end_offset], **kw)
Vincent Pelletier's avatar
Vincent Pelletier committed
944
        setattr(self.__class__, name, method)
945 946 947 948 949 950
        # 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
951 952
        result = getattr(self, name)
      return result
953

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
    def _searchAndActivate(self, method_id, method_args=(), method_kw={},
                           activate_kw={}, min_uid=None, **kw):
      """Search the catalog and run a script by activity on all found objects

      This method is configurable (via 'packet_size' & 'activity_count'
      parameters) so that it can work efficiently with databases of any size.

      'activate_kw' may specify an active process to collect results.
      Note however, we don't use Base_makeActiveResult so you're likely to get
      ConflictError at the beginning. You could avoid this by making sure
      'result_list' is already initialized on the active process.
      """
      catalog_kw = dict(kw)
      packet_size = catalog_kw.pop('packet_size', 30)
      limit = packet_size * catalog_kw.pop('activity_count', 100)
      if min_uid:
        catalog_kw['uid'] = {'query': min_uid, 'range': 'nlt'}
      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:
          tag = activate_kw.get('tag')
          if not tag:
            activate_kw['tag'] = tag = 'searchAndActivate_%r' % time.time()
          _tag = '%s_%s' % (tag, min_uid)
          self.activate(tag=tag, after_tag=_tag, activity='SQLQueue') \
              ._searchAndActivate(method_id,method_args, method_kw,
                                  dict(activate_kw), r[-1].getUid(), **kw)
          activate_kw['tag'] = _tag
        r = [x.getPath() for x in r]
        r.sort()
        activate = self.getPortalObject().portal_activities.activate
        for i in xrange(0, result_count, packet_size):
          activate(activity='SQLQueue', **activate_kw).callMethodOnObjectList(
            r[i:i+packet_size], method_id, *method_args, **method_kw)

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

999
InitializeClass(CatalogTool)