Folder.py 64.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
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
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#          Jean-Paul Smets-Solanes <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.
#
##############################################################################

30
import transaction
31
from collections import deque
32
from functools import wraps
33
from AccessControl import ClassSecurityInfo, getSecurityManager
34
from AccessControl.ZopeGuards import NullIter, guarded_getattr
35
from Acquisition import aq_base, aq_parent, aq_inner
36
from BTrees.Length import Length
37
from OFS.Folder import Folder as OFSFolder
38 39
from OFS.ObjectManager import ObjectManager, checkValidId
from zExceptions import BadRequest
40 41
from OFS.History import Historical
import ExtensionClass
42
from Persistence import Persistent
43
from Products.CMFCore.exceptions import AccessControl_Unauthorized
44
from Products.CMFCore.CMFCatalogAware import CMFCatalogAware
45
from Products.CMFCore.PortalFolder import ContentFilter
46
from Products.ERP5Type.Base import Base
47
from Products.ERP5Type.ConsistencyMessage import ConsistencyMessage
48
from Products.ERP5Type.CopySupport import CopyContainer
49
from Products.ERP5Type import PropertySheet
50 51
from Products.ERP5Type.XMLExportImport import Folder_asXML
from Products.ERP5Type.Utils import sortValueList
52
from Products.ERP5Type import Permissions
53
from Products.ERP5Type.Globals import InitializeClass
54
from Products.ERP5Type.Accessor import Base as BaseAccessor
55 56 57 58
try:
  from Products.CMFCore.CMFBTreeFolder import CMFBTreeFolder
except ImportError:
  from Products.BTreeFolder2.CMFBTreeFolder import CMFBTreeFolder
59
from Products.BTreeFolder2.BTreeFolder2 import BTreeFolder2Base, BTreeFolder2
60 61
try:
  from Products.HBTreeFolder2.CMFHBTreeFolder import CMFHBTreeFolder
62 63
  from Products.HBTreeFolder2.HBTreeFolder2 import HBTreeFolder2Base
  from Products.HBTreeFolder2.HBTreeFolder2 import HBTreeFolder2
64 65
except ImportError:
  class CMFHBTreeFolder:
66
    pass
67

68
  class HBTreeFolder2Base:
69
    pass
70 71

  class HBTreeFolder2:
72
    pass
73
from DateTime import DateTime
74 75
from random import randint
import os
76
from zLOG import LOG, WARNING
77
import warnings
78
from urlparse import urlparse
79
from Products.ERP5Type.Message import translateString
80
from ZODB.POSException import ConflictError
81

82 83 84 85 86 87 88
# Dummy Functions for update / upgrade
def dummyFilter(object,REQUEST=None):
  return 1

def dummyTestAfter(object,REQUEST=None):
  return []

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
class ExceptionRaised(object):
  raised = False

  def __nonzero__(self):
    return self.raised

  def __call__(self, func):
    def wrapper(*args, **kw):
      try:
        return func(*args, **kw)
      except:
        self.raised = True
        raise
    return wraps(func)(wrapper)

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
# Above this many subobjects, migrate _count from Length to FragmentedLength
# to accomodate concurrent accesses.
FRAGMENTED_LENGTH_THRESHOLD = 1000
class FragmentedLength(Persistent):
  """
  Drop-in replacement for BTrees.Length, which splits storage by zope node.
  The intent is that per-node conflicts should be roughly constant, but adding
  more nodes should not increase overall conflict rate.

  Inherit from Persistent in order to be able to resolve our own conflicts
  (first time a node touches an instance of this class), which should be a rare
  event per-instance.
  Contain BTrees.Length instances for intra-node conflict resolution
  (inter-threads).
  """
  def __init__(self, legacy=None):
    self._map = {}
    if legacy is not None:
      # Key does not matter as long as it is independent from the node
      # constructing this instance.
      self._map[None] = legacy

  def set(self, new):
    self._map.clear()
    self.change(new)

  def change(self, delta):
    try:
      self._map[getCurrentNode()].change(delta)
    except KeyError:
      self._map[getCurrentNode()] = Length(delta)
      # _map is mutable, notify persistence that we have to be serialised.
      self._p_changed = 1

  def __call__(self):
    return sum(x() for x in self._map.values())

  @staticmethod
  def _p_resolveConflict(old_state, current_state, my_state):
    # Minimal implementation for sanity: only handle addition of one by "me" as
    # long as current_state does not contain the same key. Anything else is a
    # conflict.
    try:
      my_added_key, = set(my_state['_map']).difference(old_state['_map'])
    except ValueError:
      raise ConflictError
    if my_added_key in current_state:
      raise ConflictError
    current_state['_map'][my_added_key] = my_state['_map'][my_added_key]
    return current_state

155
class FolderMixIn(ExtensionClass.Base):
156 157
  """A mixin class for folder operations, add content, delete content etc.
  """
158 159
  # flag to hold the status of migration for this folder
  _migration_in_progress = False
160 161 162 163 164

  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

165 166 167 168 169 170 171
  security.declarePublic('isTempObject')
  def isTempObject(self):
    """Return true if self is an instance of a temporary document class.
    """
    # Note: Folder inherits from Base and FolderMixIn but Base has priority.
    return 0

172 173
  security.declarePublic('newContent')
  def newContent(self, id=None, portal_type=None, id_group=None,
174
          default=None, method=None, container=None, temp_object=0, **kw):
175 176 177 178
    """Creates a new content.
    This method is public, since TypeInformation.constructInstance will perform
    the security check.
    """
179
    pt = self._getTypesTool()
180 181
    if container is None:
      container = self
182 183 184 185
    temp_container = container.isTempObject()

    # The only case where the id is unused (because the new object is not added
    # to its parent) is when a temp object is created inside a non-temp object.
186
    if id is None and (temp_container or not temp_object):
187 188 189 190 191 192
      new_id_kw = {}
      if method is not None:
        new_id_kw['method'] = method
      new_id = str(container.generateNewId(id_group=id_group,
                                           default=default,
                                           **new_id_kw))
193 194
    else:
      new_id = str(id)
195

196
    if portal_type is None:
Aurel's avatar
Aurel committed
197
      # XXX This feature is very confusing
198
      # And made the code more difficult to update
199 200 201 202
      allowed_content_type_list = container.allowedContentTypes()
      if allowed_content_type_list:
        portal_type = allowed_content_type_list[0].id
      else:
Jérome Perrin's avatar
Jérome Perrin committed
203
        raise ValueError('Creation disallowed')
Julien Muchembled's avatar
Julien Muchembled committed
204
    else:
205 206 207
      type_info = pt.getTypeInfo(container)
      if type_info is not None and not type_info.allowType(portal_type) and \
          'portal_trash' not in container.getPhysicalPath():
208
        raise ValueError('Disallowed subobject type: %s on %r' % (portal_type, container))
209

