CategoryTool.py 81.3 KB
Newer Older
1
# -*- coding: utf-8 -*-
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2 3 4
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
#
# 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.
#
##############################################################################

"""\
ERP portal_categories tool.
"""
33
from collections import deque
34
from BTrees.OOBTree import OOTreeSet
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35 36
from OFS.Folder import Folder
from Products.CMFCore.utils import UniqueObject
37
from Products.ERP5Type.Globals import InitializeClass, DTMLFile
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38
from AccessControl import ClassSecurityInfo
39
from AccessControl import Unauthorized, getSecurityManager
40
from Acquisition import aq_base, aq_inner
Jean-Paul Smets's avatar
Jean-Paul Smets committed
41 42
from Products.ERP5Type import Permissions
from Products.ERP5Type.Base import Base
43
from Products.ERP5Type.Cache import getReadOnlyTransactionCache
44
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Jean-Paul Smets's avatar
Jean-Paul Smets committed
45 46
from Products.CMFCategory import _dtmldir
from Products.CMFCore.PortalFolder import ContentFilter
47
from Products.CMFCategory.Renderer import Renderer
48
from Products.CMFCategory.Category import Category, BaseCategory
49
from OFS.Traversable import NotFound
50
import types
Jean-Paul Smets's avatar
Jean-Paul Smets committed
51

52
import re
Jean-Paul Smets's avatar
Jean-Paul Smets committed
53

54
from zLOG import LOG, PROBLEM, WARNING, ERROR
Jean-Paul Smets's avatar
Jean-Paul Smets committed
55

Yoshinori Okuji's avatar
Yoshinori Okuji committed
56 57
_marker = object()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
58 59 60
class CategoryError( Exception ):
    pass

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

class RelatedIndex(): # persistent.Persistent can be added
                      # without breaking compatibility

  def __repr__(self):
    try:
      contents = ', '.join('%s=%r' % (k, list(v))
                           for (k, v) in self.__dict__.iteritems())
    except Exception:
      contents = '...'
    return '<%s(%s) at 0x%x>' % (self.__class__.__name__, contents, id(self))

  def __nonzero__(self):
    return any(self.__dict__.itervalues())

  def add(self, base, relative_url):
    try:
      getattr(self, base).add(relative_url)
    except AttributeError:
      setattr(self, base, OOTreeSet((relative_url,)))

  def remove(self, base, relative_url):
    try:
      getattr(self, base).remove(relative_url)
    except (AttributeError, KeyError):
      pass


Jean-Paul Smets's avatar
Jean-Paul Smets committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
class CategoryTool( UniqueObject, Folder, Base ):
    """
      The CategoryTool object is the placeholder for all methods
      and algorithms related to categories and relations in CMF.

      The default category tool (this one) implements methods such
      as getCategoryMembershipList and setCategoryMembershipList
      which store categorymembership as a list of relative url in
      a property called categories.

      Category membership lists are ordered. For each base_category
      the first category membership in the category membership list is
      called the default category membership. For example, if a resource
      can be counted in meters, kilograms and cubic meters and if the
      default unit is meters, the category membership list for this resource
      from the quantity_unit point of view is::

        quantity_unit/length/meter
        quantity_unit/weight/kilogram
        quantity_unit/volume/m3

      Membership is ordered and multiple. For example, if a swim suit uses
Jérome Perrin's avatar
Jérome Perrin committed
111 112 113 114
      three colors (eg : color1, color2, color3 which are used in the top, belt
      and in the bottom) and if a particular variation of that swim suit has
      two of the three colors the same (eg black, blue, black) then the
      category membership list from the color point of view is::
Jean-Paul Smets's avatar
Jean-Paul Smets committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

        color/black
        color/blue
        color/black

        TODO: Add sort methods everywhere

        NB:
          All values are by default acquired
          Future accessors should provide non acquired values

        XX:
          Why is portal_categoires a subclass of Base ? Because of uid ?
          If yes, then it should be migrated into ERP5Category and __init__ indefined here
    """

    id              = 'portal_categories'
    meta_type       = 'CMF Categories'
133
    portal_type     = 'Category Tool'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
    allowed_types = ( 'CMF Base Category', )


    # Declarative Security
    security = ClassSecurityInfo()

    #
    #   ZMI methods
    #
    manage_options = ( ( { 'label'      : 'Overview'
                         , 'action'     : 'manage_overview'
                         }
                        ,
                        )
                     + Folder.manage_options
                     )

    security.declareProtected( Permissions.ManagePortal
                             , 'manage_overview' )
    manage_overview = DTMLFile( 'explainCategoryTool', _dtmldir )


    # Multiple inheritance inconsistency caused by Base must be circumvented
    def __init__( self, *args, **kwargs ):
      Base.__init__(self, self.id, **kwargs)

    # Filter content (ZMI))
    def filtered_meta_types(self, user=None):
        # Filters the list of available meta types.
        all = CategoryTool.inheritedAttribute('filtered_meta_types')(self)
        meta_types = []
        for meta_type in self.all_meta_types():
            if meta_type['name'] in self.allowed_types:
                meta_types.append(meta_type)
        return meta_types

    # Filter Utilities
    def _buildFilter(self, spec, filter, kw):
      if filter is None:
        filt = {}
      else:
        # Work on a copy since we are going to modify it
        filt = filter.copy()
      if spec is not None: filt['meta_type'] = spec
      filt.update(kw)
      return filt

    def _buildQuery(self, spec, filter, kw):
182
      return ContentFilter(**self._buildFilter(spec, filter, kw))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
183 184

    # Category accessors
185
    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryList')
186
    def getBaseCategoryList(self, context=None, sort=False):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
187 188 189 190 191 192 193 194 195 196 197 198
      """
        Returns the ids of base categories of the portal_categories tool
        if no context is provided, otherwise, returns the base categories
        defined for the class

        Two alias are provided :

        getBaseCategoryIds -- backward compatibility with early ERP5 versions

        baseCategoryIds -- for zope users conveniance
      """
      if context is None:
199
        result = self.objectIds()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
200
      else:
201
        # XXX Incompatible with ERP5Type per portal type categories
202
        result = list(context._categories[:])
203 204 205
      if sort:
        result.sort()
      return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
206 207

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryIds')
208
    getBaseCategoryIds = getBaseCategoryList
Jean-Paul Smets's avatar
Jean-Paul Smets committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

    security.declareProtected(Permissions.AccessContentsInformation, 'baseCategoryIds')
    baseCategoryIds = getBaseCategoryIds

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryValueList')
    def getBaseCategoryValueList(self, context=None):
      """
        Returns the base categories of the portal_categories tool
        if no context is provided, otherwise returns the base categories
        for the class

        Two alias are provided :

        getBaseCategoryValues -- backward compatibility with early ERP5 versions

        baseCategoryValues -- for zope users conveniance
      """
      if context is None:
        return self.objectValues()
      else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
229
        return [self[x] for x in context._categories] # XXX Incompatible with ERP5Type per portal type categories
Jean-Paul Smets's avatar
Jean-Paul Smets committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243

    security.declareProtected(Permissions.AccessContentsInformation,
                                                         'getBaseCategoryValues')
    getBaseCategoryValues = getBaseCategoryValueList

    security.declareProtected(Permissions.AccessContentsInformation, 'baseCategoryValues')
    baseCategoryValues = getBaseCategoryValues

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryValue')
    def getCategoryValue(self, relative_url, base_category = None):
      """
        Returns a Category object from a given category url
        and optionnal base category id
      """
244
      cache = getReadOnlyTransactionCache()
245 246 247 248 249 250
      if cache is not None:
        key = ('getCategoryValue', relative_url, base_category)
        try:
          return cache[key]
        except KeyError:
          pass
251

Jean-Paul Smets's avatar
Jean-Paul Smets committed
252 253 254
      try:
        relative_url = str(relative_url)
        if base_category is not None:
Romain Courteaud's avatar
Romain Courteaud committed
255
          relative_url = '%s/%s' % (base_category, relative_url)
256 257 258
        relative_url = \
        self._removeDuplicateBaseCategoryIdInCategoryPath(base_category,
                                                                 relative_url)
Julien Muchembled's avatar
Julien Muchembled committed
259
        value = self.unrestrictedTraverse(relative_url)
260
      except (TypeError, KeyError, NotFound):
261
        value = None
262

263 264 265 266
      if cache is not None:
        cache[key] = value

      return value
267

Romain Courteaud's avatar
Romain Courteaud committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
#     security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryValue')
#     def getCategoryValue(self, relative_url, base_category = None):
#       """
#         Returns a Category object from a given category url
#         and optionnal base category id
#       """
#       try:
#         relative_url = str(relative_url)
#         context = aq_base(self)
#         if base_category is not None:
#           context = context.unrestrictedTraverse(base_category)
#           context = aq_base(context)
#         node = context.unrestrictedTraverse(relative_url)
#         return node.__of__(self)
#       except:
#         return None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryUid')
    def getCategoryUid(self, relative_url, base_category = None):
      """
        Returns the uid of a Category from a given base category
        and the relative_url of a category
      """
      node = self.getCategoryValue(relative_url,  base_category = base_category)
      if node is not None:
        return node.uid
      else:
        return None

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryValueFromUid')
    def getCategoryValueFromUid(self, uid):
      """
        Returns the a Category object from its uid by looking up in a
        a portal_catalog which must be ZSQLCataglog
      """
      return self.portal_catalog.getobject(uid)

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryId')
    def getBaseCategoryId(self, relative_url, base_category = None):
      """
        Returns the id of the base category from a given relative url
        and optional base category
      """
      if base_category is not None:
        return base_category
      try:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
