CatalogTool.py 31.4 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

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

from AccessControl.PermissionRole import rolesForPermissionOn

from Products.PageTemplates.Expressions import SecureModuleImporter
from Products.CMFCore.Expression import Expression
from Products.PageTemplates.Expressions import getEngine

47 48
import os, time, urllib

Jean-Paul Smets's avatar
Jean-Paul Smets committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
from zLOG import LOG

class IndexableObjectWrapper(CMFCoreIndexableObjectWrapper):

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

    def allowedRolesAndUsers(self):
        """
        Return a list of roles and users with View permission.
        Used by PortalCatalog to filter out items you're not allowed to see.
        """
65 66 67 68 69 70 71
        # Try to import CPS (import here to make sure no circular)
        try:
          from Products.NuxUserGroups.CatalogToolWithGroups import mergedLocalRoles
          withgroups = 1
        except ImportError:
          withgroups = 0

Jean-Paul Smets's avatar
Jean-Paul Smets committed
72 73 74 75
        ob = self.__ob
        allowed = {}
        for r in rolesForPermissionOn('View', ob):
            allowed[r] = 1
76 77
        if withgroups:
          localroles = mergedLocalRoles(ob, withgroups=1)
78
          #LOG("allowedRolesAndUsers",0,str(allowed.keys()))
79 80 81
        else:
          # CMF
          localroles = _mergedLocalRoles(ob)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
82 83 84
        for user, roles in localroles.items():
            for role in roles:
                if allowed.has_key(role):
85 86 87 88
                    if withgroups:
                      allowed[user] = 1
                    else:
                      allowed['user:' + user] = 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
89
                # Added for ERP5 project by JP Smets
90 91 92 93 94
                if role != 'Owner':
                  if withgroups:
                    allowed[user + ':' + role] = 1
                  else:
                    allowed['user:' + user + ':' + role] = 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
95 96
        if allowed.has_key('Owner'):
            del allowed['Owner']
97
        #LOG("allowedRolesAndUsers",0,str(allowed.keys()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        return list(allowed.keys())

class CatalogTool (UniqueObject, ZCatalog, CMFCoreCatalogTool):
    """
    This is a ZSQLCatalog that filters catalog queries.
    It is based on ZSQLCatalog
    """
    id = 'portal_catalog'
    meta_type = 'ERP5 Catalog'
    security = ClassSecurityInfo()

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


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

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

    security.declareProtected( CMFCorePermissions.ManagePortal
                , 'manage_filter' )
    manage_filter = DTMLFile( 'dtml/manageFilter', globals() )