210 211 212 213 214
    type_info = pt.getTypeInfo(portal_type)
    if type_info is None:
      raise ValueError('No such content type: %s' % portal_type)

    new_instance = type_info.constructInstance(
215 216
                           container=container,
                           id=new_id,
217
                           temp_object=temp_object or temp_container,
218
                           **kw)
219 220
    if temp_container:
      container._setObject(new_id, new_instance.aq_base)
221 222 223 224 225 226 227
    elif self._migration_in_progress:
      raise RuntimeError("Folder is running migration to HBTree")
    else:
      # make sure another zope hasn't started to migrate to HBTree
      connection = self._p_jar
      connection is None or connection.readCurrent(self)

228
    return new_instance
Aurel's avatar
Aurel committed
229

230 231 232 233 234 235
  security.declareProtected(
            Permissions.DeletePortalContent, 'deleteContent')
  def deleteContent(self, id):
    """ delete items in this folder.
      `id` can be a list or a string.
    """
236 237
    if self._migration_in_progress:
      raise RuntimeError("Folder is running migration to HBTree")
238
    error_message = 'deleteContent only accepts string or list of strings not '
239 240
    if isinstance(id, str):
      self._delObject(id)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
241
    elif isinstance(id, (list, tuple)):
242
      for my_id in id:
243 244 245 246
        if isinstance(my_id, str):
          self._delObject(my_id)
        else:
          raise TypeError, error_message + str(type(my_id))
247
    else:
248
      raise TypeError, error_message + str(type(id))
249

250 251 252
  def _generatePerDayId(self):
    """
    Generate id base on date, useful for HBTreeFolder
253
    We also append random id
254
    """
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
255
    current_date = DateTime().strftime('%Y%m%d')
256
    my_id = self._generateRandomId()
257 258
    return "%s-%s" %(current_date, my_id)

259 260 261 262 263 264 265 266
  def _generateRandomId(self):
    """
      Generate a random Id.
      10000 factor makes the odd to generate an already existing Id of 1 out
      of 10000, not depending on the number of objects present in this folder.
      len(self)+1 to make sure generation works on an empty Folder.
    """
    return '%X' % (randint(1, 10000 * (len(self) + 1)), )
Aurel's avatar
Aurel committed
267

268 269 270 271 272 273
  def _generateNextId(self):
    """
      Get the last generated Id, increment it until no object with generated
      Id exist, then save the Id.
    """
    try:
274
      my_id = int(self.getLastId()) + 1
275 276 277 278 279 280 281 282
    except TypeError:
      my_id = 1
    while self.hasContent(str(my_id)):
      my_id = my_id + 1
    my_id = str(my_id)
    self._setLastId(my_id) # Make sure no reindexing happens
    return my_id

283 284
  def _generatePerNodeId(self):
    """
285
    Generate id base on the node id defined in the zope.conf,
286 287 288 289
    useful for import and mass creation
    of objects inside a module using activities
    We also append random id
    """
290
    new_id = "%s-%s" %(getCurrentNode().replace("-", "_"),
291
                       self._generateRandomId())
292
    try:
293
       checkValidId(self, new_id)
294 295 296
    except BadRequest:
      return self._generateNextId()
    return new_id
297

298 299 300 301 302 303 304 305
  def _generatePerNodeNumberId(self):
    """
    Generate id base on node number, useful for import and mass creation
    of objects inside a module using activities
    We also append random id
    """
    activity_tool = self.getPortalObject().portal_activities
    node_list = list(activity_tool.getNodeList())
306
    current_node = getCurrentNode()
307
    try:
308
      node_number = node_list.index(current_node) + 1
309 310
    except ValueError:
      # Not a processing node
311
      node_number = 0
312 313
    return "%03d-%s" %(node_number, self._generateRandomId())

314 315 316 317 318 319 320 321
  def _generatePerDayNodeNumberId(self):
    """
    Generate id base on date and node number, useful for import and mass
    creation of objects inside a module using activities. We also append
    random id.
    """
    activity_tool = self.getPortalObject().portal_activities
    node_list = list(activity_tool.getNodeList())
322
    current_node = getCurrentNode()
323 324 325 326 327 328 329 330 331
    try:
      node_number = node_list.index(current_node) + 1
    except ValueError:
      # Not a processing node
      node_number = 0
    current_date = DateTime().strftime('%Y%m%d')
    my_id = self._generateRandomId()
    return "%s.%03d-%s" %(current_date, node_number, my_id)

332 333 334 335 336 337 338 339 340 341 342
  # Getter defines to address migration of a site to ZODB Property Sheets,
  # otherwise installing erp5_property_sheets fails in generateNewId() as
  # getIdGenerator accessor does not exist yet
  getIdGenerator = BaseAccessor.Getter('getIdGenerator', 'id_generator',
                                       'string', default='')

  getLastId = BaseAccessor.Getter('getLastId', 'last_id', 'string',
                                  default='0')

  _setLastId = BaseAccessor.Setter('_setLastId', 'last_id', 'string')

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  # Automatic ID Generation method
  security.declareProtected(Permissions.View, 'generateNewId')
  def generateNewId(self,id_group=None,default=None,method=None):
    """
      Generate a new Id which has not been taken yet in this folder.
      Eventually increment the id number until an available id
      can be found

      Permission is view because we may want to add content to a folder
      without changing the folder content itself.
    """
    my_id = None
    if id_group is None:
      id_group = self.getIdGroup()
    if id_group in (None, 'None'):
      id_generator = self.getIdGenerator()
      if not isinstance(id_generator, str):
360 361
        LOG('Folder.generateNewId', 0, '%s.id_generator is not a string.'
            ' Falling back on default behaviour.' % (self.absolute_url(), ))
362
        id_generator = ''
363 364 365 366
      if id_generator != '':
        # Custom aq_dynamic function (like the one defined on WebSite objects)
        # can find an object which has no name. So we must recognise the
        # default value of id_generator and force safe fallback in this case.
367 368
        idGenerator = getattr(self, id_generator, None)
        if idGenerator is None:
369
          raise ValueError("Could not find id_generator %r" % (id_generator,))
370 371 372 373
      else:
        idGenerator = self._generateNextId
      my_id = idGenerator()
      while self.hasContent(my_id):
374
        my_id = idGenerator()
375
    else:
376 377 378
      new_id_kw = {}
      if method is not None:
        new_id_kw['method'] = method
379
      my_id = str(self.portal_ids.generateNewId(id_generator='document',
380
                  id_group=id_group, default=default, **new_id_kw))
381 382 383
    return my_id

  security.declareProtected(Permissions.View, 'hasContent')
384
  def hasContent(self, id):
385 386 387
    return self.hasObject(id)

  # Get the content
388
  security.declareProtected(Permissions.AccessContentsInformation, 'searchFolder')
389 390 391 392 393
  def searchFolder(self, **kw):
    """
      Search the content of a folder by calling
      the portal_catalog.
    """
394
    kw['parent_uid'] = self.getUid()
395 396 397 398 399

    # Make sure that if we use parent base category
    # We do not have conflicting parent uid values
    delete_parent_uid = 0
    if kw.has_key('selection_domain'):
