CategoryTool.py 72.7 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#
# 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.
"""

from OFS.Folder import Folder
from Products.CMFCore.utils import UniqueObject
from Globals import InitializeClass, DTMLFile
from AccessControl import ClassSecurityInfo
37
from AccessControl import Unauthorized, getSecurityManager
38
from Acquisition import aq_base, aq_inner
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39 40
from Products.ERP5Type import Permissions
from Products.ERP5Type.Base import Base
41
from Products.ERP5Type.Cache import getReadOnlyTransactionCache
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42 43
from Products.CMFCategory import _dtmldir
from Products.CMFCore.PortalFolder import ContentFilter
44
from Products.CMFCategory.Renderer import Renderer
45
from OFS.Traversable import NotFound
Jean-Paul Smets's avatar
Jean-Paul Smets committed
46

47
import re
Jean-Paul Smets's avatar
Jean-Paul Smets committed
48

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

Yoshinori Okuji's avatar
Yoshinori Okuji committed
51 52
_marker = object()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
class CategoryError( Exception ):
    pass

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
78 79 80 81
      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
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

        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'
100
    portal_type     = 'Category Tool'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    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):
      return apply( ContentFilter, (), self._buildFilter(spec, filter, kw) )

    # Category accessors
152
    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryList')
153
    def getBaseCategoryList(self, context=None, sort=False):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
154 155 156 157 158 159 160 161 162 163 164 165
      """
        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:
166
        result = self.objectIds()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
167
      else:
168 169 170 171 172
        # XXX Incompatible with ERP5Type per portal type categories
        result = context._categories[:]
      if sort:
        result.sort()
      return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
173 174

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryIds')
175
    getBaseCategoryIds = getBaseCategoryList
Jean-Paul Smets's avatar
Jean-Paul Smets committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

    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
196
        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
197 198 199 200 201 202 203 204 205 206 207 208 209 210

    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
      """
211
      cache = getReadOnlyTransactionCache(self)
212 213 214 215 216 217
      if cache is not None:
        key = ('getCategoryValue', relative_url, base_category)
        try:
          return cache[key]
        except KeyError:
          pass
218

Jean-Paul Smets's avatar
Jean-Paul Smets committed
219 220 221
      try:
        relative_url = str(relative_url)
        if base_category is not None:
Romain Courteaud's avatar
Romain Courteaud committed
222 223
          relative_url = '%s/%s' % (base_category, relative_url)
        node = self.unrestrictedTraverse(relative_url)
224
        value = node
225
      except (TypeError, KeyError, NotFound):
226
        value = None
227

228 229 230 231
      if cache is not None:
        cache[key] = value

      return value
232

Romain Courteaud's avatar
Romain Courteaud committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
#     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
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

    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
279
        return relative_url.split('/', 1)[0]
280
      except KeyError :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
281 282 283 284 285 286 287 288 289 290 291
        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
292
      except (AttributeError, KeyError):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
293 294 295 296 297
        return None

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryParentUidList')
    def getCategoryParentUidList(self, relative_url, base_category = None, strict=0):
      """
298 299 300 301 302 303 304
        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
305 306 307 308 309 310 311 312

        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
      """
      uid_dict = {}
Yoshinori Okuji's avatar
Yoshinori Okuji committed
313 314
      if isinstance(relative_url, str):
        relative_url = (relative_url,)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
315 316 317 318
      for path in relative_url:
        try:
          o = self.getCategoryValue(path, base_category=base_category)
          if o is not None:
319 320
            my_base_category = self.getBaseCategoryId(path)
            bo = self.get(my_base_category, None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
321 322 323 324 325 326 327 328 329
            if bo is not None:
              bo_uid = int(bo.getUid())
              uid_dict[(int(o.uid), bo_uid, 1)] = 1 # Strict Membership
              if o.meta_type == 'CMF Category' or o.meta_type == 'CMF Base Category':
                # This goes up in the category tree
                # XXX we should also go up in some other cases....
                # ie. when some documents act as categories
                if not strict:
                  while o.meta_type == 'CMF Category':
330
                    o = o.aq_parent # We want acquisition here without aq_inner
Jean-Paul Smets's avatar
Jean-Paul Smets committed
331
                    uid_dict[(int(o.uid), bo_uid, 0)] = 1 # Non Strict Membership
332
        except (KeyError, AttributeError):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
          LOG('WARNING: CategoriesTool',0, 'Unable to find uid for %s' % path)
      return uid_dict.keys()

    security.declareProtected(Permissions.AccessContentsInformation, 'getUids')
    getUids = getCategoryParentUidList

    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:
372
        base_category_list = self.getBaseCategoryList()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
373
      elif isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
374 375 376 377 378 379 380
        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
381
          result.extend(category.getCategoryChildRelativeUrlList(base=base,recursive=recursive))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
382 383 384
      return result

    security.declareProtected(Permissions.AccessContentsInformation, 'getPathList')
385 386 387 388
    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
389 390 391 392

    security.declareProtected(Permissions.AccessContentsInformation,
                                                      'getCategoryChildTitleItemList')
    def getCategoryChildTitleItemList(self, base_category=None,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
393
                                recursive=1, base=0, display_none_category=0, sort_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
394 395 396 397
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getTitle as default method
      """
