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

import string

from Globals import InitializeClass, DTMLFile
from AccessControl import ClassSecurityInfo
from Acquisition import aq_base, aq_inner, aq_parent
34
from Products.CMFCore.utils import getToolByName
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35 36 37

from Products.ERP5Type import Permissions
from Products.ERP5Type import PropertySheet
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38
from Products.ERP5Type.Core.Folder import Folder
39
from Products.CMFCategory.Renderer import Renderer
40
from Products.ERP5Type.Utils import sortValueList
41 42 43
from Products.ERP5Type.Cache import CachingMethod

DEFAULT_CACHE_FACTORY = 'erp5_ui_long'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
44 45 46 47 48 49 50 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 121 122 123 124 125 126 127

from zLOG import LOG

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...
    isPortalContent = 1
    isRADContent = 1
    isCategory = 1
    icon = None

    allowed_types = (
                  'CMF Category',
               )

    # Declarative security
    security = ClassSecurityInfo()
128
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    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,
156
                                                    'getLogicalPath')
157
    def getLogicalPath(self, item_method = 'getTitle'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
158
      """
159
        Returns logical path, starting under base category.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
160
      """
161 162 163 164 165 166
      objectlist = []
      base = self.getBaseCategory()
      current = self
      while not current is base :
        objectlist.insert(0, current)
        current = aq_parent(current)
167 168 169 170

      # it s better for the user to display something than only ''...
      logical_title_list = []
      for object in objectlist:
171
        logical_title = getattr(object, item_method)()
172 173 174 175
        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
176

177 178 179 180 181 182
    def getTranslatedLogicalPath(self):
      """
        Returns translated logical path, started under base category.
      """
      return self.getLogicalPath(item_method='getTranslatedTitle')

183 184 185 186 187 188
    def getCompactLogicalPath(self):
      """
        Returns compact logical path, started under base category.
      """
      return self.getLogicalPath(item_method='getCompactTitle')

189 190
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getIndentedTitle')
191
    def getIndentedTitle(self, item_method = 'getTitle'):
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
      """
        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:
        logical_title_list.append('&nbsp;' * 4 * (path_len - 1))
      
208
      logical_title = getattr(self, item_method)()
209
      if logical_title in [None, '']:
Jérome Perrin's avatar
typo  
Jérome Perrin committed
210
        logical_title = self.getId()
211 212 213
      logical_title_list.append(logical_title)
      return ''.join(logical_title_list)

214 215 216 217 218 219 220 221
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getTranslatedIndentedTitle')
    def getTranslatedIndentedTitle(self):
      """
        Returns translated logical path, started under base category.
      """
      return self.getIndentedTitle(item_method='getTranslatedTitle')

222 223
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getCategoryChildValueList')
224
    def getCategoryChildValueList(self, recursive=1, include_if_child=1,
225
                                  is_self_excluded=1, sort_on=None,
226
                                  sort_order=None, local_sort_method=None,
227 228
                                  local_sort_id=None, checked_permission=None,
                                  **kw):
229 230 231
      """
          List the child objects of this category and all its subcategories.

232
          recursive         - if set to 1, list recursively
233

234 235
          include_if_child  - if set to 1, categories having child categories
                              are not included
236
          
237
          is_self_excluded  - if set to 1, exclude this category from the list
238 239

          sort_on, sort_order - the same semantics as ZSQLCatalog
240 241 242 243
                              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.
244

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

248 249
          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
250

251 252 253
          local_sort_id     - When using the default preorder traversal, sort
                              objects of the same depth by comparing their
                              'local_sort_id' property.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
254

Jérome Perrin's avatar
Jérome Perrin committed
255
          Renderer parameters are also supported here.
256
      """
257 258
      if is_self_excluded or (
                    not(include_if_child) and
259
                    len(self.objectIds(self.allowed_types)) > 0):
260 261 262
        value_list = []
      else:
        value_list = [self]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
263

264 265
      child_value_list = self.objectValues(self.allowed_types)
      if local_sort_id:
266 267
        local_sort_method = lambda a, b: cmp(a.getProperty(local_sort_id, 0),
                                             b.getProperty(local_sort_id, 0))
268 269 270 271 272
      if local_sort_method:
        # sort objects at the current level
        child_value_list = list(child_value_list)
        child_value_list.sort(local_sort_method)

273
      if recursive:
274 275
        for c in child_value_list:
          # Do not global pass sort parameters intentionally, because sorting
276
          # needs to be done only at the end of recursive calls.
277
          value_list.extend(c.getCategoryChildValueList(recursive=1,
278
                                       is_self_excluded=0,
279 280 281
                                       include_if_child=include_if_child,
                                       local_sort_method=local_sort_method,
                                       local_sort_id=local_sort_id))
282
      else:
283
        for c in child_value_list:
284
          value_list.append(c)
285

286 287 288 289 290 291 292 293 294
      if checked_permission is not None:
        checkPermission = self.portal_membership.checkPermission
        def permissionFilter(obj):
          if checkPermission(checked_permission, obj):
            return 1
          else:
            return 0
        value_list = filter(permissionFilter, value_list)

295
      return sortValueList(value_list, sort_on, sort_order, **kw)
296

Jean-Paul Smets's avatar
Jean-Paul Smets committed
297 298 299
    # List names recursively
    security.declareProtected(Permissions.AccessContentsInformation,
                                                    'getCategoryChildRelativeUrlList')
300
    def getCategoryChildRelativeUrlList(self, base='', recursive=1, checked_permission=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
301 302 303 304 305 306 307 308 309 310
      """
          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
      """
      if base == 0 or base is None: base = '' # Make sure we get a meaningful base
      if base == 1: base = self.getBaseCategoryId() + '/' # Make sure we get a meaningful base
311
      url_list = []
312 313
      for value in self.getCategoryChildValueList(recursive=recursive,
                                                  checked_permission=checked_permission):
314 315
        url_list.append(base + value.getRelativeUrl())
      return url_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
316 317 318 319 320 321

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

    security.declareProtected(Permissions.AccessContentsInformation,
                                                      'getCategoryChildTitleItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
322
    def getCategoryChildTitleItemList(self, recursive=1, base=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
323 324 325 326
      """
      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
327 328
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='title', base=base, **kw)
329