Jean-Paul Smets's avatar
Jean-Paul Smets committed
125 126 127 128
    security.declareProtected( CMFCorePermissions.ManagePortal
                , 'manage_schema' )
    manage_schema = DTMLFile( 'dtml/manageSchema', globals() )

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 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 262 263 264 265 266 267 268 269 270 271
    # Setup properties for various configs : CMF, ERP5, CPS, etc.
    def setupPropertiesForConfig(self, config_id='erp5'):
        if config_id.lower() == 'erp5':
            self.sql_catalog_produce_reserved = 'z_produce_reserved_uid_list'
            self.sql_catalog_clear_reserved = 'z_clear_reserved'
            self.sql_catalog_object = ('z_update_object', 'z_catalog_category', 'z_catalog_movement',
                                                 'z_catalog_roles_and_users', 'z_catalog_stock', 'z_catalog_subject',)
            self.sql_uncatalog_object = ('z0_uncatalog_category', 'z0_uncatalog_movement',
                                                   'z0_uncatalog_roles_and_users',
                                                   'z0_uncatalog_stock', 'z0_uncatalog_subject', 'z_uncatalog_object', )
            self.sql_update_object = ('z0_uncatalog_category', 'z0_uncatalog_movement',
                                                'z0_uncatalog_roles_and_users',
                                                'z0_uncatalog_stock', 'z0_uncatalog_subject', 'z_catalog_category',
                                                'z_catalog_movement', 'z_catalog_roles_and_users', 'z_catalog_stock',
                                                'z_catalog_subject', 'z_update_object', )
            self.sql_clear_catalog = ('z0_drop_catalog', 'z0_drop_category', 'z0_drop_movement',
                                                'z0_drop_roles_and_users',
                                                'z0_drop_stock', 'z0_drop_subject', 'z_create_catalog',
                                                'z_create_category', 'z_create_movement', 'z_create_roles_and_users',
                                                'z_create_stock', 'z_create_subject',
                                                'z_clear_reserved', )
            self.sql_search_results = 'z_search_results'
            self.sql_count_results = 'z_count_results'
            self.sql_getitem_by_path = 'z_getitem_by_path'
            self.sql_getitem_by_uid = 'z_getitem_by_uid'
            self.sql_catalog_schema = 'z_show_columns'
            self.sql_unique_values = 'z_unique_values'
            self.sql_catalog_paths = 'z_catalog_paths'
            self.sql_catalog_keyword_search_keys = ('Description', 'SearchableText', 'Title', )
            self.sql_catalog_full_text_search_keys = ('Description', 'SearchableText', 'Title', )
            self.sql_catalog_request_keys = ()
            self.sql_search_result_keys = ('catalog.uid', 'catalog.security_uid', 'catalog.path',
                                           'catalog.relative_url', 'catalog.parent_uid', 'catalog.CreationDate',
                                           'catalog.Creator', 'catalog.Date', 'catalog.Description',
                                           'catalog.PrincipiaSearchSource', 'catalog.SearchableText', 
                                           'catalog.EffectiveDate',
                                           'catalog.ExpiresDate', 'catalog.ModificationDate', 'catalog.Title',
                                           'catalog.Type', 'catalog.bobobase_modification_time', 'catalog.created',
                                           'catalog.effective', 'catalog.expires', 'catalog.getIcon',
                                           'catalog.id', 'catalog.in_reply_to', 'catalog.meta_type',
                                           'catalog.portal_type', 'catalog.modified', 'catalog.review_state',
                                           'catalog.opportunity_state', 'catalog.default_source_reference', 
                                           'catalog.default_destination_reference',
                                           'catalog.default_source_title', 'catalog.default_destination_title', 
                                           'catalog.default_source_section_title',
                                           'catalog.default_destination_section_title', 'catalog.default_causality_id', 
                                           'catalog.location',
                                           'catalog.ean13_code', 'catalog.validation_state',
                                           'catalog.simulation_state',
                                           'catalog.causality_state', 'catalog.discussion_state', 'catalog.invoice_state',
                                           'catalog.payment_state', 'catalog.event_state', 'catalog.order_id',
                                           'catalog.reference', 'catalog.source_reference',
                                           'catalog.destination_reference', 'catalog.summary',)
            self.sql_search_tables = ('catalog', 'category', 'roles_and_users', 'movement', 'subject', )
            self.sql_catalog_tables = 'z_show_tables'

        elif config_id.lower() == 'cps3':
            self.sql_catalog_produce_reserved = 'z_produce_reserved_uid_list'
            self.sql_catalog_clear_reserved = 'z_clear_reserved'
            self.sql_catalog_object = ('z_update_object', 'z_catalog_roles_and_users', 'z_catalog_subject',
                                                 'z_catalog_local_users_with_roles', 'z_catalog_cps', )
            self.sql_uncatalog_object = ('z0_uncatalog_roles_and_users', 'z0_uncatalog_cps',
                                                   'z0_uncatalog_local_users_with_roles', 'z0_uncatalog_subject',
                                                   'z_uncatalog_object', )
            self.sql_update_object = ('z0_uncatalog_roles_and_users', 'z0_uncatalog_subject',
                                                'z_catalog_roles_and_users', 'z_catalog_subject',
                                                'z_update_object', 'z_update_cps')
            self.sql_clear_catalog = ('z0_drop_catalog', 'z0_drop_roles_and_users', 'z0_drop_cps',
                                                'z0_drop_local_users_with_roles', 'z0_drop_subject', 'z_create_catalog',
                                                'z_create_roles_and_users', 'z_create_local_users_with_roles',
                                                'z_create_subject', 'z_create_cps',
                                                'z_clear_reserved', )
            self.sql_search_results = 'z_search_results'
            self.sql_count_results = 'z_count_results'
            self.sql_getitem_by_path = 'z_getitem_by_path'
            self.sql_getitem_by_uid = 'z_getitem_by_uid'
            self.sql_catalog_schema = 'z_show_columns'
            self.sql_unique_values = 'z_unique_values'
            self.sql_catalog_paths = 'z_catalog_paths'
            self.sql_catalog_keyword_search_keys = ('Description', 'SearchableText', 'Title', )
            # XXX Not sure about local_users_with_roles.allowedRolesAndUser
            # self.sql_catalog_keyword_search_keys = ('Description', 'SearchableText', 'Title', 
            #                                                   'local_users_with_roles.allowedRolesAndUser' )
            self.sql_catalog_full_text_search_keys = ('Description', 'SearchableText', 'Title', )
            self.sql_catalog_request_keys = ()
            # XXX Check if cps.* is useful or not for result_keys
            self.sql_search_result_keys = ('catalog.uid', 'catalog.security_uid', 'catalog.path',
                                           'catalog.relative_url', 'catalog.parent_uid', 'catalog.CreationDate',
                                           'catalog.Creator', 'catalog.Date', 'catalog.Description',
                                           'catalog.PrincipiaSearchSource', 'catalog.SearchableText', 
                                           'catalog.EffectiveDate',
                                           'catalog.ExpiresDate', 'catalog.ModificationDate', 'catalog.Title',
                                           'catalog.Type', 'catalog.bobobase_modification_time', 'catalog.created',
                                           'catalog.effective', 'catalog.expires', 'catalog.getIcon',
                                           'catalog.id', 'catalog.in_reply_to', 'catalog.meta_type',
                                           'catalog.portal_type', 'catalog.modified', 'catalog.review_state',
                                           'catalog.opportunity_state', 'catalog.default_source_reference', 
                                           'catalog.default_destination_reference',
                                           'catalog.default_source_title', 'catalog.default_destination_title', 
                                           'catalog.default_source_section_title',
                                           'catalog.default_destination_section_title', 'catalog.default_causality_id', 
                                           'catalog.location',
                                           'catalog.ean13_code', 'catalog.validation_state',
                                           'catalog.simulation_state',
                                           'catalog.causality_state', 'catalog.discussion_state', 'catalog.invoice_state',
                                           'catalog.payment_state', 'catalog.event_state', 'catalog.order_id',
                                           'catalog.reference', 'catalog.source_reference',
                                           'catalog.destination_reference', 'catalog.summary',)
            self.sql_search_tables = ('catalog', 'cps', 'local_users_with_roles', 'roles_and_users', 'subject', )
            self.sql_catalog_tables = 'z_show_tables'

            # CPS specific
            self.sql_catalog_topic_search_keys = ('cps_filter_sets',)

        elif config_id.lower() == 'cmf':
            pass
            # XXX TODO

    def addDefaultSQLMethods(self, config_id='erp5'):
        addSQLMethod = self.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod
        product_path = package_home(globals())
        zsql_dirs = []

        # Common methods
        zsql_dirs.append(os.path.join(product_path, 'sql', 'common_mysql'))
        # Specific methods
        if config_id.lower() == 'erp5':
            zsql_dirs.append(os.path.join(product_path, 'sql', 'erp5_mysql'))
        elif config_id.lower() == 'cps3':
            zsql_dirs.append(os.path.join(product_path, 'sql', 'cps3_mysql'))
        # XXX TODO : add other cases

        #print ("zsql_dir = %s" % str(zsql_dir))
        # Iterate over the sql directory. Add all sql methods in that directory.
        for directory in zsql_dirs:
            for entry in os.listdir(directory):
                if len(entry) > 5 and entry[-5:] == '.zsql':
                    id = entry[:-5]
                    # Create an empty SQL method first.
                    addSQLMethod(id = id, title = '', connection_id = '', arguments = '', template = '')
                    sql_method = getattr(self, id)
                    # Set parameters of the SQL method from the contents of a .zsql file.
                    sql_method.fromFile(os.path.join(directory, entry))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
