CategoryTool.py 64.9 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 37 38 39
#
# 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
from Acquisition import aq_base
from Products.ERP5Type import Permissions
from Products.ERP5Type.Base import Base
40
from Products.ERP5Type.Cache import getReadOnlyTransactionCache
Jean-Paul Smets's avatar
Jean-Paul Smets committed
41 42
from Products.CMFCategory import _dtmldir
from Products.CMFCore.PortalFolder import ContentFilter
43
from Products.CMFCategory.Renderer import Renderer
44
from OFS.Traversable import NotFound
Jean-Paul Smets's avatar
Jean-Paul Smets committed
45

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

48
from zLOG import LOG, PROBLEM
Jean-Paul Smets's avatar
Jean-Paul Smets committed
49

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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
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
77 78 79 80
      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
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

        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'
99
    portal_type     = 'Category Tool'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 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
    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
151 152
    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryList')
    def getBaseCategoryList(self, context=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166
      """
        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:
        return self.objectIds()
      else:
167
        return context._categories # XXX Incompatible with ERP5Type per portal type categories
Jean-Paul Smets's avatar
Jean-Paul Smets committed
168 169

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryIds')
170
    getBaseCategoryIds = getBaseCategoryList
Jean-Paul Smets's avatar
Jean-Paul Smets committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

    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
191
        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
192 193 194 195 196 197 198 199 200 201 202 203 204 205

    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
      """
206
      cache = getReadOnlyTransactionCache(self)
207 208 209 210 211 212 213
      if cache is not None:
        key = ('getCategoryValue', relative_url, base_category)
        try:
          return cache[key]
        except KeyError:
          pass
          
Jean-Paul Smets's avatar
Jean-Paul Smets committed
214 215 216
      try:
        relative_url = str(relative_url)
        if base_category is not None:
Romain Courteaud's avatar
Romain Courteaud committed
217 218
          relative_url = '%s/%s' % (base_category, relative_url)
        node = self.unrestrictedTraverse(relative_url)
219
        value = node
220
      except (TypeError, KeyError, NotFound):
221 222 223 224 225 226 227
        value = None
        
      if cache is not None:
        cache[key] = value

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

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

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryParentUidList')
    def getCategoryParentUidList(self, relative_url, base_category = None, strict=0):
      """
293 294 295 296 297 298 299
        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
300 301 302 303 304 305 306 307

        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
308 309
      if isinstance(relative_url, str):
        relative_url = (relative_url,)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
310 311 312 313
      for path in relative_url:
        try:
          o = self.getCategoryValue(path, base_category=base_category)
          if o is not None:
314 315
            my_base_category = self.getBaseCategoryId(path)
            bo = self.get(my_base_category, None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
316 317 318 319 320 321 322 323 324
            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':
325
                    o = o.aq_parent # We want acquisition here without aq_inner
Jean-Paul Smets's avatar
Jean-Paul Smets committed
326
                    uid_dict[(int(o.uid), bo_uid, 0)] = 1 # Non Strict Membership
327
        except (KeyError, AttributeError):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
328 329 330 331 332 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
          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:
367
        base_category_list = self.getBaseCategoryList()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
368
      elif isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
369 370 371 372 373 374 375
        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
376
          result.extend(category.getCategoryChildRelativeUrlList(base=base,recursive=recursive))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
377 378 379
      return result

    security.declareProtected(Permissions.AccessContentsInformation, 'getPathList')
380 381 382 383
    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
384 385 386 387

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

    security.declareProtected(Permissions.AccessContentsInformation,
397
                              'getCategoryChildIdItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
398
    def getCategoryChildIdItemList(self, base_category=None,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
399
              recursive=1, base=0, display_none_category=0, sort_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
400 401 402 403
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getId as default method
      """
404 405 406 407 408 409 410
      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
411 412

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

      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
431
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
432 433

      recursive -- if set to 0 do not apply recursively
434 435

      See Category.getCategoryChildItemList for extra accepted arguments
Jean-Paul Smets's avatar
Jean-Paul Smets committed
436
      """
437
      if isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
438 439
        base_category_list = [base_category]
      elif base_category is None:
440
        base_category_list = self.getBaseCategoryList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
441 442
      else:
        base_category_list = base_category
Jean-Paul Smets's avatar
Jean-Paul Smets committed
443
      if display_none_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
444 445 446 447 448 449
        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
450
          result.extend(category.getCategoryChildItemList(
451 452 453
                               base=base,
                               recursive=recursive,
                               display_id=display_id,
Yoshinori Okuji's avatar
Yoshinori Okuji committed
454
                               **kw ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
455 456
      return result

457 458
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getBaseItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
459 460 461 462
    getBaseItemList = getCategoryChildItemList

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

      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
477
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
478 479 480

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

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

Romain Courteaud's avatar
Romain Courteaud committed
498
#       LOG('CMFCategoryTool.asItemList, value_list',0,value_list)
Sebastien Robin's avatar
Sebastien Robin committed
499
      return Renderer(base_category=base_category,**kw).render(value_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
500 501 502 503 504 505 506

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

    security.declareProtected( Permissions.AccessContentsInformation, 'setCategoryMembership' )
    def setCategoryMembership(self, context, base_category_list, category_list, base=0, keep_default=1,
                                 spec=(), filter=None, **kw ):
      """
        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

      """
      #LOG("set Category 1",0,str(category_list))
      # XXX We must use filters in the future
607
      # where_expression = self._buildQuery(spec, filter, kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
608
      portal_type = kw.get('portal_type', ())
Yoshinori Okuji's avatar
Yoshinori Okuji committed
609
      if isinstance(portal_type, str):
610 611 612
        portal_type = (portal_type,)
      if spec is (): 
        spec = portal_type
613
      #LOG("set Category",0,str(category_list))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
614 615 616

      default_dict = {}
      self._cleanupCategories(context)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
617
      if isinstance(category_list, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
618 619 620
        category_list = (category_list,)
      elif category_list is None:
        category_list = ()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
621
      if isinstance(base_category_list, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
622 623 624 625
        base_category_list = [base_category_list]
      new_category_list = []
      for path in self._getCategoryList(context):
        my_base_id = self.getBaseCategoryId(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
626
        if my_base_id not in base_category_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
627 628
          # Keep each membership which is not in the
          # specified list of base_category ids
629
          new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
630 631 632 633 634 635 636 637 638
        else:
          if spec is ():
            # If spec is (), then we should keep nothing
            # Everything will be replaced
            keep_it = 0
          else:
            # Only keep this if not in our spec
            try:
              my_type = self.unrestrictedTraverse(path).portal_type
639
              keep_it = (my_type not in spec)
640
            except (KeyError, AttributeError):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
641 642
              keep_it = 0
          if keep_it:
643
            new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
644 645 646 647 648 649 650 651 652 653
          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:
654
            default_new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
655 656
        else:
          if path[len(base_category_list[0])+1:] in category_list:
657
            default_new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
658 659 660 661
      # 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:
662
        if path != '':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
663 664 665 666 667
          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
668
                new_category_list.append(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
669
          else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
670
            new_path = base_category_list[0] + '/' + path
Jean-Paul Smets's avatar
Jean-Paul Smets committed
671
            if new_path not in default_new_category_list:
672
              new_category_list.append(new_path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
673
      #LOG("set Category",0,str(new_category_list))
674
      #LOG("set Category",0,str(default_new_category_list))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
      self._setCategoryList(context, tuple(default_new_category_list + new_category_list))

    security.declareProtected( Permissions.AccessContentsInformation, 'setDefaultCategoryMembership' )
    def setDefaultCategoryMembership(self, context, base_category, default_category,
                                              spec=(), filter=None, portal_type=(), base=0 ):
      """
        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

      """
      self._cleanupCategories(context)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
695
      if isinstance(default_category, (tuple, list)):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
696 697 698 699 700 701 702 703 704
        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:
705
        if category == default_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
706
          found_one = 1
707
        elif category != default_category or found_one:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
708
          new_category_list.append(category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
709 710 711 712 713
      self.setCategoryMembership(context, base_category, new_category_list,
           spec=spec, filter=filter, portal_type=portal_type, base=base, keep_default = 0)

    security.declareProtected( Permissions.AccessContentsInformation,
                                                        'getSingleCategoryMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
714
    def getSingleCategoryMembershipList(self, context, base_category, base=0,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
                                          spec=(), filter=None, **kw):
      """
        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
      """
      # XXX We must use filters in the future
730
      # where_expression = self._buildQuery(spec, filter, kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
731 732 733
      portal_type = kw.get('portal_type', ())
      if spec is (): spec = portal_type

734
      # We must treat parent in a different way
735
      #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)))
736
      if base_category == 'parent':
737
        parent = context.aq_inner.aq_parent # aq_inner is required to make sure we use containment
738 739 740 741 742
        if parent.portal_type in spec:
          if base:
            return ['parent/' + parent.getRelativeUrl()]
          else:
            return [parent.getRelativeUrl()]
743 744 745
        #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
746
      result = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
747
      append = result.append
Jean-Paul Smets's avatar
Jean-Paul Smets committed
748
      # XXX We must use filters in the future
749
      # where_expression = self._buildQuery(spec, filter, kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
750 751
      spec = kw.get('portal_type', ())
      # Make sure spec is a list or tuple
Yoshinori Okuji's avatar
Yoshinori Okuji committed
752
      if isinstance(spec, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
753 754
        spec = [spec]
      # Filter categories
Yoshinori Okuji's avatar
Yoshinori Okuji committed
755
      if getattr(aq_base(context), 'categories', _marker) is not _marker:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
756
        for category_url in self._getCategoryList(context):
757 758 759 760 761
          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
762
          if my_base_category == base_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
763
            #LOG("getSingleCategoryMembershipList",0,"%s %s %s %s" % (context.getRelativeUrl(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
764
            #                  my_base_category, base_category, category_url))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
765 766
            if spec is ():
              if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
767
                append(category_url)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
768
              else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
769
                append(category_url[len(my_base_category)+1:])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
770
            else:
771
              my_reference = self.unrestrictedTraverse(category_url, None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
772 773 774
              if my_reference is not None:
                if my_reference.portal_type in spec:
                  if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
775
                    append(category_url)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
776
                  else:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
777
                    append(category_url[len(my_base_category)+1:])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
778 779 780 781
      return result

    security.declareProtected( Permissions.AccessContentsInformation,
                                      'getSingleCategoryAcquiredMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
782
    def getSingleCategoryAcquiredMembershipList(self, context, base_category, base=0,
783
                                         spec=(), filter=None, acquired_object_dict = None, **kw ):
784
      cache = getReadOnlyTransactionCache(self)
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
      if cache is not None:
        key = ('getSingleCategoryAcquiredMembershipList', context._p_oid, base_category, base, spec, 
               filter, str(kw))
        try:
          return cache[key]
        except KeyError:
          pass
          
      result = self._getSingleCategoryAcquiredMembershipList(context, base_category, base=base,
                                                             spec=spec, filter=filter, 
                                                             acquired_object_dict = acquired_object_dict,
                                                             **kw)
      if cache is not None:
        cache[key] = result
        
      return result
      
                                      
803 804 805 806 807
    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
808 809 810 811 812 813 814 815 816 817 818 819
      """
        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
820

821 822 823 824 825
        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

826 827 828 829 830 831 832 833
        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
834
      """
835 836
      #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
837
      # XXX We must use filters in the future
838
      # where_expression = self._buildQuery(spec, filter, kw)
839

Jean-Paul Smets's avatar
Jean-Paul Smets committed
840
      portal_type = kw.get('portal_type', ())
841
      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
842

Yoshinori Okuji's avatar
Yoshinori Okuji committed
843
      if isinstance(spec, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
844
        spec = [spec]
845

Yoshinori Okuji's avatar
Yoshinori Okuji committed
846
      if isinstance(acquired_portal_type, str):
847 848
        acquired_portal_type = [acquired_portal_type]

849
      if acquired_object_dict is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
850 851 852 853
        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
854 855
          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
856 857
          if spec is ():
            if () in type_dict:
858 859
              return []
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
860
              type_dict[()] = 1
861
          else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
862 863 864 865 866
            for pt in spec:
              if pt in type_dict:
                return []
              else:
                type_dict[pt] = 1
Yoshinori Okuji's avatar
Yoshinori Okuji committed
867
          acquired_object_dict[context_base_key] = type_dict
868
        else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
869 870 871 872 873
          type_dict = {}
          if spec is ():
            type_dict[()] = 1
          else:
            for pt in spec:
874
              type_dict[pt] = 1
Yoshinori Okuji's avatar
Yoshinori Okuji committed
875
          acquired_object_dict = acquired_object_dict.copy()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
876
          acquired_object_dict[context_base_key] = type_dict
877

Jean-Paul Smets's avatar
Jean-Paul Smets committed
878
      result = self.getSingleCategoryMembershipList( context, base_category, base=base,
879 880
                            spec=spec, filter=filter, **kw ) # Not acquired because this is the first try
                                                             # to get a local defined category
Aurel's avatar
Aurel committed
881
      
882
      base_category_value = self.getCategoryValue(base_category)
883
      #LOG("result", 0, str(result))
884
      if base_category_value is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
885
        # If we do not mask or append, return now if not empty
886 887
        if base_category_value.getAcquisitionMaskValue() and \
                not base_category_value.getAcquisitionAppendValue() and \
Jean-Paul Smets's avatar
Jean-Paul Smets committed
888
                len(result) > 0:
889
          # If acquisition masks and we do not append values, then we must return now
Jean-Paul Smets's avatar
Jean-Paul Smets committed
890 891
          return result
        # First we look at local ids
892
        for object_id in base_category_value.getAcquisitionObjectIdList():
893
          my_acquisition_object = None
894
          if object_id in context.objectIds():
895
            my_acquisition_object = getattr(context, object_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
896
          if my_acquisition_object is not None:
897 898 899
            #my_acquisition_object_path = my_acquisition_object.getPhysicalPath()
            #if my_acquisition_object_path in acquired_object_dict:
            #  continue
900
            #acquired_object_dict[my_acquisition_object_path] = 1
901
            if my_acquisition_object.portal_type in base_category_value.getAcquisitionPortalTypeList():
902 903 904 905
              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 = []
906 907 908
            #if base_category_value.acquisition_mask_value:
            #  # If acquisition masks, then we must return now
            #  return new_result
909
            if getattr(base_category_value, 'acquisition_append_value', False):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
910
              # If acquisition appends, then we must append to the result
Yoshinori Okuji's avatar
Yoshinori Okuji committed
911
              result.extend(new_result)
912 913
            elif len(new_result) > 0:
              return new_result # Found enough information to return
Jean-Paul Smets's avatar
Jean-Paul Smets committed
914
        # Next we look at references
915
        #LOG("Get Acquired BC", 0, base_category_value.getAcquisitionBaseCategoryList())
916
        acquisition_base_category_list = base_category_value.getAcquisitionBaseCategoryList()
917
        alt_base_category_list = base_category_value.getFallbackBaseCategoryList()
918
        all_acquisition_base_category_list = acquisition_base_category_list + alt_base_category_list
919 920
        acquisition_pt = base_category_value.getAcquisitionPortalTypeList(())
        for my_base_category in base_category_value.getAcquisitionBaseCategoryList():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
921
          # We implement here special keywords
Jean-Paul Smets's avatar
Jean-Paul Smets committed
922
          if my_base_category == 'parent':
923
            parent = context.aq_inner.aq_parent # aq_inner is required to make sure we use containment
Yoshinori Okuji's avatar
Yoshinori Okuji committed
924
            if getattr(aq_base(parent), 'portal_type', _marker) is _marker:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
925 926
              my_acquisition_object_list = []
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
927 928 929
              #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))
930 931
              #my_acquisition_object_path = parent.getPhysicalPath()
              #if my_acquisition_object_path in acquired_object_dict:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
932
              if acquisition_pt is () or parent.portal_type in acquisition_pt:
933
                my_acquisition_object_list = [parent]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
934 935 936
              else:
                my_acquisition_object_list = []
          else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
937
            #LOG('getAcquiredCategoryMembershipList', 0, 'my_acquisition_object = %s, acquired_object_dict = %s' % (str(context), str(acquired_object_dict)))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
938
            my_acquisition_list = self.getSingleCategoryAcquiredMembershipList(context,
939
                        my_base_category,
940
                        portal_type=tuple(base_category_value.getAcquisitionPortalTypeList(())),
941 942
                        acquired_object_dict=acquired_object_dict)
            my_acquisition_object_list = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
943
            for c in my_acquisition_list:
944 945 946 947 948
              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
949 950
          #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
951 952 953
          original_result = result
          result = list(result) # make a copy
          for my_acquisition_object in my_acquisition_object_list:
954
            #LOG('getSingleCategoryAcquiredMembershipList', 0, 'my_acquisition_object = %s, acquired_object_dict = %s' % (str(my_acquisition_object), str(acquired_object_dict)))
955 956
            #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__()))
957
            #if my_acquisition_object is not None:
958
            if my_acquisition_object is not None:
959 960 961 962
              #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
963
              #if hasattr(my_acquisition_object, '_categories'): # This would be a bug since we have category acquisition
Jean-Paul Smets's avatar
Jean-Paul Smets committed
964
                # We should only consider objects which define that category
965 966 967
                #LOG('my_acquisition_object',0, str(getattr(my_acquisition_object, '_categories', ())))
                #LOG('my_acquisition_object',0, str(base_category))
                if base_category in getattr(my_acquisition_object, '_categories', ()):
968
                  if (not acquired_portal_type) or my_acquisition_object.portal_type in acquired_portal_type:
969
                    #LOG("Recursive call ",0,str((spec, my_acquisition_object.portal_type)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
970
                    new_result = self.getSingleCategoryAcquiredMembershipList(my_acquisition_object,
971
                        base_category, spec=spec, filter=filter, portal_type=portal_type, base=base,
972
                        acquired_portal_type=acquired_portal_type,
973
                        acquired_object_dict=acquired_object_dict)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
974
                  else:
975
                    #LOG("No recursive call ",0,str((spec, my_acquisition_object.portal_type)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
976
                    new_result = []
977
                  if getattr(base_category_value, 'acquisition_append_value', False):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
978
                    # If acquisition appends, then we must append to the result
Yoshinori Okuji's avatar
Yoshinori Okuji committed
979
                    result.extend(new_result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
980
                  elif len(new_result) > 0:
981
                    #LOG("new_result ",0,str(new_result))
982 983
                    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
984 985
                      # If copy is set and result was empty, then copy it once
                      # If sync is set, then copy it again
986
                      self.setCategoryMembership( context, base_category, new_result,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
987 988 989
                                    spec=spec, filter=filter, portal_type=portal_type, base=base )
                    # We found it, we can return
                    return new_result
990 991


992 993 994
          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
995 996
            # If copy is set and result was empty, then copy it once
            # If sync is set, then copy it again
997
            self.setCategoryMembership( context, base_category, result,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
998
                                         spec=spec, filter=filter, portal_type=portal_type, base=base )
999
        if len(result)==0 and len(base_category_value.getFallbackBaseCategoryList())>0:
1000
          # We must then try to use the alt base category
1001
          for base_category in base_category_value.getFallbackBaseCategoryList():
1002 1003 1004 1005
            # 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
1006
            category_value_list = [self.resolveCategory(x) for x in category_list]
1007 1008
            # Then build the alternate category
            if base:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1009 1010
              base_category_id = base_category_value.getId()
              for category_value in category_value_list:
1011
                if category_value is None :
1012 1013 1014 1015
                  message = "category does not exists for %s (%s)"%(
                                       context.getPath(), category_list)
                  LOG('CMFCategory', PROBLEM, message)
                  raise CategoryError (message)
1016 1017 1018
                else :
                  result.append('%s/%s' % (base_category_id, category_value.getRelativeUrl()))
            else :
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1019
              for category_value in category_value_list:
1020 1021 1022 1023 1024 1025 1026
                if category_value is None :
                  message = "category does not exists for %s (%s)"%(
                                       context.getPath(), category_list)
                  LOG('CMFCategory', PROBLEM, message)
                  raise CategoryError (message)
                else :
                  result.append(category_value.getRelativeUrl())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1027 1028 1029
      # WE MUST IMPLEMENT HERE THE REST OF THE SEMANTICS
      #LOG("Get Acquired Category Result ",0,str(result))
      return result
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1030
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1031 1032
    security.declareProtected( Permissions.AccessContentsInformation,
                                               'getAcquiredCategoryMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1033
    def getAcquiredCategoryMembershipList(self, context, base_category = None, base=1,
1034
                                          spec=(), filter=None, acquired_object_dict=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1035 1036 1037
      """
        Returns all acquired category values
      """
1038
      #LOG("Get Acquired Category List", 0, "%s %s" % (base_category, context.getRelativeUrl()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1039
      result = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1040
      extend = result.extend
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1041
      if base_category is None:
1042
        base_category_list = context._categories # XXX incompatible with ERP5Type per portal categories
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1043
      elif isinstance(base_category, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1044
        base_category_list = [base_category]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1045
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1046
        base_category_list = base_category
1047
      #LOG('CT.getAcquiredCategoryMembershipList base_category_list',0,base_category_list)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1048
      getSingleCategoryAcquiredMembershipList = self.getSingleCategoryAcquiredMembershipList
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1049
      for base_category in base_category_list:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1050 1051
        extend(getSingleCategoryAcquiredMembershipList(context, base_category, base=base,
                                    spec=spec, filter=filter, acquired_object_dict=acquired_object_dict, **kw ))
1052
        #LOG('CT.getAcquiredCategoryMembershipList new result',0,result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1053 1054 1055
      return result

    security.declareProtected( Permissions.AccessContentsInformation, 'isMemberOf' )
1056
    def isMemberOf(self, context, category, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1057 1058 1059
      """
        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)
