CategoryTool.py 46 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 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 128 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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solane <jp@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

"""\
ERP portal_categories tool.
"""

from OFS.Folder import Folder
from Products.CMFCore.utils import UniqueObject
from Globals import InitializeClass, DTMLFile
from AccessControl import ClassSecurityInfo
from Acquisition import aq_base
from Products.ERP5Type import Permissions
from Products.ERP5Type.Base import Base
from Products.CMFCategory import _dtmldir
from Products.CMFCore.PortalFolder import ContentFilter

import string, re

from zLOG import LOG

class CategoryError( Exception ):
    pass

class CategoryTool( UniqueObject, Folder, Base ):
    """
      The CategoryTool object is the placeholder for all methods
      and algorithms related to categories and relations in CMF.

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

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

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

      Membership is ordered and multiple. For example, if a swim suit uses
      three colors (eg : color1, color2, color3 which are used in the top, belt and in
      the bottom) and if a particular variation of that swim suit has two of the three colors        the same (eg black, blue, black) then the category membership list from the color point        of view is::

        color/black
        color/blue
        color/black

        TODO: Add sort methods everywhere

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

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

    id              = 'portal_categories'
    meta_type       = 'CMF Categories'
    allowed_types = ( 'CMF Base Category', )


    # Declarative Security
    security = ClassSecurityInfo()

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

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


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

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

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

    def _buildQuery(self, spec, filter, kw):
      return apply( ContentFilter, (), self._buildFilter(spec, filter, kw) )

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

        Two alias are provided :

        getBaseCategoryIds -- backward compatibility with early ERP5 versions

        baseCategoryIds -- for zope users conveniance
      """
      if context is None:
        return self.objectIds()
      else:
        return context._categories

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

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

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

        Two alias are provided :

        getBaseCategoryValues -- backward compatibility with early ERP5 versions

        baseCategoryValues -- for zope users conveniance
      """
      if context is None:
        return self.objectValues()
      else:
        return map(lambda x:self[x], context._categories)

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

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

    security.declareProtected(Permissions.AccessContentsInformation, 'getCategoryValue')
    def getCategoryValue(self, relative_url, base_category = None):
      """
        Returns a Category object from a given category url
        and optionnal base category id
      """
      try:
        relative_url = str(relative_url)
        if base_category is not None:
          relative_url = '%s/%s' % (base_category, relative_url)
        node = self.unrestrictedTraverse(relative_url)
        return node
      except:
        return None

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

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

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryId')
    def getBaseCategoryId(self, relative_url, base_category = None):
      """
        Returns the id of the base category from a given relative url
        and optional base category
      """
      if base_category is not None:
        return base_category
      try:
        return relative_url.split('/')[0]
      except:
        return None

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseCategoryUid')
    def getBaseCategoryUid(self, relative_url, base_category = None):
      """
        Returns the uid of the base category from a given relative_url
        and optional base category
      """
      try:
        return self.getCategoryValue(self.getBaseCategoryId(relative_url,
                        base_category = base_category)).uid
      except:
        return None

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

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

        strict       -- if set to 1, only return uids of parents, not
                        relative_url
      """
      uid_dict = {}
      if type(relative_url) is type('a'): relative_url = (relative_url,)
      for path in relative_url:
        try:
          o = self.getCategoryValue(path, base_category=base_category)
          if o is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