272

273
    def _listAllowedRolesAndUsers(self, user):
274 275 276 277 278
      try:
        from Products.NuxUserGroups.CatalogToolWithGroups import _getAllowedRolesAndUsers
        return _getAllowedRolesAndUsers(user)
      except ImportError:
        return CMFCoreCatalogTool._listAllowedRolesAndUsers(self, user)
279

Jean-Paul Smets's avatar
Jean-Paul Smets committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    # Schema Management
    def editColumn(self, column_id, sql_definition, method_id, default_value, REQUEST=None, RESPONSE=None):
      """
        Modifies a schema column of the catalog
      """
      new_schema = []
      for c in self.getIndexList():
        if c.id == index_id:
          new_c = {'id': index_id, 'sql_definition': sql_definition, 'method_id': method_id, 'default_value': default_value}
        else:
          new_c = c
        new_schema.append(new_c)
      self.setColumnList(new_schema)

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

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

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

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

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

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

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


    # Filtering
Jean-Paul Smets's avatar
Jean-Paul Smets committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 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 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
    def editFilter(self, REQUEST=None, RESPONSE=None):
      """
      This methods allows to set a filter on each zsql method called,
      so we can test if we should or not call a zsql method, so we can
      increase a lot the speed.
      """
      for zsql_method in self.objectValues():
        # We will first look if the filter is activated
        id = zsql_method.id
        if not self.filter_dict.has_key(id):
          self.filter_dict[id] = PersistentMapping()
          self.filter_dict[id]['filtered']=0
          self.filter_dict[id]['type']=[]
          self.filter_dict[id]['expression']=""
        if REQUEST.has_key('%s_box' % id):
          self.filter_dict[id]['filtered'] = 1
        else:
          self.filter_dict[id]['filtered'] = 0

        if REQUEST.has_key('%s_expression' % id):
          expression = REQUEST['%s_expression' % id]
          if expression == "":
            self.filter_dict[id]['expression'] = ""
            self.filter_dict[id]['expression_instance'] = None
          else:
            expr_instance = Expression(expression)
            self.filter_dict[id]['expression'] = expression
            self.filter_dict[id]['expression_instance'] = expr_instance
        else:
          self.filter_dict[id]['expression'] = ""
          self.filter_dict[id]['expression_instance'] = None

        if REQUEST.has_key('%s_type' % id):
          list_type = REQUEST['%s_type' % id]
          if type(list_type) is type('a'):
            list_type = [list_type]
          self.filter_dict[id]['type'] = list_type
        else:
          self.filter_dict[id]['type'] = []

      if RESPONSE is not None:
        RESPONSE.redirect('manage_filter')

    def isMethodFiltered(self, method_name):
      """
      Returns 1 if the method is already filtered,
      else it returns 0
      """
      # Reset Filtet dict
      # self.filter_dict= PersistentMapping()
      if not hasattr(self,'filter_dict'):
        self.filter_dict = PersistentMapping()
        return 0
      if self.filter_dict.has_key(method_name):
        return self.filter_dict[method_name]['filtered']
      return 0

    def getExpression(self, method_name):
      """
      Returns 1 if the method is already filtered,
      else it returns 0
      """
      if not hasattr(self,'filter_dict'):
        self.filter_dict = PersistentMapping()
        return ""
      if self.filter_dict.has_key(method_name):
        return self.filter_dict[method_name]['expression']
      return ""

    def getExpressionInstance(self, method_name):
      """
      Returns 1 if the method is already filtered,
      else it returns 0
      """
      if not hasattr(self,'filter_dict'):
        self.filter_dict = PersistentMapping()
        return None
      if self.filter_dict.has_key(method_name):
        return self.filter_dict[method_name]['expression_instance']
      return None

    def isPortalTypeSelected(self, method_name,portal_type):
      """
      Returns 1 if the method is already filtered,
      else it returns 0
      """
      if not hasattr(self,'filter_dict'):
        self.filter_dict = PersistentMapping()
        return 0
      if self.filter_dict.has_key(method_name):
        result = portal_type in (self.filter_dict[method_name]['type'])
        return result
      return 0


    def getFilterableMethodList(self):
      """
      Returns only zsql methods wich catalog or uncatalog objets
      """
      method_dict = {}
      for method_id in self.sql_catalog_object + self.sql_uncatalog_object + self.sql_update_object:
        method_dict[method_id] = 1
      method_list = map(lambda method_id: getattr(self, method_id, None), method_dict.keys())
      return filter(lambda method: method is not None, method_list)

    def getExpressionContext(self, ob):
        '''
        An expression context provides names for TALES expressions.
        '''
        data = {
            'here':         ob,
            'container':    aq_parent(aq_inner(ob)),
            'nothing':      None,
            'root':         ob.getPhysicalRoot(),
            'request':      getattr( ob, 'REQUEST', None ),
            'modules':      SecureModuleImporter,
            'user':         getSecurityManager().getUser(),
            }
        return getEngine().getContext(data)

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
    security.declarePublic( 'getAllowedRolesAndUsers' )
    def getAllowedRolesAndUsers(self, **kw):
      """
        Return allowed roles and users.
        This is supposed to be used with Z SQL Methods to check permissions
        when you list up documents.
      """
      user = _getAuthenticatedUser(self)
      allowedRolesAndUsers = self._listAllowedRolesAndUsers( user )

      # Patch for ERP5 by JP Smets in order
      # to implement worklists and search of local roles
      if kw.has_key('local_roles'):
        # Only consider local_roles if it is not empty
        if kw['local_roles'] != '' and  kw['local_roles'] != [] and  kw['local_roles'] is not None:
          local_roles = kw['local_roles']
          # Turn it into a list if necessary according to ';' separator
          if type(local_roles) == type('a'):
            local_roles = local_roles.split(';')
          # Local roles now has precedence (since it comes from a WorkList)
          allowedRolesAndUsers = []
          for role in local_roles:
            allowedRolesAndUsers.append('user:%s:%s' % (user, role))

      return allowedRolesAndUsers