400 401 402 403 404 405
      if not isinstance(kw['selection_domain'], dict):
        warnings.warn("To pass a DomainSelection instance is deprecated.\n"
                      "Please use a domain dict instead.",
                      DeprecationWarning)
        kw['selection_domain'] = kw['selection_domain'].asDomainDict()
      if kw['selection_domain'].has_key('parent'):
406 407
        delete_parent_uid = 1
    if kw.has_key('selection_report'):
408 409 410 411 412
      if not isinstance(kw['selection_report'], dict):
        warnings.warn("To pass a DomainSelection instance is deprecated.\n"
                      "Please use a domain dict instead.",
                      DeprecationWarning)
        kw['selection_report'] = kw['selection_report'].asDomainDict()
413
      if kw['selection_report'].has_key('parent'):
414 415 416 417
        delete_parent_uid = 1
    if delete_parent_uid:
      del kw['parent_uid']

418
    return self.portal_catalog.searchResults(**kw)
419

420
  security.declareProtected(Permissions.AccessContentsInformation, 'countFolder')
421 422 423 424 425
  def countFolder(self, **kw):
    """
      Search the content of a folder by calling
      the portal_catalog.
    """
426
    kw['parent_uid'] = self.getUid()
427 428 429 430 431

    # Make sure that if we use parent base category
    # We do not have conflicting parent uid values
    delete_parent_uid = 0
    if kw.has_key('selection_domain'):
432 433 434 435 436 437
      if not isinstance(kw['selection_domain'], dict):
        warnings.warn("To pass a DomainSelection instance is deprecated.\n"
                      "Please use a domain dict instead.",
                      DeprecationWarning)
        kw['selection_domain'] = kw['selection_domain'].asDomainDict()
      if kw['selection_domain'].has_key('parent'):
438 439
        delete_parent_uid = 1
    if kw.has_key('selection_report'):
440 441 442 443 444
      if not isinstance(kw['selection_report'], dict):
        warnings.warn("To pass a DomainSelection instance is deprecated.\n"
                      "Please use a domain dict instead.",
                      DeprecationWarning)
        kw['selection_report'] = kw['selection_report'].asDomainDict()
445
      if kw['selection_report'].has_key('parent'):
446 447 448 449
        delete_parent_uid = 1
    if delete_parent_uid:
      del kw['parent_uid']

450
    return self.portal_catalog.countResults(**kw)
451 452 453 454 455 456 457 458 459

  # Count objects in the folder
  security.declarePrivate('_count')
  def _count(self, **kw):
    """
      Returns the number of items in the folder.
    """
    return self.countFolder(**kw)[0][0]

460 461 462 463 464 465 466 467
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getWebSiteValue')
  def getWebSiteValue(self):
    """
    Since aq_dynamic will not work well to get Web Site for language
    specified case (eg. web_site_module/site/fr/web_page_module), we
    call aq_parent instead to reach the Web Site.
    """
468 469 470 471 472
    getWebSiteValue = getattr(aq_parent(self), 'getWebSiteValue', None)
    if getWebSiteValue is not None:
      return getWebSiteValue()
    else:
      return None
473 474 475 476 477 478 479 480 481

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getWebSectionValue')
  def getWebSectionValue(self):
    """
    Since aq_dynamic will not work well to get Web Section for language
    specified case (eg. web_site_module/site/fr/section/web_page_module),
    we call aq_parent instead to reach the Web Section.
    """
482 483 484 485 486
    getWebSectionValue = getattr(aq_parent(self), 'getWebSectionValue', None)
    if getWebSectionValue is not None:
      return getWebSectionValue()
    else:
      return None
487

488 489 490 491 492 493 494 495 496 497 498 499
  def _recurseCallMethod(self, method_id, method_args=(), method_kw={},
                         restricted=False, id_list=None, min_id=None, **kw):
    """Run a script by activity on objects found recursively from this folder

    This method is configurable (via activate_kw['group_*'] & 'activity_count'
    parameters) so that it can work efficiently with databases of any size.

    'activate_kw' may specify an active process to collect results.

    In order to activate objects that don't inherit ActiveObject,
    only placeless default activate parameters are taken into account.
    """
500 501
    hook_raised = ExceptionRaised()
    my_getattr = guarded_getattr if restricted else getattr
502
    activate = self.getPortalObject().portal_activities.activateObject
503 504 505 506 507 508 509 510 511
    validate = restricted and getSecurityManager().validate
    activity_count = kw.get('activity_count', 1000)
    if activity_count is None:
      check_limit = lambda: None
    else:
      check_limit = iter(xrange(activity_count)).next
    try:
      recurse_stack = kw['_recurse_stack']
    except KeyError:
512
      recurse_stack = [deque(id_list) if id_list else min_id or '']
513
      kw['_recurse_stack'] = recurse_stack
514 515 516 517 518 519 520 521 522 523 524 525
      # We are called by user (and not in a subsequent activity).
      # Complete activate_kw, without mutating received value.
      activate_kw = self.getDefaultActivateParameterDict.im_func(None)
      activate_kw.update(kw.get('activate_kw', ()))
      activate_kw.setdefault('active_process', None)
      activate_kw.setdefault('activity', 'SQLQueue')
      cost = activate_kw.setdefault('group_method_cost', .034) # 30 objects
      if cost != 1:
        activate_kw.setdefault('group_method_id', None) # dummy group method
      kw['activate_kw'] = activate_kw
    else:
      activate_kw = kw['activate_kw']
526 527
    min_depth = kw.get('min_depth', 0)
    max_depth = kw.get('max_depth', 0)
528 529 530 531 532 533 534 535 536 537 538 539
    get_activate_kw_method_id = kw.get('get_activate_kw_method_id')
    if get_activate_kw_method_id is None:
      getActivateKw = lambda document, activate_kw: activate_kw
      recurse_activate_kw = activate_kw
    else:
      getActivateKw = hook_raised(my_getattr(self, get_activate_kw_method_id))
      # Isolate caller-accessible mutable activate_kw from the on we need to
      # re-invoke ourselves. Doing it once only should be sufficient (and saves a
      # dict copy on each iteration) as all the values we care about (set above
      # in this script) are immutable. Anything else is already under the control
      # of caller, either via arguments or via default activate parameter dict.
      recurse_activate_kw = activate_kw.copy()
540 541 542 543 544
    skip_method_id = kw.get('skip_method_id')
    if skip_method_id is None:
      skip = lambda document: False
    else:
      skip = hook_raised(my_getattr(self, skip_method_id))
545
    def recurse(container, depth):
546
      if getattr(aq_base(container), 'getPhysicalPath', None) is None or skip(container):
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
        return
      if (max_depth is None or depth < max_depth) and \
         isinstance(container, ObjectManager) and len(container):
        try:
          next_id = recurse_stack[depth]
        except IndexError:
          next_id = ''
          recurse_stack.append(next_id)
        if isinstance(next_id, basestring):
          folder_handler = isinstance(container, Folder) and \
                          container._folder_handler
          if not folder_handler:
            next_id = deque(x for x in container.objectIds() if x >= next_id)
            recurse_stack[depth] = next_id
          else:
562
            for id, ob in container.iteritems(next_id):
563 564 565 566 567 568 569 570 571 572 573 574
              if not restricted or validate(container, container, id, ob):
                recurse_stack[depth] = id
                recurse(ob, depth + 1)
            recurse_stack[-1] = next_id = None
        while next_id:
          id = next_id[0]
          ob = container._getOb(id)
          if not restricted or validate(container, container, id, ob):
            recurse(ob, depth + 1)
          del next_id[0]
      if min_depth <= depth:
        check_limit()
575
        getattr(activate(container, **getActivateKw(container, recurse_activate_kw)),
576 577 578 579 580
                method_id)(*method_args, **method_kw)
      del recurse_stack[depth:]
    try:
      recurse(self, 0)
    except StopIteration:
581 582
      if hook_raised:
        raise
583
      reactivate_kw = activate_kw.copy()
584
      reactivate_kw['group_method_id'] = reactivate_kw['group_id'] = '' # no grouping
585 586
      reactivate_kw['activity'] = 'SQLQueue'
      activate(self, **reactivate_kw)._recurseCallMethod(
587 588 589
        method_id, method_args, method_kw, restricted=restricted, **kw)

  security.declarePublic('recurseCallMethod')
590
  def recurseCallMethod(self, method_id, *args, **kw):
591
    """Restricted version of _recurseCallMethod"""
592 593 594
    if method_id[0] == '_':
        raise AccessControl_Unauthorized(method_id)
    return self._recurseCallMethod(method_id, restricted=True, *args, **kw)
595

596 597 598 599 600 601 602 603 604 605
  security.declarePublic('isURLAncestorOf')
  def isURLAncestorOf(self, given_url):
    """
      This method returns True if the given_url is child of the url of
      the document that the method is called on, False otherwise.

      Note that the method compares the urls as strings and does
      not access any document in given path,
      hence it does not compute the inner acquisition path.
    """
606
    document_url = self.absolute_url()
607 608 609 610 611 612 613 614 615 616 617
    parsed_given_url = urlparse(given_url)
    parsed_document_url = urlparse(document_url)
    # XXX note that the following check:
    # - does not support relative urls
    # - does not canonicalize domain name, e.g.
    #   http://foo:80/erp5, http://foo/erp5 and http://foo:www/erp5
    #   will not match.
    return parsed_given_url.scheme == parsed_document_url.scheme and \
        parsed_given_url.netloc == parsed_document_url.netloc and \
        (parsed_given_url.path + '/').startswith((parsed_document_url.path + '/'))

618 619
InitializeClass(FolderMixIn)

620 621 622 623 624 625 626 627 628 629 630
class OFSFolder2(OFSFolder):
  """
  Make OFSFolder behave more consistently with (H)BTreeFolder2, especially
  exception-wise.
  """
  def _getOb(self, *args, **kw):
    try:
      return OFSFolder._getOb(self, *args, **kw)
    except AttributeError as exc:
      raise KeyError(exc.args)

631
OFS_HANDLER = 0
632 633
BTREE_HANDLER = 1
HBTREE_HANDLER = 2
634
_OFS_PROPERTY_ID = '_dummy_property_for_ofsfolder' # Dummy
635 636 637
_BTREE_PROPERTY_ID = '_tree'
_HBTREE_PROPERTY_ID = '_htree'
_HANDLER_LIST = (
638
  (_OFS_PROPERTY_ID, lambda self, id: None, OFSFolder2),
639 640 641 642 643
  (_BTREE_PROPERTY_ID, BTreeFolder2Base.__init__, CMFBTreeFolder),
  (_HBTREE_PROPERTY_ID, HBTreeFolder2Base.__init__, CMFHBTreeFolder),
)
# Bad value, accidentally put everywhere long ago
_BROKEN_BTREE_HANDLER = 'CMFBTreeFolderHandler'
644

645
class Folder(OFSFolder2, CMFBTreeFolder, CMFHBTreeFolder, Base, FolderMixIn):
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
  """
  A Folder is a subclass of Base but not of XMLObject.
  Folders are not considered as documents and are therefore
  not synchronisable.

  ERP5 folders are implemented as CMFBTreeFolder objects
  and can store up to a million documents on a standard
  computer.
  ERP5 folders will eventually use in the near future the
  AdaptableStorage implementation in order to reach performances
  of 10 or 100 millions of documents in a single folder.

  ERP5 folders include an automatic id generation feature
  which allows user not to define an id when they create
  a new document in a folder.

  ERP5 folders use the ZSQLCatalog to search for objects
663
  or display content.
664 665 666 667 668 669 670 671 672 673

  An ERP5 Binder document class will eventually be defined
  in order to implement a binder of documents which can itself
  be categorized.
  """

  meta_type = 'ERP5 Folder'
  portal_type = 'Folder'
  add_permission = Permissions.AddPortalContent

674 675 676 677 678
  # Overload _properties define in OFS/Folder
  # _properties=({'id':'title', 'type': 'string','mode':'wd'},)
  # because it conflicts with title accessor generation
  _properties=()

679 680 681
  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)
Aurel's avatar
Aurel committed
682

683 684 685 686 687 688 689 690
  manage_options = ( CMFBTreeFolder.manage_options +
                     Historical.manage_options +
                     CMFCatalogAware.manage_options
                   )
  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.SimpleItem
                    , PropertySheet.Folder
691
                    , PropertySheet.CategoryCore
692 693 694 695 696 697 698
                    )

  # Class inheritance fixes
  security.declareProtected( Permissions.ModifyPortalContent, 'edit' )
  edit = Base.edit
  security.declareProtected( Permissions.ModifyPortalContent, '_edit' )
  _edit = Base._edit
699 700
  security.declareProtected( Permissions.ModifyPortalContent, 'setTitle' )
  setTitle = Base.setTitle
701 702 703 704
  security.declareProtected( Permissions.AccessContentsInformation, 'title_or_id' )
  title_or_id = Base.title_or_id
  security.declareProtected( Permissions.AccessContentsInformation, 'Title' )
  Title = Base.Title
705 706
  _setPropValue = Base._setPropValue
  _propertyMap = Base._propertyMap # are there any others XXX ?
707
  PUT_factory = None
708 709 710
  # XXX Prevent inheritance from PortalFolderBase
  description = None

711
  # Per default we use BTree folder
712
  _folder_handler = BTREE_HANDLER
713
  _dummy_property_for_ofsfolder = () # Just a marker property for code simplicity (*cough*)
714

715 716 717 718
  # Overload __init__ so that we do not take into account title
  # This is required for test_23_titleIsNotDefinedByDefault
  def __init__(self, id):
    self.id = id