398
      return self.getCategoryChildItemList(base_category=base_category, recursive = recursive,base=base,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
399
       display_none_category=display_none_category,display_id='getTitle', sort_id=sort_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
400 401

    security.declareProtected(Permissions.AccessContentsInformation,
402
                              'getCategoryChildIdItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
403
    def getCategoryChildIdItemList(self, base_category=None,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
404
              recursive=1, base=0, display_none_category=0, sort_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
405 406 407 408
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getId as default method
      """
409 410 411 412 413 414 415
      return self.getCategoryChildItemList(
                          base_category=base_category,
                          recursive = recursive,
                          base=base,
                          display_none_category=display_none_category,
                          display_id='getId',
                          sort_id=sort_id )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
416 417

    security.declareProtected(Permissions.AccessContentsInformation,
418
                              'getCategoryChildItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
419
    def getCategoryChildItemList(self, base_category=None, display_id = None,
420
          recursive=1, base=0, display_none_category=1, sort_id=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
421 422 423 424
      """
      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
425
        (c.relative_url,c.display_id())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
426 427 428 429 430 431 432 433 434 435

      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
436
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
437 438

      recursive -- if set to 0 do not apply recursively
439 440

      See Category.getCategoryChildItemList for extra accepted arguments
Jean-Paul Smets's avatar
Jean-Paul Smets committed
441
      """
442
      if isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
443 444
        base_category_list = [base_category]
      elif base_category is None:
445
        base_category_list = self.getBaseCategoryList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
446 447
      else:
        base_category_list = base_category
Jean-Paul Smets's avatar
Jean-Paul Smets committed
448
      if display_none_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
449 450 451 452 453 454
        result = [('', '')]
      else:
        result = []
      for base_category in base_category_list:
        category = self[base_category]
        if category is not None:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
455
          result.extend(category.getCategoryChildItemList(
456 457 458
                               base=base,
                               recursive=recursive,
                               display_id=display_id,
Yoshinori Okuji's avatar
Yoshinori Okuji committed
459
                               **kw ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
460 461
      return result

462 463
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getBaseItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
464 465 466 467
    getBaseItemList = getCategoryChildItemList

    # Category to Tuple Conversion
    security.declareProtected(Permissions.View, 'asItemList')
Sebastien Robin's avatar
Sebastien Robin committed
468
    def asItemList(self, relative_url, base_category=None,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
469 470
      """
      Returns a list of tuples, each tuple is calculated by applying
Jean-Paul Smets's avatar
Jean-Paul Smets committed
471
      display_id on each category provided in relative_url
Jean-Paul Smets's avatar
Jean-Paul Smets committed
472 473 474 475 476 477 478 479 480 481

      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
482
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
483 484 485

      recursive -- if set to 0 do not apply recursively
      """
Sebastien Robin's avatar
Sebastien Robin committed
486 487 488 489
      #if display_id is None:
      #  for c in relative_url:
      #    result += [(c, c)]
      #else:
Romain Courteaud's avatar
Romain Courteaud committed
490
#       LOG('CMFCategoryTool.asItemList, relative_url',0,relative_url)
Sebastien Robin's avatar
Sebastien Robin committed
491 492 493
      value_list = []
      for c in relative_url:
        o = self.getCategoryValue(c, base_category=base_category)
Romain Courteaud's avatar
Romain Courteaud committed
494
#         LOG('CMFCategoryTool.asItemList, (o,c)',0,(o,c))
Sebastien Robin's avatar
Sebastien Robin committed
495 496 497 498
        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
499 500 501 502

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

Romain Courteaud's avatar
Romain Courteaud committed
503
#       LOG('CMFCategoryTool.asItemList, value_list',0,value_list)
Sebastien Robin's avatar
Sebastien Robin committed
504
      return Renderer(base_category=base_category,**kw).render(value_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
505 506 507 508 509 510 511

    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
512
      if isinstance(category_list, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
513
        category_list = [category_list]
Yoshinori Okuji's avatar
Yoshinori Okuji committed
514
      if category_list is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
515 516 517
        category_list = []
      new_list = []
      for v in category_list:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
518
        new_list.append('%s/%s' % (base_category, v))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
519 520 521 522 523 524 525 526 527 528 529
      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,
530
                                  spec=(), filter=None, **kw  ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544
      """
        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
545
      # where_expression = self._buildQuery(spec, filter, kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
546 547 548 549 550 551
      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
552
      if not isinstance(base_category, (tuple, list)):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
553 554 555
        category_list = [base_category]
      else:
        category_list = base_category
Yoshinori Okuji's avatar
Yoshinori Okuji committed
556
      if not isinstance(spec, (tuple, list)):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
557 558 559
        spec = [spec]
      for path in self._getCategoryList(context):
        # LOG('getCategoryMembershipList',0,str(path))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
560
        my_base_category = path.split('/', 1)[0]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
561
        for my_category in category_list:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
562
          if isinstance(my_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
563 564 565 566 567 568
            category = my_category
          else:
            category = my_category.getRelativeUrl()
          if my_base_category == category:
            if spec is ():
              if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
569
                membership.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
570
              else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
571
                membership.append(path[len(category)+1:])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
572 573 574 575 576 577
            else:
              try:
               o = self.unrestrictedTraverse(path)
               # LOG('getCategoryMembershipList',0,str(o.portal_type))
               if o.portal_type in spec:
                if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
578
                  membership.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
579
                else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
580 581
                  membership.append(path[len(category)+1:])
              except KeyError:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
582 583 584 585 586 587
                LOG('WARNING: CategoriesTool',0, 'Unable to find object for path %s' % path)
      # We must include parent if specified explicitely
      if 'parent' in category_list:
        parent = context.aq_parent
        if parent.portal_type in spec:
          if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
588
            membership.append('parent/' + parent.getRelativeUrl())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
589
          else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
590
            membership.append(parent.getRelativeUrl())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
591 592 593 594
      return membership

    security.declareProtected( Permissions.AccessContentsInformation, 'setCategoryMembership' )
    def setCategoryMembership(self, context, base_category_list, category_list, base=0, keep_default=1,
595 596
                                 spec=(), filter=None,
                                 checked_permission=None, **kw ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
597 598 599 600 601 602 603 604 605 606 607 608 609
      """
        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

610 611 612
        checked_permission        --    a string which defined the permission 
                                        to filter the object on

Jean-Paul Smets's avatar
Jean-Paul Smets committed
613
      """
614 615
#       LOG("CategoryTool, setCategoryMembership", 0 ,
#           'category_list: %s' % str(category_list))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
616
      # XXX We must use filters in the future
617
      # where_expression = self._buildQuery(spec, filter, kw)
618
      if spec is ():
619 620 621
        portal_type = kw.get('portal_type', ())
        if isinstance(portal_type, str):
          portal_type = (portal_type,)
622
        spec = portal_type
623

Jean-Paul Smets's avatar
Jean-Paul Smets committed
624
      self._cleanupCategories(context)
625

Yoshinori Okuji's avatar
Yoshinori Okuji committed
626
      if isinstance(category_list, str):
627
        category_list = (category_list, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
628 629
      elif category_list is None:
        category_list = ()
630 631 632
      elif isinstance(category_list, (list, tuple)):
        pass
      else:
633 634 635
        raise TypeError, 'Category must be of string, tuple of string ' \
                         'or list of string type.'

Yoshinori Okuji's avatar
Yoshinori Okuji committed
636
      if isinstance(base_category_list, str):
637 638 639 640 641 642 643 644 645 646 647
        base_category_list = (base_category_list, )

      # Build the ckecked_permission filter
      if checked_permission is not None:
        checkPermission = self.portal_membership.checkPermission
        def permissionFilter(obj):
          if checkPermission(checked_permission, obj):
            return 0
          else:
            return 1

Jean-Paul Smets's avatar
Jean-Paul Smets committed
648
      new_category_list = []
649
      default_dict = {}
Jean-Paul Smets's avatar
Jean-Paul Smets committed
650 651
      for path in self._getCategoryList(context):
        my_base_id = self.getBaseCategoryId(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
652
        if my_base_id not in base_category_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
653 654
          # Keep each membership which is not in the
          # specified list of base_category ids
655
          new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
656
        else:
657 658 659 660 661 662 663 664 665 666 667 668 669
          keep_it = 0
          if (spec is not ()) or (checked_permission is not None):
            obj = self.unrestrictedTraverse(path, None)
            if obj is not None:
              if spec is not ():
                # If spec is (), then we should keep nothing
                # Everything will be replaced
                # If spec is not (), Only keep this if not in our spec
                  my_type = obj.portal_type
                  keep_it = (my_type not in spec)
              if (not keep_it) and (checked_permission is not None):
                keep_it = permissionFilter(obj)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
670
          if keep_it:
671
            new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
672 673 674 675 676 677 678 679 680 681
          elif keep_default:
            # We must remember the default value
            # for each replaced category
            if not default_dict.has_key(my_base_id):
              default_dict[my_base_id] = path
      # We now create a list of default category values
      default_new_category_list = []
      for path in default_dict.values():
        if base or len(base_category_list) > 1:
          if path in category_list:
682
            default_new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
683 684
        else:
          if path[len(base_category_list[0])+1:] in category_list:
685
            default_new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
686 687 688 689
      # Before we append new category values (except default values)
      # We must make sure however that multiple links are possible
      default_path_found = {}
      for path in category_list:
690
        if path != '':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
691 692 693 694 695
          if base or len(base_category_list) > 1:
            # Only keep path which are member of base_category_list
            if self.getBaseCategoryId(path) in base_category_list:
              if path not in default_new_category_list or default_path_found.has_key(path):
                default_path_found[path] = 1
696
                new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
697
          else:
698
            new_path = '%s/%s' % (base_category_list[0], path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
699
            if new_path not in default_new_category_list:
700
              new_category_list.append(new_path)
701 702 703 704
#       LOG("CategoryTool, setCategoryMembership", 0 ,
#           'new_category_list: %s' % str(new_category_list))
#       LOG("CategoryTool, setCategoryMembership", 0 ,
#           'default_new_category_list: %s' % str(default_new_category_list))
705
      self.setCategoryList(context, tuple(default_new_category_list + new_category_list))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
706

707

Jean-Paul Smets's avatar
Jean-Paul Smets committed
708 709
    security.declareProtected( Permissions.AccessContentsInformation, 'setDefaultCategoryMembership' )
    def setDefaultCategoryMembership(self, context, base_category, default_category,
710 711 712
                                              spec=(), filter=None,
                                              portal_type=(), base=0,
                                              checked_permission=None ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
713 714 715 716 717 718 719 720 721 722 723 724 725
      """
        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

726 727 728
        checked_permission        --    a string which defined the permission 
                                        to filter the object on

Jean-Paul Smets's avatar
Jean-Paul Smets committed
729 730
      """
      self._cleanupCategories(context)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
731
      if isinstance(default_category, (tuple, list)):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
732 733 734 735 736 737 738 739 740
        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:
741
        if category == default_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
742
          found_one = 1
743
        elif category != default_category or found_one:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
744
          new_category_list.append(category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
745 746 747
      self.setCategoryMembership(context, base_category, new_category_list,
           spec=spec, filter=filter, portal_type=portal_type, base=base, keep_default = 0)

748 749
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getSingleCategoryMembershipList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
750
    def getSingleCategoryMembershipList(self, context, base_category, base=0,
751 752
                                         spec=(), filter=None, 
                                         checked_permission=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
753 754 755 756 757 758 759 760 761 762 763 764
      """
        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
765 766 767

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

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

785
      # We must treat parent in a different way
786
      #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)))
787
      if base_category == 'parent':
788
        parent = context.aq_inner.aq_parent # aq_inner is required to make sure we use containment
789
        if parent.portal_type in spec:
790 791 792 793
          parent_relative_url = parent.getRelativeUrl()
          if (checked_permission is None) or \
            (permissionFilter(parent_relative_url) is not None):
            if base:
794
              return ['parent/%s' % parent_relative_url]
795
            else:
796
              return [parent_relative_url]
797 798 799
        #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
800
      # XXX We must use filters in the future
801
      # where_expression = self._buildQuery(spec, filter, kw)
802 803
      result = []
      append = result.append
Jean-Paul Smets's avatar
Jean-Paul Smets committed
804
      # Make sure spec is a list or tuple
Yoshinori Okuji's avatar
Yoshinori Okuji committed
805
      if isinstance(spec, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
806 807
        spec = [spec]
      # Filter categories
Yoshinori Okuji's avatar
Yoshinori Okuji committed
808
      if getattr(aq_base(context), 'categories', _marker) is not _marker:
809

Jean-Paul Smets's avatar
Jean-Paul Smets committed
810
        for category_url in self._getCategoryList(context):
811 812 813 814 815
          try:
            index = category_url.index('/')
            my_base_category = category_url[:index]
          except ValueError:
            my_base_category = category_url
Jean-Paul Smets's avatar
Jean-Paul Smets committed
816
          if my_base_category == base_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
817
            #LOG("getSingleCategoryMembershipList",0,"%s %s %s %s" % (context.getRelativeUrl(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
818
            #                  my_base_category, base_category, category_url))
819 820 821 822 823 824 825
            if (checked_permission is None) or \
                (permissionFilter(category_url) is not None):
              if spec is ():
                if base:
                  append(category_url)
                else:
                  append(category_url[len(my_base_category)+1:])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
826
              else:
827 828 829 830 831 832 833 834
                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
835 836 837

    security.declareProtected( Permissions.AccessContentsInformation,
                                      'getSingleCategoryAcquiredMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
838
    def getSingleCategoryAcquiredMembershipList(self, context, base_category, base=0,
839
                                         spec=(), filter=None, acquired_object_dict = None, **kw ):
840
      cache = getReadOnlyTransactionCache(self)
841
      if cache is not None:
842
        key = ('getSingleCategoryAcquiredMembershipList', context.getPhysicalPath(), base_category, base, spec,
843 844 845 846 847
               filter, str(kw))
        try:
          return cache[key]
        except KeyError:
          pass
848

849
      result = self._getSingleCategoryAcquiredMembershipList(context, base_category, base=base,
850
                                                             spec=spec, filter=filter,
851 852 853 854
                                                             acquired_object_dict = acquired_object_dict,
                                                             **kw)
      if cache is not None:
        cache[key] = result
855

856
      return result
857 858


859 860 861 862 863
    def _getSingleCategoryAcquiredMembershipList(self, context, base_category,
                                         base = 0, spec = (), filter = None,
                                         acquired_portal_type = (),
                                         acquired_object_dict = None,
                                         **kw ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
864 865 866 867 868 869 870 871 872 873 874 875
      """
        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
876

877 878 879
        checked_permission        --    a string which defined the permission 
                                        to filter the object on

880 881 882 883 884
        acquired_object_dict      --    this is the list of object used by acquisition, so
                                        we can check if we already have used this object

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

885 886 887 888 889 890 891 892
        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

        acquisition_sync_value    --    if set to 1, keep self and looked up value in sync

Jean-Paul Smets's avatar
Jean-Paul Smets committed
893
      """
894 895
      #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
896
      # XXX We must use filters in the future
897
      # where_expression = self._buildQuery(spec, filter, kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
898
      portal_type = kw.get('portal_type', ())
899
      if spec is (): spec = portal_type # This is bad XXX - JPS - spec is for meta_type, not for portal_type - be consistent !
Jean-Paul Smets's avatar
Jean-Paul Smets committed
900

Yoshinori Okuji's avatar
Yoshinori Okuji committed
901
      if isinstance(spec, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
902
        spec = [spec]
903

Yoshinori Okuji's avatar
Yoshinori Okuji committed
904
      if isinstance(acquired_portal_type, str):
905 906
        acquired_portal_type = [acquired_portal_type]

907
      if acquired_object_dict is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
908 909 910 911
        acquired_object_dict = {} # Initial call may include filter, etc. - do not keep
      else:
        context_base_key = (tuple(context.getPhysicalPath()), base_category)
        if context_base_key in acquired_object_dict:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
912 913
          acquired_object_dict = acquired_object_dict.copy()
          type_dict = acquired_object_dict[context_base_key].copy()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
914 915
          if spec is ():
            if () in type_dict:
916 917
              return []
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
918
              type_dict[()] = 1
919
          else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
920 921 922 923 924
            for pt in spec:
              if pt in type_dict:
                return []
              else:
                type_dict[pt] = 1
Yoshinori Okuji's avatar
Yoshinori Okuji committed
925
          acquired_object_dict[context_base_key] = type_dict
926
        else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
927 928 929 930 931
          type_dict = {}
          if spec is ():
            type_dict[()] = 1
          else:
            for pt in spec:
932
              type_dict[pt] = 1
Yoshinori Okuji's avatar
Yoshinori Okuji committed
933
          acquired_object_dict = acquired_object_dict.copy()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
934
          acquired_object_dict[context_base_key] = type_dict
935

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

940
      base_category_value = self.getCategoryValue(base_category)
941
      #LOG("result", 0, str(result))
942
      if base_category_value is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
943
        # If we do not mask or append, return now if not empty
944 945
        if base_category_value.getAcquisitionMaskValue() and \
                not base_category_value.getAcquisitionAppendValue() and \
946
                result:
947
          # If acquisition masks and we do not append values, then we must return now
Jean-Paul Smets's avatar
Jean-Paul Smets committed
948 949
          return result
        # First we look at local ids
950
        for object_id in base_category_value.getAcquisitionObjectIdList():
951 952 953 954
          try:
            my_acquisition_object = context[object_id]
          except (KeyError, AttributeError):
            my_acquisition_object = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
955
          if my_acquisition_object is not None:
956 957 958
            #my_acquisition_object_path = my_acquisition_object.getPhysicalPath()
            #if my_acquisition_object_path in acquired_object_dict:
            #  continue
959
            #acquired_object_dict[my_acquisition_object_path] = 1
960
            if my_acquisition_object.portal_type in base_category_value.getAcquisitionPortalTypeList():
961 962 963 964
              new_result = self.getSingleCategoryAcquiredMembershipList(my_acquisition_object,
                  base_category, spec=spec, filter=filter, portal_type=portal_type, base=base, acquired_object_dict=acquired_object_dict)
            else:
              new_result = []
965 966 967
            #if base_category_value.acquisition_mask_value:
            #  # If acquisition masks, then we must return now
            #  return new_result
968
            if base_category_value.getAcquisitionAppendValue():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
969
              # If acquisition appends, then we must append to the result
Yoshinori Okuji's avatar
Yoshinori Okuji committed
970
              result.extend(new_result)
971
            elif new_result:
972
              return new_result # Found enough information to return
Jean-Paul Smets's avatar
Jean-Paul Smets committed
973
        # Next we look at references
974
        #LOG("Get Acquired BC", 0, base_category_value.getAcquisitionBaseCategoryList())
975
        acquisition_base_category_list = base_category_value.getAcquisitionBaseCategoryList()
976
        alt_base_category_list = base_category_value.getFallbackBaseCategoryList()
977
        all_acquisition_base_category_list = acquisition_base_category_list + alt_base_category_list
978
        acquisition_pt = base_category_value.getAcquisitionPortalTypeList(None)
979
        for my_base_category in acquisition_base_category_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
980
          # We implement here special keywords
Jean-Paul Smets's avatar
Jean-Paul Smets committed
981
          if my_base_category == 'parent':
982
            parent = context.aq_inner.aq_parent # aq_inner is required to make sure we use containment
Yoshinori Okuji's avatar
Yoshinori Okuji committed
983
            if getattr(aq_base(parent), 'portal_type', _marker) is _marker:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
984 985
              my_acquisition_object_list = []
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
986 987 988
              #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))
989 990
              #my_acquisition_object_path = parent.getPhysicalPath()
              #if my_acquisition_object_path in acquired_object_dict:
991
              if acquisition_pt is None or parent.portal_type in acquisition_pt:
992
                my_acquisition_object_list = [parent]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
993 994 995
              else:
                my_acquisition_object_list = []
          else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
996
            #LOG('getAcquiredCategoryMembershipList', 0, 'my_acquisition_object = %s, acquired_object_dict = %s' % (str(context), str(acquired_object_dict)))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
997
            my_acquisition_list = self.getSingleCategoryAcquiredMembershipList(context,
998
                        my_base_category,
999
                        portal_type=tuple(base_category_value.getAcquisitionPortalTypeList(())),
1000 1001
                        acquired_object_dict=acquired_object_dict)
            my_acquisition_object_list = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1002
            for c in my_acquisition_list:
1003 1004 1005 1006 1007
              o = self.resolveCategory(c)
              if o is not None:
                my_acquisition_object_list.append(o)
            #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
1008 1009
          #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
1010 1011 1012
          original_result = result
          result = list(result) # make a copy
          for my_acquisition_object in my_acquisition_object_list:
1013
            #LOG('getSingleCategoryAcquiredMembershipList', 0, 'my_acquisition_object = %s, acquired_object_dict = %s' % (str(my_acquisition_object), str(acquired_object_dict)))
1014 1015
            #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__()))
1016
            #if my_acquisition_object is not None:
1017
            if my_acquisition_object is not None:
1018 1019 1020 1021
              #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
1022 1023 1024
              #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))
1025 1026 1027
                
                # We should only consider objects which define that category
                if base_category in getattr(my_acquisition_object, '_categories', ()) or base_category_value.getFallbackBaseCategoryList():
1028
                  if (not acquired_portal_type) or my_acquisition_object.portal_type in acquired_portal_type:
1029
                    #LOG("Recursive call ",0,str((spec, my_acquisition_object.portal_type)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1030
                    new_result = self.getSingleCategoryAcquiredMembershipList(my_acquisition_object,
1031
                        base_category, spec=spec, filter=filter, portal_type=portal_type, base=base,
1032
                        acquired_portal_type=acquired_portal_type,
1033
                        acquired_object_dict=acquired_object_dict)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1034
                  else:
1035
                    #LOG("No recursive call ",0,str((spec, my_acquisition_object.portal_type)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1036
                    new_result = []
1037
                  if getattr(base_category_value, 'acquisition_append_value', False):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1038
                    # If acquisition appends, then we must append to the result
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1039
                    result.extend(new_result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1040
                  elif len(new_result) > 0:
1041
                    #LOG("new_result ",0,str(new_result))
1042 1043
                    if (getattr(base_category_value, 'acquisition_copy_value', False) and len(original_result) == 0) \
                                                    or getattr(base_category_value, 'acquisition_sync_value', False):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1044 1045
                      # If copy is set and result was empty, then copy it once
                      # If sync is set, then copy it again
1046
                      self.setCategoryMembership( context, base_category, new_result,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1047 1048 1049
                                    spec=spec, filter=filter, portal_type=portal_type, base=base )
                    # We found it, we can return
                    return new_result
1050 1051


1052 1053 1054
          if (getattr(base_category_value, 'acquisition_copy_value', False) or \
              getattr(base_category_value, 'acquisition_sync_value', False))\
              and len(result) > 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1055 1056
            # If copy is set and result was empty, then copy it once
            # If sync is set, then copy it again
1057
            self.setCategoryMembership( context, base_category, result,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1058
                                         spec=spec, filter=filter, portal_type=portal_type, base=base )
1059
        if len(result)==0 and len(base_category_value.getFallbackBaseCategoryList())>0:
1060
          # We must then try to use the alt base category
1061
          for base_category in base_category_value.getFallbackBaseCategoryList():
1062 1063 1064 1065
            # First get the category list
            category_list = self.getSingleCategoryAcquiredMembershipList( context, base_category, base=1,
                                 spec=spec, filter=filter, acquired_object_dict=acquired_object_dict, **kw )
            # Then convert it into value
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1066
            category_value_list = [self.resolveCategory(x) for x in category_list]
1067 1068
            # Then build the alternate category
            if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1069 1070
              base_category_id = base_category_value.getId()
              for category_value in category_value_list:
1071
                if category_value is None :
1072 1073
                  message = "category does not exists for %s (%s)"%(
                                       context.getPath(), category_list)
1074
                  LOG('CMFCategory', ERROR, message)
1075
                  raise CategoryError (message)
1076 1077 1078
                else :
                  result.append('%s/%s' % (base_category_id, category_value.getRelativeUrl()))
            else :
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1079
              for category_value in category_value_list:
1080 1081 1082
                if category_value is None :
                  message = "category does not exists for %s (%s)"%(
                                       context.getPath(), category_list)
1083
                  LOG('CMFCategory', ERROR, message)
1084 1085 1086
                  raise CategoryError (message)
                else :
                  result.append(category_value.getRelativeUrl())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1087 1088 1089
      # WE MUST IMPLEMENT HERE THE REST OF THE SEMANTICS
      #LOG("Get Acquired Category Result ",0,str(result))
      return result
1090

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1091 1092
    security.declareProtected( Permissions.AccessContentsInformation,
                                               'getAcquiredCategoryMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1093
    def getAcquiredCategoryMembershipList(self, context, base_category = None, base=1,
1094
                                          spec=(), filter=None, acquired_object_dict=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1095 1096 1097
      """
        Returns all acquired category values
      """
1098
      #LOG("Get Acquired Category List", 0, "%s %s" % (base_category, context.getRelativeUrl()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1099
      result = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1100
      extend = result.extend
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1101
      if base_category is None:
1102
        base_category_list = context._categories # XXX incompatible with ERP5Type per portal categories
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1103
      elif isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1104
        base_category_list = [base_category]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1105
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1106
        base_category_list = base_category
1107
      #LOG('CT.getAcquiredCategoryMembershipList base_category_list',0,base_category_list)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1108
      getSingleCategoryAcquiredMembershipList = self.getSingleCategoryAcquiredMembershipList
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1109
      for base_category in base_category_list:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1110 1111
        extend(getSingleCategoryAcquiredMembershipList(context, base_category, base=base,
                                    spec=spec, filter=filter, acquired_object_dict=acquired_object_dict, **kw ))
1112
        #LOG('CT.getAcquiredCategoryMembershipList new result',0,result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1113 1114 1115
      return result

    security.declareProtected( Permissions.AccessContentsInformation, 'isMemberOf' )
1116
    def isMemberOf(self, context, category, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1117 1118 1119
      """
        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)
1120 1121

        Keywords parameters :
1122
         - strict_membership:  if we want strict membership checking
1123
         - strict : alias for strict_membership (deprecated but still here for
1124
                    skins backward compatibility. )
1125

1126 1127 1128
        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
1129
      """
1130
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
1131 1132
      if getattr(aq_base(context), 'isCategory', 0):
        if context.isMemberOf(category, strict_membership=strict_membership):
1133
          return 1
1134
      base_category = category.split('/', 1)[0] # Extract base_category for optimisation
1135
      if strict_membership:
1136
        for c in self.getAcquiredCategoryMembershipList(context, base_category=base_category):
1137
          if c == category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1138 1139
            return 1
      else:
1140 1141 1142
        for c in self.getAcquiredCategoryMembershipList(context, base_category=base_category):
          if c == category or c.startswith(category + '/'):
            return 1
1143 1144 1145
      return 0

    security.declareProtected( Permissions.AccessContentsInformation, 'isAcquiredMemberOf' )
1146
    def isAcquiredMemberOf(self, context, category, strict=0):
1147 1148 1149 1150 1151 1152
      """
        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)
      """
      if getattr(aq_base(context), 'isCategory', 0):
        return context.isAcquiredMemberOf(category)
1153 1154 1155 1156 1157 1158 1159 1160
      if strict:
        for c in self._getAcquiredCategoryList(context):
          if c == category:
            return 1
      else:
        for c in self._getAcquiredCategoryList(context):
          if c.find(category) >= 0:
            return 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1161 1162
      return 0

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    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)
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
      for c in self._getAcquiredCategoryList(context):
        if c.find(category) >= 0:
          return 1
      return 0

    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)
1188 1189 1190 1191 1192
      for c in self._getAcquiredCategoryList(context):
        if c.find(category) >= 0:
          return 1
      return 0

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1193 1194 1195 1196 1197 1198 1199
    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryList' )
    def getCategoryList(self, context):
      self._cleanupCategories(context)
      return self._getCategoryList(context)

    security.declareProtected( Permissions.AccessContentsInformation, '_getCategoryList' )
    def _getCategoryList(self, context):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1200 1201
      if getattr(aq_base(context), 'categories', _marker) is not _marker:
        if isinstance(context.categories, tuple):
1202
          result = list(context.categories)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1203
        elif isinstance(context.categories, list):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1204 1205 1206
          result = context.categories
        else:
          result = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1207
      elif isinstance(context, dict):
1208
        result = list(context.get('categories', []))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1209 1210 1211
      else:
        result = []
      if getattr(context, 'isCategory', 0):
1212 1213 1214
        category_url = context.getRelativeUrl()
        if category_url not in result:
          result.append(context.getRelativeUrl()) # Pure category is member of itself
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1215 1216
      return result

1217 1218 1219 1220 1221
    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
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    security.declareProtected( Permissions.ModifyPortalContent, '_setCategoryList' )
    def _setCategoryList(self, context, value):
       context.categories = tuple(value)

    security.declareProtected( Permissions.AccessContentsInformation, 'getAcquiredCategoryList' )
    def getAcquiredCategoryList(self, context):
      """
        Returns the list of acquired categories
      """
      self._cleanupCategories(context)
      return self._getAcquiredCategoryList(context)

    security.declareProtected( Permissions.AccessContentsInformation, '_getAcquiredCategoryList' )
    def _getAcquiredCategoryList(self, context):
      result = self.getAcquiredCategoryMembershipList(context,
1237
                     base_category = self.getBaseCategoryList(context=context))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1238
      append = result.append
1239 1240 1241 1242
      non_acquired = self._getCategoryList(context)
      for c in non_acquired:
        # Make sure all local categories are considered
        if c not in result:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1243
          append(c)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1244
      if getattr(context, 'isCategory', 0):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1245
        append(context.getRelativeUrl()) # Pure category is member of itself
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1246 1247 1248 1249 1250 1251 1252 1253
      return result

    security.declareProtected( Permissions.ModifyPortalContent, '_cleanupCategories' )
    def _cleanupCategories(self, context):
      # Make sure _cleanupCategories does not modify objects each time it is called
      # or we get many conflicts
      requires_update = 0
      categories = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1254
      append = categories.append
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1255
      if getattr(context, 'categories', _marker) is not _marker:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1256
        for cat in self._getCategoryList(context):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1257
          if isinstance(cat, str):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1258
            append(cat)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1259 1260
          else:
            requires_update = 1
1261
      if requires_update: self.setCategoryList(context, tuple(categories))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1262 1263

    # Catalog related methods
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1264
    def updateRelatedCategory(self, category, previous_category_url, new_category_url):
1265 1266 1267 1268
      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
1269
      new_category = re.sub('(?P<start>.*)/%s/(?P<stop>.*)' %
1270
            previous_category_url,'\g<start>/%s/\g<stop>' % new_category_url,new_category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1271 1272
      new_category = re.sub('(?P<start>.*)/%s$' %
            previous_category_url,'\g<start>/%s' % new_category_url, new_category)
1273 1274
      return new_category

1275 1276 1277
    def updateRelatedContent(self, context,
                             previous_category_url, new_category_url):
      """Updates related object when an object have moved.
1278

1279 1280 1281 1282 1283 1284
          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
1285
      """
1286 1287
      for brain in self.Base_zSearchRelatedObjectsByCategory(
                                              category_uid = context.getUid()):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1288
        o = brain.getObject()
1289 1290 1291
        if o is not None:
          category_list = []
          for category in self.getCategoryList(o):
1292 1293 1294
            new_category = self.updateRelatedCategory(category,
                                                      previous_category_url,
                                                      new_category_url)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1295
            category_list.append(new_category)
1296
          self.setCategoryList(o, category_list)
1297

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

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

1310 1311 1312 1313 1314
      for brain in self.Base_zSearchRelatedObjectsByPredicate(
                                              category_uid = context.getUid()):
        o = brain.getObject()
        if o is not None:
          category_list = []
1315
          for category in o.getMembershipCriterionCategoryList():
1316 1317 1318 1319
            new_category = self.updateRelatedCategory(category,
                                                      previous_category_url,
                                                      new_category_url)
            category_list.append(new_category)
1320
          o._setMembershipCriterionCategoryList(category_list)
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335

          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)



1336
      aq_context = aq_base(context)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1337
      # Update related recursively if required
1338
      if getattr(aq_context, 'listFolderContents', None) is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1339
        for o in context.listFolderContents():
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
          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' )
1354
    def getRelatedValueList(self, context, base_category_list=None,
1355
                            spec=(), filter=None, base=1, 
1356
                            checked_permission=None, **kw):
1357 1358 1359 1360
      """
        This methods returns the list of objects related to the context
        with the given base_category_list.
      """
1361
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1362
      portal_type = kw.get('portal_type')
1363

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1364
      if isinstance(portal_type, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1365
        portal_type = [portal_type]
1366 1367 1368
      if spec is (): 
        # We do not want to care about spec
        spec = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1369

1370 1371 1372 1373
      # Base Category may not be related, besides sub categories
      if context.getPortalType() == 'Base Category':
        category_list = [context.getRelativeUrl()]
      else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1374
        if isinstance(base_category_list, str):
1375 1376 1377 1378 1379 1380
          base_category_list = [base_category_list]
        elif base_category_list is () or base_category_list is None:
          base_category_list = self.getBaseCategoryList()
        category_list = []
        for base_category in base_category_list:
          category_list.append("%s/%s" % (base_category, context.getRelativeUrl()))
1381

1382 1383 1384 1385
      brain_result = self.Base_zSearchRelatedObjectsByCategoryList(
                           category_list=category_list,
                           portal_type=portal_type,
                           strict_membership=strict_membership)
1386

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1387
      result = []
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
      if checked_permission is None:
        # No permission to check
        for b in brain_result:
          o = b.getObject()
          if o is not None:
            result.append(o)
      else:
        # Check permissions on object
        if isinstance(checked_permission, str):
          checked_permission = (checked_permission, )
          checkPermission = self.portal_membership.checkPermission
          for b in brain_result:
            obj = b.getObject()
            if obj is not None:
              for permission in checked_permission:
                if not checkPermission(permission, obj):
                  break
                result.append(obj)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1406 1407

      return result
1408 1409 1410
      # XXX missing filter and **kw stuff
      #return self.search_category(category_list=category_list,
      #                            portal_type=spec)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1411
      # future implementation with brains, much more efficient
1412

1413 1414 1415
    security.declareProtected( Permissions.AccessContentsInformation,
                               'getRelatedPropertyList' )
    def getRelatedPropertyList(self, context, base_category_list=None,
1416
                               property_name=None, spec=(), 
1417 1418
                               filter=None, base=1, 
                               checked_permission=None, **kw):
1419 1420 1421 1422 1423
      """
        This methods returns the list of property_name on  objects
        related to the context with the given base_category_list.
      """
      result = []
1424 1425
      for o in self.getRelatedValueList(
                          context=context,
1426
                          base_category_list=base_category_list, spec=spec,
1427 1428
                          filter=filter, base=base, 
                          checked_permission=checked_permission, **kw):
1429 1430
        result.append(o.getProperty(property_name, None))
      return result
1431

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1432 1433
    # SQL Expression Building
    security.declareProtected(Permissions.AccessContentsInformation, 'buildSQLSelector')
1434
    def buildSQLSelector(self, category_list, query_table='category', none_sql_value=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1435 1436 1437 1438
      """
        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
1439
        to generate a much more complex where_expression with table aliases
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1440 1441

        List of lists
1442 1443 1444

        - 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
1445
      """
Vincent Pelletier's avatar
Vincent Pelletier committed
1446 1447 1448 1449 1450 1451
      def renderUIDValue(uid):
        uid = ((uid is None) and (none_sql_value, ) or (uid, ))[0]
        if uid is None:
          return 'is NULL'
        else:
          return '= %s' % (uid, )
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1452
      if isinstance(category_list, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1453
        category_list = [category_list]
Vincent Pelletier's avatar
Vincent Pelletier committed
1454 1455 1456 1457 1458 1459
      sql_expr = ['(%s.category_uid %s AND %s.base_category_uid %s)' %\
                  (query_table, renderUIDValue(self.getCategoryUid(x)),
                   query_table, renderUIDValue(self.getBaseCategoryUid(x)))
                   for x in category_list if isinstance(x, str) and x]
      # XXX: This "if" is meaningless. But as it changes the return value,
      # it's dagerous to remove it without good testing.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1460
      if len(sql_expr) > 0:
1461
        sql_expr = ' OR '.join(sql_expr)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1462 1463 1464
      return sql_expr

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberValueList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1465
    def getCategoryMemberValueList(self, context, base_category = None,
1466
                                         spec = (), filter=None, portal_type=(), **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1467 1468 1469
      """
      This returns a catalog_search resource with can then be used by getCategoryMemberItemList
      """
Kevin Deldycke's avatar
Kevin Deldycke committed
1470
      if base_category is None:
1471
        if context.getPortalType() in ( "Base Category", "Category") :
Kevin Deldycke's avatar
Kevin Deldycke committed
1472 1473 1474
          base_category = context.getBaseCategoryId()
        else:
          raise CategoryError('getCategoryMemberValueList must know the base category')
1475
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1476

1477
      domain_dict = {base_category: ('portal_categories', context.getRelativeUrl())}
1478 1479
      if strict_membership:
        catalog_search = self.portal_catalog(portal_type = portal_type,
1480
                           selection_report = domain_dict)
1481 1482
      else:
        catalog_search = self.portal_catalog(portal_type = portal_type,
1483
                           selection_domain = domain_dict)
1484

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1485 1486 1487
      return catalog_search

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberItemList' )
1488
    def getCategoryMemberItemList(self, context, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1489
      """
1490 1491 1492
      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
1493
        strict_membership : returns only object belonging to this category, not
1494 1495
                            objects belonging to child categories.
        strict            : a deprecated alias for strict_membership
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1496
      """
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1497
      k = {}
1498
      for v in ('portal_type', 'spec', 'strict', 'strict_membership'):
1499
        if v in kw:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1500 1501
          k[v] = kw[v]
      catalog_search = self.getCategoryMemberValueList(context, **k)
1502
      return Renderer(**kw).render(catalog_search)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1503 1504 1505

    security.declareProtected( Permissions.AccessContentsInformation,
                                                                'getCategoryMemberTitleItemList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1506
    def getCategoryMemberTitleItemList(self, context, base_category = None,
1507
                                      spec = (), filter=None, portal_type=(), strict_membership = 0,
1508
                                      strict="DEPRECATED"):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1509 1510 1511 1512
      """
      This returns a title list of items belonging to a category

      """
1513
      return self.getCategoryMemberItemList(self, context, base_category = base_category,
1514
                                spec = spec, filter=filter, portal_type=portal_type,
1515 1516
                                strict_membership = strict_membership, strict = strict,
                                display_id = 'getTitle')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1517

1518
    security.declarePublic('resolveCategory')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1519 1520 1521
    def resolveCategory(self, relative_url):
        """
          Finds an object from a relative_url
1522
          Method is public since we use restrictedTraverse
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1523
        """
1524
        cache = getReadOnlyTransactionCache(self)
1525 1526 1527 1528 1529 1530
        if cache is not None:
          key = ('resolveCategory', relative_url)
          try:
            return cache[key]
          except KeyError:
            pass
1531

1532 1533 1534 1535 1536 1537 1538 1539
        # 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.
        # 
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
        # 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.
        # 
        # 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)
        # 
        # 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.
        # 
        # 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.
        # 
        # 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.
        # 
        # 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.
        # 
        # Documents may contain Documents, but only to a downward direction.
        # Otherwise, things get more abstract in a tree.
        # 
        # 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.
1590 1591 1592 1593 1594 1595 1596
        if isinstance(relative_url, basestring):
          stack = relative_url.split('/')
        else:
          stack = list(relative_url)
        stack.reverse()

        validate = getSecurityManager().validate
1597 1598
        def restrictedGetOb(container, key):
          obj = container._getOb(key, None)
1599 1600 1601
          if obj is not None:
            if not validate(container, container, key, obj):
              raise Unauthorized('unauthorized access to element %s' % key)
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
          return obj

        # 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.
        obj = self
        if stack:
          portal = aq_inner(self.getPortalObject())
          key = stack.pop()
          obj = restrictedGetOb(self, key)
          if obj is None:
            obj = restrictedGetOb(portal, key)
            if obj is not None:
              obj = obj.__of__(self)
          else:
            while stack:
              container = obj
              key = stack.pop()
              obj = restrictedGetOb(container, key)
              if obj is not None:
                break
              obj = restrictedGetOb(self, key)
              if obj is None:
                obj = restrictedGetOb(portal, key)
                if obj is not None:
                  obj = obj.__of__(container)
                break

          while obj is not None and stack:
            key = stack.pop()
            obj = restrictedGetOb(obj, key)
1633 1634 1635 1636

        if obj is None:
          LOG('CMFCategory', WARNING, 
              'Could not access object %s' % relative_url)
1637

1638
        if cache is not None:
1639
          cache[key] = obj
1640

1641
        return obj
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1642 1643 1644 1645

InitializeClass( CategoryTool )

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