Jean-Paul Smets's avatar
Jean-Paul Smets committed
493 494 495 496 497 498
    # searchResults has inherited security assertions.
    def searchResults(self, REQUEST=None, **kw):
        """
            Calls ZCatalog.searchResults with extra arguments that
            limit the results to what the user is allowed to see.
        """
499 500
        kw[ 'allowedRolesAndUsers' ] = self.getAllowedRolesAndUsers(**kw) # XXX allowedRolesAndUsers naming is wrong

Jean-Paul Smets's avatar
Jean-Paul Smets committed
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
        # Patch for ERP5 by JP Smets in order
        # to implement worklists and search of local roles
        if kw.has_key('local_roles'):
          # Only consider local_roles if it is not empty
          if kw['local_roles'] != '' and  kw['local_roles'] != [] and  kw['local_roles'] is not None:
            local_roles = kw['local_roles']
            # Turn it into a list if necessary according to ';' separator
            if type(local_roles) == type('a'):
              local_roles = local_roles.split(';')
            # Local roles now has precedence (since it comes from a WorkList)
            kw[ 'allowedRolesAndUsers' ] = []
            for role in local_roles:
                 kw[ 'allowedRolesAndUsers' ].append('user:%s:%s' % (user, role))

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

522
        #LOG("search allowedRolesAndUsers",0,str(kw[ 'allowedRolesAndUsers' ]))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