719

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
  @property
  def _count(self):
    count = self.__dict__.get('_count')
    if isinstance(count, Length) and count() > FRAGMENTED_LENGTH_THRESHOLD:
      count = self._count = FragmentedLength(count)
    return count

  @_count.setter
  def _count(self, value):
    if isinstance(value, Length) and value() > FRAGMENTED_LENGTH_THRESHOLD:
      value = FragmentedLength(value)
    self.__dict__['_count'] = value
    self._p_changed = 1

  @_count.deleter
  def _count(self):
    del self.__dict__['_count']
    self._p_changed = 1

739
  security.declarePublic('newContent')
740 741 742 743
  def newContent(self, *args, **kw):
    """ Create a new content """
    # Create data structure if none present
    return FolderMixIn.newContent(self, *args, **kw)
744 745 746

  def _getFolderHandlerData(self):
    # Internal API working around bogus _folder_handler values.
747 748 749 750 751 752 753 754 755 756 757
    # This method is a hot-spot for all Folder accesses. DO NOT SLOW IT DOWN.
    try:
      # Fast path: folder is sane.
      return _HANDLER_LIST[self._folder_handler]
    # Note: TypeError and not IndexError, as bogus value is a string and
    # _HANDLER_LIST only accepts integers indices.
    except TypeError:
      # Slow path: handle insane folders.
      if self._folder_handler == _BROKEN_BTREE_HANDLER:
        return _HANDLER_LIST[BTREE_HANDLER]
      raise
758

759
  security.declareProtected(Permissions.AccessContentsInformation, 'isBTree')
760
  def isBTree(self):
761 762 763
    """
    Tell if we are a BTree
    """
764
    return self._folder_handler in (BTREE_HANDLER, _BROKEN_BTREE_HANDLER)
765 766
  
  security.declareProtected(Permissions.AccessContentsInformation, 'isHBTree')
767 768 769 770 771
  def isHBTree(self):
    """
    Tell if we are a HBTree
    """
    return self._folder_handler == HBTREE_HANDLER
772 773

  security.declareProtected( Permissions.ManagePortal, 'migrateToHBTree' )
774
  def migrateToHBTree(self, migration_generate_id_method=None, new_generate_id_method='_generatePerDayId', REQUEST=None):
775 776 777 778 779
    """
    Function to migrate from a BTree folder to HBTree folder.
    It will first call setId on all folder objects to have right id
    to be used with an hbtreefolder.
    Then it will migrate foder from btree to hbtree.
780
    """
781
    BUNDLE_COUNT = 10
782 783

    # if folder is already migrated or migration process is in progress
784
    # do not do anything beside logging
785
    if self._migration_in_progress or self.isHBTree():
786 787 788
      LOG('migrateToHBTree', WARNING,
        'Folder %s already migrated'%(self.getPath(),))
      return
789 790
    # lock folder migration
    self._migration_in_progress = True
791

792
    # we may want to change all objects ids before migrating to new folder type
793 794
    # set new id generator here so that object created while migration
    # got a right id
795 796
    if new_generate_id_method is not None:
      self.setIdGenerator(new_generate_id_method)
797
    if migration_generate_id_method not in (None, ''):
798
      tag = "%s/%s/migrate" %(self.getId(),migration_generate_id_method)
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
      id_list  = list(self.objectIds())
      # set new id by bundle
      for x in xrange(len(self) / BUNDLE_COUNT):
        self.activate(activity="SQLQueue", tag=tag).ERP5Site_setNewIdPerBundle(
          self.getPath(),
          id_list[x*BUNDLE_COUNT:(x+1)*BUNDLE_COUNT],
          migration_generate_id_method, tag)

      remaining_id_count = len(self) % BUNDLE_COUNT
      if remaining_id_count:
        self.activate(activity="SQLQueue", tag=tag).ERP5Site_setNewIdPerBundle(
          self.getPath(),
          id_list[-remaining_id_count:],
          migration_generate_id_method, tag)
    else:
814
      tag = 'nothing'
815 816
    # copy from btree to hbtree
    self.activate(activity="SQLQueue", after_tag=tag)._launchCopyObjectToHBTree(tag)
817

818
    if REQUEST is not None:
819
      psm = translateString('Migration to HBTree is running.')
820 821 822 823 824 825 826 827 828 829
      ret_url = '%s/%s?portal_status_message=%s' % \
                (self.absolute_url(),
                 REQUEST.get('form_id', 'view'), psm)
      return REQUEST.RESPONSE.redirect( ret_url )

  def _finishCopyObjectToHBTree(self):
    """
    Remove remaining attributes from previous btree
    and migration
    """
830
    for attr in "_tree", "_mt_index", "_migration_in_progress":
831 832 833 834
      try:
        delattr(self, attr)
      except AttributeError:
        pass
835

836 837 838 839
  def _launchCopyObjectToHBTree(self, tag):
    """
    Launch activity per bundle to move object
    from a btree to an hbtree
840
    """
841 842
    # migrate folder from btree to hbtree
    id_list = list(self.objectIds())
843 844
    self._folder_handler = HBTREE_HANDLER
    HBTreeFolder2Base.__init__(self, self.id)
845 846 847 848
    # launch activity per bundle to copy/paste to hbtree
    BUNDLE_COUNT = 100
    for x in xrange(len(id_list) / BUNDLE_COUNT):
      self.activate(activity="SQLQueue", tag=tag)._copyObjectToHBTree(
849 850
        id_list=id_list[x*BUNDLE_COUNT:(x+1)*BUNDLE_COUNT],)

851 852 853 854 855 856
    remaining_id_count = len(id_list) % BUNDLE_COUNT
    if remaining_id_count:
      self.activate(activity="SQLQueue", tag=tag)._copyObjectToHBTree(
        id_list=id_list[-remaining_id_count:],)
    # remove uneeded attribute
    self.activate(activity="SQLQueue", after_tag=tag)._finishCopyObjectToHBTree()
857

858 859 860 861 862
  def _copyObjectToHBTree(self, id_list=None,):
    """
    Move object from a btree container to
    a hbtree one
    """
863 864
    getOb = CMFBTreeFolder._getOb
    setOb = CMFHBTreeFolder._setOb
865 866
    for id in id_list:
      obj = getOb(self, id)
867 868 869 870 871 872 873
      setOb(self, id, obj)

  # Override all BTree and HBTree methods to use if/else
  # method to check wich method must be called
  # We use this method instead of plugin because it make
  # less function call and thus Folder faster
  def _initBTrees(self):
874
    return self._getFolderHandlerData()[2]._initBTrees(self)
875 876 877

  def hashId(self, id):
    """Return a hash of id
878
    """
879
    return self._getFolderHandlerData()[2].hashId(self, id)
880 881 882 883

  def _populateFromFolder(self, source):
    """Fill this folder with the contents of another folder.
    """
884 885 886 887
    property_id, init, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      init(self, self.id)
    return folder._populateFromFolder(self, source)
888 889 890 891

  def manage_fixCount(self):
    """Calls self._fixCount() and reports the result as text.
    """
892
    return self._getFolderHandlerData()[2].manage_fixCount(self)
893 894

  def _fixCount(self):
895
    return self._getFolderHandlerData()[2]._fixCount(self)