330 331 332 333 334
    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
335
      given list of base categories. Uses getTranslatedTitle as default method
336
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
337
      return self.getCategoryChildItemList(recursive=recursive,
338 339
                      display_id='translated_title', base=base, **kw)

340 341 342 343 344
    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
345
      given list of base categories. Uses getTitleOrId as default method
346 347
      """
      return self.getCategoryChildItemList(recursive = recursive, display_id='title_or_id', base=base, **kw)
348 349 350 351 352 353 354 355 356
    
    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,
357
                                    display_id='title_and_id', base=base, **kw)
358

359 360 361 362 363 364 365 366
    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
      given list of base categories. Uses title_and_id as default method
      """
      return self.getCategoryChildItemList(recursive=recursive,
Jérome Perrin's avatar
Jérome Perrin committed
367 368
                                           display_id='compact_title',
                                           base=base, **kw)
369

370
    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
371
                                       'getCategoryChildLogicalPathItemList')
372 373 374 375 376
    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
377 378 379
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='logical_path',
                                           base=base, **kw)
380
    
Jérome Perrin's avatar
Jérome Perrin committed
381 382
    def getCategoryChildTranslatedLogicalPathItemList(self,
                                              recursive=1, base=0, **kw):
383 384 385 386 387
      """
      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
388
      return self.getCategoryChildItemList(recursive=recursive,
Jérome Perrin's avatar
Jérome Perrin committed
389
                       display_id='translated_logical_path', base=base, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
390

391
    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
392 393 394
                             'getCategoryChildCompactLogicalPathItemList')
    def getCategoryChildCompactLogicalPathItemList(self,
                                                   recursive=1, base=0, **kw):
395 396 397 398
      """
      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
399 400 401
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='compact_logical_path',
                                           base=base, **kw)
402
    
403
    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
404 405 406
                                     'getCategoryChildIndentedTitleItemList')
    def getCategoryChildIndentedTitleItemList(self,
                                              recursive=1, base=0, **kw):
407 408 409 410
      """
      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
411
      return self.getCategoryChildItemList(recursive=recursive,
412 413
          display_id='indented_title', base=base, **kw)

414 415 416 417 418 419 420 421 422 423 424
    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)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
425
    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
426
                                              'getCategoryChildIdItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
427
    def getCategoryChildIdItemList(self, recursive=1, base=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
428 429 430 431
      """
      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
432 433
      return self.getCategoryChildItemList(recursive=recursive,
                                           display_id='id', base=base, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
434 435 436


    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
437
                              'getCategoryChildItemList')