523 524 525 526 527 528 529 530 531
        return apply(ZCatalog.searchResults, (self, REQUEST), kw)

    __call__ = searchResults

    def countResults(self, REQUEST=None, **kw):
        """
            Calls ZCatalog.countResults with extra arguments that
            limit the results to what the user is allowed to see.
        """
532
        kw[ 'allowedRolesAndUsers' ] = self.getAllowedRolesAndUsers(**kw) # XXX allowedRolesAndUsers naming is wrong
Jean-Paul Smets's avatar
Jean-Paul Smets committed
533 534 535

        # Forget about permissions in statistics
        # (we should not count lines more than once
536
        if kw.has_key('select_expression'): del kw[ 'allowedRolesAndUsers' ]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
537

538 539 540 541 542 543
        #if not _checkPermission(
        #    CMFCorePermissions.AccessInactivePortalContent, self ):
        #    base = aq_base( self )
        #    now = DateTime()
        #    #kw[ 'effective' ] = { 'query' : now, 'range' : 'max' }
        #    #kw[ 'expires'   ] = { 'query' : now, 'range' : 'min' }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
544 545 546

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

547 548
    def catalog_object(self, object, uid, idxs=None, is_object_moved=0):
        if idxs is None: idxs = []
549
        wf = getToolByName(self, 'portal_workflow')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