314
        return relative_url.split('/', 1)[0]
315
      except KeyError :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
316 317 318 319 320 321 322 323 324 325 326
        return None

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryUid')
    def getBaseCategoryUid(self, relative_url, base_category = None):
      """
        Returns the uid of the base category from a given relative_url
        and optional base category
      """
      try:
        return self.getCategoryValue(self.getBaseCategoryId(relative_url,
                        base_category = base_category)).uid
327
      except (AttributeError, KeyError):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
328 329 330 331 332
        return None

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryParentUidList')
    def getCategoryParentUidList(self, relative_url, base_category = None, strict=0):
      """
333 334 335 336 337 338 339
        Returns the uids of all categories provided in categorie. This
        method can support relative_url such as site/group/a/b/c which
        base category is site yet use categories defined in group.

        It is also able to use acquisition to create complex categories
        such as site/group/a/b/c/b1/c1 where b and b1 are both children
        categories of a.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
340

341
        relative_url -- a single relative url or a list of relative urls
Jean-Paul Smets's avatar
Jean-Paul Smets committed
342 343 344 345

        strict       -- if set to 1, only return uids of parents, not
                        relative_url
      """
346
      uid_set = set()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
347 348
      if isinstance(relative_url, str):
        relative_url = (relative_url,)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
349 350 351 352
      for path in relative_url:
        try:
          o = self.getCategoryValue(path, base_category=base_category)
          if o is not None:
353 354 355 356 357 358 359 360
            if base_category is None:
              my_base_category = self.getBaseCategoryId(path)
            else:
              my_base_category = base_category
            bo_uid = self[my_base_category].getUid()
            uid_set.add((o.getUid(), bo_uid, 1)) # Strict Membership
            if not strict:
              while o.portal_type == 'Category':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
361 362 363
                # This goes up in the category tree
                # XXX we should also go up in some other cases....
                # ie. when some documents act as categories
364
                o = o.aq_parent # We want acquisition here without aq_inner
365 366 367 368
                o_uid = o.getUid()
                if o_uid == bo_uid:
                  break
                uid_set.add((o_uid, bo_uid, 0)) # Non Strict Membership
369
        except (KeyError, AttributeError):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
370
          LOG('WARNING: CategoriesTool',0, 'Unable to find uid for %s' % path)
371
      return list(uid_set) # cast to list for <dtml-in>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryChildUidList')
    def getCategoryChildUidList(self, relative_url, base_category = None, strict=0):
      """
        Returns the uids of all categories provided in categories

        relative_url -- a single relative url of a list of
                        relative urls

        strict       -- if set to 1, only return uids of parents, not
                        relative_url
      """
      ## TBD

    # Recursive listing API
    security.declareProtected(Permissions.AccessContentsInformation,
                                                  'getCategoryChildRelativeUrlList')
    def getCategoryChildRelativeUrlList(self, base_category=None, base=0, recursive=1):
      """
      Returns a list of relative urls by parsing recursively all categories in a
      given list of base categories

      base_category -- A single base category id or a list of base category ids
                       if not provided, base category will be set with the list
                       of all current category ids

      base -- if set to 1, relative_url will start with the base category id
              if set to 0 and if base_category is a single id, relative_url
              are relative to the base_category (and thus  doesn't start
              with the base category id)

      recursive -- if set to 0 do not apply recursively
      """
      if base_category is None:
406
        base_category_list = self.getBaseCategoryList()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
407
      elif isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
408 409 410 411 412 413 414
        base_category_list = [base_category]
      else:
        base_category_list = base_category
      result = []
      for base_category in base_category_list:
        category = self[base_category]
        if category is not None:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
415
          result.extend(category.getCategoryChildRelativeUrlList(base=base,recursive=recursive))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
416 417 418
      return result

    security.declareProtected(Permissions.AccessContentsInformation, 'getPathList')
419 420 421 422
    getPathList = getCategoryChildRelativeUrlList # Exists for backward compatibility

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryChildList')
    getCategoryChildList = getCategoryChildRelativeUrlList # This is more consistent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
423 424 425

    security.declareProtected(Permissions.AccessContentsInformation,
                                                      'getCategoryChildTitleItemList')