1060 1061 1062 1063 1064 1065
        
        Keywords parameters : 
         - strict_membership:  if we want strict membership checking
         - strict : alias for strict_membership (deprecated but still here for 
                    skins backward compatibility. )
 
1066 1067 1068
        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
1069
      """
1070
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
1071
      if getattr(aq_base(context), 'isCategory', 0) :
1072
        if context.isMemberOf(category, strict_membership = strict_membership) == 1 :
1073
          return 1
1074
      base_category = category.split('/')[0] # Extract base_category for optimisation
1075
      if strict_membership:
1076
        for c in self.getAcquiredCategoryMembershipList(context, base_category = base_category):
1077
          if c == category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1078 1079
            return 1
      else:
1080
        for c in self.getAcquiredCategoryMembershipList(context, base_category = base_category): 
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
          if c.find(category) == 0:
            # The names begin with the same string
            c_right_split = c.split(category)[1]
            if (len(c_right_split) > 0):
              # Be sure that we have a sub category, and not name like this: 'europe1' in 'europe10'
              if c_right_split[0] == '/':
                return 1
            else:
              # Same category
              return 1
1091 1092 1093
      return 0

    security.declareProtected( Permissions.AccessContentsInformation, 'isAcquiredMemberOf' )
1094
    def isAcquiredMemberOf(self, context, category, strict=0):
1095 1096 1097 1098 1099 1100
      """
        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)