550 551 552 553
        if wf is not None:
            vars = wf.getCatalogVariablesFor(object)
        else:
            vars = {}
554
        #LOG('catalog_object vars', 0, str(vars))            
Jean-Paul Smets's avatar
Jean-Paul Smets committed
555
        w = IndexableObjectWrapper(vars, object)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
556 557
        (security_uid, optimised_roles_and_users) = self.getSecurityUid(object, w)
        #LOG('catalog_object optimised_roles_and_users', 0, str(optimised_roles_and_users))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
558
        # XXX we should build vars begore building the wrapper
Jean-Paul Smets's avatar
Jean-Paul Smets committed
559 560
        if optimised_roles_and_users is not None:
          vars['optimised_roles_and_users'] = optimised_roles_and_users
561
        else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
562
          vars['optimised_roles_and_users'] = None
563
        vars['security_uid'] = security_uid
564
        #LOG("IndexableObjectWrapper", 0,str(w.allowedRolesAndUsers()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
565
        #try:
566
        #LOG('catalog_object wrapper', 0, str(w.__dict__))  
Jean-Paul Smets's avatar
Jean-Paul Smets committed
567
        ZCatalog.catalog_object(self, w, uid, idxs=idxs, is_object_moved=is_object_moved)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
568 569 570 571 572 573 574 575 576
        #except:
          # When we import data into Zope
          # the ZSQLCatalog does not work currently
          # since most of the time the SQL tables are not
          # created (yet)
          # It is better not to return an error for now
        #  pass

    security.declarePrivate('reindexObject')