426
    def getCategoryChildTitleItemList(self, base_category=None, *args, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
427 428 429 430
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getTitle as default method
      """
431
      return self.getCategoryChildItemList(base_category, 'title', *args, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
432 433

    security.declareProtected(Permissions.AccessContentsInformation,
434
                              'getCategoryChildIdItemList')
435
    def getCategoryChildIdItemList(self, base_category=None, *args, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
436 437 438 439
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getId as default method
      """
440
      return self.getCategoryChildItemList(base_category, 'id', *args, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
441 442

    security.declareProtected(Permissions.AccessContentsInformation,
443
                              'getCategoryChildItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
444
    def getCategoryChildItemList(self, base_category=None, display_id = None,
445
          recursive=1, base=0, display_none_category=1, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
446 447 448 449
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Each tuple contains::

Jean-Paul Smets's avatar
Jean-Paul Smets committed
450
        (c.relative_url,c.display_id())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
451 452 453 454 455 456 457 458 459 460

      base_category -- A single base category id or a list of base category ids
                       if not provided, base category will be set with the list
                       of all current category ids

      base -- if set to 1, relative_url will start with the base category id
              if set to 0 and if base_category is a single id, relative_url
              are relative to the base_category (and thus  doesn't start
              with the base category id)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
461
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
462 463

      recursive -- if set to 0 do not apply recursively
464 465

      See Category.getCategoryChildItemList for extra accepted arguments
Jean-Paul Smets's avatar
Jean-Paul Smets committed
466
      """
467
      if isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
468 469
        base_category_list = [base_category]
      elif base_category is None:
470
        base_category_list = self.getBaseCategoryList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
471 472
      else:
        base_category_list = base_category
Jean-Paul Smets's avatar
Jean-Paul Smets committed
473
      if display_none_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
474 475 476 477 478 479
        result = [('', '')]
      else:
        result = []
      for base_category in base_category_list:
        category = self[base_category]
        if category is not None:
480
          result += category.getCategoryChildItemList(
481 482 483
                               base=base,
                               recursive=recursive,
                               display_id=display_id,
484 485
                               display_none_category=0,
                               **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
486 487
      return result

488 489
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getBaseItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
490 491 492 493
    getBaseItemList = getCategoryChildItemList

    # Category to Tuple Conversion
    security.declareProtected(Permissions.View, 'asItemList')
Sebastien Robin's avatar
Sebastien Robin committed
494
    def asItemList(self, relative_url, base_category=None,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
495 496
      """
      Returns a list of tuples, each tuple is calculated by applying
Jean-Paul Smets's avatar
Jean-Paul Smets committed
497
      display_id on each category provided in relative_url
Jean-Paul Smets's avatar
Jean-Paul Smets committed
498 499 500 501 502 503 504 505 506 507

      base_category -- A single base category id or a list of base category ids
                       if not provided, base category will be set with the list
                       of all current category ids

      base -- if set to 1, relative_url will start with the base category id
              if set to 0 and if base_category is a single id, relative_url
              are relative to the base_category (and thus  doesn't start
              with the base category id)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
508
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
509 510 511

      recursive -- if set to 0 do not apply recursively
      """
Sebastien Robin's avatar
Sebastien Robin committed
512 513 514 515
      #if display_id is None:
      #  for c in relative_url:
      #    result += [(c, c)]
      #else:
Romain Courteaud's avatar
Romain Courteaud committed
516
#       LOG('CMFCategoryTool.asItemList, relative_url',0,relative_url)
Sebastien Robin's avatar
Sebastien Robin committed
517 518 519
      value_list = []
      for c in relative_url:
        o = self.getCategoryValue(c, base_category=base_category)
Romain Courteaud's avatar
Romain Courteaud committed
520
#         LOG('CMFCategoryTool.asItemList, (o,c)',0,(o,c))
Sebastien Robin's avatar
Sebastien Robin committed
521 522 523 524
        if o is not None:
          value_list.append(o)
        else:
          LOG('WARNING: CategoriesTool',0, 'Unable to find category %s' % c)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
525 526 527 528

      #if sort_id is not None:
      #  result.sort()

Romain Courteaud's avatar
Romain Courteaud committed
529
#       LOG('CMFCategoryTool.asItemList, value_list',0,value_list)
Sebastien Robin's avatar
Sebastien Robin committed
530
      return Renderer(base_category=base_category,**kw).render(value_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
531 532 533 534 535 536 537

    security.declareProtected(Permissions.View, 'getItemList')
    getItemList = asItemList

    # Convert a list of membership to path
    security.declareProtected(Permissions.View, 'asPathList')
    def asPathList(self, base_category, category_list):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
538
      if isinstance(category_list, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
539
        category_list = [category_list]
Yoshinori Okuji's avatar
Yoshinori Okuji committed
540
      if category_list is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
541 542 543
        category_list = []
      new_list = []
      for v in category_list:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
544
        new_list.append('%s/%s' % (base_category, v))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
545 546 547 548 549 550 551 552 553 554 555
      return new_list

    # Alias for compatibility
    security.declareProtected(Permissions.View, 'formSelectionToPathList')
    formSelectionToPathList = asPathList


    # Category implementation
    security.declareProtected( Permissions.AccessContentsInformation,
                                                  'getCategoryMembershipList' )
    def getCategoryMembershipList(self, context, base_category, base=0,
556
                                  spec=(), filter=None, **kw  ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570
      """
        Returns a list of category membership
        represented as a list of relative URLs

        context       --    the context on which we are looking for categories

        base_category --    a single base category (string) or a list of base categories

        spec          --    a list or a tuple of portal types

        base          --    if set to 1, returns relative URLs to portal_categories
                            if set to 0, returns relative URLs to the base category
      """
      # XXX We must use filters in the future
571
      # where_expression = self._buildQuery(spec, filter, kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
572 573 574 575 576 577
      portal_type = kw.get('portal_type', ())
      if spec is (): spec = portal_type

      # LOG('getCategoryMembershipList',0,str(spec))
      # LOG('getCategoryMembershipList',0,str(base_category))
      membership = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
578
      if not isinstance(base_category, (tuple, list)):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
579 580 581
        category_list = [base_category]
      else:
        category_list = base_category
582 583 584 585
      if isinstance(spec, str):
        spec = (spec,)
      elif isinstance(spec, list):
        spec = tuple(spec)
586
      spec_len = len(spec)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
587 588
      for path in self._getCategoryList(context):
        # LOG('getCategoryMembershipList',0,str(path))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
589
        my_base_category = path.split('/', 1)[0]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
590
        for my_category in category_list:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
591
          if isinstance(my_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
592 593 594 595
            category = my_category
          else:
            category = my_category.getRelativeUrl()
          if my_base_category == category:
596
            path = self._removeDuplicateBaseCategoryIdInCategoryPath(my_base_category, path)
597
            if spec_len == 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
598
              if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
599
                membership.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
600
              else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
601
                membership.append(path[len(category)+1:])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
602 603
            else:
              try:
Nicolas Delaby's avatar
Nicolas Delaby committed
604 605 606 607 608 609 610
                o = self.unrestrictedTraverse(path)
                # LOG('getCategoryMembershipList',0,str(o.portal_type))
                if o.portal_type in spec:
                  if base:
                    membership.append(path)
                  else:
                    membership.append(path[len(category)+1:])
Yoshinori Okuji's avatar
Yoshinori Okuji committed
611
              except KeyError:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
612 613 614
                LOG('WARNING: CategoriesTool',0, 'Unable to find object for path %s' % path)
      # We must include parent if specified explicitely
      if 'parent' in category_list:
615 616
        parent = context.aq_inner.aq_parent # aq_inner is required to make sure we use containment
                                            # just as in ERP5Type.Base.getParentValue
617
        # Handle parent base category is a special way
618
        membership.append(parent)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
619 620 621
      return membership

    security.declareProtected( Permissions.AccessContentsInformation, 'setCategoryMembership' )
622 623 624 625 626 627 628 629
    def setCategoryMembership(self, context, *args, **kw):
      self._setCategoryMembership(context, *args, **kw)
      context.reindexObject()

    def _setCategoryMembership(self, context, base_category_list,
                               category_list, base=0, keep_default=1,
                               spec=(), filter=None, checked_permission=None,
                               **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
630 631 632 633 634 635 636 637 638 639 640 641 642
      """
        Sets the membership of the context on the specified base_category
        list and for the specified portal_type spec

        context            --    the context on which we are looking for categories

        base_category_list --    a single base category (string) or a list of base categories
                                 or a single base category object or a list of base category objects

        category_list      --    a single category (string) or a list of categories

        spec               --    a list or a tuple of portal types

643
        checked_permission        --    a string which defined the permission
644 645
                                        to filter the object on

Jean-Paul Smets's avatar
Jean-Paul Smets committed
646
      """
647 648
#       LOG("CategoryTool, setCategoryMembership", 0 ,
#           'category_list: %s' % str(category_list))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
649
      # XXX We must use filters in the future
650
      # where_expression = self._buildQuery(spec, filter, kw)
651
      if spec is ():
652 653 654
        portal_type = kw.get('portal_type', ())
        if isinstance(portal_type, str):
          portal_type = (portal_type,)
655
        spec = portal_type
656

Yoshinori Okuji's avatar
Yoshinori Okuji committed
657
      if isinstance(category_list, str):
658
        category_list = (category_list, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
659 660
      elif category_list is None:
        category_list = ()
661

Yoshinori Okuji's avatar
Yoshinori Okuji committed
662
      if isinstance(base_category_list, str):
663 664 665 666 667
        base_category_list = (base_category_list, )

      if checked_permission is not None:
        checkPermission = self.portal_membership.checkPermission

668 669 670
      new_category_list = deque()
      default_base_category_set = set()
      default_category_set = set()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
671 672
      for path in self._getCategoryList(context):
        my_base_id = self.getBaseCategoryId(path)
673 674
        if my_base_id in base_category_list:
          if spec or checked_permission is not None:
675 676
            obj = self.unrestrictedTraverse(path, None)
            if obj is not None:
677 678 679 680 681 682 683 684 685 686 687 688
              # If spec is (), then we should keep nothing
              # Everything will be replaced
              # If spec is not (), Only keep this if not in our spec
              if (spec and obj.portal_type not in spec) or not (
                  checked_permission is None or
                  checkPermission(checked_permission, obj)):
                new_category_list.append(path)
                continue
          # We must remember the default value for each replaced category
          if keep_default and my_base_id not in default_base_category_set:
            default_base_category_set.add(my_base_id)
            default_category_set.add(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
689
        else:
690 691 692
          # Keep each membership which is not in the
          # specified list of base_category ids
          new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
693 694
      # Before we append new category values (except default values)
      # We must make sure however that multiple links are possible
695 696
      base = '' if base or len(base_category_list) > 1 \
        else base_category_list[0] + '/'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
697
      for path in category_list:
698 699 700 701 702 703 704 705
        if path not in ('', None):
          if base:
            path = base + path
          elif self.getBaseCategoryId(path) not in base_category_list:
            continue
          if path in default_category_set:
            default_category_set.remove(path)
            new_category_list.appendleft(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
706
          else:
707 708
            new_category_list.append(path)
      self._setCategoryList(context, new_category_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
709

710

Jean-Paul Smets's avatar
Jean-Paul Smets committed
711 712
    security.declareProtected( Permissions.AccessContentsInformation, 'setDefaultCategoryMembership' )
    def setDefaultCategoryMembership(self, context, base_category, default_category,
713 714 715
                                              spec=(), filter=None,
                                              portal_type=(), base=0,
                                              checked_permission=None ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
716 717 718 719 720 721 722 723 724 725 726 727 728
      """
        Sets the membership of the context on the specified base_category
        list and for the specified portal_type spec

        context            --    the context on which we are looking for categories

        base_category_list --    a single base category (string) or a list of base categories
                                 or a single base category object or a list of base category objects

        category_list      --    a single category (string) or a list of categories

        spec               --    a list or a tuple of portal types

729
        checked_permission        --    a string which defined the permission
730 731
                                        to filter the object on

Jean-Paul Smets's avatar
Jean-Paul Smets committed
732
      """
Yoshinori Okuji's avatar
Yoshinori Okuji committed
733
      if isinstance(default_category, (tuple, list)):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
734 735 736 737 738 739 740 741 742
        default_category = default_category[0]
      category_list = self.getCategoryMembershipList(context, base_category,
                           spec=spec, filter=filter, portal_type=portal_type, base=base)
      new_category_list = [default_category]
      found_one = 0
      # We will keep from the current category_list
      # everything except the first occurence of category
      # this allows to have multiple occurences of the same category
      for category in category_list:
743
        if category == default_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
744
          found_one = 1
745
        elif category != default_category or found_one:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
746
          new_category_list.append(category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
747 748 749
      self.setCategoryMembership(context, base_category, new_category_list,
           spec=spec, filter=filter, portal_type=portal_type, base=base, keep_default = 0)

750 751
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getSingleCategoryMembershipList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
752
    def getSingleCategoryMembershipList(self, context, base_category, base=0,
753
                                         spec=(), filter=None,
754
                                         checked_permission=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
755 756 757 758 759 760 761 762 763 764 765 766
      """
        Returns the local membership of the context for a single base category
        represented as a list of relative URLs

        context       --    the context on which we are looking for categories

        base_category --    a single base category (string)

        spec          --    a list or a tuple of portal types

        base          --    if set to 1, returns relative URLs to portal_categories
                            if set to 0, returns relative URLs to the base category
767

768
        checked_permission        --    a string which defined the permission
769
                                        to filter the object on
Jean-Paul Smets's avatar
Jean-Paul Smets committed
770 771
      """
      # XXX We must use filters in the future
772
      # where_expression = self._buildQuery(spec, filter, kw)
773
      if spec is ():
774
        spec = kw.get('portal_type', ())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
775

776
      # Build the ckecked_permission filter
777
      if checked_permission is not None:
778
        checkPermission = self.getPortalObject().portal_membership.checkPermission
779
        def permissionFilter(category):
780
          object = self.unrestrictedTraverse(category) # XXX Why unrestrictedTraverse and not resolveCategory ?
781 782 783 784
          if object is not None and checkPermission(checked_permission, object):
            return category
          else:
            return None
785

786
      # We must treat parent in a different way
787
      #LOG('getSingleCategoryMembershipList', 0, 'base_category = %s, spec = %s, base = %s, context = %s, context.aq_inner.aq_parent = %s' % (repr(base_category), repr(spec), repr(base), repr(context), repr(context.aq_inner.aq_parent)))
788
      if base_category == 'parent':
789
        parent = context.aq_inner.aq_parent # aq_inner is required to make sure we use containment
790
                                            # just as in Base.getParentValue
791
        if parent.portal_type in spec:
792 793 794
          parent_relative_url = parent.getRelativeUrl()
          if (checked_permission is None) or \
            (permissionFilter(parent_relative_url) is not None):
795 796 797 798 799 800
            # We do not take into account base here
            # because URL categories tend to fail
            # if temp objects are used and generated through
            # traversal (see WebSite and WebSection in ERP5)
            return [parent] # A hack to be able to handle temp objects
            # Previous code bellow for information
801
            if base:
802
              return ['parent/%s' % parent_relative_url] # This will fail if temp objects are used
803
            else:
804
              return [parent_relative_url] # This will fail if temp objects are used
805 806 807
        #LOG('getSingleCategoryMembershipList', 0, 'not in spec: parent.portal_type = %s, spec = %s' % (repr(parent.portal_type), repr(spec)))
        return []

Jean-Paul Smets's avatar
Jean-Paul Smets committed
808
      # XXX We must use filters in the future
809
      # where_expression = self._buildQuery(spec, filter, kw)
810 811
      result = []
      append = result.append
Jean-Paul Smets's avatar
Jean-Paul Smets committed
812
      # Make sure spec is a list or tuple
Yoshinori Okuji's avatar
Yoshinori Okuji committed
813
      if isinstance(spec, str):
814 815 816
        spec = (spec,)
      elif isinstance(spec, list):
        spec = tuple(spec)
817
      spec_len = len(spec)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
818
      # Filter categories
Yoshinori Okuji's avatar
Yoshinori Okuji committed
819
      if getattr(aq_base(context), 'categories', _marker) is not _marker:
820

Jean-Paul Smets's avatar
Jean-Paul Smets committed
821
        for category_url in self._getCategoryList(context):
822
          my_base_category = category_url.split('/', 1)[0]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
823
          if my_base_category == base_category:
824
            category_url = self._removeDuplicateBaseCategoryIdInCategoryPath(my_base_category, category_url)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
825
            #LOG("getSingleCategoryMembershipList",0,"%s %s %s %s" % (context.getRelativeUrl(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
826
            #                  my_base_category, base_category, category_url))
827 828
            if (checked_permission is None) or \
                (permissionFilter(category_url) is not None):
829
              if spec_len == 0:
830 831 832 833
                if base:
                  append(category_url)
                else:
                  append(category_url[len(my_base_category)+1:])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
834
              else:
835 836 837 838 839 840 841 842
                my_reference = self.unrestrictedTraverse(category_url, None)
                if my_reference is not None:
                  if my_reference.portal_type in spec:
                    if base:
                      append(category_url)
                    else:
                      append(category_url[len(my_base_category)+1:])
      return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
843 844 845

    security.declareProtected( Permissions.AccessContentsInformation,
                                      'getSingleCategoryAcquiredMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
846
    def getSingleCategoryAcquiredMembershipList(self, context, base_category, base=0,
847
                                         spec=(), filter=None, _acquired_object_set=None, **kw ):
Julien Muchembled's avatar
Julien Muchembled committed
848 849 850
      # XXX: This cache is rarely useful, and the overhead quite important.
      #      It would certainly become counter-productive if any significative
      #      improvement was done to the cached methods.
851
      cache = getReadOnlyTransactionCache()
852
      if cache is not None:
Julien Muchembled's avatar
Julien Muchembled committed
853 854
        key = ('getSingleCategoryAcquiredMembershipList', context,
               base_category, base, spec, filter, repr(kw))
855 856 857 858
        try:
          return cache[key]
        except KeyError:
          pass
859

860
      result = self._getSingleCategoryAcquiredMembershipList(context, base_category, base=base,
861
                                                             spec=spec, filter=filter,
862
                                                             _acquired_object_set=_acquired_object_set,
863 864 865
                                                             **kw)
      if cache is not None:
        cache[key] = result
866

867
      return result
868

869
    def _filterCategoryListByPermission(self, base_category, base, category_list, permission):
870 871 872 873 874
      """This method returns a category list filtered by a permission.
      If the permission is None, returns a passed list as it is.
      """
      if permission is None:
        return category_list
875
      checkPermission = self.getPortalObject().portal_membership.checkPermission
876 877 878 879 880
      resolveCategory = self.resolveCategory
      new_category_list = []
      append = new_category_list.append
      for category in category_list:
        try:
881 882 883 884 885
          if base:
            category_path = category
          else:
            category_path = '%s/%s' % (base_category, category)
          value = resolveCategory(category_path)
886 887 888 889 890
          if checkPermission(permission, value):
            append(category)
        except Unauthorized:
          pass
      return new_category_list
891

892 893 894
    def _getSingleCategoryAcquiredMembershipList(self, context, base_category,
                                         base = 0, spec = (), filter = None,
                                         acquired_portal_type = (),
895
                                         checked_permission = None,
896
                                         _acquired_object_set=None,
897
                                         **kw ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
898 899 900 901 902 903 904 905 906 907 908 909
      """
        Returns the acquired membership of the context for a single base category
        represented as a list of relative URLs

        context       --    the context on which we are looking for categories

        base_category --    a single base category (string)

        spec          --    a list or a tuple of portal types

        base          --    if set to 1, returns relative URLs to portal_categories
                            if set to 0, returns relative URLs to the base category
910

911
        checked_permission        --    a string which defined the permission
912 913
                                        to filter the object on

914 915
        alt_base_category         --    an alternative base category if the first one fails

916 917 918 919 920 921
        acquisition_copy_value    --    if set to 1, the looked up value will be copied
                            as an attribute of self

        acquisition_mask_value    --    if set to 1, the value of the category of self
                            has priority on the looked up value

922 923 924
        _acquired_object_set is a special, internal parameter to deal with
        recursive calls on the same object.

Jean-Paul Smets's avatar
Jean-Paul Smets committed
925
      """
926 927
      #LOG("Get Acquired Category ",0,str((base_category, context,)))
      #LOG("Get Acquired Category acquired_object_dict: ",0,str(acquired_object_dict))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
928
      # XXX We must use filters in the future
929
      # where_expression = self._buildQuery(spec, filter, kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
930
      portal_type = kw.get('portal_type', ())
931 932
      if spec is ():
        spec = portal_type # This is bad XXX - JPS - spec is for meta_type, not for portal_type - be consistent !
Yoshinori Okuji's avatar
Yoshinori Okuji committed
933
      if isinstance(spec, str):
934 935 936
        spec = (spec,)
      elif isinstance(spec, list):
        spec = tuple(spec)
937

Yoshinori Okuji's avatar
Yoshinori Okuji committed
938
      if isinstance(acquired_portal_type, str):
939 940
        acquired_portal_type = [acquired_portal_type]

941 942
      if _acquired_object_set is None:
        _acquired_object_set = set()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
943
      else:
944 945 946 947 948 949
        uid = context.getUid()
        key = (uid, base_category, tuple(spec))
        if key in _acquired_object_set:
          return []
        _acquired_object_set = _acquired_object_set.copy()
        _acquired_object_set.add(key)
950

Jean-Paul Smets's avatar
Jean-Paul Smets committed
951
      result = self.getSingleCategoryMembershipList( context, base_category, base=base,
952 953
                            spec=spec, filter=filter, **kw ) # Not acquired because this is the first try
                                                             # to get a local defined category
954

955
      base_category_value = self.getCategoryValue(base_category)
956
      #LOG("result", 0, str(result))
957
      if base_category_value is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
958
        # If we do not mask or append, return now if not empty
959 960 961
        if result \
                and base_category_value.getAcquisitionMaskValue() \
                and not base_category_value.getAcquisitionAppendValue():
962
          # If acquisition masks and we do not append values, then we must return now
963
          return self._filterCategoryListByPermission(base_category, base, result, checked_permission)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
964
        # First we look at local ids
965
        for object_id in base_category_value.getAcquisitionObjectIdList():
966 967 968 969
          try:
            my_acquisition_object = context[object_id]
          except (KeyError, AttributeError):
            my_acquisition_object = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
970
          if my_acquisition_object is not None:
971 972 973
            #my_acquisition_object_path = my_acquisition_object.getPhysicalPath()
            #if my_acquisition_object_path in acquired_object_dict:
            #  continue
974
            #acquired_object_dict[my_acquisition_object_path] = 1
975
            if my_acquisition_object.portal_type in base_category_value.getAcquisitionPortalTypeList():
976
              new_result = self.getSingleCategoryAcquiredMembershipList(my_acquisition_object,
977
                  base_category, spec=spec, filter=filter, portal_type=portal_type, base=base, _acquired_object_set=_acquired_object_set)
978 979
            else:
              new_result = []
980 981 982
            #if base_category_value.acquisition_mask_value:
            #  # If acquisition masks, then we must return now
            #  return new_result
983
            if base_category_value.getAcquisitionAppendValue():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
984
              # If acquisition appends, then we must append to the result
Yoshinori Okuji's avatar
Yoshinori Okuji committed
985
              result.extend(new_result)
986
            elif new_result:
987
              return self._filterCategoryListByPermission(base_category, base, new_result, checked_permission) # Found enough information to return
Jean-Paul Smets's avatar
Jean-Paul Smets committed
988
        # Next we look at references
989
        #LOG("Get Acquired BC", 0, base_category_value.getAcquisitionBaseCategoryList())
990
        acquisition_base_category_list = base_category_value.getAcquisitionBaseCategoryList()
991
        alt_base_category_list = base_category_value.getFallbackBaseCategoryList()
992
        all_acquisition_base_category_list = acquisition_base_category_list + alt_base_category_list
993
        acquisition_pt = base_category_value.getAcquisitionPortalTypeList()
994
        for my_base_category in acquisition_base_category_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
995
          # We implement here special keywords
Jean-Paul Smets's avatar
Jean-Paul Smets committed
996
          if my_base_category == 'parent':
997
            parent = context.aq_inner.aq_parent # aq_inner is required to make sure we use containment
998 999 1000
            parent_portal_type = getattr(aq_base(parent), 'portal_type',
                                         _marker)
            if parent_portal_type is _marker:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1001 1002
              my_acquisition_object_list = []
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1003 1004 1005
              #LOG("Parent Object List ",0,str(parent.getRelativeUrl()))
              #LOG("Parent Object List ",0,str(parent.portal_type))
              #LOG("Parent Object List ",0,str(acquisition_pt))
1006 1007
              #my_acquisition_object_path = parent.getPhysicalPath()
              #if my_acquisition_object_path in acquired_object_dict:
1008 1009
              if len(acquisition_pt) == 0 \
                      or parent_portal_type in acquisition_pt:
1010
                my_acquisition_object_list = [parent]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1011 1012 1013
              else:
                my_acquisition_object_list = []
          else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1014
            #LOG('getAcquiredCategoryMembershipList', 0, 'my_acquisition_object = %s, acquired_object_dict = %s' % (str(context), str(acquired_object_dict)))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1015
            my_acquisition_list = self.getSingleCategoryAcquiredMembershipList(context,
1016
                        my_base_category,
1017
                        portal_type=tuple(acquisition_pt),
1018
                        _acquired_object_set=_acquired_object_set)
1019
            my_acquisition_object_list = []
1020 1021 1022 1023 1024 1025 1026
            if my_acquisition_list:
              resolveCategory = self.resolveCategory
              append = my_acquisition_object_list.append
              for c in my_acquisition_list:
                o = resolveCategory(c)
                if o is not None:
                  append(o)
1027 1028
            #my_acquisition_object_list = context.getValueList(my_base_category,
            #                       portal_type=tuple(base_category_value.getAcquisitionPortalTypeList(())))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1029 1030
          #LOG("Get Acquired PT",0,str(base_category_value.getAcquisitionPortalTypeList(())))
          #LOG("Object List ",0,str(my_acquisition_object_list))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1031 1032 1033
          original_result = result
          result = list(result) # make a copy
          for my_acquisition_object in my_acquisition_object_list:
1034
            #LOG('getSingleCategoryAcquiredMembershipList', 0, 'my_acquisition_object = %s, acquired_object_dict = %s' % (str(my_acquisition_object), str(acquired_object_dict)))
1035 1036
            #LOG('getSingleCategoryAcquiredMembershipList', 0, 'my_acquisition_object.__dict__ = %s' % str(my_acquisition_object.__dict__))
            #LOG('getSingleCategoryAcquiredMembershipList', 0, 'my_acquisition_object.__hash__ = %s' % str(my_acquisition_object.__hash__()))
1037
            #if my_acquisition_object is not None:
1038
            if my_acquisition_object is not None:
1039 1040 1041 1042
              #my_acquisition_object_path = my_acquisition_object.getPhysicalPath()
              #if my_acquisition_object_path in acquired_object_dict:
              #  continue
              #acquired_object_dict[my_acquisition_object_path] = 1
1043 1044 1045
              #if hasattr(my_acquisition_object, '_categories'): # This would be a bug since we have category acquisition
                #LOG('my_acquisition_object',0, str(getattr(my_acquisition_object, '_categories', ())))
                #LOG('my_acquisition_object',0, str(base_category))
1046

1047 1048
                # We should only consider objects which define that category
                if base_category in getattr(my_acquisition_object, '_categories', ()) or base_category_value.getFallbackBaseCategoryList():
1049
                  if (not acquired_portal_type) or my_acquisition_object.portal_type in acquired_portal_type:
1050
                    #LOG("Recursive call ",0,str((spec, my_acquisition_object.portal_type)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1051
                    new_result = self.getSingleCategoryAcquiredMembershipList(my_acquisition_object,
1052
                        base_category, spec=spec, filter=filter, portal_type=portal_type, base=base,
1053
                        acquired_portal_type=acquired_portal_type,
1054
                        _acquired_object_set=_acquired_object_set)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1055
                  else:
1056
                    #LOG("No recursive call ",0,str((spec, my_acquisition_object.portal_type)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1057
                    new_result = []
1058
                  if base_category_value.getAcquisitionAppendValue():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1059
                    # If acquisition appends, then we must append to the result
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1060
                    result.extend(new_result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1061
                  elif len(new_result) > 0:
1062
                    #LOG("new_result ",0,str(new_result))
1063 1064
                    if len(original_result) == 0 \
                            and base_category_value.getAcquisitionCopyValue():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1065 1066
                      # If copy is set and result was empty, then copy it once
                      # If sync is set, then copy it again
1067
                      self.setCategoryMembership( context, base_category, new_result,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1068 1069
                                    spec=spec, filter=filter, portal_type=portal_type, base=base )
                    # We found it, we can return
1070
                    return self._filterCategoryListByPermission(base_category, base, new_result, checked_permission)
1071 1072


1073
          if len(result) > 0 \
1074
                  and base_category_value.getAcquisitionCopyValue():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1075 1076
            # If copy is set and result was empty, then copy it once
            # If sync is set, then copy it again
1077
            self.setCategoryMembership( context, base_category, result,
1078 1079 1080 1081 1082
                                         spec=spec, filter=filter,
                                         portal_type=portal_type, base=base )
        fallback_base_category_list \
                = base_category_value.getFallbackBaseCategoryList()
        if len(result) == 0 and len(fallback_base_category_list) > 0:
1083
          # We must then try to use the alt base category
1084 1085 1086 1087 1088
          getSingleCategoryAcquiredMembershipList \
                  = self.getSingleCategoryAcquiredMembershipList
          resolveCategory = self.resolveCategory
          append = result.append
          for base_category in fallback_base_category_list:
1089
            # First get the category list
1090
            category_list = getSingleCategoryAcquiredMembershipList( context, base_category, base=1,
1091
                                 spec=spec, filter=filter, _acquired_object_set=_acquired_object_set, **kw )
1092
            # Then convert it into value
1093
            category_value_list = [resolveCategory(x) for x in category_list]
1094 1095
            # Then build the alternate category
            if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1096 1097
              base_category_id = base_category_value.getId()
              for category_value in category_value_list:
1098
                if category_value is None :
1099 1100
                  message = "category does not exists for %s (%s)"%(
                                       context.getPath(), category_list)
1101
                  LOG('CMFCategory', ERROR, message)
1102
                  raise CategoryError (message)
1103
                else :
1104
                  append('%s/%s' % (base_category_id, category_value.getRelativeUrl()))
1105
            else :
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1106
              for category_value in category_value_list:
1107 1108 1109
                if category_value is None :
                  message = "category does not exists for %s (%s)"%(
                                       context.getPath(), category_list)
1110
                  LOG('CMFCategory', ERROR, message)
1111 1112
                  raise CategoryError (message)
                else :
1113
                  append(category_value.getRelativeUrl())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1114 1115
      # WE MUST IMPLEMENT HERE THE REST OF THE SEMANTICS
      #LOG("Get Acquired Category Result ",0,str(result))
1116
      return self._filterCategoryListByPermission(base_category, base, result, checked_permission)
1117

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1118 1119
    security.declareProtected( Permissions.AccessContentsInformation,
                                               'getAcquiredCategoryMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1120
    def getAcquiredCategoryMembershipList(self, context, base_category = None, base=1,
1121
                                          spec=(), filter=None, _acquired_object_set=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1122 1123 1124
      """
        Returns all acquired category values
      """
1125
      #LOG("Get Acquired Category List", 0, "%s %s" % (base_category, context.getRelativeUrl()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1126
      result = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1127
      extend = result.extend
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1128
      if base_category is None:
1129
        base_category_list = context._categories # XXX incompatible with ERP5Type per portal categories
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1130
      elif isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1131
        base_category_list = [base_category]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1132
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1133
        base_category_list = base_category
1134
      #LOG('CT.getAcquiredCategoryMembershipList base_category_list',0,base_category_list)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1135
      getSingleCategoryAcquiredMembershipList = self.getSingleCategoryAcquiredMembershipList
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1136
      for base_category in base_category_list:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1137
        extend(getSingleCategoryAcquiredMembershipList(context, base_category, base=base,
1138
                                    spec=spec, filter=filter, _acquired_object_set=_acquired_object_set, **kw ))
1139
        #LOG('CT.getAcquiredCategoryMembershipList new result',0,result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1140 1141 1142
      return result

    security.declareProtected( Permissions.AccessContentsInformation, 'isMemberOf' )
1143
    def isMemberOf(self, context, category, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1144 1145 1146
      """
        Tests if an object if member of a given category
        Category is a string here. It could be more than a string (ex. an object)
1147 1148

        Keywords parameters :
1149
         - strict_membership:  if we want strict membership checking
1150
         - strict : alias for strict_membership (deprecated but still here for
1151
                    skins backward compatibility. )
1152

1153 1154 1155
        XXX - there should be 2 different methods, one which acuiqred
        and the other which does not. A complete review of
        the use of isMemberOf is required
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1156
      """
1157
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
1158 1159
      if getattr(aq_base(context), 'isCategory', 0):
        if context.isMemberOf(category, strict_membership=strict_membership):
1160
          return 1
1161
      base_category = category.split('/', 1)[0] # Extract base_category for optimisation
1162
      if strict_membership:
1163
        for c in self.getAcquiredCategoryMembershipList(context, base_category=base_category):
1164
          if c == category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1165 1166
            return 1
      else:
1167 1168 1169
        for c in self.getAcquiredCategoryMembershipList(context, base_category=base_category):
          if c == category or c.startswith(category + '/'):
            return 1
1170 1171
      return 0

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    security.declareProtected( Permissions.AccessContentsInformation, 'isAcquiredMemberOf' )
    def isAcquiredMemberOf(self, context, category):
      """
        Tests if an object if member of a given category
        Category is a string here. It could be more than a string (ex. an object)

        XXX Should include acquisition ?
      """
      if getattr(aq_base(context), 'isCategory', 0):
        return context.isAcquiredMemberOf(category)
1182
      for c in self.getAcquiredCategoryList(context):
1183 1184 1185 1186
        if c.find(category) >= 0:
          return 1
      return 0

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1187 1188
    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryList' )
    def getCategoryList(self, context):
1189 1190 1191
      result = getattr(aq_base(context), 'categories', None)
      if result is not None:
        result = list(result)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1192
      elif isinstance(context, dict):
1193
        return list(context.get('categories', ()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1194 1195 1196
      else:
        result = []
      if getattr(context, 'isCategory', 0):
1197 1198
        category_url = context.getRelativeUrl()
        if category_url not in result:
1199
          result.append(category_url) # Pure category is member of itself
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1200 1201
      return result

1202 1203
    _getCategoryList = getCategoryList

1204 1205 1206 1207 1208
    security.declareProtected( Permissions.ModifyPortalContent, 'setCategoryList' )
    def setCategoryList(self, context, value):
       self._setCategoryList(context, value)
       context.reindexObject()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1209 1210
    security.declareProtected( Permissions.ModifyPortalContent, '_setCategoryList' )
    def _setCategoryList(self, context, value):
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
      old = set(getattr(aq_base(context), 'categories', ()))
      context.categories = value = tuple(value)
      if context.isTempDocument():
        return
      value = set(value)
      relative_url = context.getRelativeUrl()
      for edit, value in ("remove", old - value), ("add", value - old):
        for path in value:
          base = self.getBaseCategoryId(path)
          try:
            if self[base].isRelatedLocallyIndexed():
              path = self._removeDuplicateBaseCategoryIdInCategoryPath(base, path)
              ob = aq_base(self.unrestrictedTraverse(path))
              try:
                related = ob._related_index
              except AttributeError:
                if edit is "remove":
                  continue
                related = ob._related_index = RelatedIndex()
              getattr(related, edit)(base, relative_url)
          except KeyError:
            pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1233 1234 1235 1236

    security.declareProtected( Permissions.AccessContentsInformation, 'getAcquiredCategoryList' )
    def getAcquiredCategoryList(self, context):
      result = self.getAcquiredCategoryMembershipList(context,
1237
                     base_category = self.getBaseCategoryList(context=context))
1238
      for c in self._getCategoryList(context):
1239 1240
        # Make sure all local categories are considered
        if c not in result:
1241
          result.append(c)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1242 1243 1244
      return result

    # Catalog related methods
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1245
    def updateRelatedCategory(self, category, previous_category_url, new_category_url):
1246 1247 1248 1249
      new_category = re.sub('^%s$' %
            previous_category_url,'%s' % new_category_url,category)
      new_category = re.sub('^%s/(?P<stop>.*)' %
            previous_category_url,'%s/\g<stop>' % new_category_url,new_category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1250
      new_category = re.sub('(?P<start>.*)/%s/(?P<stop>.*)' %
1251
            previous_category_url,'\g<start>/%s/\g<stop>' % new_category_url,new_category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1252 1253
      new_category = re.sub('(?P<start>.*)/%s$' %
            previous_category_url,'\g<start>/%s' % new_category_url, new_category)
1254 1255
      return new_category

1256 1257 1258
    def updateRelatedContent(self, context,
                             previous_category_url, new_category_url):
      """Updates related object when an object have moved.
1259

1260 1261 1262 1263 1264 1265
          o context: the moved object
          o previous_category_url: the related url of this object before
            the move
          o new_category_url: the related url of the object after the move

      TODO: make this method resist to very large updates (ie. long transaction)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1266
      """
1267 1268
      for brain in self.Base_zSearchRelatedObjectsByCategory(
                                              category_uid = context.getUid()):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1269
        o = brain.getObject()
1270 1271 1272
        if o is not None:
          category_list = []
          for category in self.getCategoryList(o):
1273 1274 1275
            new_category = self.updateRelatedCategory(category,
                                                      previous_category_url,
                                                      new_category_url)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1276
            category_list.append(new_category)
1277
          self.setCategoryList(o, category_list)
1278

1279 1280
          if getattr(aq_base(o),
                    'notifyAfterUpdateRelatedContent', None) is not None:
1281
            o.notifyAfterUpdateRelatedContent(previous_category_url,
1282 1283 1284 1285
                                              new_category_url) # XXX - wrong programming Approach
                                                                # for ERP5 - either use interaction
                                                                # workflows or interactors rather
                                                                # than creating notifyWhateverMethod
1286

1287
        else:
1288 1289 1290
          LOG('CMFCategory', PROBLEM,
              'updateRelatedContent: %s does not exist' % brain.path)

1291 1292 1293 1294 1295
      for brain in self.Base_zSearchRelatedObjectsByPredicate(
                                              category_uid = context.getUid()):
        o = brain.getObject()
        if o is not None:
          category_list = []
1296
          for category in o.getMembershipCriterionCategoryList():
1297 1298 1299 1300
            new_category = self.updateRelatedCategory(category,
                                                      previous_category_url,
                                                      new_category_url)
            category_list.append(new_category)
1301
          o._setMembershipCriterionCategoryList(category_list)
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316

          if getattr(aq_base(o),
                    'notifyAfterUpdateRelatedContent', None) is not None:
            o.notifyAfterUpdateRelatedContent(previous_category_url,
                                              new_category_url) # XXX - wrong programming Approach
                                                                # for ERP5 - either use interaction
                                                                # workflows or interactors rather
                                                                # than creating notifyWhateverMethod

        else:
          LOG('CMFCategory', PROBLEM,
              'updateRelatedContent: %s does not exist' % brain.path)



1317
      aq_context = aq_base(context)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1318
      # Update related recursively if required
1319
      if getattr(aq_context, 'listFolderContents', None) is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1320
        for o in context.listFolderContents():
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
          new_o_category_url = o.getRelativeUrl()
          # Relative Url is based on parent new_category_url so we must
          # replace new_category_url with previous_category_url to find
          # the new category_url for the subobject
          previous_o_category_url = self.updateRelatedCategory(
                                                   new_o_category_url,
                                                   new_category_url,
                                                   previous_category_url)

          self.updateRelatedContent(o, previous_o_category_url,
                                    new_o_category_url)

    security.declareProtected( Permissions.AccessContentsInformation,
                               'getRelatedValueList' )
1335
    def getRelatedValueList(self, context, base_category_list=None,
1336
                            checked_permission=None, **kw):
1337 1338 1339 1340
      """
        This methods returns the list of objects related to the context
        with the given base_category_list.
      """
1341
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1342
      portal_type = kw.get('portal_type')
1343

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1344
      if isinstance(portal_type, str):
1345
        portal_type = portal_type,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1346

1347
      # Base Category may not be related, besides sub categories
1348 1349 1350 1351
      relative_url = context.getRelativeUrl()
      local_index_dict = {}
      if isinstance(context, BaseCategory):
        category_list = relative_url,
1352
      else:
1353
        category_list = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1354
        if isinstance(base_category_list, str):
1355
          base_category_list = base_category_list,
1356 1357 1358
        elif base_category_list is () or base_category_list is None:
          base_category_list = self.getBaseCategoryList()
        for base_category in base_category_list:
1359 1360 1361 1362 1363 1364 1365 1366
          if self[base_category].isRelatedLocallyIndexed():
            category = base_category + '/'
            local_index_dict[base_category] = '' \
              if relative_url.startswith(category) else category
          else:
            category_list.append("%s/%s" % (base_category, relative_url))

      search = self.getPortalObject().Base_zSearchRelatedObjectsByCategoryList
1367
      result_dict = {}
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
      if local_index_dict:
        # For some base categories, lookup indexes in ZODB.
        recurse = isinstance(context, Category) and not strict_membership
        def check_local():
          r = set(getattr(related, base_category, ()))
          r.difference_update(result_dict)
          for r in r:
            try:
              ob = self.unrestrictedTraverse(r)
              if category in aq_base(ob).categories:
                result_dict[r] = ob
                continue
              # Do not add 'r' to result_dict, because 'ob' may be linked in
              # another way.
            except (AttributeError, KeyError):
              result_dict[r] = None
            related.remove(base_category, r)
        tv = getTransactionalVariable().setdefault(
          'CategoriesTool.getRelatedValueList', {})
        try:
          related = aq_base(context)._related_index
        except AttributeError:
          related = RelatedIndex()
        include_self = False
        for base_category, category in local_index_dict.iteritems():
          if not category:
            # Categories are member of themselves.
            include_self = True
            result_dict[relative_url] = context
          category += relative_url
          if tv.get(category, -1) < recurse:
            # Update local index with results from catalog for backward
            # compatibility. But no need to do it several times in the same
            # transaction.
            for r in search(category_list=category,
                            portal_type=None,
                            strict_membership=strict_membership):
              r = r.relative_url
              # relative_url is empty if object is deleted (but not yet
              # unindexed). Nothing specific to do in such case because
              # category tool won't match.
              try:
                ob = self.unrestrictedTraverse(r)
                categories = aq_base(ob).categories
              except (AttributeError, KeyError):
                result_dict[r] = None
                continue
              if category in categories:
                related.add(base_category, r)
                result_dict[r] = ob
              elif recurse:
                for p in categories:
                  if p.startswith(category + '/'):
                    try:
                      o = self.unrestrictedTraverse(p)
                      p = aq_base(o)._related_index
                    except KeyError:
                      continue
                    except AttributeError:
                      p = o._related_index = RelatedIndex()
                    result_dict[r] = ob
                    p.add(base_category, r)
            tv[category] = recurse
          # Get and check all objects referenced by local index for the base
          # category that is currently considered.
          check_local()
        # Modify context only if it's worth it.
        if related and not hasattr(aq_base(context), '_related_index'):
          context._related_index = related
        # In case of non-strict membership search, include all objects that
        # are linked to a subobject of context.
        if recurse:
          r = [context]
          while r:
            for ob in r.pop().objectValues():
              r.append(ob)
              relative_url = ob.getRelativeUrl()
              if include_self:
                result_dict[relative_url] = ob
              try:
                related = aq_base(ob)._related_index
              except AttributeError:
                continue
              for base_category, category in local_index_dict.iteritems():
                category += relative_url
                check_local()
        # Filter out objects that are not of requested portal type.
        result = [ob for ob in result_dict.itervalues() if ob is not None and (
          not portal_type or ob.getPortalType() in portal_type)]
        # Finish with base categories that are only indexed in catalog,
        # making sure we don't return duplicate values.
1459
      else:
1460 1461
        # Catalog-only search.
        result = []
1462
      if category_list:
1463 1464 1465
        for r in search(category_list=category_list,
                        portal_type=portal_type,
                        strict_membership=strict_membership):
1466 1467 1468 1469 1470
          if r.relative_url not in result_dict:
            try:
              result.append(self.unrestrictedTraverse(r.path))
            except KeyError:
              pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1471

1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
      if checked_permission is None:
        return result

      # Check permissions on object
      if isinstance(checked_permission, str):
        checked_permission = checked_permission,
      checkPermission = self.portal_membership.checkPermission
      def check(ob):
        for permission in checked_permission:
          if checkPermission(permission, ob):
            return True
      return filter(check, result)
1484

1485 1486 1487
    security.declareProtected( Permissions.AccessContentsInformation,
                               'getRelatedPropertyList' )
    def getRelatedPropertyList(self, context, base_category_list=None,
1488
                               property_name=None,
1489
                               checked_permission=None, **kw):
1490 1491 1492 1493 1494
      """
        This methods returns the list of property_name on  objects
        related to the context with the given base_category_list.
      """
      result = []
1495 1496
      for o in self.getRelatedValueList(
                          context=context,
1497
                          base_category_list=base_category_list,
1498
                          checked_permission=checked_permission, **kw):
1499 1500
        result.append(o.getProperty(property_name, None))
      return result
1501

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1502 1503
    # SQL Expression Building
    security.declareProtected(Permissions.AccessContentsInformation, 'buildSQLSelector')
1504
    def buildSQLSelector(self, category_list, query_table='category', none_sql_value=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1505 1506 1507 1508
      """
        Returns an SQL selector expression from a list of categories
        We make here a simple method wich simply checks membership
        This is like an OR. More complex selections (AND of OR) will require
1509
        to generate a much more complex where_expression with table aliases
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1510 1511

        List of lists
1512 1513 1514

        - none_sql_value is used in order to specify what is the None value into
          sql tables
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1515
      """
1516 1517 1518 1519 1520 1521 1522
      result = self.buildAdvancedSQLSelector(category_list, query_table,
                 none_sql_value, strict=False)['where_expression']
      # Quirk to keep strict backward compatibility. Should be removed when
      # tested.
      if result == '':
        result = []
      return result
1523

1524 1525 1526 1527
    # SQL Expression Building
    security.declareProtected(Permissions.AccessContentsInformation, 'buildAdvancedSQLSelector')
    def buildAdvancedSQLSelector(self, category_list, query_table='category',
          none_sql_value=None, strict=True, catalog_table_name='catalog'):
1528 1529 1530 1531
      # XXX: about "strict" parameter: This is a transition parameter,
      # allowing someone hitting a bug to revert to original behaviour easily.
      # It is not a correct name, as pointed out by Jerome. But instead of
      # searching for another name, it would be much better to just remove it.
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
      """
        Return chunks of SQL to check for category membership.

        none_sql_value (default=None):
          Specify the SQL value of None in SQL.
          None means SQL NULL.

        strict (boolean, default=True):
          False:
            Resulting query will match any document which matches at least one
            of given categories.
          True:
            Resulting query will match any document which matches all given
            categories, except for categories which are not defined on the
            document. This usefull for example for predicates, where one wants
            to fetch all predicates applicable for a given set of conditions,
            including generic predicates which check only a subset of those
            conditions.
            Performance hint: Order given category list to have most
            discriminant factors before lesser discriminant ones.
      """
      result = {}
Vincent Pelletier's avatar
Vincent Pelletier committed
1554 1555 1556
      def renderUIDValue(uid):
        uid = ((uid is None) and (none_sql_value, ) or (uid, ))[0]
        if uid is None:
1557
          return 'NULL'
Vincent Pelletier's avatar
Vincent Pelletier committed
1558
        else:
1559 1560 1561 1562 1563 1564
          return '%s' % (uid, )
      def renderUIDWithOperator(uid):
        value = renderUIDValue(uid)
        if value == 'NULL':
          return 'IS NULL'
        return '= %s' % (value, )
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1565
      if isinstance(category_list, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1566
        category_list = [category_list]
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
      if strict:
        category_uid_dict = {}
        ordered_base_category_uid_list = []
        # Fetch all category and base category uids, and regroup by
        # base_category.
        for category in category_list:
          if isinstance(category, str) and category:
            base_category_uid = self.getBaseCategoryUid(category)
            category_uid_list = category_uid_dict.setdefault(base_category_uid, [])
            if len(category_uid_list) == 0:
              # New base category, append it to the ordered list.
              ordered_base_category_uid_list.append(base_category_uid)
1579 1580 1581 1582 1583 1584 1585 1586
            category_uid = self.getCategoryUid(category)
            category_uid_list.append(category_uid)

          if category_uid is None and category != 'NULL':
            raise TypeError(
              "Invalid category passed to buildAdvancedSQLSelector: %r"
                % category )

1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
        # Generate "left join" and "where" expressions.
        left_join_list = [catalog_table_name]
        where_expression_list = []
        format_dict = {'catalog': catalog_table_name}
        for base_category_uid in ordered_base_category_uid_list:
          alias_name = 'base_%s' % (base_category_uid, )
          format_dict['alias'] = alias_name
          format_dict['condition'] = renderUIDWithOperator(base_category_uid)
          left_join_list.append(
            '`%(alias)s` ON (`%(catalog)s`.uid = `%(alias)s`.uid AND '\
            '`%(alias)s`.category_strict_membership = "1" AND '\
            '`%(alias)s`.base_category_uid %(condition)s)' % format_dict)
          category_uid_name = '`%s`.category_uid' % (alias_name, )
          category_uid_list = category_uid_dict[base_category_uid]
          if category_uid_list == [None]:
            # Only one UID and it's None: do not allow NULL value to be selected.
            where_expression_list.append('(%s %s)' % \
              (category_uid_name, renderUIDWithOperator(base_category_uid)))
          else:
            # In any other case, allow it.
Sebastien Robin's avatar
Sebastien Robin committed
1607 1608
            where_expression_list.append('(%s IS NULL OR %s = 0 OR %s IN (%s))' % \
              (category_uid_name, category_uid_name, category_uid_name,
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
               ', '.join([renderUIDValue(x) for x in category_uid_list])))
        result['from_expression'] = {catalog_table_name:
          ('\nLEFT JOIN `%s` AS ' % (query_table, )).join(left_join_list)}
        result['where_expression'] = '(%s)' % (' AND '.join(where_expression_list), )
      else:
        result['where_expression'] = \
          ' OR '.join(['(%s.category_uid %s AND %s.base_category_uid %s)' %\
                       (query_table, renderUIDWithOperator(self.getCategoryUid(x)),
                        query_table, renderUIDWithOperator(self.getBaseCategoryUid(x)))
                       for x in category_list if isinstance(x, str) and x])
      return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1620 1621

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberValueList' )
1622 1623
    def getCategoryMemberValueList(self, context, base_category=None,
                                         portal_type=(), strict_membership=False, strict=False, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1624 1625 1626
      """
      This returns a catalog_search resource with can then be used by getCategoryMemberItemList
      """
Kevin Deldycke's avatar
Kevin Deldycke committed
1627
      if base_category is None:
1628
        base_category = context.getBaseCategoryId()
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
      if context.portal_type == 'Base Category' and context.getId() == base_category:
        # Looking for all documents which are member of context a
        # (Base Category) via a relationship of its own type: assume this means
        # caller wants to retrieve documents having any document related via a
        # relationship of the type of context.
        # XXX: ignoring "strict*" argument. It does not have much meaning in
        # this case anyway.
        key = 'category.base_category_uid'
      else:
        key = (
1639 1640 1641
          'strict_'
          if strict_membership or strict else
          'default_'
1642 1643 1644
        ) + base_category + '_uid'
      sql_kw = {
        key: context.getUid(),
1645 1646 1647 1648
      }
      if portal_type:
        sql_kw['portal_type'] = portal_type
      return self.getPortalObject().portal_catalog(**sql_kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1649 1650

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberItemList' )
1651
    def getCategoryMemberItemList(self, context, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1652
      """
1653 1654 1655
      This returns a list of items belonging to a category.
      The following parameters are accepted :
        portal_type       : returns only objects from the given portal_type
1656
        strict_membership : returns only object belonging to this category, not
1657 1658
                            objects belonging to child categories.
        strict            : a deprecated alias for strict_membership
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1659
      """
1660 1661 1662 1663 1664 1665
      return Renderer(**kw).render(self.getCategoryMemberValueList(
        context,
        portal_type=kw.get('portal_type'),
        strict_membership=kw.get('strict_membership'),
        strict=kw.get('strict'),
      ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1666 1667 1668

    security.declareProtected( Permissions.AccessContentsInformation,
                                                                'getCategoryMemberTitleItemList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1669
    def getCategoryMemberTitleItemList(self, context, base_category = None,
1670
                                      spec = (), filter=None, portal_type=(), strict_membership = 0,
1671
                                      strict="DEPRECATED"):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1672 1673 1674 1675
      """
      This returns a title list of items belonging to a category

      """
1676
      return self.getCategoryMemberItemList(self, context, base_category = base_category,
1677
                                spec = spec, filter=filter, portal_type=portal_type,
1678
                                strict_membership = strict_membership, strict = strict,
1679
                                display_id = 'title')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1680

1681
    security.declarePublic('resolveCategory')
1682
    def resolveCategory(self, relative_url):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1683 1684
        """
          Finds an object from a relative_url
1685
          Method is public since we use restrictedTraverse
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1686
        """
1687 1688 1689
        return self._resolveCategory(relative_url, True)

    def _resolveCategory(self, relative_url, restricted=False):
1690 1691 1692
        if not isinstance(relative_url, str):
          # Handle parent base category is a special way
          return relative_url
1693
        cache = getReadOnlyTransactionCache()
1694
        if cache is not None:
1695
          cache_key = ('resolveCategory', relative_url)
1696
          try:
1697
            return cache[cache_key]
1698 1699
          except KeyError:
            pass
1700

1701 1702 1703 1704 1705 1706 1707
        # This below is complicated, because we want to avoid acquisitions
        # in most cases, but we still need to restrict the access.
        # For instance, if the relative url is source/person_module/yo,
        # only person_module should be acquired. This becomes very critical,
        # for example, with source/sale_order_module/1/1/1, because
        # we do not want to acquire a Sale Order when a Line or a Cell is
        # not present.
1708
        #
1709 1710 1711
        # I describe my own idea about the categorisation system in ERP5
        # here, because I think it is important to understand why
        # resolveCategory is implemented in this way.
1712
        #
1713 1714 1715 1716 1717 1718 1719 1720 1721
        # The goal of resolveCategory is to provide either a conceptual
        # element or a concrete element from a certain viewpoint. There
        # are 5 different actors in this system:
        #
        #   - Categorisation Utility (= Category Tool)
        #   - Abstract concept (= Base Category)
        #   - Certain view (= Category)
        #   - Classification of documents (= Module or Tool)
        #   - Document (= Document)
1722
        #
1723 1724 1725 1726
        # Categories are conceptually a tree structure with the root
        # of Category Tool. The next level is always Base Categories,
        # to represent abstract concepts. The deeper going down in a tree,
        # the more concrete a viewpoint is.
1727
        #
1728 1729 1730 1731 1732
        # Base Categories may contain other Base Categories, because an
        # abstract concept can be a part of another abstract concept,
        # simply representing a multi-level concept. Base Categories may
        # contain Categories, because an abstract concept gets more concrete.
        # This is the same for Modules and Tools.
1733
        #
1734 1735 1736 1737 1738
        # Categories may contain Categories only in a way that views
        # are more concrete downwards. Thus a category may not acquire
        # a Base Category or a upper-level category. Also, Categories
        # may not contain Modules or Tools, because they don't narrow
        # views.
1739
        #
1740 1741 1742 1743 1744 1745 1746 1747
        # In a sense, Modules and Tools are similar to Categories,
        # as they do narrow things down, but they are fundamentally
        # different from Categories, because their purpose is to
        # classify data processed based on business or system procedures,
        # while Categories provide a backbone of supporting such
        # procedures by more abstract viewpoints. The difference between
        # Modules and Tools are about whether procedures are business
        # oriented or system oriented.
1748
        #
1749 1750
        # Documents may contain Documents, but only to a downward direction.
        # Otherwise, things get more abstract in a tree.
1751
        #
1752 1753 1754 1755 1756 1757 1758
        # According to those ideas, the current implementation may not
        # always behave correctly, because you can resolve a category
        # which violates the rules. For example, you can resolve
        # 'base_category/portal_categories'. This is an artifact,
        # and can be considered as a bug. In the future, Tools and Modules
        # should be clarified if they should behave as Category-like
        # objects, so that the resolver can detect violations.
1759 1760 1761 1762 1763
        if isinstance(relative_url, basestring):
          stack = relative_url.split('/')
        else:
          stack = list(relative_url)
        stack.reverse()
1764
        __traceback_info__ = relative_url
1765

1766 1767 1768 1769 1770 1771
        if restricted:
          validate = getSecurityManager().validate
          def getOb(container):
            obj = container._getOb(key, None)
            if obj is None or validate(container, container, key, obj):
              return obj
Julien Muchembled's avatar
Julien Muchembled committed
1772
            raise Unauthorized('unauthorized access to element %s' % key)
1773 1774 1775
        else:
          def getOb(container):
            return container._getOb(key, None)
1776 1777 1778 1779

        # XXX Currently, resolveCategory accepts that a category might
        # not start with a Base Category, but with a Module. This is
        # probably wrong. For compatibility, this behavior is retained.
1780 1781
        # JPS: I confirm that category should always start with a base
        # category
1782 1783 1784 1785
        obj = self
        if stack:
          portal = aq_inner(self.getPortalObject())
          key = stack.pop()
1786
          obj = getOb(self)
1787
          if obj is None:
1788
            obj = getOb(portal)
1789 1790 1791 1792 1793 1794
            if obj is not None:
              obj = obj.__of__(self)
          else:
            while stack:
              container = obj
              key = stack.pop()
1795
              obj = getOb(container)
1796 1797
              if obj is not None:
                break
1798
              obj = getOb(self)
1799
              if obj is None:
1800
                obj = getOb(portal)
1801 1802 1803 1804 1805 1806
                if obj is not None:
                  obj = obj.__of__(container)
                break

          while obj is not None and stack:
            key = stack.pop()
1807
            obj = getOb(obj)
1808 1809

        if obj is None:
1810
          LOG('CMFCategory', WARNING,
1811
              'Could not get object %s' % relative_url)
1812

1813
        if cache is not None:
1814
          cache[cache_key] = obj
1815

1816
        return obj
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1817

Sebastien Robin's avatar
Sebastien Robin committed
1818 1819 1820 1821 1822 1823
    # Use Base class's methods for properties instead of patched PropertyManager's
    _propertyMap = Base._propertyMap
    _setProperty = Base._setProperty
    getProperty = Base.getProperty
    hasProperty = Base.hasProperty

1824 1825 1826 1827 1828 1829 1830
    def _removeDuplicateBaseCategoryIdInCategoryPath(self, base_category_id,
                                                     path):
      """Specific Handling to remove duplicated base_categories in path
      values like in following example: 'region/region/europe/west'.
      """
      splitted_path = path.split('/', 2)
      if len(splitted_path) >= 2 and base_category_id == splitted_path[1]:
1831 1832
        # Duplicate found, strip len(base_category_id + '/') in path
        path = path[len(base_category_id)+1:]
1833 1834 1835
      return path


Jean-Paul Smets's avatar
Jean-Paul Smets committed
1836 1837 1838
InitializeClass( CategoryTool )

# Psyco
1839
from Products.ERP5Type.PsycoWrapper import psyco
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1840
psyco.bind(CategoryTool)