269 270
            base_category = self.getBaseCategoryId(path)
            bo = self.get(base_category, None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
            if bo is not None:
              bo_uid = int(bo.getUid())
              uid_dict[(int(o.uid), bo_uid, 1)] = 1 # Strict Membership
              if o.meta_type == 'CMF Category' or o.meta_type == 'CMF Base Category':
                # This goes up in the category tree
                # XXX we should also go up in some other cases....
                # ie. when some documents act as categories
                if not strict:
                  while o.meta_type == 'CMF Category':
                    o = o.aq_parent
                    uid_dict[(int(o.uid), bo_uid, 0)] = 1 # Non Strict Membership
        except:
          LOG('WARNING: CategoriesTool',0, 'Unable to find uid for %s' % path)
      return uid_dict.keys()

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

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

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

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

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

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

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

      recursive -- if set to 0 do not apply recursively
      """
      if base_category is None:
        base_category_list = self.getBaseCategoryIdList()
      elif type(base_category) == type('a'):
        base_category_list = [base_category]
      else:
        base_category_list = base_category
      result = []
      for base_category in base_category_list:
        category = self[base_category]
        if category is not None:
          result += category.getCategoryChildRelativeUrlList(base=base,recursive=recursive)
      return result

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

    security.declareProtected(Permissions.AccessContentsInformation,
                                                      'getCategoryChildTitleItemList')
    def getCategoryChildTitleItemList(self, base_category=None,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
340
                                recursive=1, base=0, display_none_category=0, sort_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
341 342 343 344 345
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getTitle as default method
      """
      return self.getCategoryChildItemList(recursive = recursive,base=base,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
346
       display_none_category=display_none_category,display_id='getTitle', sort_id=sort_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
347 348 349 350

    security.declareProtected(Permissions.AccessContentsInformation,
                                                      'getCategoryChildIdItemList')
    def getCategoryChildIdItemList(self, base_category=None,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
351
              recursive=1, base=0, display_none_category=0, sort_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
352 353 354 355 356
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Uses getId as default method
      """
      return self.getCategoryChildItemList(recursive = recursive,base=base,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
357
         display_none_category=display_none_category,display_id='getId', sort_id=sort_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
358 359 360

    security.declareProtected(Permissions.AccessContentsInformation,
                                                      'getCategoryChildItemList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
361 362
    def getCategoryChildItemList(self, base_category=None, display_id = None,
            recursive=1, base=0, display_none_category=1, sort_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
363 364 365 366
      """
      Returns a list of tuples by parsing recursively all categories in a
      given list of base categories. Each tuple contains::

Jean-Paul Smets's avatar
Jean-Paul Smets committed
367
        (c.relative_url,c.display_id())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
368 369 370 371 372 373 374 375 376 377

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

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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
378
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
379 380 381 382 383 384 385 386 387

      recursive -- if set to 0 do not apply recursively
      """
      if type(base_category) == type('a'):
        base_category_list = [base_category]
      elif base_category is None:
        base_category_list = self.getBaseCategoryIdList()
      else:
        base_category_list = base_category
Jean-Paul Smets's avatar
Jean-Paul Smets committed
388
      if display_none_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
389 390 391 392 393 394 395
        result = [('', '')]
      else:
        result = []
      for base_category in base_category_list:
        category = self[base_category]
        if category is not None:
          result += category.getCategoryChildItemList(base=base,recursive=recursive,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
396
                                                            display_id=display_id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
397 398 399 400 401 402 403 404 405 406 407
      #if sort_id is not None:
      #  result.sort()

      return result

    security.declareProtected(Permissions.AccessContentsInformation, 'getBaseItemList')
    getBaseItemList = getCategoryChildItemList

    # Category to Tuple Conversion
    security.declareProtected(Permissions.View, 'asItemList')
    def asItemList(self, relative_url, base_category=None,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
408
            display_id = None, base = 0, sort_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
409 410
      """
      Returns a list of tuples, each tuple is calculated by applying
Jean-Paul Smets's avatar
Jean-Paul Smets committed
411
      display_id on each category provided in relative_url
Jean-Paul Smets's avatar
Jean-Paul Smets committed
412 413 414 415 416 417 418 419 420 421

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

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

Jean-Paul Smets's avatar
Jean-Paul Smets committed
422
      display_id -- method called to build the couple
Jean-Paul Smets's avatar
Jean-Paul Smets committed
423 424 425 426

      recursive -- if set to 0 do not apply recursively
      """
      result = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
427
      if display_id is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
428 429 430 431 432 433 434
        for c in relative_url:
          result += [(c, c)]
      else:
        for c in relative_url:
          o = self.getCategoryValue(c, base_category=base_category)
          if o is not None:
            try:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
435
              v = getattr(o, display_id)()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 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 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
              result = result + [(c,v)]
            except:
              LOG('WARNING: CategoriesTool',0, 'Unable to call %s on %s' %
                  (method, c))
          else:
            LOG('WARNING: CategoriesTool',0, 'Unable to find category %s' % c)

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

      return result

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

    # Convert a list of membership to path
    security.declareProtected(Permissions.View, 'asPathList')
    def asPathList(self, base_category, category_list):
      if type(category_list) == type('a'):
        category_list = [category_list]
      if category_list == None:
        category_list = []
      new_list = []
      for v in category_list:
        new_list += ['%s/%s' % (base_category,v)]
      return new_list

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


    # Category implementation
    security.declareProtected( Permissions.AccessContentsInformation,
                                                  'getCategoryMembershipList' )
    def getCategoryMembershipList(self, context, base_category, base=0,
                                spec=(), filter=None, **kw  ):
      """
        Returns a list of category membership
        represented as a list of relative URLs

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

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

        spec          --    a list or a tuple of portal types

        base          --    if set to 1, returns relative URLs to portal_categories
                            if set to 0, returns relative URLs to the base category
      """
      # XXX We must use filters in the future
      # query = self._buildQuery(spec, filter, kw)
      portal_type = kw.get('portal_type', ())
      if spec is (): spec = portal_type

      # LOG('getCategoryMembershipList',0,str(spec))
      # LOG('getCategoryMembershipList',0,str(base_category))
      membership = []
      if type(base_category) not in (type(()), type([])):
        category_list = [base_category]
      else:
        category_list = base_category
      if type(spec) is not type([]) and type(spec) is not type(()):
        spec = [spec]
      for path in self._getCategoryList(context):
        # LOG('getCategoryMembershipList',0,str(path))
        my_base_category = path.split('/')[0]
        for my_category in category_list:
          if type(my_category) is type('a'):
            category = my_category
          else:
            category = my_category.getRelativeUrl()
          if my_base_category == category:
            if spec is ():
              if base:
                membership += [path]
              else:
                membership += [path[len(category)+1:]]
            else:
              try:
               o = self.unrestrictedTraverse(path)
               # LOG('getCategoryMembershipList',0,str(o.portal_type))
               if o.portal_type in spec:
                if base:
                  membership += [path]
                else:
                  membership += [path[len(category)+1:]]
              except:
                LOG('WARNING: CategoriesTool',0, 'Unable to find object for path %s' % path)
      # We must include parent if specified explicitely
      if 'parent' in category_list:
        parent = context.aq_parent
        if parent.portal_type in spec:
          if base:
            membership += ['parent/' + parent.getRelativeUrl()]
          else:
            membership += [parent.getRelativeUrl()]
      return membership

    security.declareProtected( Permissions.AccessContentsInformation, 'setCategoryMembership' )
    def setCategoryMembership(self, context, base_category_list, category_list, base=0, keep_default=1,
                                 spec=(), filter=None, **kw ):
      """
        Sets the membership of the context on the specified base_category
        list and for the specified portal_type spec

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

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

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

        spec               --    a list or a tuple of portal types

      """
      #LOG("set Category 1",0,str(category_list))
      # XXX We must use filters in the future
      # query = self._buildQuery(spec, filter, kw)
      portal_type = kw.get('portal_type', ())
      if spec is (): spec = portal_type

      default_dict = {}
      self._cleanupCategories(context)
      if type(category_list) is type('a'):
        category_list = (category_list,)
      elif category_list is None:
        category_list = ()
      if type(base_category_list) is type('a'):
        base_category_list = [base_category_list]
      new_category_list = []
      for path in self._getCategoryList(context):
        my_base_id = self.getBaseCategoryId(path)
        if not my_base_id in base_category_list:
          # Keep each membership which is not in the
          # specified list of base_category ids
          new_category_list += [path]
        else:
          if spec is ():
            # If spec is (), then we should keep nothing
            # Everything will be replaced
            keep_it = 0
          else:
            # Only keep this if not in our spec
            try:
              my_type = self.unrestrictedTraverse(path).portal_type
              keep_it = 1
              for spec_type in spec:
                if spec_type == my_type:
                  keep_it = 0
            except:
              keep_it = 0
          if keep_it:
            new_category_list += [path]
          elif keep_default:
            # We must remember the default value
            # for each replaced category
            if not default_dict.has_key(my_base_id):
              default_dict[my_base_id] = path
      # We now create a list of default category values
      default_new_category_list = []
      for path in default_dict.values():
        if base or len(base_category_list) > 1:
          if path in category_list:
            default_new_category_list += [path]
        else:
          if path[len(base_category_list[0])+1:] in category_list:
            default_new_category_list += [path]
      # Before we append new category values (except default values)
      # We must make sure however that multiple links are possible
      default_path_found = {}
      for path in category_list:
        if path is not '':
          if base or len(base_category_list) > 1:
            # Only keep path which are member of base_category_list
            if self.getBaseCategoryId(path) in base_category_list:
              if path not in default_new_category_list or default_path_found.has_key(path):
                default_path_found[path] = 1
                new_category_list += [path]
          else:
            new_path = base_category_list[0] + '/' + path
            if new_path not in default_new_category_list:
              new_category_list += [new_path]
      #LOG("set Category",0,str(new_category_list))
      self._setCategoryList(context, tuple(default_new_category_list + new_category_list))

    security.declareProtected( Permissions.AccessContentsInformation, 'setDefaultCategoryMembership' )
    def setDefaultCategoryMembership(self, context, base_category, default_category,
                                              spec=(), filter=None, portal_type=(), base=0 ):
      """
        Sets the membership of the context on the specified base_category
        list and for the specified portal_type spec

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

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

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

        spec               --    a list or a tuple of portal types

      """
      self._cleanupCategories(context)
      if type(default_category) is type([]) or type(default_category) is type(()):
        default_category = default_category[0]
      category_list = self.getCategoryMembershipList(context, base_category,
                           spec=spec, filter=filter, portal_type=portal_type, base=base)
      new_category_list = [default_category]
      found_one = 0
      # We will keep from the current category_list
      # everything except the first occurence of category
      # this allows to have multiple occurences of the same category
      for category in category_list:
        if category != default_category or found_one:
          new_category_list += [category]
          found_one = 1
      self.setCategoryMembership(context, base_category, new_category_list,
           spec=spec, filter=filter, portal_type=portal_type, base=base, keep_default = 0)

    security.declareProtected( Permissions.AccessContentsInformation,
                                                        'getSingleCategoryMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
658
    def getSingleCategoryMembershipList(self, context, base_category, base=0,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
                                          spec=(), filter=None, **kw):
      """
        Returns the local membership of the context for a single base category
        represented as a list of relative URLs

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

        base_category --    a single base category (string)

        spec          --    a list or a tuple of portal types

        base          --    if set to 1, returns relative URLs to portal_categories
                            if set to 0, returns relative URLs to the base category
      """
      # XXX We must use filters in the future
      # query = self._buildQuery(spec, filter, kw)
      portal_type = kw.get('portal_type', ())
      if spec is (): spec = portal_type

      result = []
      # XXX We must use filters in the future
      # query = self._buildQuery(spec, filter, kw)
      spec = kw.get('portal_type', ())
      # Make sure spec is a list or tuple
      if type(spec) is type('a'):
        spec = [spec]
      # Filter categories
      if hasattr(context, 'categories'):
        for category_url in self._getCategoryList(context):
          my_base_category = category_url.split('/')[0]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
689
          if my_base_category == base_category:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
690
            #LOG("getSingleCategoryMembershipList",0,"%s %s %s %s" % (context.getRelativeUrl(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
691
            #                  my_base_category, base_category, category_url))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
            if spec is ():
              if base:
                result += [category_url]
              else:
                result += [category_url[len(my_base_category)+1:]]
            else:
              try:
                my_reference = self.unrestrictedTraverse(category_url)
              except KeyError:
                # object does not exist
                my_reference = None
              if my_reference is not None:
                if my_reference.portal_type in spec:
                  if base:
                    result += [category_url]
                  else:
                    result += [category_url[len(my_base_category)+1:]]
      return result


    security.declareProtected( Permissions.AccessContentsInformation,
                                      'getSingleCategoryAcquiredMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
714
    def getSingleCategoryAcquiredMembershipList(self, context, base_category, base=0,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728
                                         spec=(), filter=None, **kw ):
      """
        Returns the acquired membership of the context for a single base category
        represented as a list of relative URLs

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

        base_category --    a single base category (string)

        spec          --    a list or a tuple of portal types

        base          --    if set to 1, returns relative URLs to portal_categories
                            if set to 0, returns relative URLs to the base category
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
729
      #LOG("Get Acquired Category ",0,str((base_category, context)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
730 731 732 733 734 735 736
      # XXX We must use filters in the future
      # query = self._buildQuery(spec, filter, kw)
      portal_type = kw.get('portal_type', ())
      if spec is (): spec = portal_type

      if type(spec) is type('a'):
        spec = [spec]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
737
      result = self.getSingleCategoryMembershipList( context, base_category, base=base,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
738
                            spec=spec, filter=filter, **kw )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
739
      base_category = self.getCategoryValue(base_category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
740 741 742 743 744 745 746 747 748 749 750 751
      if base_category is not None:
        # If we do not mask or append, return now if not empty
        if not base_category.getAcquisitionMaskValue() and \
                not base_category.getAcquisitionAppendValue() and \
                len(result) > 0:
          return result
        # First we look at local ids
        for object_id in base_category.getAcquisitionObjectIdList():
          my_acquisition_object = context.get(object_id)
          if my_acquisition_object is not None:
            if spec is () or my_acquisition_object.portal_type in spec:
              new_result = self.getSingleCategoryMembershipList(my_acquisition_object,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
752
                  base_category, spec=spec, filter=filter, portal_type=portal_type, base=base)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
753 754 755 756 757 758 759 760 761
            if base_category.acquisition_mask_value:
              # If acquisition masks, then we must return now
              return new_result
            if base_category.acquisition_append_value:
              # If acquisition appends, then we must append to the result
              result += new_result
        # Next we look at references
        #LOG("Get Acquired BC",0,str(base_category.getAcquisitionBaseCategoryList()))
        acquisition_pt = base_category.getAcquisitionPortalTypeList(())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
762
        for my_base_category in base_category.getAcquisitionBaseCategoryList():
Jean-Paul Smets's avatar
Jean-Paul Smets committed
763
          # We implement here special keywords
Jean-Paul Smets's avatar
Jean-Paul Smets committed
764
          if my_base_category == 'parent':
Jean-Paul Smets's avatar
Jean-Paul Smets committed
765 766 767 768 769 770 771 772 773 774 775 776
            parent = context.aq_parent
            if parent is self.getPortalObject():
              my_acquisition_object_list = []
            else:
              #LOG("Parent Object List ",0,str(parent.getRelativeUrl()))
              #LOG("Parent Object List ",0,str(parent.portal_type))
              #LOG("Parent Object List ",0,str(acquisition_pt))
              if acquisition_pt is () or parent.portal_type in acquisition_pt:
                my_acquisition_object_list = [parent]
              else:
                my_acquisition_object_list = []
          else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
777
            my_acquisition_object_list = context.getValueList(my_base_category,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
778 779 780 781 782 783 784 785 786
                                   portal_type=tuple(base_category.getAcquisitionPortalTypeList(())))
          #LOG("Get Acquired PT",0,str(base_category.getAcquisitionPortalTypeList(())))
          #LOG("Object List ",0,str(my_acquisition_object_list))
          original_result = result
          result = list(result) # make a copy
          for my_acquisition_object in my_acquisition_object_list:
            if my_acquisition_object is not None:
              if hasattr(my_acquisition_object, '_categories'):
                # We should only consider objects which define that category
Jean-Paul Smets's avatar
Jean-Paul Smets committed
787
                if base_category in my_acquisition_object._categories:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
788 789
                  if spec is () or my_acquisition_object.portal_type in spec:
                    new_result = self.getSingleCategoryAcquiredMembershipList(my_acquisition_object,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
790
                        base_category, spec=spec, filter=filter, portal_type=portal_type, base=base)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
791 792 793 794 795 796 797 798 799 800
                  else:
                    new_result = []
                  if base_category.acquisition_append_value:
                    # If acquisition appends, then we must append to the result
                    result += new_result
                  elif len(new_result) > 0:
                    if (base_category.acquisition_copy_value and len(original_result) == 0) \
                                                    or base_category.acquisition_sync_value:
                      # If copy is set and result was empty, then copy it once
                      # If sync is set, then copy it again
Jean-Paul Smets's avatar
Jean-Paul Smets committed
801
                      self.setCategoryMembership( context, base_category, new_result,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
802 803 804 805 806 807 808
                                    spec=spec, filter=filter, portal_type=portal_type, base=base )
                    # We found it, we can return
                    return new_result
          if (base_category.acquisition_copy_value or base_category.acquisition_sync_value)\
                                                         and len(result) > 0:
            # If copy is set and result was empty, then copy it once
            # If sync is set, then copy it again
Jean-Paul Smets's avatar
Jean-Paul Smets committed
809
            self.setCategoryMembership( context, base_category, result,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
810 811 812 813 814 815 816
                                         spec=spec, filter=filter, portal_type=portal_type, base=base )
      # WE MUST IMPLEMENT HERE THE REST OF THE SEMANTICS
      #LOG("Get Acquired Category Result ",0,str(result))
      return result

    security.declareProtected( Permissions.AccessContentsInformation,
                                               'getAcquiredCategoryMembershipList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
817
    def getAcquiredCategoryMembershipList(self, context, base_category = None, base=1,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
818 819 820 821
                                                               spec=(), filter=None, **kw):
      """
        Returns all acquired category values
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
822
      #LOG("Get Acquired Category", 0, "%s %s" % (base_category, context.getRelativeUrl()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
823
      result = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
824 825 826 827
      if base_category is None:
        base_category_list = context._categories
      elif type(base_category) is type('a'):
        base_category_list = [base_category]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
828
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
829 830 831
        base_category_list = base_category
      for base_category in base_category_list:
        result += self.getSingleCategoryAcquiredMembershipList(context, base_category, base=base,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
832 833 834 835
                                    spec=spec, filter=filter, **kw )
      return result

    security.declareProtected( Permissions.AccessContentsInformation, 'isMemberOf' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
836
    def isMemberOf(self, context, category, strict=0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
837 838 839 840 841 842 843
      """
        Tests if an object if member of a given category
        Category is a string here. It could be more than a string (ex. an object)

        XXX Should include acquisition ?
      """
      if getattr(aq_base(context), 'isCategory', 0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
844 845 846 847 848 849 850 851 852
        return context.isMemberOf(category, strict=strict)
      if strict:
        for c in self._getCategoryList(context):
          if c.find(category) >= 0:
            return 1
      else:
        for c in self._getCategoryList(context):
          if c == category:
            return 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
      return 0

    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryList' )
    def getCategoryList(self, context):
      self._cleanupCategories(context)
      return self._getCategoryList(context)

    security.declareProtected( Permissions.AccessContentsInformation, '_getCategoryList' )
    def _getCategoryList(self, context):
      if hasattr(context, 'categories'):
        if type(context.categories) == type((1,)):
          result = context.categories
        elif type(context.categories) == type([]):
          result = context.categories
        else:
          result = []
      elif type(context) is type({}):
        result = context.get('categories', {})
      else:
        result = []
      if getattr(context, 'isCategory', 0):
        result = tuple(list(result) + [context.getRelativeUrl()]) # Pure category is member of itself
      return result

    security.declareProtected( Permissions.ModifyPortalContent, '_setCategoryList' )
    def _setCategoryList(self, context, value):
       context.categories = tuple(value)

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

    security.declareProtected( Permissions.AccessContentsInformation, '_getAcquiredCategoryList' )
    def _getAcquiredCategoryList(self, context):
      result = self.getAcquiredCategoryMembershipList(context,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
892
                     base_category = self.getBaseCategoryIdList(context=context))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
      if getattr(context, 'isCategory', 0):
        result = tuple(list(result) + [context.getRelativeUrl()]) # Pure category is member of itself
      return result

    security.declareProtected( Permissions.ModifyPortalContent, '_cleanupCategories' )
    def _cleanupCategories(self, context):
      # Make sure _cleanupCategories does not modify objects each time it is called
      # or we get many conflicts
      requires_update = 0
      categories = []
      if hasattr(context, 'categories'):
        for cat in self._getCategoryList(context):
          if type(cat) == type('a'):
            categories += [cat]
          else:
            requires_update = 1
      if requires_update: self._setCategoryList(context, tuple(categories))

    # Catalog related methods
    def updateRelatedContent(self, context, previous_category_url, new_category_url):
      """
        TODO: make this method resist to very large updates (ie. long transaction)
      """
      for brain in self.search_related(category_uid = context.getUid()):
        o = brain.getObject()
        category_list = []
        for category in self.getCategoryList(o):
          new_category = re.sub('(?P<start>.*)/%s/(?P<stop>.*)' %
               previous_category_url,'\g<start>/%s/\g<stop>' % new_category_url,category)
          new_category = re.sub('(?P<start>.*)/%s$' %
               previous_category_url,'\g<start>/%s' % new_category_url, new_category)
          category_list += [new_category]
        LOG('updateRelatedContent of %s' % o.getRelativeUrl(), 0, str(category_list))
        self._setCategoryList(o, category_list)
      aq_context = aq_base(self)
      # Update related recursively if required
      if hasattr(aq_context, 'listFolderContents'):
        for o in context.listFolderContents():
          new_o_category_url = o.getRelativeUrl() # Relative Url is based on parent new_category_url             # so we must replace new_category_url with previous_category_url to find
          # the previous category_url for a
          previous_o_category_url = re.sub('(?P<start>.*)/%s$' %
               new_category_url,'\g<start>/%s' % previous_category_url, new_o_category_url)
          self.updateRelatedContent(o, previous_o_category_url, new_o_category_url)

    security.declareProtected( Permissions.ModifyPortalContent, 'getRelatedValueList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
938
    def getRelatedValueList(self, context, base_category_list,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
939
                                       spec=(), filter=None, base=1, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
940 941
      #LOG('getRelatedValueList',0,'base_category_list: %s, filter: %s, kw: %s' %
      #        (str(base_category_list),str(filter),str(kw)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
942 943 944 945 946 947
      portal_type = kw.get('portal_type')

      if type(portal_type) is type('a'):
        portal_type = [portal_type]
      if spec is (): spec = None # We do not want to care about spec

Jean-Paul Smets's avatar
Jean-Paul Smets committed
948 949 950 951
      if type(base_category_list) is type('a'):
        base_category_list = [base_category_list]
      elif base_category_list is () or base_category_list is None:
        base_category_list = self.getBaseCategoryIdList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
952
      category_list = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
953 954 955
      #LOG('getRelatedValueList',0,'base_category_list: %s' % str(base_category_list))
      for base_category in base_category_list:
        category_list += ["%s/%s" % (base_category, context.getRelativeUrl())]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

      brain_result = self.search_category(category_list = category_list,
                                          portal_type = portal_type )

      result = []
      for b in brain_result:
        o = b.getObject()
        if o is not None:
          result.append(o)

      return result
                                  # XXX missing filter and **kw stuff
      #return self.search_category(category_list = category_list, portal_type = spec)
      # future implementation with brains, much more efficient

    # SQL Expression Building
    security.declareProtected(Permissions.AccessContentsInformation, 'buildSQLSelector')
    def buildSQLSelector(self, category_list):
      """
        Returns an SQL selector expression from a list of categories
        We make here a simple method wich simply checks membership
        This is like an OR. More complex selections (AND of OR) will require
        to generate a much more complex query with table aliases

        List of lists
      """
      if type(category_list) == type('a'):
        category_list = [category_list]
      sql_expr = []
      for category in category_list:
        if category is None:
          pass
        elif type(category) == type('a'):
          if category != '':
            category_uid = self.getCategoryUid(category)
            base_category_uid = self.getBaseCategoryUid(category)
            if category_uid is None: category_uid = 'NULL'
            if base_category_uid is None: base_category_uid = 'NULL'
            sql_expr += ['category.category_uid = %s AND category.base_category_uid = %s' %
                      (category_uid, base_category_uid)]
        else:
          single_sql_expr = []
          for single_category in category:
            if single_sql_expr != '':
              category_uid = self.getCategoryUid(single_category)
              base_category_uid = self.getBaseCategoryUid(single_category)
              if category_uid is None: category_uid = 'NULL'
              if base_category_uid is None: base_category_uid = 'NULL'
              single_sql_expr += \
                ['category.category_uid = %s AND category.base_category_uid = %s' %
                 (category_uid, base_category_uid)]
          if len(single_sql_expr) > 0:
            sql_expr += "( %s )" % string.join(single_sql_expr, ' OR ')
      if len(sql_expr) > 0:
        sql_expr = string.join(sql_expr, ' OR ')
      return sql_expr


    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberValueList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1015
    def getCategoryMemberValueList(self, context, base_category = None,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
                                         spec = (), filter=None, portal_type=(), strict = 0):
      """
      This returns a catalog_search resource with can then be used by getCategoryMemberItemList

      """
      cat_sql = context.asSqlExpression()


      if spec is ():
        catalog_search = self.portal_catalog(query = cat_sql)
      else:
        catalog_search = self.portal_catalog(portal_type = portal_type, query = cat_sql)


      return catalog_search


    security.declareProtected( Permissions.AccessContentsInformation, 'getCategoryMemberItemList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1034 1035
    def getCategoryMemberItemList(self, context, base_category = None,
         spec = (), filter=None, portal_type=(), strict = 0, display_id = None, sort_id=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1036
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1037
      This returns with "display_id" method a list of items belonging to a category
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1038 1039 1040 1041

      """
      result = []

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1042
      if base_category is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1043 1044
        base = ''
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1045
        base = base_category + '/'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1046 1047 1048 1049

      catalog_search = self.getCategoryMemberValueList(context)

      for b in catalog_search:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1050
        if display_id is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1051 1052 1053 1054 1055
          v = base + b.relative_url
          result += [(v,v)]
        else:
          try:
            o = b.getObject()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1056
            v = getattr(o, display_id)()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1057 1058
            result += [(v,base + b.relative_url)]
          except:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1059
            LOG('WARNING: CategoriesTool',0, 'Unable to call %s on %s' % (display_id, b))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1060 1061 1062 1063 1064 1065 1066 1067

      if sort_id is not None:
        result.sort()

      return result

    security.declareProtected( Permissions.AccessContentsInformation,
                                                                'getCategoryMemberTitleItemList' )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1068
    def getCategoryMemberTitleItemList(self, context, base_category = None,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1069 1070 1071 1072 1073
                                      spec = (), filter=None, portal_type=(), strict = 0):
      """
      This returns a title list of items belonging to a category

      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1074 1075
      getCategoryMemberItemList(self, context, base_category = base_category,
        spec = spec, filter=filter, portal_type=portal_type, strict = strict, display_id = 'getTitle')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100


    security.declarePrivate('resolveCategory')
    def resolveCategory(self, relative_url):
        """
          Finds an object from a relative_url
        """
        try:
          obj = self.restrictedTraverse(relative_url)
          if obj is None:
            REQUEST = self.REQUEST
            url = '%s/%s' % ('/'.join(self.getPhysicalPath()), relative_url)
            #LOG("CMFCategory:",0,"Trying url %s" % url )
            obj = self.portal_catalog.resolve_url(url, REQUEST)
          #LOG('Obj type', 0, str(obj.getUid()))
          return obj
        except:
          LOG("CMFCategory WARNING",0,"Could not access object relative_url %s" % relative_url )
          return None

InitializeClass( CategoryTool )

# Psyco
import psyco
psyco.bind(CategoryTool)