577
    def reindexObject(self, object, idxs=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
578 579 580 581
        '''Update catalog after object data has changed.
        The optional idxs argument is a list of specific indexes
        to update (all of them by default).
        '''
582
        if idxs is None: idxs = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
583 584 585 586 587 588 589 590 591 592 593 594 595 596
        url = self.__url(object)
        self.catalog_object(object, url, idxs=idxs)

    security.declarePrivate('unindexObject')
    def unindexObject(self, object, path=None):
        """
          Remove from catalog.
        """
        if path is None:
          url = self.__url(object)
        else:
          url = path
        self.uncatalog_object(url)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
597
    security.declarePrivate('moveObject')
598
    def moveObject(self, object, idxs=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
599 600 601 602 603 604
        """
          Reindex in catalog, taking into account
          peculiarities of ERP5Catalog / ZSQLCatalog

          Useless ??? XXX
        """
605
        if idxs is None: idxs = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
606 607
        url = self.__url(object)
        self.catalog_object(object, url, idxs=idxs, is_object_moved=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
608

Jean-Paul Smets's avatar
Jean-Paul Smets committed
609 610 611 612
    security.declarePrivate('getSecurityUid')
    def getSecurityUid(self, object, w):
        """
          Cache a uid for each security permission
613

Jean-Paul Smets's avatar
Jean-Paul Smets committed
614 615 616 617 618 619
          We try to create a unique security (to reduce number of lines)
          and to assign security only to root document
        """
        # Find parent document (XXX this extra step should be deactivated on complex ERP5 installations)
        object_path = object.getPhysicalPath()
        portal_path = object.portal_url.getPortalObject().getPhysicalPath()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
620 621 622 623
        if len(object_path) > len(portal_path) + 2 and getattr(object, 'isRADContent', 0):
          # This only applied to ERP5 Contents (not CPS)
          # We are now in the case of a subobject of a root document          
          # We want to return single security information          
Jean-Paul Smets's avatar
Jean-Paul Smets committed
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
          document_object = aq_inner(object)
          for i in range(0, len(object_path) - len(portal_path) - 2):
            document_object = document_object.aq_parent
          document_w = IndexableObjectWrapper({}, document_object)
          return self.getSecurityUid(document_object, document_w)
        # Get security information
        allowed_roles_and_users = w.allowedRolesAndUsers()
        # Sort it
        allowed_roles_and_users = list(allowed_roles_and_users)
        allowed_roles_and_users.sort()
        allowed_roles_and_users = tuple(allowed_roles_and_users)
        # Make sure no diplicates
        if not hasattr(aq_base(self), 'security_uid_dict'):
          self._clearSecurityCache()
        if self.security_uid_dict.has_key(allowed_roles_and_users):
          return (self.security_uid_dict[allowed_roles_and_users], None)
        self.security_uid_index = self.security_uid_index + 1
        self.security_uid_dict[allowed_roles_and_users] = self.security_uid_index
        return (self.security_uid_index, allowed_roles_and_users)

644
    # Overriden methods
Jean-Paul Smets's avatar
Jean-Paul Smets committed
645 646 647
    def _clearSecurityCache(self):
        self.security_uid_dict = OIBTree()
        self.security_uid_index = 0
648

Jean-Paul Smets's avatar
Jean-Paul Smets committed
649
    def refreshCatalog(self, clear=0):
650
        """ clear security cache and re-index everything we can find """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
651 652
        self._clearSecurityCache()
        return ZCatalog.refreshCatalog(self, clear=clear)
653

Jean-Paul Smets's avatar
Jean-Paul Smets committed
654 655 656 657
    def manage_catalogClear(self, REQUEST=None, RESPONSE=None, URL1=None):
        """ clear security cache and the rest """
        self._clearSecurityCache()
        return ZCatalog.manage_catalogClear(self, REQUEST=REQUEST, RESPONSE=RESPONSE, URL1=URL1)
658

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
    def manage_catalogIndexAll(self, REQUEST, RESPONSE, URL1):
      """ adds all objects to the catalog starting from the parent """
      elapse = time.time()
      c_elapse = time.clock()
  
      def reindex(oself, r_dict):
        path = oself.getPhysicalPath()
        if r_dict.has_key(path): return
        r_dict[path] = 1
        try:
          oself.reindexObject()
          get_transaction().commit() # Allows to reindex up to 10,000 objects without problems
        except:
          # XXX better exception handling required
          pass
        for o in oself.objectValues():
          reindex(o, r_dict)
      
      new_dict = {}        
      reindex(self.aq_parent, new_dict)
  
      elapse = time.time() - elapse
      c_elapse = time.clock() - c_elapse
  
      RESPONSE.redirect(URL1 +
                '/manage_catalogAdvanced?manage_tabs_message=' +
                urllib.quote('Catalog Indexed<br>'
                      'Total time: %s<br>'
                      'Total CPU time: %s' % (`elapse`, `c_elapse`)))                                    
    
Jean-Paul Smets's avatar
Jean-Paul Smets committed
689
InitializeClass(CatalogTool)