Category.py 40.8 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
#
# 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.
#
##############################################################################

import string

31
from Products.ERP5Type.Globals import InitializeClass, DTMLFile
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32
from AccessControl import ClassSecurityInfo
33
from AccessControl import getSecurityManager
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34 35 36 37
from Acquisition import aq_base, aq_inner, aq_parent

from Products.ERP5Type import Permissions
from Products.ERP5Type import PropertySheet
38
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
39
from Products.ERP5Type.Accessor.Base import Getter as BaseGetter
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40
from Products.ERP5Type.Core.Folder import Folder
41
from Products.CMFCategory.Renderer import Renderer
42
from Products.ERP5Type.Utils import sortValueList
43 44 45
from Products.ERP5Type.Cache import CachingMethod

DEFAULT_CACHE_FACTORY = 'erp5_ui_long'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
46 47 48

from zLOG import LOG

49 50
NBSP_UTF8 = u'\xA0'.encode('utf-8')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
51 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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
manage_addCategoryForm=DTMLFile('dtml/category_add', globals())

def addCategory( self, id, title='', REQUEST=None ):
    """
        Add a new Category and generate UID by calling the
        ZSQLCatalog
    """
    sf = Category( id )
    sf._setTitle(title)
    self._setObject( id, sf )
    sf = self._getOb( id )
    sf.reindexObject()
    if REQUEST is not None:
        return self.manage_main(self, REQUEST, update_menu=1)

class Category(Folder):
    """
        Category objects allow to define classification categories
        in an ERP5 portal. For example, a document may be assigned a color
        attribute (red, blue, green). Rather than assigning an attribute
        with a pop-up menu (which is still a possibility), we can prefer
        in certain cases to associate to the object a category. In this
        example, the category will be named color/red, color/blue or color/green

        Categories can include subcategories. For example, a region category can
        define
            region/europe
            region/europe/west/
            region/europe/west/france
            region/europe/west/germany
            region/europe/south/spain
            region/americas
            region/americas/north
            region/americas/north/us
            region/americas/south
            region/asia

        In this example the base category is 'region'.

        Categories are meant to be indexed with the ZSQLCatalog (and thus
        a unique UID will be automatically generated each time a category is
        indexed).

        Categories allow define sets and subsets of objects and can be used
        for many applications :

        - association of a document to a URL

        - description of organisations (geographical, professional)

        Through acquisition, it is possible to create 'virtual' classifications based
        on existing documents or categories. For example, if there is a document at
        the URL
            organisation/nexedi
        and there exists a base category 'client', then the portal_categories tool
        will allow to create a virtual category
            client/organisation/nexedi

        Virtual categories allow not to duplicate information while providing
        a representation power equivalent to RDF or relational databases.

        Categories are implemented as a subclass of BTreeFolders

        NEW: categories should also be able to act as a domain. We should add
        a Domain interface to categories so that we do not need to regenerate
        report trees for categories.
    """

    meta_type='CMF Category'
    portal_type='Category' # may be useful in the future...
121
    isCategory = ConstantGetter('isCategory', value=True)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
122 123 124 125 126 127 128 129
    icon = None

    allowed_types = (
                  'CMF Category',
               )

    # Declarative security
    security = ClassSecurityInfo()
130
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    security.declareProtected(Permissions.ManagePortal,
                              'manage_editProperties',
                              'manage_changeProperties',
                              'manage_propertiesForm',
                                )

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.SimpleItem )

    # Declarative constructors
    constructors =   (manage_addCategoryForm, addCategory)

    # Filtered Types allow to define which meta_type subobjects
    # can be created within the ZMI
    def filtered_meta_types(self, user=None):
        # Filters the list of available meta types.
        # so that only Category objects appear inside the
        # CategoryTool contents
        all = Category.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

    security.declareProtected(Permissions.AccessContentsInformation,
158
                                                    'getLogicalPath')