1101 1102 1103 1104 1105 1106 1107 1108
      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
1109 1110
      return 0

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    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)
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
      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)
1136 1137 1138 1139 1140
      for c in self._getAcquiredCategoryList(context):
        if c.find(category) >= 0:
          return 1
      return 0

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1141 1142 1143 1144 1145 1146 1147
    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
1148 1149
      if getattr(aq_base(context), 'categories', _marker) is not _marker:
        if isinstance(context.categories, tuple):
1150
          result = list(context.categories)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1151
        elif isinstance(context.categories, list):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1152 1153 1154
          result = context.categories
        else:
          result = []
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1155
      elif isinstance(context, dict):
1156
        result = list(context.get('categories', []))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1157 1158 1159
      else:
        result = []
      if getattr(context, 'isCategory', 0):
1160 1161 1162
        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
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
      return result

    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,
1180
                     base_category = self.getBaseCategoryList(context=context))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1181
      append = result.append
1182 1183 1184 1185
      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
1186
          append(c)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1187
      if getattr(context, 'isCategory', 0):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1188
        append(context.getRelativeUrl()) # Pure category is member of itself
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1189 1190 1191 1192 1193 1194 1195 1196
      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
1197
      append = categories.append
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1198
      if getattr(context, 'categories', _marker) is not _marker:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1199
        for cat in self._getCategoryList(context):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1200
          if isinstance(cat, str):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1201
            append(cat)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1202 1203 1204 1205 1206
          else:
            requires_update = 1
      if requires_update: self._setCategoryList(context, tuple(categories))

    # Catalog related methods
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1207
    def updateRelatedCategory(self, category, previous_category_url, new_category_url):