438 439
    def getCategoryChildItemList(self, recursive=1, base=0,
                                       cache=DEFAULT_CACHE_FACTORY, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
440 441 442 443
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Each tuple contains::

444
        (c.relative_url, c.display_id())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
445 446 447 448 449 450 451 452

      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
453
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
454 455

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

Jérome Perrin's avatar
Jérome Perrin committed
457
      All parameters supported by getCategoryChildValueList and Render are
458
      supported here.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
459
      """
460
      def _renderCategoryChildItemList(recursive=1, base=0, **kw):
Jérome Perrin's avatar
Jérome Perrin committed
461
        value_list = self.getCategoryChildValueList(recursive=recursive, **kw)
462 463 464
        return Renderer(base=base, **kw).render(value_list)

      if not cache:
Jérome Perrin's avatar
Jérome Perrin committed
465 466
        return _renderCategoryChildItemList(
                      recursive=recursive, base=base, **kw)
467

Jérome Perrin's avatar
Jérome Perrin committed
468 469
      # Some methods are language dependent so we include the language in the
      # key
470
      localizer = getToolByName(self, 'Localizer')
Jérome Perrin's avatar
Jérome Perrin committed
471
      language = localizer.get_selected_language()
472
      m = CachingMethod(_renderCategoryChildItemList,
Jérome Perrin's avatar
Jérome Perrin committed
473
            ('Category_getCategoryChildItemList', language, self.getPath()))
474 475

      return m(recursive=recursive, base=base, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
476 477 478 479 480 481 482

    # 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
483 484 485
      return self.getCategoryChildItemList(base=0,
                                           display_none_category=1,
                                           recursive=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
486 487

    # Alias for compatibility
Jérome Perrin's avatar
Jérome Perrin committed
488 489
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getBaseItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
490
    def getBaseItemList(self, base=0, prefix=''):
Jérome Perrin's avatar
Jérome Perrin committed
491 492 493
      return self.getCategoryChildItemList(base=base,
                                           display_none_category=0,
                                           recursive=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
494 495

    security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin's avatar
Jérome Perrin committed
496
                              'getCategoryRelativeUrl')
497
    def getCategoryRelativeUrl(self, base=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
498 499 500 501 502 503 504 505 506 507 508 509 510 511
      """
        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:
512
          return my_parent.getCategoryRelativeUrl(base=base) + '/' + self.id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
513 514 515 516 517 518 519 520
      else:
        if base:
          return self.getBaseCategoryId() + '/' + self.id
        else:
          return self.id


    # Alias for compatibility
Jérome Perrin's avatar
Jérome Perrin committed
521 522
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getCategoryName')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
523 524 525 526 527 528 529 530 531 532 533
    getCategoryName = getCategoryRelativeUrl

    # Predicate interface
    _operators = []

    def test(self, context):
      """
        A Predicate can be tested on a given context
      """
      return context.isMemberOf(self.getCategoryName())

534 535
    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
536 537 538 539 540
      """
        A Predicate can be rendered as an sql expression. This
        can be useful to create reporting trees based on the
        ZSQLCatalog
      """
541 542 543 544
      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
545
      if strict_membership:
Romain Courteaud's avatar
Romain Courteaud committed
546 547 548
        sql_text = '(%s.category_uid = %s AND %s.base_category_uid = %s ' \
                   'AND %s.category_strict_membership = 1)' % \
                                 (table, self.getUid(), table, 
549
                                  base_category.getBaseCategoryUid(), table)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
550
      else:
Romain Courteaud's avatar
Romain Courteaud committed
551
        sql_text = '(%s.category_uid = %s AND %s.base_category_uid = %s)' % \
552
            (table, self.getUid(), table, base_category.getBaseCategoryUid())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
553 554
      # Now useless since we precompute the mapping
      #for o in self.objectValues():
555
      #  sql_text += ' OR %s' % o.asSQLExpression()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
556 557
      return sql_text

558 559 560
    security.declareProtected( Permissions.AccessContentsInformation, 'asSqlExpression' )
    asSqlExpression = asSQLExpression
  
Jean-Paul Smets's avatar
Jean-Paul Smets committed
561 562 563 564 565 566 567 568 569 570 571 572
    # 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:])

    security.declareProtected( Permissions.View, 'isMemberOf' )
573
    def isMemberOf(self, category, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
574 575 576
      """
        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)
577 578 579 580 581
        Keywords parameters : 
         - strict_membership:  if we want strict membership checking
         - strict : alias for strict_membership (deprecated but still here for 
                    skins backward compatibility. )
         
Jean-Paul Smets's avatar
Jean-Paul Smets committed
582
      """
583 584
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
      if strict_membership:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
585
        if self.getRelativeUrl().find(category) >= 0:
586
          if len(self.getRelativeUrl()) == len(category) + self.getRelativeUrl().find(category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
587 588 589 590
            return 1
      else:
        if self.getRelativeUrl().find(category) >= 0:
          return 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
591 592 593
      return 0

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberValueList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
594
    def getCategoryMemberValueList(self, base_category = None,
595
                            spec=(), filter=None, portal_type=(), **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
596 597 598
      """
      Returns a list of objects or brains
      """
599
      strict_membership = kw.get('strict_membership', kw.get('strict', 0))
600 601
      if base_category is None:
        base_category = self.getBaseCategoryId()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
602
      return self.portal_categories.getCategoryMemberValueList(self,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
603
            base_category = base_category,
604
            spec=spec, filter=filter, portal_type=portal_type, strict_membership=strict_membership)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
605 606

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberItemList' )
607
    def getCategoryMemberItemList(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
608 609 610
      """
      Returns a list of objects or brains
      """
611
      return self.portal_categories.getCategoryMemberItemList(self, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
612 613 614

    security.declareProtected( Permissions.AccessContentsInformation,
                                                               'getCategoryMemberTitleItemList' )
615
    def getCategoryMemberTitleItemList(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
616 617 618
      """
      Returns a list of objects or brains
      """
619 620 621
      kw['display_id'] = 'getTitle'
      kw['display_method'] = None
      return self.portal_categories.getCategoryMemberItemList(self, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
622

623 624 625 626 627 628 629 630 631 632 633
    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
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
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
    isPortalContent = 1
    isRADContent = 1
    isBaseCategory = 1

    constructors =   (manage_addBaseCategoryForm, addBaseCategory)

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

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

674
    def asSQLExpression(self, strict_membership=0, table='category', base_category=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
675 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
      """
      if strict_membership:
Romain Courteaud's avatar
Romain Courteaud committed
681 682 683
        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
684
      else:
Romain Courteaud's avatar
Romain Courteaud committed
685 686
        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
687 688
      # Now useless since we precompute the mapping
      #for o in self.objectValues():
689
      #  sql_text += ' OR %s' % o.asSQLExpression()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
690 691
      return sql_text

Romain Courteaud's avatar
Romain Courteaud committed
692 693
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getBaseCategoryId')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
694 695 696 697 698 699 700 701
    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

Romain Courteaud's avatar
Romain Courteaud committed
702 703
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getBaseCategoryUid')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
704 705 706 707 708 709
    def getBaseCategoryUid(self):
      """
        The base category uid of this object
        acquired through portal categories. Very
        useful to implement relations and virtual categories.
      """
710
      return self.getBaseCategory().getUid()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
711

Romain Courteaud's avatar
Romain Courteaud committed
712 713
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getBaseCategoryValue')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
714 715 716 717 718 719 720 721
    def getBaseCategoryValue(self):
      """
        The base category of this object
        acquired through portal categories. Very
        useful to implement relations and virtual categories.
      """
      return self

722
    security.declareProtected(Permissions.AccessContentsInformation,
723 724
                                                 'getCategoryChildValueList')
    def getCategoryChildValueList(self, is_self_excluded=1, recursive=1,
725
                     include_if_child=1, sort_on=None, sort_order=None,
726 727
                     local_sort_method=None, local_sort_id=None,
                     checked_permission=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
728
      """
729
          List the child objects of this category and all its subcategories.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
730

731
          recursive - if set to 1, list recursively
732 733 734 735 736 737 738 739 740 741 742 743

          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
                        ...
744 745 746 747 748 749 750 751 752 753 754
          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.
          
          local_sort_id     - When using the default preorder traversal, sort
                              objects of the same depth by comparing their
                              'local_sort_id' property.
          
Jérome Perrin's avatar
Jérome Perrin committed
755
          Renderer parameters are also supported here.
756

Jean-Paul Smets's avatar
Jean-Paul Smets committed
757
      """
758 759 760
      if is_self_excluded:
        value_list = []
      else:
761
        value_list = [self]
762 763 764

      child_value_list = self.objectValues(self.allowed_types)
      if local_sort_id:
765 766
        local_sort_method = lambda a, b: cmp(a.getProperty(local_sort_id, 0),
                                             b.getProperty(local_sort_id, 0))
767 768 769 770
      if local_sort_method:
        # sort objects at the current level
        child_value_list = list(child_value_list)
        child_value_list.sort(local_sort_method)
771
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
772
      if recursive:
773
        for c in child_value_list:
774
          value_list.extend(c.getCategoryChildValueList(recursive=1,
775
                                        is_self_excluded=0,
776 777 778
                                        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
779
      else:
780
        for c in child_value_list:
781 782 783
          if include_if_child:
            value_list.append(c)
          else:
784
            if len(c.objectIds(self.allowed_types))==0:
785
              value_list.append(c)
786 787 788 789 790 791 792 793 794 795

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

796
      return sortValueList(value_list, sort_on, sort_order, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
797 798

    # Alias for compatibility
799
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
800
                              'getBaseCategory')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
801 802 803 804 805
    getBaseCategory = getBaseCategoryValue

InitializeClass( Category )
InitializeClass( BaseCategory )