159
    def getLogicalPath(self, item_method = 'getTitle'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
160
      """
161
        Returns logical path, starting under base category.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
162
      """
163 164 165 166 167 168
      objectlist = []
      base = self.getBaseCategory()
      current = self
      while not current is base :
        objectlist.insert(0, current)
        current = aq_parent(current)
169 170 171 172

      # it s better for the user to display something than only ''...
      logical_title_list = []
      for object in objectlist:
173
        logical_title = getattr(object, item_method)()
174 175 176 177
        if logical_title in [None, '']:
          logical_title = object.getId()
        logical_title_list.append(logical_title)
      return '/'.join(logical_title_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
178

179 180
    security.declareProtected(Permissions.AccessContentsInformation,
                            'getTranslatedLogicalPath')
181 182 183 184 185 186
    def getTranslatedLogicalPath(self):
      """
        Returns translated logical path, started under base category.
      """
      return self.getLogicalPath(item_method='getTranslatedTitle')

187 188
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getCompactLogicalPath')
189 190 191 192 193 194
    def getCompactLogicalPath(self):
      """
        Returns compact logical path, started under base category.
      """
      return self.getLogicalPath(item_method='getCompactTitle')

195 196 197 198 199 200 201 202
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getTranslatedCompactLogicalPath')
    def getTranslatedCompactLogicalPath(self):
      """
        Returns translated compact logical path, started under base category.
      """
      return self.getLogicalPath(item_method='getCompactTranslatedTitle')

203 204
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getIndentedTitle')
205
    def getIndentedTitle(self, item_method = 'getTitle'):
206 207 208 209 210 211 212 213 214 215 216 217 218 219
      """
        Returns title or id, indented from base_category.
      """
      path_len = 0
      base = self.getBaseCategory()
      current = self
      while not current is base :
        path_len += 1
        current = aq_parent(current)

      # it s better for the user to display something than only ''...
      logical_title_list = []

      if path_len >= 2:
220 221
        logical_title_list.append(NBSP_UTF8 * 4 * (path_len - 1))

222
      logical_title = getattr(self, item_method)()
223
      if logical_title in [None, '']:
Jérome Perrin's avatar
typo  
Jérome Perrin committed
224
        logical_title = self.getId()
225 226 227
      logical_title_list.append(logical_title)
      return ''.join(logical_title_list)

Nicolas Delaby's avatar
Nicolas Delaby committed
228 229 230 231 232 233 234 235
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getIndentedShortTitle')
    def getIndentedShortTitle(self):
      """
        Returns short_title or id, indented from base_category.
      """
      return self.getIndentedTitle(item_method='getShortTitle')

236 237 238 239 240 241
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getIndentedTitleAndId')
    def getIndentedTitleAndId(self, item_method='getTitleAndId'):
      """
        Returns title or id, indented from base_category.
      """
Romain Courteaud's avatar
Romain Courteaud committed
242
      return self.getIndentedTitle(item_method=item_method)
243

244 245 246 247
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getTranslatedIndentedTitle')
    def getTranslatedIndentedTitle(self):
      """
248
        Returns translated indented title, started under base category.
249 250 251
      """
      return self.getIndentedTitle(item_method='getTranslatedTitle')

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getIndentedCompactTitle')
    def getIndentedCompactTitle(self):
      """
        Returns indented compact title, started under base category.
      """
      return self.getIndentedTitle(item_method='getCompactTitle')

    security.declareProtected(Permissions.AccessContentsInformation,
                              'getTranslatedIndentedCompactTitle')
    def getTranslatedIndentedCompactTitle(self):
      """
        Returns translated indented compact title, started under base category.
      """
      return self.getIndentedTitle(item_method='getCompactTranslatedTitle')

268 269
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getCategoryChildValueList')
270
    def getCategoryChildValueList(self, recursive=1, include_if_child=1,
271
                                  is_self_excluded=1, sort_on=None,
272
                                  sort_order=None, local_sort_method=None,
273 274
                                  local_sort_id=None, checked_permission=None,
                                  **kw):
275 276 277
      """
          List the child objects of this category and all its subcategories.

278
          recursive         - if set to 1, list recursively
279

280 281 282 283
          include_if_child  - if set to 0, categories having child categories
                              are not included.
                              DEPRECATED, use filter_node=1 if you don't want
                              to display categories having childs.
284

285
          is_self_excluded  - if set to 1, exclude this category from the list
286 287

          sort_on, sort_order - the same semantics as ZSQLCatalog
288 289 290 291
                              sort_on specifies properties used for sorting
                              sort_order specifies how categories are sorted.
                              The default is to do a preorder tree traversal on
                              all sub-objects.
292

293 294
                              WARNING: using these parameters can slow down
                              significantly, because this is written in Python
Jean-Paul Smets's avatar
Jean-Paul Smets committed
295

296 297
          local_sort_method - When using the default preorder traversal, use
                              this function to sort objects of the same depth.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
298

299 300
          local_sort_id     - When using the default preorder traversal, sort
                              objects of the same depth by comparing their
301 302 303
                              'local_sort_id' property. local_sort_id can be a
                              list, in this case properties are compared in the
                              same order than this list.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
304

Jérome Perrin's avatar
Jérome Perrin committed
305
          Renderer parameters are also supported here.
306
      """
307 308
      if is_self_excluded or (
                    not(include_if_child) and
309
                    len(self.objectIds(self.allowed_types)) > 0):
310 311 312
        value_list = []
      else:
        value_list = [self]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
313

314 315
      child_value_list = self.objectValues(self.allowed_types)
      if local_sort_id:
316 317 318 319 320 321 322 323 324 325 326
        if isinstance(local_sort_id, (tuple, list)):
          def sort_method(a, b):
            for sort_id in local_sort_id:
              diff = cmp(a.getProperty(sort_id, 0), b.getProperty(sort_id, 0))
              if diff != 0:
                return diff
            return 0
          local_sort_method = sort_method
        else:
          local_sort_method = lambda a, b: cmp(a.getProperty(local_sort_id, 0),
                                               b.getProperty(local_sort_id, 0))
327 328 329 330 331
      if local_sort_method:
        # sort objects at the current level
        child_value_list = list(child_value_list)
        child_value_list.sort(local_sort_method)

332
      if recursive:
333
        for c in child_value_list:
334 335
          # Do not pass sort_on / sort_order parameters intentionally, because
          # sorting needs to be done only at the end of recursive calls.
336
          value_list.extend(c.getCategoryChildValueList(recursive=1,
337
                                       is_self_excluded=0,
338 339 340
                                       include_if_child=include_if_child,
                                       local_sort_method=local_sort_method,
                                       local_sort_id=local_sort_id))
341
      else:
342
        for c in child_value_list:
343
          value_list.append(c)
344

345 346 347
      if checked_permission is not None:
        checkPermission = self.portal_membership.checkPermission
        def permissionFilter(obj):
Jérome Perrin's avatar
Jérome Perrin committed
348
          return checkPermission(checked_permission, obj)
349 350
        value_list = filter(permissionFilter, value_list)

351
      return sortValueList(value_list, sort_on, sort_order, **kw)
352

Jean-Paul Smets's avatar
Jean-Paul Smets committed
353 354 355
    # List names recursively
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getCategoryChildRelativeUrlList')
356 357
    def getCategoryChildRelativeUrlList(self, base='', recursive=1,
                                        checked_permission=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
358 359 360 361 362 363 364 365
      """
          List the path of this category and all its subcategories.

          base -- a boolean or a string. If it is a string, then use
                  that string as a base

          recursive - if set to 1, list recursively
      """
366 367
      if not base:
        base = '' # Make sure we get a meaningful base
368 369 370
      elif isinstance(base, str):
        base = base + '/'
      elif base:
371
        base = self.getBaseCategoryId() + '/' # Make sure we get a meaningful base
372
      url_list = []
373
      for value in self.getCategoryChildValueList(recursive=recursive,
374 375
                                                  checked_permission=checked_permission,
                                                  **kw):
376 377
        url_list.append(base + value.getRelativeUrl())
      return url_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
378 379 380 381 382 383

    security.declareProtected(Permissions.AccessContentsInformation, 'getPathList')
    getPathList = getCategoryChildRelativeUrlList

    security.declareProtected(Permissions.AccessContentsInformation,
                                                      'getCategoryChildTitleItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
384
    def getCategoryChildTitleItemList(self, recursive=1, base=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
385 386 387 388
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getTitle as default method
      """
Jérome Perrin's avatar
Jérome Perrin committed
389 390
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='title', base=base, **kw)
391

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

402 403 404 405 406
    security.declareProtected(Permissions.AccessContentsInformation,
                                                      'getCategoryChildTitleOrIdItemList')
    def getCategoryChildTitleOrIdItemList(self, recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
407
      given list of base categories. Uses getTitleOrId as default method
408 409
      """
      return self.getCategoryChildItemList(recursive = recursive, display_id='title_or_id', base=base, **kw)
410

411 412 413 414 415 416 417 418
    security.declareProtected(Permissions.AccessContentsInformation,
                                       'getCategoryChildTitleAndIdItemList')
    def getCategoryChildTitleAndIdItemList(self, recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses title_and_id as default method
      """
      return self.getCategoryChildItemList(recursive=recursive,
419
                                    display_id='title_and_id', base=base, **kw)
420

421 422 423 424 425
    security.declareProtected(Permissions.AccessContentsInformation,
                                       'getCategoryChildCompactTitleItemList')
    def getCategoryChildCompactTitleItemList(self, recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
426
      given list of base categories. Uses compact_title as default method
427 428
      """
      return self.getCategoryChildItemList(recursive=recursive,
Jérome Perrin's avatar
Jérome Perrin committed
429 430
                                           display_id='compact_title',
                                           base=base, **kw)
431

432
    security.declareProtected(Permissions.AccessContentsInformation,
433 434
                        'getCategoryChildTranslatedCompactTitleItemList')
    def getCategoryChildTranslatedCompactTitleItemList(self, recursive=1, base=0, **kw):
435 436 437 438 439
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses translated_compact_title as default method
      """
      return self.getCategoryChildItemList(recursive=recursive,
440
                                           display_id='compact_translated_title',
441
                                           base=base, **kw)
442

443
    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
444
                                       'getCategoryChildLogicalPathItemList')
445 446 447 448 449
    def getCategoryChildLogicalPathItemList(self, recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getLogicalPath as default method
      """
Jérome Perrin's avatar
Jérome Perrin committed
450 451 452
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='logical_path',
                                           base=base, **kw)
453

454 455
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getCategoryChildTranslatedLogicalPathItemList')
Jérome Perrin's avatar
Jérome Perrin committed
456 457
    def getCategoryChildTranslatedLogicalPathItemList(self,
                                              recursive=1, base=0, **kw):
458 459 460 461 462
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses translation of getLogicalPath
      as default method
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
463
      return self.getCategoryChildItemList(recursive=recursive,
Jérome Perrin's avatar
Jérome Perrin committed
464
                       display_id='translated_logical_path', base=base, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
465

466 467 468 469 470 471 472 473 474 475 476 477
    security.declareProtected(Permissions.AccessContentsInformation,
                             'getCategoryChildTranslatedCompactLogicalPathItemList')
    def getCategoryChildTranslatedCompactLogicalPathItemList(self,
                                                             recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getLogicalPath as default method
      """
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='translated_compact_logical_path',
                                           base=base, **kw)

478
    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
479 480 481
                             'getCategoryChildCompactLogicalPathItemList')
    def getCategoryChildCompactLogicalPathItemList(self,
                                                   recursive=1, base=0, **kw):
482 483 484 485
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getLogicalPath as default method
      """
Jérome Perrin's avatar
Jérome Perrin committed
486 487 488
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='compact_logical_path',
                                           base=base, **kw)
489

490
    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
491 492 493
                                     'getCategoryChildIndentedTitleItemList')
    def getCategoryChildIndentedTitleItemList(self,
                                              recursive=1, base=0, **kw):
494 495 496 497
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getIndentedTitle as default method
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
498
      return self.getCategoryChildItemList(recursive=recursive,
499 500
          display_id='indented_title', base=base, **kw)

501 502 503 504 505 506 507 508 509 510 511
    security.declareProtected(Permissions.AccessContentsInformation,
                                     'getCategoryChildIndentedTitleAndIdItemList')
    def getCategoryChildIndentedTitleAndIdItemList(self,
                                              recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getIndentedTitle as default method
      """
      return self.getCategoryChildItemList(recursive=recursive,
          display_id='indented_title_and_id', base=base, **kw)

512 513 514 515 516 517 518 519 520 521 522
    security.declareProtected(Permissions.AccessContentsInformation,
                                     'getCategoryChildTranslatedIndentedTitleItemList')
    def getCategoryChildTranslatedIndentedTitleItemList(self,
                                              recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getIndentedTitle as default method
      """
      return self.getCategoryChildItemList(recursive=recursive,
          display_id='translated_indented_title', base=base, **kw)

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getCategoryChildIndentedCompactTitleItemList')
    def getCategoryChildIndentedCompactTitleItemList(self,
                                              recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getIndentedTitle as default method
      """
      return self.getCategoryChildItemList(recursive=recursive,
          display_id='indented_compact_title', base=base, **kw)

    security.declareProtected(Permissions.AccessContentsInformation,
                              'getCategoryChildTranslatedIndentedCompactTitleItemList')
    def getCategoryChildTranslatedIndentedCompactTitleItemList(self,
                                              recursive=1, base=0, **kw):
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getIndentedTitle as default method
      """
      return self.getCategoryChildItemList(recursive=recursive,
          display_id='translated_indented_compact_title', base=base, **kw)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
545
    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
546
                                              'getCategoryChildIdItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
547
    def getCategoryChildIdItemList(self, recursive=1, base=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
548 549 550 551
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getId as default method
      """
Jérome Perrin's avatar
Jérome Perrin committed
552 553
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='id', base=base, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
554 555 556


    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
557
                              'getCategoryChildItemList')
558
    def getCategoryChildItemList(self, recursive=1, base=0,
559 560
                                       cache=DEFAULT_CACHE_FACTORY,
                                       current_category_list=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
561 562 563 564
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Each tuple contains::

565
        (c.relative_url, c.display_id())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
566 567 568 569 570 571 572 573

      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)

              if set to string, use string as base

Jean-Paul Smets's avatar
Jean-Paul Smets committed
574
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
575 576

      recursive -- if set to 0 do not apply recursively
577

578 579 580 581 582
      current_category_list -- allows to provide list of categories which is not part of the
                          default ItemList. Very useful for displaying values in a popup
                          menu which can no longer be selected. It is required to give
                          url including base category.

Jérome Perrin's avatar
Jérome Perrin committed
583
      All parameters supported by getCategoryChildValueList and Render are
584
      supported here.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
585
      """
586
      def _renderCategoryChildItemList(recursive=1, base=0, **kw):
Jérome Perrin's avatar
Jérome Perrin committed
587
        value_list = self.getCategoryChildValueList(recursive=recursive, **kw)
588 589
        return Renderer(base=base, **kw).render(value_list)

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
      if cache:
        _renderCategoryChildItemList = CachingMethod(
          _renderCategoryChildItemList,
          (
            'Category_getCategoryChildItemList',
            self.getPortalObject().Localizer.get_selected_language(),
            self.getPath(),
            getSecurityManager().getUser().getId() if 'checked_permission' in kw else None,
          ),
          cache_factory=cache,
        )
      item_list = _renderCategoryChildItemList(recursive=recursive, base=base, **kw)

      if current_category_list:
        kw['display_none_category'] = False
        current_category_item_list = Renderer(base=base, **kw).render(
          map(self.portal_categories.resolveCategory, current_category_list))
        item_set = {tuple(x) for x in item_list}
        additional_item_list = []
        for current_category_item in current_category_item_list:
          if not(tuple(current_category_item) in item_set):
            additional_item_list.append(current_category_item)
        if additional_item_list:
          item_list = item_list + additional_item_list
      return item_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
615 616 617 618 619 620 621

    # Alias for compatibility
    security.declareProtected(Permissions.View, 'getFormItemList')
    def getFormItemList(self):
      """
        Alias for compatibility and accelation
      """
Jérome Perrin's avatar
Jérome Perrin committed
622 623 624
      return self.getCategoryChildItemList(base=0,
                                           display_none_category=1,
                                           recursive=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
625 626

    # Alias for compatibility
Jérome Perrin's avatar
Jérome Perrin committed
627 628
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getBaseItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
629
    def getBaseItemList(self, base=0, prefix=''):
Jérome Perrin's avatar
Jérome Perrin committed
630 631 632
      return self.getCategoryChildItemList(base=base,
                                           display_none_category=0,
                                           recursive=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
633 634

    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
635
                              'getCategoryRelativeUrl')
636
    def getCategoryRelativeUrl(self, base=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650
      """
        Returns a relative_url of this category relative
        to its base category (if base is 0) or to
        portal_categories (if base is 1)
      """
      my_parent = aq_parent(self)

      if my_parent is not None:
        if my_parent.meta_type != self.meta_type:
          if base:
            return self.getBaseCategoryId() + '/' + self.id
          else:
            return self.id
        else:
651
          return my_parent.getCategoryRelativeUrl(base=base) + '/' + self.id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
652 653 654 655 656 657 658 659
      else:
        if base:
          return self.getBaseCategoryId() + '/' + self.id
        else:
          return self.id


    # Alias for compatibility
Jérome Perrin's avatar
Jérome Perrin committed
660 661
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getCategoryName')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
662 663 664 665 666
    getCategoryName = getCategoryRelativeUrl

    # Predicate interface
    _operators = []

667
    security.declareProtected(Permissions.AccessContentsInformation, 'test')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
668 669 670 671 672 673
    def test(self, context):
      """
        A Predicate can be tested on a given context
      """
      return context.isMemberOf(self.getCategoryName())

674 675
    security.declareProtected( Permissions.AccessContentsInformation, 'asSQLExpression' )
    def asSQLExpression(self, strict_membership=0, table='category', base_category = None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
676 677 678 679 680
      """
        A Predicate can be rendered as an sql expression. This
        can be useful to create reporting trees based on the
        ZSQLCatalog
      """
681 682 683 684
      if base_category is None:
        base_category = self
      elif type(base_category) is type('a'):
        base_category = self.portal_categories[base_category]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
685
      if strict_membership:
Romain Courteaud's avatar
Romain Courteaud committed
686 687
        sql_text = '(%s.category_uid = %s AND %s.base_category_uid = %s ' \
                   'AND %s.category_strict_membership = 1)' % \
688
                                 (table, self.getUid(), table,
689
                                  base_category.getBaseCategoryUid(), table)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
690
      else:
Romain Courteaud's avatar
Romain Courteaud committed
691
        sql_text = '(%s.category_uid = %s AND %s.base_category_uid = %s)' % \
692
            (table, self.getUid(), table, base_category.getBaseCategoryUid())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
693 694
      # Now useless since we precompute the mapping
      #for o in self.objectValues():
695
      #  sql_text += ' OR %s' % o.asSQLExpression()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
696 697
      return sql_text

698 699
    security.declareProtected( Permissions.AccessContentsInformation, 'asSqlExpression' )
    asSqlExpression = asSQLExpression
700

Jean-Paul Smets's avatar
Jean-Paul Smets committed
701 702 703 704 705 706 707 708 709 710 711
    # A Category's categories is self


    security.declareProtected( Permissions.AccessContentsInformation, 'getRelativeUrl' )
    def getRelativeUrl(self):
      """
        We must eliminate portal_categories in the RelativeUrl
        since it is never present in the category list
      """
      return '/'.join(self.portal_url.getRelativeContentPath(self)[1:])

712
    security.declareProtected( Permissions.AccessContentsInformation, 'isMemberOf' )
713
    def isMemberOf(self, category, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
714 715 716
      """
        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)
717
        Keywords parameters :
718
         - strict_membership:  if we want strict membership checking
719
         - strict : alias for strict_membership (deprecated but still here for
720
                    skins backward compatibility. )
721

Jean-Paul Smets's avatar
Jean-Paul Smets committed
722
      """
723 724
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
      if strict_membership:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
725
        if self.getRelativeUrl().find(category) >= 0:
726
          if len(self.getRelativeUrl()) == len(category) + self.getRelativeUrl().find(category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
727 728 729 730
            return 1
      else:
        if self.getRelativeUrl().find(category) >= 0:
          return 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
731 732 733
      return 0

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberValueList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
734
    def getCategoryMemberValueList(self, base_category = None,
735
                            spec=(), filter=None, portal_type=(), **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
736 737 738
      """
      Returns a list of objects or brains
      """
739
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
740 741
      if base_category is None:
        base_category = self.getBaseCategoryId()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
742
      return self.portal_categories.getCategoryMemberValueList(self,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
743
            base_category = base_category,
744
            spec=spec, filter=filter, portal_type=portal_type, strict_membership=strict_membership)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
745 746

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberItemList' )
747
    def getCategoryMemberItemList(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
748 749 750
      """
      Returns a list of objects or brains
      """
751
      return self.portal_categories.getCategoryMemberItemList(self, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
752 753 754

    security.declareProtected( Permissions.AccessContentsInformation,
                                                               'getCategoryMemberTitleItemList' )
755
    def getCategoryMemberTitleItemList(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
756 757 758
      """
      Returns a list of objects or brains
      """
759
      kw['display_id'] = 'title'
760 761
      kw['display_method'] = None
      return self.portal_categories.getCategoryMemberItemList(self, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
762

763 764 765 766 767 768 769 770 771 772 773
    security.declareProtected( Permissions.AccessContentsInformation, 'getBreadcrumbList' )
    def getBreadcrumbList(self):
      """
      Returns a list of objects or brains
      """
      title_list = []
      if not self.isBaseCategory:
        title_list.extend(self.aq_parent.getBreadcrumbList())
        title_list.append(self.getTitle())
      return title_list

Jean-Paul Smets's avatar
Jean-Paul Smets committed
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
manage_addBaseCategoryForm=DTMLFile('dtml/base_category_add', globals())

def addBaseCategory( self, id, title='', REQUEST=None ):
    """
        Add a new Category and generate UID
    """
    sf = BaseCategory( id )
    sf._setTitle(title)
    self._setObject( id, sf )
    sf = self._getOb( id )
    sf.reindexObject()
    if REQUEST is not None:
        return self.manage_main(self, REQUEST, update_menu=1)






class BaseCategory(Category):
    """
      Base Categories allow to implement virtual categories
      through acquisition
    """
    meta_type='CMF Base Category'
    portal_type='Base Category' # maybe useful some day
800
    isBaseCategory = ConstantGetter('isBaseCategory', value=True)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
801 802 803 804 805 806 807 808 809

    constructors =   (manage_addBaseCategoryForm, addBaseCategory)

    property_sheets = ( PropertySheet.Base
                      , PropertySheet.SimpleItem
                      , PropertySheet.BaseCategory)

    # Declarative security
    security = ClassSecurityInfo()
810
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
811

812 813 814
    # BBB: Required to start instance with old
    #      version of erp5_property_sheets BT.
    related_locally_indexed = False
815
    security.declarePrivate('isRelatedLocallyIndexed')
816 817 818 819
    def isRelatedLocallyIndexed(self):
      """Determines if related values should be indexed on target documents"""
      return self.related_locally_indexed

820
    security.declareProtected(Permissions.AccessContentsInformation, 'asSQLExpression')
821
    def asSQLExpression(self, strict_membership=0, table='category', base_category=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
822 823 824 825 826 827
      """
        A Predicate can be rendered as an sql expression. This
        can be useful to create reporting trees based on the
        ZSQLCatalog
      """
      if strict_membership:
Romain Courteaud's avatar
Romain Courteaud committed
828 829 830
        sql_text = '(%s.category_uid = %s AND %s.base_category_uid = %s ' \
                   'AND %s.category_strict_membership = 1)' % \
                                (table, self.uid, table, self.uid, table)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
831
      else:
Romain Courteaud's avatar
Romain Courteaud committed
832 833
        sql_text = '(%s.category_uid = %s AND %s.base_category_uid = %s)' % \
                               (table, self.uid, table, self.uid)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
834 835
      # Now useless since we precompute the mapping
      #for o in self.objectValues():
836
      #  sql_text += ' OR %s' % o.asSQLExpression()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
837 838
      return sql_text

839
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
840
                              'getBaseCategoryId')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
841 842 843 844 845 846 847 848
    def getBaseCategoryId(self):
      """
        The base category of this object
        acquired through portal categories. Very
        useful to implement relations and virtual categories.
      """
      return self.getBaseCategory().id

849
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
850
                              'getBaseCategoryUid')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
851 852 853 854 855 856
    def getBaseCategoryUid(self):
      """
        The base category uid of this object
        acquired through portal categories. Very
        useful to implement relations and virtual categories.
      """
857
      return self.getBaseCategory().getUid()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
858

859
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
860
                              'getBaseCategoryValue')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
861 862 863 864 865 866 867 868
    def getBaseCategoryValue(self):
      """
        The base category of this object
        acquired through portal categories. Very
        useful to implement relations and virtual categories.
      """
      return self

869
    security.declareProtected(Permissions.AccessContentsInformation,
870 871
                                                 'getCategoryChildValueList')
    def getCategoryChildValueList(self, is_self_excluded=1, recursive=1,
872
                     include_if_child=1, sort_on=None, sort_order=None,
873 874
                     local_sort_method=None, local_sort_id=None,
                     checked_permission=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
875
      """
876
          List the child objects of this category and all its subcategories.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
877

878
          recursive - if set to 1, list recursively
879 880 881 882 883 884 885 886 887 888 889 890

          include_if_child - if set to 1, then a category is listed even if
                      has childs. if set to 0, then don't list if child.
                      for example:
                        region/europe
                        region/europe/france
                        region/europe/germany
                        ...
                      becomes:
                        region/europe/france
                        region/europe/germany
                        ...
891 892 893 894 895 896
          sort_on, sort_order - sort categories in 'sort_order' by comparing
                  the 'sort_on' attribute. The default is to do a preorder tree
                  traversal on all subobjects.

          local_sort_method - When using the default preorder traversal, use
                              this function to sort objects of the same depth.
897

898 899
          local_sort_id     - When using the default preorder traversal, sort
                              objects of the same depth by comparing their
900 901 902
                              'local_sort_id' property. local_sort_id can be a
                              list, in this case properties are compared in the
                              same order than this list.
903

Jérome Perrin's avatar
Jérome Perrin committed
904
          Renderer parameters are also supported here.
905

Jean-Paul Smets's avatar
Jean-Paul Smets committed
906
      """
907 908 909
      if is_self_excluded:
        value_list = []
      else:
910
        value_list = [self]
911 912 913

      child_value_list = self.objectValues(self.allowed_types)
      if local_sort_id:
914 915 916 917 918 919 920 921 922 923
        if isinstance(local_sort_id, (tuple, list)):
          def sort_method(a, b):
            for sort_id in local_sort_id:
              diff = cmp(a.getProperty(sort_id, 0), b.getProperty(sort_id, 0))
              if diff != 0:
                return diff
            return 0
          local_sort_method = sort_method
        else:
          local_sort_method = lambda a, b: cmp(a.getProperty(local_sort_id, 0),
924
                                             b.getProperty(local_sort_id, 0))
925 926 927 928
      if local_sort_method:
        # sort objects at the current level
        child_value_list = list(child_value_list)
        child_value_list.sort(local_sort_method)
929

Jean-Paul Smets's avatar
Jean-Paul Smets committed
930
      if recursive:
931
        for c in child_value_list:
932
          value_list.extend(c.getCategoryChildValueList(recursive=1,
933
                                        is_self_excluded=0,
934 935 936
                                        include_if_child=include_if_child,
                                        local_sort_id=local_sort_id,
                                        local_sort_method=local_sort_method))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
937
      else:
938
        for c in child_value_list:
939 940 941
          if include_if_child:
            value_list.append(c)
          else:
942
            if len(c.objectIds(self.allowed_types))==0:
943
              value_list.append(c)
944 945 946 947

      if checked_permission is not None:
        checkPermission = self.portal_membership.checkPermission
        def permissionFilter(obj):
Jérome Perrin's avatar
Jérome Perrin committed
948
          return checkPermission(checked_permission, obj)
949 950
        value_list = filter(permissionFilter, value_list)

951
      return sortValueList(value_list, sort_on, sort_order, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
952 953

    # Alias for compatibility
954
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
955
                              'getBaseCategory')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
956 957
    getBaseCategory = getBaseCategoryValue

958 959 960 961 962 963 964 965
    # Hardcode these getters as they are used when generating
    # accessors
    getReadPermission = BaseGetter('getReadPermission', 'read_permission',
                                   'string')

    getWritePermission = BaseGetter('getWritePermission', 'write_permission',
                                    'string')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
966 967
InitializeClass( Category )
InitializeClass( BaseCategory )