1208 1209 1210 1211
      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
1212
      new_category = re.sub('(?P<start>.*)/%s/(?P<stop>.*)' %
1213
            previous_category_url,'\g<start>/%s/\g<stop>' % new_category_url,new_category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1214 1215
      new_category = re.sub('(?P<start>.*)/%s$' %
            previous_category_url,'\g<start>/%s' % new_category_url, new_category)
1216 1217
      return new_category

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    def updateRelatedContent(self, context,
                             previous_category_url, new_category_url):
      """Updates related object when an object have moved.
      
          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
1228
      """
1229 1230
      for brain in self.Base_zSearchRelatedObjectsByCategory(
                                              category_uid = context.getUid()):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1231
        o = brain.getObject()
1232 1233 1234
        if o is not None:
          category_list = []
          for category in self.getCategoryList(o):
1235 1236 1237
            new_category = self.updateRelatedCategory(category,
                                                      previous_category_url,
                                                      new_category_url)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1238
            category_list.append(new_category)
1239
          self._setCategoryList(o, category_list)
1240

1241 1242
          if getattr(aq_base(o),
                    'notifyAfterUpdateRelatedContent', None) is not None:
1243 1244 1245
            o.notifyAfterUpdateRelatedContent(previous_category_url,
                                              new_category_url)

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

1250
      aq_context = aq_base(context)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1251
      # Update related recursively if required
1252
      if getattr(aq_context, 'listFolderContents', None) is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1253
        for o in context.listFolderContents():
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
          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' )
1268 1269 1270 1271 1272 1273
    def getRelatedValueList(self, context, base_category_list=None,
                           spec=(), filter=None, base=1, **kw):
      """
        This methods returns the list of objects related to the context
        with the given base_category_list.
      """
1274
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1275
      portal_type = kw.get('portal_type')
1276
      
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1277
      if isinstance(portal_type, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1278 1279 1280
        portal_type = [portal_type]
      if spec is (): spec = None # We do not want to care about spec

1281 1282 1283 1284
      # 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
1285
        if isinstance(base_category_list, str):
1286 1287 1288 1289 1290 1291
          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()))