896

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
  def _fixFolderHandler(self):
    """Fixes _folder_handler if it is a string

    Bug affecting BTree folders in ERP5Type/patches/Folder.py introduced
    string value for _folder_handler, which mades methods isBTree and isHBTree
    fail.

    Returns True in case of founded and fixed error, in case
    of no error returns False.
    """
    if isinstance(self._folder_handler,str):
      delattr(self, '_folder_handler')
      return True
    return False

912 913 914
  def manage_cleanup(self):
    """Calls self._cleanup() and reports the result as text.
    """
915 916 917 918
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return 1
    return folder.manage_cleanup(self)
919 920

  def _cleanup(self):
921 922 923 924
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return 1
    return folder._cleanup(self)
925 926 927 928 929

  def _getOb(self, id, *args, **kw):
    """
    Return the named object from the folder.
    """
930 931 932 933 934 935 936 937 938
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      if args:
        return args[0]
      elif 'default' in kw:
        return kw['default']
      else:
        raise KeyError(id)
    return folder._getOb(self, id, *args, **kw)
939 940 941 942

  def _setOb(self, id, object):
    """Store the named object in the folder.
    """
943 944 945 946
    property_id, init, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      init(self, self.id)
    return folder._setOb(self, id, object)
947 948 949 950

  def _delOb(self, id):
    """Remove the named object from the folder.
    """
951
    return self._getFolderHandlerData()[2]._delOb(self, id)
952 953 954 955

  def getBatchObjectListing(self, REQUEST=None):
    """Return a structure for a page template to show the list of objects.
    """
956
    return self._getFolderHandlerData()[2].getBatchObjectListing(self, REQUEST)
957 958 959 960

  def manage_object_workspace(self, ids=(), REQUEST=None):
    '''Redirects to the workspace of the first object in
    the list.'''
961
    return self._getFolderHandlerData()[2].manage_object_workspace(self, ids, REQUEST)
962

Aurel's avatar
Aurel committed
963
  def manage_main(self, *args, **kw):
964
    ''' List content.'''
965
    return self._getFolderHandlerData()[2].manage_main.__of__(self)(self, *args, **kw)
966 967 968 969

  def tpValues(self):
    """Ensures the items don't show up in the left pane.
    """
970
    return self._getFolderHandlerData()[2].tpValues(self)
971 972 973

  def objectCount(self):
    """Returns the number of items in the folder."""
974 975 976 977
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return 0
    return folder.objectCount(self)
978

979 980 981
  def has_key(self, id):
    """Indicates whether the folder has an item by ID.
    """
982 983 984 985
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return False
    return folder.has_key(self, id)
986 987 988 989

  def getTreeIdList(self, htree=None):
    """ recursively build a list of btree ids
    """
990
    return self._getFolderHandlerData()[2].getTreeIdList(self, htree)
991

992
  def objectIds(self, spec=None, **kw):
993 994 995
    if self._folder_handler == HBTREE_HANDLER:
      if self._htree is None:
        return []
996
      assert spec is None
997 998
      if kw.has_key("base_id"):
        return CMFHBTreeFolder.objectIds(self, base_id=kw["base_id"])
999 1000 1001 1002 1003
      return CMFHBTreeFolder.objectIds(self)
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return []
    return folder.objectIds(self, spec)
1004

1005
  def objectItems(self, spec=None, **kw):
1006 1007 1008
    if self._folder_handler == HBTREE_HANDLER:
      if  self._htree is None:
        return []
1009
      assert spec is None
1010 1011
      if kw.has_key("base_id"):
        return CMFHBTreeFolder.objectItems(self, base_id=kw["base_id"])
1012 1013 1014 1015 1016
      return CMFHBTreeFolder.objectItems(self)
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return []
    return folder.objectItems(self, spec)
1017 1018

  def objectIds_d(self, t=None):
1019 1020 1021 1022
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return {}
    return folder.objectIds_d(self, t)
1023 1024

  def _checkId(self, id, allow_dup=0):
1025
    return self._getFolderHandlerData()[2]._checkId(self, id, allow_dup)
1026

1027
  def _setObject(self, *args, **kw):
1028 1029 1030 1031
    property_id, init, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      init(self, self.id)
    return folder._setObject(self, *args, **kw)
1032 1033 1034 1035 1036

  def get(self, id, default=None):
    """
    Return the named object from the folder.
    """
1037
    return self._getFolderHandlerData()[2].get(self, id, default)
1038 1039 1040

  def generateId(self, prefix='item', suffix='', rand_ceiling=999999999):
    """Returns an ID not used yet by this folder.
1041

1042 1043 1044 1045
    The ID is unlikely to collide with other threads and clients.
    The IDs are sequential to optimize access to objects
    that are likely to have some relation.
    """
1046
    return self._getFolderHandlerData()[2].generateId(self, prefix, suffix, rand_ceiling)
1047 1048

  def __getattr__(self, name):
1049 1050 1051 1052 1053 1054
    # Subobject ids are forbidden to start with an underscore.
    # This saves time by not even attempting traversal when not needed,
    # for example when AccessControl.users.BasicUser._check_context checks
    # whether given object is a bound function.
    if name.startswith('_'):
      raise AttributeError(name)
1055 1056 1057 1058
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      raise AttributeError(name)
    return folder.__getattr__(self, name)
1059

1060
  def __len__(self):
1061 1062 1063 1064
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return 0
    return folder.__len__(self)
1065 1066

  def keys(self, *args, **kw):
1067 1068 1069 1070
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return []
    return folder.keys(self, *args, **kw)
1071

1072
  def values(self, *args, **kw):
1073 1074 1075 1076
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return []
    return folder.values(self, *args, **kw)
1077

1078
  def items(self, *args, **kw):
1079 1080 1081 1082
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return []
    return folder.items(self, *args, **kw)
1083

1084 1085 1086
  def iteritems(self, *args, **kw):
    if self._folder_handler == HBTREE_HANDLER:
      result = CMFHBTreeFolder._htree_iteritems(self, *args, **kw)
1087
    elif self.isBTree():
1088 1089 1090
      if self._tree is None:
        return ()
      result = self._tree.iteritems(*args, **kw)
1091 1092
    else:
      raise NotImplementedError
1093 1094
    return NullIter(((x, y.__of__(self)) for x, y in result))

1095
  def hasObject(self, id):
1096 1097 1098 1099
    property_id, _, folder = self._getFolderHandlerData()
    if getattr(self, property_id) is None:
      return False
    return folder.hasObject(self, id)
1100

1101 1102 1103
  # Work around for the performance regression introduced in Zope 2.12.23.
  # Otherwise, we use superclass' __contains__ implementation, which uses
  # objectIds, which is inefficient in HBTreeFolder2 to lookup a single key.
1104 1105
  __contains__ = hasObject

1106 1107 1108 1109 1110
  # Override Zope default by folder id generation
  def _get_id(self, id):
    if self._getOb(id, None) is None :
      return id
    return self.generateNewId()
Aurel's avatar
Aurel committed
1111

1112
  # Implementation
1113
  hasContent = hasObject
1114

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
  security.declareProtected( Permissions.ModifyPortalContent, 'recursiveApply')
  def recursiveApply(self, filter=dummyFilter, method=None,
                    test_after=dummyTestAfter, include=1, REQUEST=None, **kw):
    """
      Apply a method to self and to all children

      filter      --    only instances which return 1 when applied filter
                        are considered

      method      --    the method to apply to acceptable instances

      test_after  --    test to apply after calling method in order to search
                        for inconsistencies

      include     --    if set to 1 (default), apply method to self


      REQUEST     --    the http REQUEST (if needed)

      **kw        --    optional parameters passed to method
    """
    update_list = []
    #LOG('Folder, recursiveApply ',0,"first one self.path: %s" % self.getPath())

    # Only apply method to self if filter is to 1 and filter returns 1
    if include==1 and filter(object=self.getObject(),REQUEST=REQUEST):
      method_message = method(object=self.getObject(),REQUEST=REQUEST, **kw)
      if type(method_message) is type([]):
        update_list += method_message
      update_list += test_after(object=self.getObject(),REQUEST=REQUEST)

    for o in self.objectValues(): # contentValues sometimes fail in BTreeFolder
      # Test on each sub object if method should be applied
      if filter(object=o,REQUEST=REQUEST):
        method_message = method(object=o,REQUEST=REQUEST, **kw)
        if type(method_message) is type([]):
          update_list += method_message
        update_list += test_after(o,REQUEST=REQUEST)
      # And commit subtransaction
1154
      #transaction.savepoint(optimistic=True)
1155
      transaction.commit() # we may use commit(1) some day XXX
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
      # Recursively call recursiveApply if o has a recursiveApply method (not acquired)
      obase = aq_base(o)
      if hasattr(obase, 'recursiveApply'):
        #LOG('Found recursiveApply', 0, o.absolute_url())
        update_list += o.recursiveApply(filter=filter, \
                              method=method, test_after=test_after,REQUEST=REQUEST,include=0,**kw)

    return update_list

  security.declareProtected( Permissions.ModifyPortalContent, 'updateAll' )
  def updateAll(self, filter=None, method=None, test_after=None, request=None, include=1,**kw):
    """
    update all objects inside this particular folder wich
    returns not None to the test.

    filter have to be a method with one parameter (the object)
    wich returns None if we must not update the object

    test_after have to be a method with one parameter (the object)
    wich returns a string

    method is the update method with also one parameter

    """
    update_list = []
    #LOG('Folder, updateAll ',0,"first one self.path: %s" % self.getPath())

    if include==1 and filter(object=self.getObject(),request=request):
      method_message = method(object=self.getObject(),request=request)
      if type(method_message) is type([]):
        update_list += method_message
      update_list += test_after(object=self.getObject(),request=request)

    for o in self.objectValues():
      # Test if we must apply the upgrade
      if filter(object=o,request=request):
        method_message = method(object=o,request=request)
        if type(method_message) is type([]):
          update_list += method_message
        update_list += test_after(object=o,request=request)
      #for object in o.objectValues():
        #LOG('Folder, updateAll ',0,"object.id: %s" % object.id)
      obase = aq_base(o)
1199
      transaction.commit()
1200 1201 1202 1203 1204 1205 1206
      if hasattr(obase, 'updateAll'):
        update_list += o.updateAll(filter=filter, \
                              method=method, test_after=test_after,request=request,include=0,**kw)

    return update_list

  security.declareProtected( Permissions.ModifyPortalContent, 'upgradeObjectClass' )
1207 1208
  def upgradeObjectClass(self, test_before, from_class, to_class, test_after,
                               test_only=0):
1209
    """
1210 1211 1212 1213 1214
    Upgrade the class of all objects inside this particular folder:
      test_before and test_after have to be a method with one parameter.

      from_class and to_class can be classes (o.__class___) or strings like:
        'Products.ERP5Type.Document.Folder.Folder'
1215

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    XXX Some comments by Seb:
    - it is not designed to work for modules with thousands of objects,
      so it totally unusable when you have millions of objects
    - it is totally unsafe. There is even such code inside :
        self.manage_delObjects(id of original object)
        commit()
        self._setObject(new object instance)
      So it is possible to definitely loose data.
    - There is no proof that upgrade is really working. With such a
      dangerous operation, it would be much more safer to have a proof,
      something like the "fix point" after doing a synchronization. Such
      checking should even be done before doing commit (like it might
      be possible to export objects in the xml format used for exports
1229
      before and after, and run a diff).
1230

1231
    """
1232
    #LOG("upgradeObjectClass: folder ", 0, self.id)
1233
    test_list = []
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    def getClassFromString(a_klass):
      from_module = '.'.join(a_klass.split('.')[:-1])
      real_klass = a_klass.split('.')[-1]
      # XXX It is possible that API Change for Python 2.6.
      mod = __import__(from_module, globals(), locals(),  [real_klass])
      return getattr(mod, real_klass)

    if isinstance(from_class, type('')):
      from_class = getClassFromString(from_class)

    if isinstance(to_class, type('')):
      to_class = getClassFromString(to_class)

1247 1248 1249 1250 1251 1252 1253 1254 1255
    for o in self.listFolderContents():
      # Make sure this sub object is not the same as object
      if o.getPhysicalPath() != self.getPhysicalPath():
        id = o.getId()
        obase = aq_base(o)
        # Check if the subobject have to also be upgraded
        if hasattr(obase,'upgradeObjectClass'):
          test_list += o.upgradeObjectClass(test_before=test_before, \
                          from_class=from_class, to_class=to_class,
1256
                          test_after=test_after, test_only=test_only)
1257

1258 1259
        # Test if we must apply the upgrade
        if test_before(o) is not None:
1260
          LOG("upgradeObjectClass: id ", 0, id)
1261
          klass = obase.__class__
1262 1263
          LOG("upgradeObjectClass: klass ", 0 ,str(klass))
          LOG("upgradeObjectClass: from_class ", 0 ,str(from_class))
1264
          if klass == from_class and not test_only:
1265
            try:
1266 1267
              newob = to_class(obase.id)
              newob.id = obase.id # This line activates obase.
1268
            except AttributeError:
1269 1270
              newob = to_class(id)
              newob.id = id
1271 1272 1273 1274 1275 1276
            keys = obase.__dict__.keys()
            for k in keys:
              if k not in ('id', 'meta_type', '__class__'):
                setattr(newob,k,obase.__dict__[k])

            self.manage_delObjects(id)
1277
            LOG("upgradeObjectClass: ",0,"add new object: %s" % str(newob.id))
1278
            transaction.commit() # XXX this commit should be after _setObject
1279
            LOG("upgradeObjectClass: ",0,"newob.__class__: %s" % str(newob.__class__))
1280 1281 1282 1283
            self._setObject(id, newob)
            object_to_test = self._getOb(id)
            test_list += test_after(object_to_test)