1292
      
1293 1294 1295 1296 1297
      brain_result = self.Base_zSearchRelatedObjectsByCategoryList(
                           category_list = category_list,
                           portal_type = portal_type,
                           strict_membership = strict_membership )
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
      result = []
      for b in brain_result:
        o = b.getObject()
        if o is not None:
          result.append(o)

      return result
                                  # XXX missing filter and **kw stuff
      #return self.search_category(category_list = category_list, portal_type = spec)
      # future implementation with brains, much more efficient
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
    
    security.declareProtected( Permissions.AccessContentsInformation,
                               'getRelatedPropertyList' )
    def getRelatedPropertyList(self, context, base_category_list=None,
                          property_name=None, spec=(), filter=None, base=1, **kw):
      """
        This methods returns the list of property_name on  objects
        related to the context with the given base_category_list.
      """
      result = []
      for o in self.getRelatedValueList(context=context,
                          base_category_list=base_category_list, spec=spec,
                          filter=filter, base=base, **kw) :
        result.append(o.getProperty(property_name, None))
      return result
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1324 1325
    # SQL Expression Building
    security.declareProtected(Permissions.AccessContentsInformation, 'buildSQLSelector')
1326
    def buildSQLSelector(self, category_list, query_table='category'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1327 1328 1329 1330
      """
        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
1331
        to generate a much more complex where_expression with table aliases
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1332 1333 1334

        List of lists
      """
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1335
      if isinstance(category_list, str):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1336 1337 1338 1339 1340
        category_list = [category_list]
      sql_expr = []
      for category in category_list:
        if category is None:
          pass
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1341 1342
        elif isinstance(category, str):
          if category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1343 1344
            category_uid = self.getCategoryUid(category)
            base_category_uid = self.getBaseCategoryUid(category)
1345 1346 1347 1348 1349 1350 1351 1352 1353
            expression = ''
            if category_uid is None:
              expression += '%s.category_uid is NULL' % query_table
            else:
              expression += '%s.category_uid = %s' % (query_table,category_uid)
            if base_category_uid is None:
              expression += ' AND %s.base_category_uid is NULL' % query_table
            else:
              expression += ' AND %s.base_category_uid = %s' % (query_table,base_category_uid)
1354
            sql_expr += ["(%s)" % expression]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1355 1356 1357 1358 1359 1360
        else:
          single_sql_expr = []
          for single_category in category:
            if single_sql_expr != '':
              category_uid = self.getCategoryUid(single_category)
              base_category_uid = self.getBaseCategoryUid(single_category)
1361 1362 1363 1364 1365 1366 1367 1368
              if category_uid is None:
                expression += '%s.category_uid is NULL' % query_table
              else:
                expression += '%s.category_uid = %s' % (query_table,category_uid)
              if base_category_uid is None:
                expression += ' AND %s.base_category_uid is NULL' % query_table
              else:
                expression += ' AND %s.base_category_uid = %s' % (query_table,base_category_uid)
1369
              single_sql_expr += ["(%s)" % expression]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1370
          if len(single_sql_expr) > 0:
1371
            sql_expr += "( %s )" % ' OR '.join(single_sql_expr)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1372
      if len(sql_expr) > 0:
1373
        sql_expr = ' OR '.join(sql_expr)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1374 1375 1376
      return sql_expr

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberValueList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1377
    def getCategoryMemberValueList(self, context, base_category = None,
1378
                                         spec = (), filter=None, portal_type=(), **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1379 1380 1381
      """
      This returns a catalog_search resource with can then be used by getCategoryMemberItemList
      """
1382
      from Products.ERP5Form.Selection import DomainSelection
Kevin Deldycke's avatar
Kevin Deldycke committed
1383
      if base_category is None:
1384
        if context.getPortalType() in ( "Base Category", "Category") :
Kevin Deldycke's avatar
Kevin Deldycke committed
1385 1386 1387
          base_category = context.getBaseCategoryId()
        else:
          raise CategoryError('getCategoryMemberValueList must know the base category')
1388
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1389

1390 1391
      domain_dict = {base_category: ('portal_categories', context.getRelativeUrl())}
      selection_domain = DomainSelection(domain_dict = domain_dict).__of__(context)
1392 1393
      if strict_membership:
        catalog_search = self.portal_catalog(portal_type = portal_type,
1394
		           selection_report = selection_domain)
1395 1396
      else:
        catalog_search = self.portal_catalog(portal_type = portal_type,
1397
                           selection_domain = selection_domain)
1398
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1399 1400 1401
      return catalog_search

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberItemList' )
1402
    def getCategoryMemberItemList(self, context, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1403
      """
1404 1405 1406 1407 1408 1409
      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
        strict_membership : returns only object belonging to this category, not 
                            objects belonging to child categories.
        strict            : a deprecated alias for strict_membership
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1410
      """
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1411
      k = {}
1412
      for v in ('portal_type', 'spec', 'strict', 'strict_membership'):
1413
        if v in kw:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1414 1415
          k[v] = kw[v]
      catalog_search = self.getCategoryMemberValueList(context, **k)
1416
      return Renderer(**kw).render(catalog_search)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1417 1418 1419

    security.declareProtected( Permissions.AccessContentsInformation,
                                                                'getCategoryMemberTitleItemList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1420
    def getCategoryMemberTitleItemList(self, context, base_category = None,
1421 1422
                                      spec = (), filter=None, portal_type=(), strict_membership = 0, 
                                      strict="DEPRECATED"):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1423 1424 1425 1426
      """
      This returns a title list of items belonging to a category

      """
1427
      return self.getCategoryMemberItemList(self, context, base_category = base_category,
1428 1429 1430
                                spec = spec, filter=filter, portal_type=portal_type, 
                                strict_membership = strict_membership, strict = strict,
                                display_id = 'getTitle')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1431 1432


1433
    security.declarePublic('resolveCategory')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1434 1435 1436
    def resolveCategory(self, relative_url):
        """
          Finds an object from a relative_url
1437
          Method is public since we use restrictedTraverse
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1438
        """
1439
        cache = getReadOnlyTransactionCache(self)
1440 1441 1442 1443 1444 1445 1446
        if cache is not None:
          key = ('resolveCategory', relative_url)
          try:
            return cache[key]
          except KeyError:
            pass
            
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1447 1448 1449 1450 1451 1452 1453 1454
        try:
          obj = self.restrictedTraverse(relative_url)
          if obj is None:
            REQUEST = self.REQUEST
            url = '%s/%s' % ('/'.join(self.getPhysicalPath()), relative_url)
            #LOG("CMFCategory:",0,"Trying url %s" % url )
            obj = self.portal_catalog.resolve_url(url, REQUEST)
          #LOG('Obj type', 0, str(obj.getUid()))
1455
          value = obj
1456
        except (KeyError, AttributeError) :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1457
          LOG("CMFCategory WARNING",0,"Could not access object relative_url %s" % relative_url )
1458 1459 1460 1461 1462 1463
          value = None
          
        if cache is not None:
          cache[key] = value
          
        return value
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1464 1465 1466 1467 1468 1469

InitializeClass( CategoryTool )

# Psyco
import psyco
psyco.bind(CategoryTool)