1284 1285 1286
          if klass == from_class and test_only:
            test_list += test_after(o)

1287 1288 1289 1290
    return test_list


  # Catalog related
1291 1292
  security.declarePublic('reindexObject')
  reindexObject = Base.reindexObject
1293

1294 1295
  security.declareProtected(Permissions.ModifyPortalContent,
                            'reindexObjectSecurity')
1296
  def reindexObjectSecurity(self, *args, **kw):
1297 1298 1299
    """
        Reindex security-related indexes on the object
    """
1300
    # In ERP5, simply reindex all objects, recursively by default.
1301 1302 1303 1304
    self._getTypeBasedMethod(
      'reindexObjectSecurity',
      'recursiveReindexObject',
    )(*args, **kw)
1305

1306
  security.declarePublic('recursiveReindexObject')
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
  def recursiveReindexObject(self, activate_kw=None, REQUEST=None, **kw):
    """Recursively indexes the content of self.
    """
    if REQUEST is not None:
      # Being able to trigger recursive reindexation from URL is convenient
      # when administrating an ERP5 instance. However, appropriate security
      # is important to prevent DoS on big objects (in number of subobjects),
      # i.e. modules. For consistency, we check the same permission as for
      # reindexObjectSecurity. A normal user is usually not allowed to modify
      # a module (only add/delete subobjects).
      if not getSecurityManager().checkPermission(
          Permissions.ModifyPortalContent, self):
        raise AccessControl_Unauthorized
1320
    if self.isAncestryIndexable():
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
      kw, activate_kw = self._getReindexAndActivateParameterDict(
        kw,
        activate_kw,
      )
      activate_kw['group_method_cost'] = 0.01
      self._recurseCallMethod(
        'immediateReindexObject',
        method_kw=kw,
        activate_kw=activate_kw,
        get_activate_kw_method_id='_updateActivateKwWithSerialisationTag',
        max_depth=None,
        skip_method_id='_isDocumentNonIndexable',
      )

  def _isDocumentNonIndexable(self, document):
1336 1337 1338 1339
    return (
      getattr(aq_base(document), 'isAncestryIndexable', None) is None or
      not document.isAncestryIndexable()
    )
1340 1341 1342 1343

  def _updateActivateKwWithSerialisationTag(self, document, activate_kw):
    activate_kw['serialization_tag'] = document.getRootDocumentPath()
    return activate_kw
1344

1345 1346
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getIndexableChildValueList' )
1347 1348 1349 1350 1351
  def getIndexableChildValueList(self):
    """
      Get indexable childen recursively.
    """
    value_list = []
1352
    if self.isAncestryIndexable():
1353
      value_list.append(self)
1354 1355 1356 1357
      if self.isSubtreeIndexable():
        for c in self.objectValues():
          if getattr(aq_base(c), 'getIndexableChildValueList', None) is not None:
            value_list.extend(c.getIndexableChildValueList())
1358 1359
    return value_list

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
  def _reindexOnCreation(self, **reindex_kw):
    """
    Immediately and recursively reindex self, a document which was created
    (bound to its parent) within current transaction.

    Here, immediate recursion is expected to be fine as document tree just
    created: assume we can iterate over what was just created without causing
    memory exhaustion.
    """
    self.immediateReindexObject(**reindex_kw)
    dummy = lambda **kw: None
    for document in self.objectValues():
      getattr(document, '_reindexOnCreation', dummy)(**reindex_kw)
1373

1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
  security.declareProtected(Permissions.ModifyPortalContent, 'moveObject')
  def moveObject(self, idxs=None):
      """
          Reindex the object in the portal catalog.
          If idxs is present, only those indexes are reindexed.
          The metadata is always updated.

          Also update the modification date of the object,
          unless specific indexes were requested.

          Passes is_object_moved to catalog to force
          reindexing without creating new uid
      """
      if idxs is None: idxs = []
      if idxs == []:
          # Update the modification date.
          if getattr(aq_base(self), 'notifyModified', _marker) is not _marker:
              self.notifyModified()
      catalog = getattr(self.getPortalObject(), 'portal_catalog', None)
      if catalog is not None:
          catalog.moveObject(self, idxs=idxs)

1396 1397
  security.declareProtected( Permissions.ModifyPortalContent,
                             'recursiveMoveObject' )
1398 1399 1400 1401 1402
  def recursiveMoveObject(self):
    """
      Called when the base of a hierarchy is renamed
    """
    # Reindex self
1403
    if self.isAncestryIndexable():
1404 1405 1406
      self.moveObject()
    # Reindex contents
    for c in self.objectValues():
1407
      if getattr(aq_base(c), 'recursiveMoveObject', None) is not None:
1408 1409 1410
        c.recursiveMoveObject()

  # Special Relation keyword : 'content' and 'container'
1411 1412
  security.declareProtected( Permissions.AccessContentsInformation,
                             '_getCategoryMembershipList' )
1413
  def _getCategoryMembershipList(self, category,
1414 1415
                                 spec=(), filter=None, portal_type=(), base=0,
                                 keep_default=None, checked_permission=None):
1416 1417 1418 1419 1420
    if category == 'content':
      content_list = self.searchFolder(portal_type=spec)
      return map(lambda x: x.relative_url, content_list)
    else:
      return Base.getCategoryMembershipList(self, category,
1421
          spec=spec, filter=filter, portal_type=portal_type, base=base)
1422 1423 1424

  security.declareProtected(Permissions.AccessContentsInformation,
                            'checkConsistency')
1425
  def checkConsistency(self, fixit=False, filter=None, **kw):
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    """
    Check the consistency of this object, then
    check recursively the consistency of every sub object.
    """
    error_list = []
    # Fix BTree
    if fixit:
      btree_ok = self._cleanup()
      if not btree_ok:
        # We must commit if we want to keep on recursing
1436
        transaction.savepoint(optimistic=True)
1437 1438
        error_list += [ConsistencyMessage(
          self, self.getRelativeUrl(), 'BTree Inconsistency (fixed)')]
1439
    # Call superclass
1440
    error_list += Base.checkConsistency(self, fixit=fixit, filter=filter, **kw)
1441 1442 1443
    # We must commit before listing folder contents
    # in case we erased some data
    if fixit:
1444
      transaction.savepoint(optimistic=True)
1445 1446
    # Then check the consistency on all sub objects
    for obj in self.contentValues():
1447 1448 1449 1450
      if obj.providesIConstraint():
        # it is not possible to checkConsistency of Constraint itself, as method
        # of this name implement consistency checking on object
        continue
1451
      if fixit:
1452
        extra_errors = obj.fixConsistency(filter=filter, **kw)
1453
      else:
1454
        extra_errors = obj.checkConsistency(filter=filter, **kw)
1455 1456 1457 1458 1459
      if len(extra_errors) > 0:
        error_list += extra_errors
    # We should also return an error if any
    return error_list

1460
  security.declareProtected(Permissions.AccessContentsInformation, 'asXML')
1461
  def asXML(self, omit_xml_declaration=True, root=None):
1462 1463 1464