ERP5Site.py 79 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
##############################################################################
Jean-Paul Smets's avatar
Jean-Paul Smets committed
3 4 5 6 7 8 9 10 11 12 13
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
14 15
"""
  Portal class
Jean-Paul Smets's avatar
Jean-Paul Smets committed
16 17
"""

18 19
import threading
from weakref import ref as weakref
20
from OFS.Application import Application
21 22
from Products.ERP5Type import Globals
from Products.ERP5Type.Globals import package_home
23

24
from Products.SiteErrorLog.SiteErrorLog import manage_addErrorLog
25
from ZPublisher import BeforeTraverse
26
from ZPublisher.BaseRequest import RequestContainer
Jean-Paul Smets's avatar
Jean-Paul Smets committed
27
from AccessControl import ClassSecurityInfo
28
from Products.CMFDefault.Portal import CMFSite
29 30
from Products.CMFCore.utils import getToolByName
from Products.ERP5Type import Permissions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31
from Products.ERP5Type.Core.Folder import FolderMixIn
32
from Acquisition import aq_base
33
from Products.ERP5Type import allowClassTool
34 35
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
from Products.ERP5Type.Cache import caching_instance_method
36
from Products.ERP5Type.Cache import CachingMethod, CacheCookieMixin
37 38
from Products.ERP5Type.ERP5Type import ERP5TypeInformation
from Products.ERP5.Document.BusinessTemplate import BusinessTemplate
39
from Products.ERP5Type.Log import log as unrestrictedLog
40
from Products.CMFActivity.Errors import ActivityPendingError
41
import ERP5Defaults
42
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Nicolas Dumazet's avatar
Nicolas Dumazet committed
43
from Products.ERP5Type.dynamic.portal_type_class import synchronizeDynamicModules
Jean-Paul Smets's avatar
Jean-Paul Smets committed
44

45
from zLOG import LOG, INFO, WARNING, ERROR
Sebastien Robin's avatar
Sebastien Robin committed
46
from string import join
47
import os
48
import warnings
49 50
MARKER = []

51

Jean-Paul Smets's avatar
Jean-Paul Smets committed
52
# Site Creation DTML
53 54 55 56 57 58 59 60 61
manage_addERP5SiteFormDtml = Globals.HTMLFile('dtml/addERP5Site', globals())

def manage_addERP5SiteForm(*args, **kw):
  """
    Make getCatalogStorageList available from inside the dtml.
  """
  kw['getCatalogStorageList'] = getCatalogStorageList
  return manage_addERP5SiteFormDtml(*args, **kw)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
62
# ERP5Site Constructor
63 64 65
def manage_addERP5Site(self,
                       id,
                       title='ERP5',
66 67
                       description='',
                       create_userfolder=1,
68
                       create_activities=True,
69 70 71
                       email_from_address='postmaster@localhost',
                       email_from_name='Portal Administrator',
                       validate_email=0,
72
                       erp5_catalog_storage='',
73 74
                       erp5_sql_connection_type='Z MySQL Database Connection',
                       erp5_sql_connection_string='test test',
75 76
                       erp5_sql_deferred_connection_type=\
                           'Z MySQL Deferred Database Connection',
77 78 79 80 81 82 83 84 85
                       cmf_activity_sql_connection_type= \
                           'Z MySQL Database Connection',
                       cmf_activity_sql_connection_string='test test',
                       light_install=0,
                       reindex=1,
                       RESPONSE=None):
  '''
  Adds a portal instance.
  '''
86
  gen = ERP5Generator()
87
  id = str(id).strip()
88 89
  p = gen.create(self,
                 id,
90
                 create_userfolder,
91
                 erp5_catalog_storage,
92 93
                 erp5_sql_connection_type,
                 erp5_sql_connection_string,
94
                 erp5_sql_deferred_connection_type,
95 96 97 98 99
                 cmf_activity_sql_connection_type,
                 cmf_activity_sql_connection_string,
                 create_activities=create_activities,
                 light_install=light_install,
                 reindex=reindex)
100 101
  gen.setupDefaultProperties(p,
                             title,
102
                             description,
103
                             email_from_address,
104 105
                             email_from_name,
                             validate_email)
106
  if RESPONSE is not None:
107 108
    RESPONSE.redirect(p.absolute_url())

109 110 111 112 113 114 115 116 117 118
def getCatalogStorageList(*args, **kw):
  """
    Returns the list of business templates available at install which can be
    used to setup a catalog storage.
  """
  result = []
  bootstrap_dir = getBootstrapDirectory()
  for item in os.listdir(bootstrap_dir):
    if item == '.svn':
      continue
119
    if item.endswith('.bt5') and os.path.isfile(item):
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
      # Simple heuristic to make it faster than extracting the whole bt
      if item.endswith('_catalog.bt5'):
        result.append((item, item))
    elif os.path.isdir(os.path.join(bootstrap_dir, item)):
      # Find if the business temlate provides erp5_catalog
      try:
        provides_file = open(os.path.join(bootstrap_dir, item, 'bt', 'provision_list'), 'r')
        provides_list = provides_file.readlines()
        provides_file.close()
      except IOError:
        provides_list = []
      if 'erp5_catalog' in provides_list:
        # Get a nice title (the first line of the description).
        try:
          title_file = open(os.path.join(bootstrap_dir, item, 'bt', 'description'), 'r')
          title = title_file.readline()
          title_file.close()
        except IOError:
          title = item
        result.append((item, title))
  return result
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

class ReferCheckerBeforeTraverseHook:
  """This before traverse hook checks the HTTP_REFERER argument in the request
  and refuses access to anything else that portal_url.

  This is enabled by calling the method enableRefererCheck on the portal.
  """
  handle = '_erp5_referer_check'

  def __call__(self, container, request):
    """Checks the request contains a valid referrer.
    """
    response = request.RESPONSE
    http_url = request.get('ACTUAL_URL', '').strip()
    http_referer = request.get('HTTP_REFERER', '').strip()
156

157 158 159 160 161 162 163
    user_password = request._authUserPW()
    if user_password:
      user = container.acl_users.getUserById(user_password[0]) or\
              container.aq_parent.acl_users.getUserById(user_password[0])
      # Manager can do anything
      if user is not None and 'Manager' in user.getRoles():
        return
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    portal_url = container.portal_url.getPortalObject().absolute_url()
    if http_referer != '':
      # if HTTP_REFERER is set, user can acces the object if referer is ok
      if http_referer.startswith(portal_url):
        return
      LOG('HTTP_REFERER_CHECK : BAD REFERER !', INFO,
          'request : "%s", referer : "%s"' % (http_url, http_referer))
      response.unauthorized()
    else:
      # no HTTP_REFERER, we only allow to reach portal_url
      for i in ('/', '/index_html', '/login_form', '/view'):
        if http_url.endswith(i):
          http_url = http_url[:-len(i)]
          break
      if len(http_url) == 0 or not portal_url.startswith(http_url):
        LOG('HTTP_REFERER_CHECK : NO REFERER !', INFO,
            'request : "%s"' % http_url)
        response.unauthorized()

184
import ZODB
185 186 187 188 189 190 191 192 193 194

class _site(threading.local):
  """Class for getting and setting the site in the thread global namespace
  """
  site = ()

  def __new__(cls):
    self = threading.local.__new__(cls)
    return self.__get, self.__set

195 196 197
  def __get(self, REQUEST=None,
            # XXX Compatibility code (ZODB >= 3.9 has no __version__ anymore)
            __opened='_opened'[getattr(ZODB, '__version__', '3.9') >= '3.9':]):
198
    """Returns the currently processed site, optionally wrapped in a request
199
    """
200 201 202
    while True:
      app, site_id = self.site[-1]
      app = app()
203
      if getattr(app._p_jar, __opened):
204 205 206 207
        if REQUEST is None:
          return getattr(app, site_id)
        return getattr(app.__of__(RequestContainer(REQUEST=REQUEST)), site_id)
      del self.site[-1]
208 209 210 211 212 213 214 215 216 217 218 219 220 221

  def __set(self, site):
    app = aq_base(site.aq_parent)
    self.site = [x for x in self.site if x[0]() is not app]
    # Use weak references for automatic cleanup. In practice, this is probably
    # useless, because there is no reason a thread reopen the database.
    self.site.append((weakref(app, self.__del), site.id))

  def __del(self, app):
    self.site = [x for x in self.site if x[0] is not app]

getSite, setSite = _site()


222
class ERP5Site(FolderMixIn, CMFSite, CacheCookieMixin):
223
  """
224 225
  The *only* function this class should have is to help in the setup
  of a new ERP5.  It should not assist in the functionality at all.
226
  """
227
  meta_type = 'ERP5 Site'
228
  portal_type = 'ERP5 Site'
229
  constructors = (('addERP5Site', manage_addERP5SiteForm), manage_addERP5Site, )
230 231 232
  uid = 0
  last_id = 0
  icon = 'portal.gif'
233 234
  # Default value, prevents error during upgrade
  isIndexable = ConstantGetter('isIndexable', value=True)
235 236

  _properties = (
237
      { 'id':'title',
238
        'type':'string'},
239
      { 'id':'description',
240 241
        'type':'text'},
      )
242 243 244 245 246 247 248 249 250
  title = ''
  description = ''

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

  security.declareProtected(Permissions.View, 'view')
  def view(self):
251 252 253 254 255
    """
      Returns the default view.
      Implemented for consistency
    """
    return self.index_html()
256

257 258 259 260 261
  def __of__(self, parent):
    self = CMFSite.__of__(self, parent)
    # Use a transactional variable for performance reason,
    # since ERP5Site.__of__ is called quite often.
    tv = getTransactionalVariable()
262 263 264
    # Check 'parent' is the root because some objects like '_components'
    # store the site in '__parent__'.
    if 'ERP5Site.__of__' not in tv and type(parent) is Application:
265 266 267 268 269
      tv['ERP5Site.__of__'] = None
      setSite(self)
      synchronizeDynamicModules(self)
    return self

270 271 272 273 274 275 276 277 278 279 280
  def manage_beforeDelete(self, item, container):
    # On Zope 2.8, skin is setup during Acquisition (in the .__of__() method).
    # On Zope 2.12, skin is setup during __before_publishing_traverse__, which
    # doesn't happen when the object is being deleted from the management
    # interface, but we need it to be set for portal_activities when we're
    # being deleted. 
    self.setupCurrentSkin(self.REQUEST)
    return ERP5Site.inheritedAttribute('manage_beforeDelete')(self,
                                                              item,
                                                              container)

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
  security.declareProtected( Permissions.ModifyPortalContent, 'manage_renameObject' )
  def manage_renameObject(self, id=None, new_id=None, REQUEST=None):
    """manage renaming an object while keeping coherency for contained
    and linked to objects inside the renamed object.

    XXX this is nearly a copy-and-paste from CopySupport.

    XXX this is not good enough when the module or the objects inside
    the module are referred to by outer objects. But addressing this problem
    requires a full traversal of the object tree, and the current
    implementation is not efficient enough for this.
    """
    ob = self.restrictedTraverse(id)
    if getattr(aq_base(ob), '_updateInternalRelatedContent', None) is not None:
      # Make sure there is no activities pending on that object
      try:
        portal_activities = getToolByName(self, 'portal_activities')
      except AttributeError:
        # There is no activity tool
        portal_activities = None
      if portal_activities is not None:
        if portal_activities.countMessage(path=ob.getPath())>0:
          raise ActivityPendingError, 'Sorry, pending activities prevent ' \
                         +  'changing id at this current stage'

      # Search for categories that have to be updated in sub objects.
      ob._recursiveSetActivityAfterTag(ob)
      path_item_list = ob.getRelativeUrl().split('/')
      ob._updateInternalRelatedContent(object=ob,
                                       path_item_list=path_item_list,
                                       new_id=new_id)
    # Rename the object
    return CMFSite.manage_renameObject(self, id=id, new_id=new_id,
                                       REQUEST=REQUEST)

316 317 318 319 320 321 322
  def _getAcquireLocalRoles(self):
    """
      Prevent local roles from being acquired outside of Portal object.
      See ERP5Security/__init__.py:mergedLocalRoles .
    """
    return False

323 324 325 326 327 328 329
  security.declareProtected(Permissions.ManagePortal, 'enableRefererCheck')
  def enableRefererCheck(self):
    """Enable a ReferCheckerBeforeTraverseHook to check users have valid
    HTTP_REFERER
    """
    BeforeTraverse.registerBeforeTraverse(self,
                                        ReferCheckerBeforeTraverseHook(),
330 331 332
                                        ReferCheckerBeforeTraverseHook.handle,
                             # we want to be registered _after_ CookieCrumbler
                                        100)
333

334 335 336 337
  def _disableRefererCheck(self):
    """Disable the HTTP_REFERER check."""
    BeforeTraverse.unregisterBeforeTraverse(self,
                                        ReferCheckerBeforeTraverseHook.handle)
338

339
  def hasObject(self, id):
340
    """
341
    Check if the portal has an id.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
342
    """
343
    return id in self.objectIds()
344

345
  security.declareProtected(Permissions.AccessContentsInformation,
346
                            'getPortalObject')
347 348
  def getPortalObject(self):
    return self
Jean-Paul Smets's avatar
Jean-Paul Smets committed
349

350 351 352 353 354
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalType')
  def getPortalType(self):
    return self.portal_type

355
  security.declareProtected(Permissions.AccessContentsInformation,
356
                            'getTitle')
357 358 359 360 361
  def getTitle(self):
    """
      Return the title.
    """
    return self.title
362

363 364 365 366 367 368
  security.declareProtected(Permissions.AccessContentsInformation, 'getUid')
  def getUid(self):
    """
      Returns the UID of the object. Eventually reindexes
      the object in order to make sure there is a UID
      (useful for import / export).
Jean-Paul Smets's avatar
Jean-Paul Smets committed
369

370 371 372
      WARNING : must be updates for circular references issues
    """
    return getattr(self, 'uid', 0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
373

374
  security.declareProtected(Permissions.AccessContentsInformation,
375
                            'getParentUid')
376 377 378 379 380
  def getParentUid(self):
    """
      A portal has no parent
    """
    return self.getUid()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
381

382 383 384 385
  # Required to allow content creation outside folders
  security.declareProtected(Permissions.View, 'getIdGroup')
  def getIdGroup(self):
    return None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
386

387 388 389 390
  # Required to allow content creation outside folders
  security.declareProtected(Permissions.ModifyPortalContent, 'setLastId')
  def setLastId(self, id):
    self.last_id = id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
391

392 393
  security.declareProtected(Permissions.AccessContentsInformation, 'getUrl')
  def getUrl(self, REQUEST=None):
394 395 396 397
    """
      Returns the absolute path of an object
    """
    return join(self.getPhysicalPath(),'/')
Sebastien Robin's avatar
Sebastien Robin committed
398

399 400 401 402 403 404 405
  security.declareProtected(Permissions.AccessContentsInformation, 'getRelativeUrl')
  def getRelativeUrl(self):
    """
      Returns the url of an object relative to the portal site.
    """
    return self.getPortalObject().portal_url.getRelativeUrl(self)

406 407 408 409
  # Old name - for compatibility
  security.declareProtected(Permissions.AccessContentsInformation, 'getPath')
  getPath = getUrl

410 411 412 413 414 415
  security.declareProtected(Permissions.AccessContentsInformation, 'opaqueValues')
  def opaqueValues(self, *args, **kw):
    # XXX nonsense of inheriting from CMFSite that calls __before_traversal__
    # and tries to load subobjects of the portal too early
    return []

416
  security.declareProtected(Permissions.AccessContentsInformation, 'searchFolder')
417 418 419 420 421 422 423
  def searchFolder(self, **kw):
    """
      Search the content of a folder by calling
      the portal_catalog.
    """
    if not kw.has_key('parent_uid'):
      kw['parent_uid'] = self.uid
424
    return self.portal_catalog.searchResults(**kw)
425 426 427 428 429 430 431 432 433

  security.declareProtected(Permissions.AccessContentsInformation, 'countFolder')
  def countFolder(self, **kw):
    """
      Count the content of a folder by calling
      the portal_catalog.
    """
    if not kw.has_key('parent_uid'):
      kw['parent_uid'] = self.uid
434
    return self.portal_catalog.countResults(**kw)
435 436 437 438 439 440 441 442

  # Proxy methods for security reasons
  def getOwnerInfo(self):
    return self.owner_info()

  security.declarePublic('getOrderedGlobalActionList')
  def getOrderedGlobalActionList(self, action_list):
    """
443 444
    Returns a dictionnary of actions, sorted by type of object

445
    This should absolutely be rewritten by using clean
446
    concepts to separate worklists XXX
447 448 449 450 451 452
    """
    sorted_workflow_actions = {}
    sorted_global_actions = []
    other_global_actions = []
    for action in action_list:
      action['disabled'] = 0
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
453 454 455 456 457 458 459 460 461 462
      workflow_title = action.get('workflow_title', None)
      if workflow_title is not None:
        if not sorted_workflow_actions.has_key(workflow_title):
          sorted_workflow_actions[workflow_title] = [
            {'title':workflow_title,
             'disabled':1,
             'workflow_id':action['workflow_id']
             }
            ]
        sorted_workflow_actions[workflow_title].append(action)
463 464
      else:
        other_global_actions.append(action)
465
    for key in sorted(sorted_workflow_actions):
466 467 468 469 470 471
      sorted_global_actions.extend(sorted_workflow_actions[key])
    sorted_global_actions.append({'title': 'Others', 'disabled': 1})
    sorted_global_actions.extend(other_global_actions)
    return sorted_global_actions

  def setupDefaultProperties(self, p, title, description,
472 473 474
                             email_from_address, email_from_name,
                             validate_email
                             ):
475
    CMFSite.setupDefaultProperties(self, p, title, description,
476 477
                           email_from_address, email_from_name,
                           validate_email)
478

479 480 481
  # Portal methods are based on the concept of having portal-specific
  # parameters for customization. In the past, we used global parameters,
  # but it was not very good because it was very difficult
482
  # to customize the settings for each portal site.
483 484
  def _getPortalConfiguration(self, id):
    """
485
    Get a portal-specific configuration.
486

487 488
    Current implementation is using properties in a portal object.
    If not found, try to get a default value for backward compatibility.
489

490 491
    This implementation can be improved by gathering information
    from appropriate places, such as portal_types, portal_categories
492
    and portal_workflow.
493 494 495
    """
    if self.hasProperty(id):
      return self.getProperty(id)
496

497 498
    # Fall back to the default.
    return getattr(ERP5Defaults, id, None)
499

500
  def _getPortalGroupedTypeList(self, group, enable_sort=True):
501
    """
502
    Return a list of portal types classified to a specific group.
503 504
    The result is sorted by language (using the user language
    as default)
505 506 507

    Enable_sort parameter was added in order to allows looking groups
    of portal type without sorting. This is better for performance
508 509 510
    """
    def getTypeList(group):
      type_list = []
Sebastien Robin's avatar
Sebastien Robin committed
511
      for pt in self.portal_types.listTypeInfo():
512 513
        if group in getattr(pt, 'group_list', ()):
          type_list.append(pt.getId())
514

515 516 517 518
      if enable_sort and len(type_list) >= 2:
        # XXX (Seb), this code must be moved in another place.
        # It is inefficient to always sort here for some particular
        # needs of the user interface
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
519 520
        translate = localizer_tool.translate
        type_list.sort(key=lambda x:translate('ui', x))
521 522
      return tuple(type_list)

523 524 525 526 527 528
    if enable_sort:
      # language should be cached in Transaction Cache if performance issue
      localizer_tool = getToolByName(self, 'Localizer')
      language = localizer_tool.get_selected_language()
    else:
      localizer_tool = language = None
529

530
    getTypeList = CachingMethod(getTypeList,
531 532 533 534
                                id=(('_getPortalGroupedTypeList', language), group,
                                    enable_sort),
                                cache_factory='erp5_content_medium',
                                )
535 536 537

    return getTypeList(group) # Although this method is called get*List, it
                              # returns a tuple - renaming to be considered
538

539 540 541 542 543 544 545 546 547
  @caching_instance_method(id='ERP5Site._getPortalGroupedTypeSet',
     cache_factory='erp5_content_long')
  def _getPortalGroupedTypeSet(self, group):
    """
    Same as _getPortalGroupedTypeList, but returns a set, better for
    performance when looking for matching portal types
    """
    return set(self._getPortalGroupedTypeList(group, enable_sort=False))

548
  def _getPortalGroupedCategoryList(self, group):
549
    """
550
    Return a list of base categories classified to a specific group.
551 552 553 554 555 556 557 558
    """
    def getCategoryList(group):
      category_list = []
      for bc in self.portal_categories.objectValues():
        if group in bc.getCategoryTypeList():
          category_list.append(bc.getId())
      return tuple(category_list)

559 560
    getCategoryList = CachingMethod(
                            getCategoryList,
561
                            id=('_getPortalGroupedCategoryList', group),
Aurel's avatar
Aurel committed
562
                            cache_factory='erp5_content_medium')
563 564 565
    return getCategoryList(group)

  def _getPortalGroupedStateList(self, group):
566
    """
567
    Return a list of workflow states classified to a specific group.
568 569 570 571 572 573 574 575 576 577
    """
    def getStateList(group):
      state_dict = {}
      for wf in self.portal_workflow.objectValues():
        if getattr(wf, 'states', None):
          for state in wf.states.objectValues():
            if group in getattr(state, 'type_list', ()):
              state_dict[state.getId()] = None
      return tuple(state_dict.keys())

578
    getStateList = CachingMethod(getStateList,
579
                                 id=('_getPortalGroupedStateList', group),
Aurel's avatar
Aurel committed
580
                                 cache_factory='erp5_content_medium')
581 582
    return getStateList(group)

583 584
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDefaultSectionCategory')
585 586
  def getPortalDefaultSectionCategory(self):
    """
587
    Return a default section category. This method is deprecated.
588 589 590 591
    """
    LOG('ERP5Site', 0, 'getPortalDefaultSectionCategory is deprecated;'+
        ' use portal_preferences.getPreferredSectionCategory instead.')
    section_category = self.portal_preferences.getPreferredSectionCategory()
592

593 594 595 596
    # XXX This is only for backward-compatibility.
    if not section_category:
      section_category = self._getPortalConfiguration(
                                'portal_default_section_category')
597

598
    return section_category
599

600 601 602 603 604 605
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalResourceTypeList')
  def getPortalResourceTypeList(self):
    """
      Return resource types.
    """
606 607 608
    return self._getPortalGroupedTypeList('resource') or \
           self._getPortalConfiguration('portal_resource_type_list')

609 610 611 612 613 614 615
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSubVariationTypeList')
  def getPortalSubVariationTypeList(self):
    """
      Return resource types.
    """
    return self._getPortalGroupedTypeList('sub_variation')
616

617 618 619 620 621 622 623
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSubVariationBaseCategoryList')
  def getPortalSubVariationBaseCategoryList(self):
    """
      Return variation base categories.
    """
    return self._getPortalGroupedCategoryList('sub_variation')
624

625 626 627 628 629 630
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalVariationTypeList')
  def getPortalVariationTypeList(self):
    """
      Return variation types.
    """
631 632 633
    return self._getPortalGroupedTypeList('variation') or \
           self._getPortalConfiguration('portal_variation_type_list')

634 635 636 637 638 639
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalNodeTypeList')
  def getPortalNodeTypeList(self):
    """
      Return node types.
    """
640 641 642
    return self._getPortalGroupedTypeList('node') or \
           self._getPortalConfiguration('portal_node_type_list')

643 644 645 646 647 648
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPaymentNodeTypeList')
  def getPortalPaymentNodeTypeList(self):
    """
      Return payment node types.
    """
649 650 651
    return self._getPortalGroupedTypeList('payment_node') or \
           self._getPortalConfiguration('portal_payment_node_type_list')

652 653 654 655 656 657
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInvoiceTypeList')
  def getPortalInvoiceTypeList(self):
    """
      Return invoice types.
    """
658 659 660
    return self._getPortalGroupedTypeList('invoice') or \
           self._getPortalConfiguration('portal_invoice_type_list')

661 662 663 664 665 666
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOrderTypeList')
  def getPortalOrderTypeList(self):
    """
      Return order types.
    """
667 668 669
    return self._getPortalGroupedTypeList('order') or \
           self._getPortalConfiguration('portal_order_type_list')

670 671 672 673 674 675
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDeliveryTypeList')
  def getPortalDeliveryTypeList(self):
    """
      Return delivery types.
    """
676 677 678
    return self._getPortalGroupedTypeList('delivery') or \
           self._getPortalConfiguration('portal_delivery_type_list')

679 680 681 682 683 684
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTransformationTypeList')
  def getPortalTransformationTypeList(self):
    """
      Return transformation types.
    """
685 686 687
    return self._getPortalGroupedTypeList('transformation') or \
           self._getPortalConfiguration('portal_transformation_type_list')

688 689 690 691 692 693 694 695 696
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalModelPathTypeList')
  def getPortalModelPathTypeList(self):
    """
      Return model_path types.
    """
    return self._getPortalGroupedTypeList('model_path') or \
           self._getPortalConfiguration('portal_model_path_type_list')

697 698 699 700 701 702
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalVariationBaseCategoryList')
  def getPortalVariationBaseCategoryList(self):
    """
      Return variation base categories.
    """
703 704 705
    return self._getPortalGroupedCategoryList('variation') or \
           self._getPortalConfiguration('portal_variation_base_category_list')

706 707 708 709 710 711
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOptionBaseCategoryList')
  def getPortalOptionBaseCategoryList(self):
    """
      Return option base categories.
    """
712 713 714
    return self._getPortalGroupedCategoryList('option') or \
           self._getPortalConfiguration('portal_option_base_category_list')

715 716 717 718 719 720
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInvoiceMovementTypeList')
  def getPortalInvoiceMovementTypeList(self):
    """
      Return invoice movement types.
    """
721 722 723
    return self._getPortalGroupedTypeList('invoice_movement') or \
           self._getPortalConfiguration('portal_invoice_movement_type_list')

724 725 726 727 728 729 730 731 732 733
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTaxMovementTypeList')
  def getPortalTaxMovementTypeList(self):
    """
      Return tax movement types.
    """
    return self._getPortalGroupedTypeList('tax_movement') or \
           self._getPortalConfiguration('portal_tax_movement_type_list')


734 735 736 737 738 739
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOrderMovementTypeList')
  def getPortalOrderMovementTypeList(self):
    """
      Return order movement types.
    """
740 741 742
    return self._getPortalGroupedTypeList('order_movement') or \
           self._getPortalConfiguration('portal_order_movement_type_list')

743 744 745 746 747 748
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDeliveryMovementTypeList')
  def getPortalDeliveryMovementTypeList(self):
    """
      Return delivery movement types.
    """
749 750 751
    return self._getPortalGroupedTypeList('delivery_movement') or \
           self._getPortalConfiguration('portal_delivery_movement_type_list')

752
  security.declareProtected(Permissions.AccessContentsInformation,
753
                            'getPortalSupplyTypeList')
754 755 756 757
  def getPortalSupplyTypeList(self):
    """
      Return supply types.
    """
758 759 760
    return self._getPortalGroupedTypeList('supply') or \
           self._getPortalConfiguration('portal_supply_type_list')

761 762 763 764 765 766 767 768
  security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalRuleTypeList')
  def getPortalRuleTypeList(self):
    """
      Return rule types.
    """
    return self._getPortalGroupedTypeList('rule')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
769 770 771 772
  security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalProjectTypeList')
  def getPortalProjectTypeList(self):
    """
773
      Return project types.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
774 775 776
    """
    return self._getPortalGroupedTypeList('project')

777
  security.declareProtected(Permissions.AccessContentsInformation,
778 779 780 781 782
                              'getPortalDocumentTypeList')
  def getPortalDocumentTypeList(self):
    """
      Return document types.
    """
783
    return self._getPortalGroupedTypeList('document')
784

785 786 787 788 789 790 791 792
  security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalEmbeddedDocumentTypeList')
  def getPortalEmbeddedDocumentTypeList(self):
    """
      Return embedded document types.
    """
    return self._getPortalGroupedTypeList('embedded_document')

793 794 795 796 797 798 799 800
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalWebDocumentTypeList')
  def getPortalWebDocumentTypeList(self):
    """
      Return web page types.
    """
    return self._getPortalGroupedTypeList('web_document')

801 802 803 804
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalFileDocumentTypeList')
  def getPortalFileDocumentTypeList(self):
    """
805
      Return file document types.
806 807 808 809 810 811 812
    """
    return self._getPortalGroupedTypeList('file_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalRecentDocumentTypeList')
  def getPortalRecentDocumentTypeList(self):
    """
813
      Return recent document types.
814 815 816 817 818 819 820
    """
    return self._getPortalGroupedTypeList('recent_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTemplateDocumentTypeList')
  def getPortalTemplateDocumentTypeList(self):
    """
821
      Return template document types.
822 823 824 825 826 827 828
    """
    return self._getPortalGroupedTypeList('template_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalMyDocumentTypeList')
  def getPortalMyDocumentTypeList(self):
    """
829
      Return my document types.
830 831 832
    """
    return self._getPortalGroupedTypeList('my_document')

833 834 835 836
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalCrawlerIndexTypeList')
  def getPortalCrawlerIndexTypeList(self):
    """
837
      Return crawler index types.
838 839 840
    """
    return self._getPortalGroupedTypeList('crawler_index')

841 842 843 844 845 846 847 848
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalBudgetVariationTypeList')
  def getPortalBudgetVariationTypeList(self):
    """
      Return budget variation types.
    """
    return self._getPortalGroupedTypeList('budget_variation')

849
  security.declareProtected(Permissions.AccessContentsInformation,
850
                            'getPortalSupplyPathTypeList')
851 852
  def getPortalSupplyPathTypeList(self):
    """
853
      Return supply path types.
854
    """
855 856 857
    return self._getPortalGroupedTypeList('supply_path') or \
           self._getPortalConfiguration('portal_supply_path_type_list')

858 859 860 861 862 863 864
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAcquisitionMovementTypeList')
  def getPortalAcquisitionMovementTypeList(self):
    """
      Return acquisition movement types.
    """
    return tuple(list(self.getPortalOrderMovementTypeList()) +
865
                 list(self.getPortalDeliveryMovementTypeList()) +
866
                 list(self.getPortalTaxMovementTypeList()) +
867 868
                 list(self.getPortalInvoiceMovementTypeList()))

869 870 871 872 873 874 875
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalMovementTypeList')
  def getPortalMovementTypeList(self):
    """
      Return movement types.
    """
    return tuple(list(self.getPortalOrderMovementTypeList()) +
876 877
                 list(self.getPortalDeliveryMovementTypeList()) +
                 list(self.getPortalInvoiceMovementTypeList()) +
878
                 list(self.getPortalTaxMovementTypeList()) +
879
                 list(self.getPortalAccountingMovementTypeList()) +
880
                 ['Simulation Movement'])
881

882 883 884 885 886 887
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSimulatedMovementTypeList')
  def getPortalSimulatedMovementTypeList(self):
    """
      Return simulated movement types.
    """
888
    return tuple([x for x in self.getPortalMovementTypeList() \
889
                  if x not in self.getPortalContainerTypeList()])
890

891 892 893 894 895 896
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalContainerTypeList')
  def getPortalContainerTypeList(self):
    """
      Return container types.
    """
897 898 899
    return self._getPortalGroupedTypeList('container') or \
           self._getPortalConfiguration('portal_container_type_list')

900 901 902 903 904 905
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalContainerLineTypeList')
  def getPortalContainerLineTypeList(self):
    """
      Return container line types.
    """
906 907 908
    return self._getPortalGroupedTypeList('container_line') or \
           self._getPortalConfiguration('portal_container_line_type_list')

909 910 911 912 913 914
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalItemTypeList')
  def getPortalItemTypeList(self):
    """
      Return item types.
    """
915 916 917
    return self._getPortalGroupedTypeList('item') or \
           self._getPortalConfiguration('portal_item_type_list')

918 919 920 921 922 923
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDiscountTypeList')
  def getPortalDiscountTypeList(self):
    """
      Return discount types.
    """
924 925 926
    return self._getPortalGroupedTypeList('discount') or \
           self._getPortalConfiguration('portal_discount_type_list')

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalProductTypeList')
  def getPortalProductTypeList(self):
    """
      Return physical goods types.
    """
    return self._getPortalGroupedTypeList('product') or \
           self._getPortalConfiguration('portal_product_type_list')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalServiceTypeList')
  def getPortalServiceTypeList(self):
    """
      Return immaterial services types.
    """
    return self._getPortalGroupedTypeList('service') or \
           self._getPortalConfiguration('portal_service_type_list')

945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSaleTypeList')
  def getPortalSaleTypeList(self):
    """
    Return sale types.
    """
    return self._getPortalGroupedTypeList('sale')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPurchaseTypeList')
  def getPortalPurchaseTypeList(self):
    """
    Return purchase types.
    """
    return self._getPortalGroupedTypeList('purchase')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInternalTypeList')
  def getPortalInternalTypeList(self):
    """
    Return internal types.
    """
    return self._getPortalGroupedTypeList('internal')

969 970 971 972 973 974
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAlarmTypeList')
  def getPortalAlarmTypeList(self):
    """
      Return alarm types.
    """
975 976 977
    return self._getPortalGroupedTypeList('alarm') or \
           self._getPortalConfiguration('portal_alarm_type_list')

978 979 980 981 982 983
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPaymentConditionTypeList')
  def getPortalPaymentConditionTypeList(self):
    """
      Return payment condition types.
    """
984 985 986
    return self._getPortalGroupedTypeList('payment_condition') or \
           self._getPortalConfiguration('portal_payment_condition_type_list')

987 988 989 990 991 992
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalBalanceTransactionLineTypeList')
  def getPortalBalanceTransactionLineTypeList(self):
    """
      Return balance transaction line types.
    """
993
    return self._getPortalGroupedTypeList('balance_transaction_line') or \
994 995
           self._getPortalConfiguration(
                  'portal_balance_transaction_line_type_list')
996

997 998 999 1000 1001 1002
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalCurrentInventoryStateList')
  def getPortalCurrentInventoryStateList(self):
    """
      Return current inventory states.
    """
1003 1004 1005
    return self._getPortalGroupedStateList('current_inventory') or \
           self._getPortalConfiguration('portal_current_inventory_state_list')

1006 1007 1008 1009 1010 1011 1012 1013 1014
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTransitInventoryStateList')
  def getPortalTransitInventoryStateList(self):
    """
      Return transit inventory states.
    """
    return self._getPortalGroupedStateList('transit_inventory') or \
           self._getPortalConfiguration('portal_transit_inventory_state_list')

1015 1016 1017 1018 1019 1020
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDraftOrderStateList')
  def getPortalDraftOrderStateList(self):
    """
      Return draft order states.
    """
1021 1022 1023
    return self._getPortalGroupedStateList('draft_order') or \
           self._getPortalConfiguration('portal_draft_order_state_list')

1024 1025 1026 1027 1028 1029
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPlannedOrderStateList')
  def getPortalPlannedOrderStateList(self):
    """
      Return planned order states.
    """
1030 1031 1032
    return self._getPortalGroupedStateList('planned_order') or \
           self._getPortalConfiguration('portal_planned_order_state_list')

1033 1034 1035 1036 1037 1038
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalReservedInventoryStateList')
  def getPortalReservedInventoryStateList(self):
    """
      Return reserved inventory states.
    """
1039
    return self._getPortalGroupedStateList('reserved_inventory') or \
1040
        self._getPortalConfiguration('portal_reserved_inventory_state_list')
1041

1042 1043 1044 1045 1046 1047
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalFutureInventoryStateList')
  def getPortalFutureInventoryStateList(self):
    """
      Return future inventory states.
    """
1048 1049 1050
    return self._getPortalGroupedStateList('future_inventory') or \
           self._getPortalConfiguration('portal_future_inventory_state_list')

1051
  security.declareProtected(Permissions.AccessContentsInformation,
1052
                          'getPortalUpdatableAmortisationTransactionStateList')
1053 1054
  def getPortalUpdatableAmortisationTransactionStateList(self):
    """
1055
      Return states when Amortisation Transaction can be updated
1056
      by amortisation_transaction_builder.
1057
    """
1058 1059
    return self._getPortalConfiguration(
        'portal_updatable_amortisation_transaction_state_list')
1060

1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalGroupedSimulationStateList')
  def getPortalGroupedSimulationStateList(self):
    """
      Return all states which is related to simulation state workflow and state type
    """
    def getStateList():
      state_dict = {}
      for wf in self.portal_workflow.objectValues():
        if getattr(wf, 'variables', None) and \
           wf.variables.getStateVar() == 'simulation_state':
          if getattr(wf, 'states', None):
            for state in wf.states.objectValues():
              if getattr(state, 'type_list', None):
                state_dict[state.getId()] = None
      return tuple(sorted(state_dict.keys()))

    getStateList = CachingMethod(getStateList,
                                 id=('getPortalGroupedSimulationStateList'),
                                 cache_factory='erp5_content_medium')
    return getStateList()

1083 1084 1085 1086 1087 1088
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalColumnBaseCategoryList')
  def getPortalColumnBaseCategoryList(self):
    """
      Return column base categories.
    """
1089 1090 1091
    return self._getPortalGroupedCategoryList('column') or \
           self._getPortalConfiguration('portal_column_base_category_list')

1092 1093 1094 1095 1096 1097
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalLineBaseCategoryList')
  def getPortalLineBaseCategoryList(self):
    """
      Return line base categories.
    """
1098 1099 1100
    return self._getPortalGroupedCategoryList('line') or \
           self._getPortalConfiguration('portal_line_base_category_list')

1101 1102 1103 1104 1105 1106
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTabBaseCategoryList')
  def getPortalTabBaseCategoryList(self):
    """
      Return tab base categories.
    """
1107 1108 1109
    return self._getPortalGroupedCategoryList('tab') or \
           self._getPortalConfiguration('portal_tab_base_category_list')

1110 1111 1112 1113
  def getPortalDefaultGapRoot(self):
    """
      Return the Accounting Plan to use by default (return the root node)
    """
1114
    LOG('ERP5Site', 0,
1115 1116 1117
        'getPortalDefaultGapRoot is deprecated; ' \
        'use portal_preferences.getPreferredAccountingTransactionGap instead.')

1118 1119
    return self.portal_preferences.getPreferredAccountingTransactionGap() or \
           self._getPortalConfiguration('portal_default_gap_root')
1120

1121 1122 1123 1124
  def getPortalAccountingMovementTypeList(self) :
    """
      Return accounting movement type list.
    """
1125
    return self._getPortalGroupedTypeList('accounting_movement') or \
1126
        self._getPortalConfiguration('portal_accounting_movement_type_list')
1127

1128 1129 1130 1131
  def getPortalAccountingTransactionTypeList(self) :
    """
      Return accounting transaction movement type list.
    """
1132
    return self._getPortalGroupedTypeList('accounting_transaction') or \
1133
      self._getPortalConfiguration('portal_accounting_transaction_type_list')
1134

1135 1136 1137 1138
  def getPortalAssignmentBaseCategoryList(self):
    """
      Return List of category values to generate security groups.
    """
1139
    return self._getPortalGroupedCategoryList('assignment') or \
1140
        self._getPortalConfiguration('portal_assignment_base_category_list')
1141

1142 1143
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTicketTypeList')
1144 1145 1146 1147 1148
  def getPortalTicketTypeList(self):
    """
    Return ticket types.
    """
    return self._getPortalGroupedTypeList('ticket')
1149

1150 1151
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalEventTypeList')
1152 1153 1154 1155 1156
  def getPortalEventTypeList(self):
    """
    Return event types.
    """
    return self._getPortalGroupedTypeList('event')
1157

1158 1159 1160 1161 1162 1163 1164 1165
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDivergenceTesterTypeList')
  def getPortalDivergenceTesterTypeList(self):
    """
    Return divergence tester types.
    """
    return self._getPortalGroupedTypeList('divergence_tester')

1166 1167 1168 1169 1170 1171 1172 1173
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTargetSolverTypeList')
  def getPortalTargetSolverTypeList(self):
    """
    Return target solver types.
    """
    return self._getPortalGroupedTypeList('target_solver')

Sebastien Robin's avatar
Sebastien Robin committed
1174 1175 1176 1177 1178 1179 1180 1181
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTargetSolverTypeList')
  def getPortalDeliverySolverTypeList(self):
    """
    Return delivery solver types.
    """
    return self._getPortalGroupedTypeList('delivery_solver')

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAmountGeneratorTypeList')
  def getPortalAmountGeneratorTypeList(self):
    """
    Return amount generator types.
    """
    return self._getPortalGroupedTypeList('amount_generator')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAmountGeneratorLineTypeList')
  def getPortalAmountGeneratorLineTypeList(self):
    """
    Return amount generator line types.
    """
    return self._getPortalGroupedTypeList('amount_generator_line')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAmountGeneratorCellTypeList')
  def getPortalAmountGeneratorCellTypeList(self):
    """
    Return amount generator cell types.
    """
    return self._getPortalGroupedTypeList('amount_generator_cell')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1206 1207 1208 1209 1210 1211 1212 1213
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalBusinessProcessTypeList')
  def getPortalBusinessProcessTypeList(self):
    """
    Return amount generator types.
    """
    return self._getPortalGroupedTypeList('business_process')

1214

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1215
  security.declareProtected(Permissions.AccessContentsInformation,
1216 1217
                            'getPortalBusinessLinkTypeList')
  def getPortalBusinessLinkTypeList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1218
    """
1219 1220 1221 1222 1223 1224 1225 1226 1227
      Return business link types.
    """
    return self._getPortalGroupedTypeList('business_link')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTradeModelPathTypeList')
  def getPortalTradeModelPathTypeList(self):
    """
      Return trade model path types.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1228
    """
1229
    return self._getPortalGroupedTypeList('trade_model_path')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1230

1231 1232 1233 1234 1235 1236 1237 1238
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalCalendarPeriodTypeList')
  def getPortalCalendarPeriodTypeList(self):
    """
    Return calendar period types.
    """
    return self._getPortalGroupedTypeList('calendar_period')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1239 1240 1241 1242 1243 1244 1245 1246
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalModuleTypeList')
  def getPortalModuleTypeList(self):
    """
    Return module types.
    """
    return self._getPortalGroupedTypeList('module')

1247 1248 1249 1250 1251 1252 1253 1254
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInventoryMovementTypeList')
  def getPortalInventoryMovementTypeList(self):
    """
    Return inventory movement types.
    """
    return self._getPortalGroupedTypeList('inventory_movement')

Sebastien Robin's avatar
Sebastien Robin committed
1255 1256 1257 1258 1259 1260 1261 1262
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInventoryTypeList')
  def getPortalInventoryTypeList(self):
    """
    Return inventory types.
    """
    return self._getPortalGroupedTypeList('inventory')

1263 1264 1265 1266 1267 1268 1269 1270
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalMovementGroupTypeList')
  def getPortalMovementGroupTypeList(self):
    """
    Return movement group types.
    """
    return self._getPortalGroupedTypeList('movement_group')

1271 1272
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getDefaultModuleId')
1273 1274
  def getDefaultModuleId(self, portal_type, default=MARKER):
    """
Romain Courteaud's avatar
Romain Courteaud committed
1275 1276
    Return default module id where a object with portal_type can
    be created.
1277 1278
    """
    portal_object = self
Romain Courteaud's avatar
Romain Courteaud committed
1279 1280 1281 1282 1283
    module_id = None
    # first try to find by naming convention
    expected_module_id = portal_type.lower().replace(' ','_')
    if portal_object._getOb(expected_module_id, None) is not None:
      module_id = expected_module_id
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    else:
      expected_module_id += '_module'
      if portal_object._getOb(expected_module_id, None) is not None:
        module_id = expected_module_id
      # then look for module where the type is allowed
      else:
        for expected_module_id in portal_object.objectIds(spec=('ERP5 Folder',)):
          module = portal_object._getOb(expected_module_id, None)
          if module is not None:
            if portal_type in self.portal_types[module.getPortalType()].\
                                      allowed_content_types:
              module_id = expected_module_id
              break
Romain Courteaud's avatar
Romain Courteaud committed
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309

    if module_id is None:
      if default is not MARKER:
        return default
      else:
        # now we fail
        LOG('ERP5Site, getDefaultModuleId', 0,
            'Unable to find default module for portal_type: %s' % \
             portal_type)
        raise ValueError, 'Unable to find module for portal_type: %s' % \
               portal_type

    return module_id
1310

1311 1312
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getDefaultModule')
1313
  def getDefaultModule(self, portal_type, default=MARKER):
1314 1315 1316
    """
      Return default module where a object with portal_type can be created
    """
1317 1318 1319 1320
    module_id = self.getDefaultModuleId(portal_type, default)
    if module_id:
      return getattr(self, module_id, None)
    return None
1321

1322
  security.declareProtected(Permissions.AddPortalContent, 'newContent')
1323
  def newContent(self, id=None, portal_type=None, **kw):
1324 1325 1326 1327 1328 1329 1330
    """
      Creates a new content
    """
    if id is None:
      raise ValueError, 'The id should not be None'
    if portal_type is None:
      raise ValueError, 'The portal_type should not be None'
1331 1332 1333 1334
    self.portal_types.constructContent(type_name=portal_type,
                                       container=self,
                                       id=id,
                                       ) # **kw) removed due to CMF bug
1335
    new_instance = self[id]
1336

1337
    if kw:
1338
      new_instance._edit(force_update=1, **kw)
1339 1340
    return new_instance

1341 1342 1343 1344 1345 1346
  security.declarePublic('getVisibleAllowedContentTypeList')
  def getVisibleAllowedContentTypeList(self):
    """Users cannot add anything in an ERP5Site using standard interface.
    """
    return ()

1347 1348 1349 1350 1351 1352
  def log(self, description, content='', level=INFO):
    """Put a log message """
    warnings.warn("The usage of ERP5Site.log is deprecated.\n"
                  "Please use Products.ERP5Type.Log.log instead.",
                  DeprecationWarning)
    unrestrictedLog(description, content = content, level = level)
1353

1354 1355 1356 1357 1358
  security.declarePublic('setPlacelessDefaultReindexParameters')
  def setPlacelessDefaultReindexParameters(self, **kw):
    # This method sets the default keyword parameters to reindex. This is useful
    # when you need to specify special parameters implicitly (e.g. to reindexObject).
    # Those parameters will affect all reindex calls, not just ones on self.
1359
    tv = getTransactionalVariable()
1360 1361 1362 1363 1364 1365 1366 1367
    key = ('default_reindex_parameter', )
    tv[key] = kw

  security.declarePublic('setPlacelessDefaultActivateParameters')
  def setPlacelessDefaultActivateParameters(self, **kw):
    # This method sets the default keyword parameters to activate. This is useful
    # when you need to specify special parameters implicitly (e.g. to reindexObject).
    # Those parameters will affect all activate calls, not just ones on self.
1368
    tv = getTransactionalVariable()
1369 1370 1371 1372 1373 1374 1375
    key = ('default_activate_parameter', )
    tv[key] = kw

  security.declarePublic('getPlacelessDefaultReindexParameters')
  def getPlacelessDefaultReindexParameters(self):
    # This method returns default reindex parameters to self.
    # The result can be either a dict object or None.
1376
    tv = getTransactionalVariable()
1377 1378 1379 1380 1381 1382 1383
    key = ('default_reindex_parameter', )
    return tv.get(key)

  security.declarePublic('getPlacelessDefaultActivateParameters')
  def getPlacelessDefaultActivateParameters(self):
    # This method returns default activate parameters to self.
    # The result can be either a dict object or None.
1384
    tv = getTransactionalVariable()
1385 1386 1387
    key = ('default_activate_parameter', )
    return tv.get(key)

1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
  security.declareProtected(Permissions.ManagePortal, 'getERP5SiteGlobalId')
  def getERP5SiteGlobalId(self):
    """Returns site global ID without any fallback"""
    return getattr(self, 'erp5_site_global_id', None)

  security.declareProtected(Permissions.ManagePortal, 'setERP5SiteGlobalId')
  def setERP5SiteGlobalId(self, global_id):
    """Sets site global ID, only in case if not set yet
    
    Such id should be very big and random, for example uuid version 4, as
    defined in RFC 4122.
    """
    if self.getERP5SiteGlobalId() in [None, '']:
      self.erp5_site_global_id = global_id

1403 1404 1405 1406 1407 1408
  security.declareProtected(Permissions.ManagePortal, 'migrateToPortalTypeClass')
  def migrateToPortalTypeClass(self):
    """Compatibility code that allows migrating a site to portal type classes.
    
    We consider that a Site is migrated if its Types Tool is migrated
    (it will always be migrated last)"""
1409 1410 1411 1412 1413 1414
    types_tool = getattr(self, 'portal_types', None)
    if types_tool is None:
      # empty site
      return
    if types_tool.__class__.__module__ == 'erp5.portal_type':
      # nothing to do, already migrated
1415
      return
1416

1417 1418 1419
    # note that the site itself is not migrated (ERP5Site is not a portal type)
    # only the tools and top level modules are.
    # Normally, PersistentMigrationMixin should take care of the rest.
1420 1421
    id_list = self.objectIds()

1422
    # make sure that Types Tool is migrated last
1423 1424 1425 1426 1427 1428
    id_list.remove('portal_types')
    id_list.append('portal_types')
    for id in id_list:
      method = getattr(self[id], '_migrateToPortalTypeClass', None)
      if method is None:
        continue
1429
      method()
1430

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1431 1432
Globals.InitializeClass(ERP5Site)

1433 1434 1435 1436 1437 1438 1439
def getBootstrapDirectory():
  """
    Return the name of the bootstrap directory
  """
  product_path = package_home(globals())
  return os.path.join(product_path, 'bootstrap')

1440 1441 1442 1443 1444 1445 1446 1447
def getBootstrapBusinessTemplateUrl(bt_title):
  """
    Return the path to download the given bootstrap business template
  """
  path = os.path.join(getBootstrapDirectory(), bt_title)
  if not os.path.exists(path):
    path += '.bt5'
  return path
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541

# This PortalGenerator class was copied wholesale from CMF 1.5 which is
# identical to the one on 1.6, and hasn't been used by CMF itself since even
# 1.5, as they already used CMFSetup by then (later replaced by GenericSetup).


factory_type_information = () # No original CMF portal_types installed by default

class PortalGenerator:

    klass = CMFSite

    def setupTools(self, p):
        """Set up initial tools"""

        addCMFCoreTool = p.manage_addProduct['CMFCore'].manage_addTool
        addCMFCoreTool('CMF Actions Tool', None)
        addCMFCoreTool('CMF Catalog', None)
        addCMFCoreTool('CMF Member Data Tool', None)
        addCMFCoreTool('CMF Skins Tool', None)
        addCMFCoreTool('CMF Types Tool', None)
        addCMFCoreTool('CMF Undo Tool', None)
        addCMFCoreTool('CMF URL Tool', None)
        addCMFCoreTool('CMF Workflow Tool', None)

        addCMFDefaultTool = p.manage_addProduct['CMFDefault'].manage_addTool
        addCMFDefaultTool('Default Discussion Tool', None)
        addCMFDefaultTool('Default Membership Tool', None)
        addCMFDefaultTool('Default Registration Tool', None)
        addCMFDefaultTool('Default Properties Tool', None)
        addCMFDefaultTool('Default Metadata Tool', None)
        addCMFDefaultTool('Default Syndication Tool', None)

        # try to install CMFUid without raising exceptions if not available
        try:
            addCMFUidTool = p.manage_addProduct['CMFUid'].manage_addTool
        except AttributeError:
            pass
        else:
            addCMFUidTool('Unique Id Annotation Tool', None)
            addCMFUidTool('Unique Id Generator Tool', None)
            addCMFUidTool('Unique Id Handler Tool', None)

    def setupMailHost(self, p):
        p.manage_addProduct['MailHost'].manage_addMailHost(
            'MailHost', smtp_host='localhost')

    def setupUserFolder(self, p):
        p.manage_addProduct['OFSP'].manage_addUserFolder()

    def setupCookieAuth(self, p):
        p.manage_addProduct['CMFCore'].manage_addCC(
            id='cookie_authentication')

    def setupRoles(self, p):
        # Set up the suggested roles.
        p.__ac_roles__ = ('Member', 'Reviewer',)

    def setupMimetypes(self, p):
        p.manage_addProduct[ 'CMFCore' ].manage_addRegistry()
        reg = p.content_type_registry

        reg.addPredicate( 'link', 'extension' )
        reg.getPredicate( 'link' ).edit( extensions="url, link" )
        reg.assignTypeName( 'link', 'Link' )

        reg.addPredicate( 'news', 'extension' )
        reg.getPredicate( 'news' ).edit( extensions="news" )
        reg.assignTypeName( 'news', 'News Item' )

        reg.addPredicate( 'document', 'major_minor' )
        reg.getPredicate( 'document' ).edit( major="text", minor="" )
        reg.assignTypeName( 'document', 'Document' )

        reg.addPredicate( 'image', 'major_minor' )
        reg.getPredicate( 'image' ).edit( major="image", minor="" )
        reg.assignTypeName( 'image', 'Image' )

        reg.addPredicate( 'file', 'major_minor' )
        reg.getPredicate( 'file' ).edit( major="application", minor="" )
        reg.assignTypeName( 'file', 'File' )

    def setupDefaultProperties(self, p, title, description,
                               email_from_address, email_from_name,
                               validate_email, default_charset=''):
        p._setProperty('email_from_address', email_from_address, 'string')
        p._setProperty('email_from_name', email_from_name, 'string')
        p._setProperty('validate_email', validate_email and 1 or 0, 'boolean')
        p._setProperty('default_charset', default_charset, 'string')
        p._setProperty('enable_permalink', 0, 'boolean')
        p.title = title
        p.description = description


Jean-Paul Smets's avatar
Jean-Paul Smets committed
1542 1543
class ERP5Generator(PortalGenerator):

1544
  klass = ERP5Site
1545

1546 1547 1548
  def create(self,
             parent,
             id,
1549
             create_userfolder,
1550
             erp5_catalog_storage,
1551
             erp5_sql_connection_type,
1552
             erp5_sql_connection_string,
1553
             erp5_sql_deferred_connection_type,
1554 1555
             cmf_activity_sql_connection_type,
             cmf_activity_sql_connection_string,
1556
             create_activities=True,
1557 1558
             reindex=1,
             **kw):
1559 1560
    id = str(id)
    portal = self.klass(id=id)
1561 1562
    # Make sure reindex will not be called until business templates
    # will be installed
1563
    setattr(portal, 'isIndexable', ConstantGetter('isIndexable', value=False))
1564 1565 1566
    parent._setObject(id, portal)
    # Return the fully wrapped object.
    p = parent.this()._getOb(id)
1567 1568

    erp5_sql_deferred_connection_string = erp5_sql_connection_string
1569 1570
    p._setProperty('erp5_catalog_storage',
                   erp5_catalog_storage, 'string')
1571
    p._setProperty('erp5_sql_connection_type',
1572
                   erp5_sql_connection_type, 'string')
1573
    p._setProperty('erp5_sql_connection_string',
1574
                   erp5_sql_connection_string, 'string')
1575
    p._setProperty('erp5_sql_deferred_connection_type',
1576
                   erp5_sql_deferred_connection_type, 'string')
1577
    p._setProperty('erp5_sql_deferred_connection_string',
1578
                   erp5_sql_deferred_connection_string, 'string')
1579
    p._setProperty('cmf_activity_sql_connection_type',
1580
                   cmf_activity_sql_connection_type, 'string')
1581
    p._setProperty('cmf_activity_sql_connection_string',
1582
                   cmf_activity_sql_connection_string, 'string')
1583
    p._setProperty('management_page_charset', 'UTF-8', 'string')
1584 1585
    self.setup(p, create_userfolder, create_activities=create_activities,
        reindex=reindex, **kw)
1586 1587
    return p

1588
  def setupLastTools(self, p, create_activities=True, **kw):
1589
    """
1590 1591 1592
    Set up finals tools
    We want to set the activity tool only at the end to
    make sure that we do not put un the queue the full reindexation
1593 1594
    """
    # Add Activity Tool
1595 1596 1597
    if create_activities and not p.hasObject('portal_activities'):
      addTool = p.manage_addProduct['CMFActivity'].manage_addTool
      addTool('CMF Activity Tool', None) # Allow user to select active/passive
1598
      # Initialize Activities
1599
      p.portal_activities.manageClearActivities(keep=0)
1600

1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
    # Add several other tools, only at the end in order
    # to make sure that they will be reindexed
    addTool = p.manage_addProduct['ERP5'].manage_addTool
    if not p.hasObject('portal_rules'):
      addTool('ERP5 Rule Tool', None)
    if not p.hasObject('portal_simulation'):
      addTool('ERP5 Simulation Tool', None)
    if not p.hasObject('portal_deliveries'):
      addTool('ERP5 Delivery Tool', None)
    if not p.hasObject('portal_orders'):
      addTool('ERP5 Order Tool', None)


1614 1615
  def setupTemplateTool(self, p, **kw):
    """
1616
    Setup the Template Tool. Security must be set strictly.
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    """
    addTool = p.manage_addProduct['ERP5'].manage_addTool
    addTool('ERP5 Template Tool', None)
    context = p.portal_templates
    permission_list = context.possible_permissions()
    for permission in permission_list:
      context.manage_permission(permission, ['Manager'], 0)

  def setupTools(self, p,**kw):
    """
1627
    Set up initial tools.
1628 1629 1630
    """
    if not 'portal_actions' in p.objectIds():
      PortalGenerator.setupTools(self, p)
1631
      p._delObject('portal_types')
1632

1633
    # It is better to remove portal_catalog
1634
    # which is ZCatalog as soon as possible,
1635
    # because the API is not the completely same as ERP5Catalog,
1636
    # and ZCatalog is useless for ERP5 after all.
1637 1638
    update = kw.get('update', 0)
    portal_catalog = getToolByName(p, 'portal_catalog', None)
1639 1640 1641
    if portal_catalog is not None and \
       portal_catalog.meta_type != 'ZSQLCatalog' and \
       not update:
1642 1643 1644 1645
      p._delObject('portal_catalog')

    # Add CMF Report Tool
    if not p.hasObject('portal_report'):
1646 1647 1648 1649 1650
      try:
        addTool = p.manage_addProduct['CMFReportTool'].manage_addTool
        addTool('CMF Report Tool', None)
      except AttributeError:
        pass
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665

    # Add ERP5 Tools
    addTool = p.manage_addProduct['ERP5'].manage_addTool
    if not p.hasObject('portal_categories'):
      addTool('ERP5 Categories', None)
    if not p.hasObject('portal_ids'):
      addTool('ERP5 Id Tool', None)
    if not p.hasObject('portal_templates'):
      self.setupTemplateTool(p)
    if not p.hasObject('portal_trash'):
      addTool('ERP5 Trash Tool', None)
    if not p.hasObject('portal_alarms'):
      addTool('ERP5 Alarm Tool', None)
    if not p.hasObject('portal_domains'):
      addTool('ERP5 Domain Tool', None)
1666 1667
    if not p.hasObject('portal_tests'):
      addTool('ERP5 Test Tool', None)
1668 1669
    if not p.hasObject('portal_password'):
      addTool('ERP5 Password Tool', None)
1670 1671
    if not p.hasObject('portal_acknowledgements'):
      addTool('ERP5 Acknowledgement Tool', None)
Aurel's avatar
Aurel committed
1672

1673 1674
    # Add ERP5Type Tool
    addTool = p.manage_addProduct['ERP5Type'].manage_addTool
1675 1676
    if not p.hasObject('portal_caches'):
      addTool('ERP5 Cache Tool', None)
1677 1678
    if not p.hasObject('portal_memcached'):
      addTool('ERP5 Memcached Tool', None)
1679 1680
    if not p.hasObject('portal_types'):
      addTool('ERP5 Types Tool', None)
1681 1682
    if not p.hasObject('portal_property_sheets'):
      addTool('ERP5 Property Sheet Tool', None)
1683

1684 1685 1686 1687 1688 1689
    try:
      addTool = p.manage_addProduct['ERP5Subversion'].manage_addTool
      if not p.hasObject('portal_subversion'):
        addTool('ERP5 Subversion Tool', None)
    except AttributeError:
      pass
1690

1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    # Add ERP5Type Tools
    addTool = p.manage_addProduct['ERP5Type'].manage_addTool
    if not p.hasObject('portal_classes'):
      if allowClassTool():
        addTool('ERP5 Class Tool', None)
      else:
        addTool('ERP5 Dummy Class Tool', None)

    # Add ERP5 SQL Catalog Tool
    addTool = p.manage_addProduct['ERP5Catalog'].manage_addTool
    if not p.hasObject('portal_catalog'):
      addTool('ERP5 Catalog', None)
Aurel's avatar
Aurel committed
1703

1704 1705 1706
    # Add Default SQL connection
    if p.erp5_sql_connection_type == 'Z MySQL Database Connection':
      if not p.hasObject('erp5_sql_connection'):
1707 1708
        addSQLConnection = p.manage_addProduct['ZMySQLDA'].\
                                     manage_addZMySQLConnection
1709 1710
        addSQLConnection('erp5_sql_connection',
                         'ERP5 SQL Server Connection',
1711
                         p.erp5_sql_connection_string)
1712 1713
    elif p.erp5_sql_connection_type == 'Z Gadfly':
      pass
1714 1715

    # Add Deferred SQL Connections
1716 1717
    if p.erp5_sql_deferred_connection_type == \
        'Z MySQL Deferred Database Connection':
1718
      if not p.hasObject('erp5_sql_deferred_connection'):
1719 1720
        addSQLConnection = p.manage_addProduct['ZMySQLDDA'].\
            manage_addZMySQLDeferredConnection
1721 1722
        addSQLConnection('erp5_sql_deferred_connection',
                         'ERP5 SQL Server Deferred Connection',
1723
                         p.erp5_sql_deferred_connection_string)
1724 1725 1726 1727
    elif p.erp5_sql_deferred_connection_type == 'Z Gadfly':
      pass

    # Add Activity SQL Connections
1728 1729
    if p.cmf_activity_sql_connection_type == 'Z MySQL Database Connection':
      if not p.hasObject('cmf_activity_sql_connection'):
1730 1731
        addSQLConnection = p.manage_addProduct['ZMySQLDA'].\
                                     manage_addZMySQLConnection
1732 1733
        addSQLConnection('cmf_activity_sql_connection',
                         'CMF Activity SQL Server Connection',
1734
                         p.cmf_activity_sql_connection_string)
1735 1736 1737 1738 1739
      # Warning : This transactionless connection is created with
      # the activity connection string and not the catalog's because
      # it's not compatible with the hot reindexing feature.
      # Though, it has nothing to do with activities.
      # The only difference compared to activity connection is the
Vincent Pelletier's avatar
Vincent Pelletier committed
1740
      # minus prepended to the connection string.
1741 1742 1743 1744 1745
      if not p.hasObject('erp5_sql_transactionless_connection'):
        addSQLConnection = p.manage_addProduct['ZMySQLDA'].\
                                     manage_addZMySQLConnection
        addSQLConnection('erp5_sql_transactionless_connection',
                         'ERP5 Transactionless SQL Server Connection',
Vincent Pelletier's avatar
Typo.  
Vincent Pelletier committed
1746
                         '-%s' % p.cmf_activity_sql_connection_string)
1747 1748
    elif p.cmf_activity_sql_connection_type == 'Z Gadfly':
      pass
1749

1750 1751 1752 1753 1754 1755 1756
    # Add ERP5Form Tools
    addTool = p.manage_addProduct['ERP5Form'].manage_addTool
    if not p.hasObject('portal_selections'):
      addTool('ERP5 Selections', None)
    if not p.hasObject('portal_preferences'):
      addTool('ERP5 Preference Tool', None)

1757 1758 1759 1760 1761 1762 1763
    try:
      # Add ERP5SyncML Tools
      addTool = p.manage_addProduct['ERP5SyncML'].manage_addTool
      if not p.hasObject('portal_synchronizations'):
        addTool('ERP5 Synchronizations', None)
    except AttributeError:
      pass
1764 1765 1766 1767 1768 1769

    # Add Message Catalog
    if not 'Localizer' in p.objectIds():
      addLocalizer = p.manage_addProduct['Localizer'].manage_addLocalizer
      addLocalizer('', ('en',))
    localizer = getToolByName(p, 'Localizer')
1770 1771
    addMessageCatalog = localizer.manage_addProduct['Localizer']\
                                      .manage_addMessageCatalog
1772 1773 1774
    if 'erp5_ui' not in localizer.objectIds():
      if 'default' in localizer.objectIds():
        localizer.manage_delObjects('default')
1775 1776 1777
      addMessageCatalog('default', 'ERP5 Localized Messages', ('en',))
      addMessageCatalog('erp5_ui', 'ERP5 Localized Interface', ('en',))
      addMessageCatalog('erp5_content', 'ERP5 Localized Content', ('en',))
1778

1779 1780 1781
    # Add an error_log
    if 'error_log' not in p.objectIds():
      manage_addErrorLog(p)
1782 1783 1784 1785
      p.error_log.setProperties(keep_entries=20,
                                copy_to_zlog=True,
                                ignored_exceptions=('NotFound', 'Redirect'))

1786 1787 1788

    # Remove unused default actions
    def removeActionsFromTool(tool, remove_list):
1789 1790 1791 1792 1793 1794 1795
      try:
        from Products.CMFCore.interfaces import IActionProvider
        if not IActionProvider.providedBy(tool):
          # On CMF 2.x, some tools (portal_membership)
          # are no longer action providers
          return
      except ImportError:
1796 1797
        # BACK: Currently ERP5 tests don't load ZCML which is needed by the
        # above import on CMF 1.5. This "try" should be removed when ERP5 tests
1798
        # start loading ZCML. 
1799
        pass
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
      action_id_list = [i.id for i in tool.listActions()]
      remove_index_list = []
      for i in remove_list:
        if i in action_id_list:
          remove_index_list.append(action_id_list.index(i))
      if remove_index_list:
        tool.deleteActions(remove_index_list)
    # membership tool
    removeActionsFromTool(p.portal_membership,
                          ('addFavorite', 'mystuff', 'favorites', 'logged_in',
                           'manage_members'))
    # actions tool
    removeActionsFromTool(p.portal_actions, ('folderContents',))
1813 1814
    # properties tool
    removeActionsFromTool(p.portal_properties, ('configPortal',))
1815 1816 1817 1818
    # remove unused action providers
    for i in ('portal_registration', 'portal_discussion', 'portal_syndication'):
      p.portal_actions.deleteActionProvider(i)

1819 1820
  def setupMembersFolder(self, p):
    """
1821
    ERP5 is not a CMS
1822 1823 1824
    """
    pass

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
  # this lists only the skin layers of Products.CMFDefault we are actually
  # interested in.
  CMFDEFAULT_FOLDER_LIST = [ 'zpt_content'
                           , 'zpt_generic'
                           , 'zpt_control'
                           , 'Images'
                           ]
  def addCMFDefaultDirectoryViews(self, p):
    """Semi-manually create DirectoryViews since CMFDefault 2.X no longer
    registers the "skins" directory, only its subdirectories, making it
    unusable with Products.CMFCore.DirectoryView.addDirectoryViews."""
    from Products.CMFCore.DirectoryView import createDirectoryView
    try:
      from Products.CMFCore.DirectoryView import _generateKey
1839 1840
      def generateKey(package, subdir):
        return _generateKey(package.__name__, subdir)
1841
    except ImportError:
1842 1843 1844
      # Means we're still on CMF 1.x, were they generate the DirectoryView
      # key using minimalpath
      # ( see Products.CMFCore.DirectoryView.addDirectoryViews() )
1845
      from Products.CMFCore.DirectoryView import minimalpath
1846
      def generateKey(package, subdir):
1847 1848 1849 1850 1851 1852 1853
        package_path = os.path.dirname(package.__file__)
        return minimalpath(os.path.join(package_path, subdir))
    import Products.CMFDefault

    ps = getToolByName(p, 'portal_skins')
    # get the layer directories actually present
    for cmfdefault_skin_layer in self.CMFDEFAULT_FOLDER_LIST:
1854 1855
      reg_key = generateKey(Products.CMFDefault,
                            'skins/' + cmfdefault_skin_layer)
1856 1857
      createDirectoryView(ps, reg_key)

1858 1859 1860 1861
  def setupDefaultSkins(self, p):
    from Products.CMFCore.DirectoryView import addDirectoryViews
    from Products.CMFActivity import cmfactivity_globals
    ps = getToolByName(p, 'portal_skins')
1862
    self.addCMFDefaultDirectoryViews(p)
1863 1864 1865
    addDirectoryViews(ps, 'skins', cmfactivity_globals)
    ps.manage_addProduct['OFSP'].manage_addFolder(id='external_method')
    ps.manage_addProduct['OFSP'].manage_addFolder(id='custom')
1866
    # Set the 'custom' layer a high priority, so it remains the first
1867 1868 1869 1870 1871
    #   layer when installing new business templates.
    ps['custom'].manage_addProperty("business_template_skin_layer_priority", 100.0, "float")
    skin_folder_list = [ 'custom'
                       , 'external_method'
                       , 'activity'
1872
                       ] + self.CMFDEFAULT_FOLDER_LIST
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
    skin_folders = ', '.join(skin_folder_list)
    ps.addSkinSelection( 'View'
                       , skin_folders
                       , make_default = 1
                       )
    ps.addSkinSelection( 'Print'
                       , skin_folders
                       , make_default = 0
                       )
    ps.addSkinSelection( 'CSV'
                       , skin_folders
                       , make_default = 0
                       )
1886 1887 1888 1889
    p.setupCurrentSkin()

  def setupWorkflow(self, p):
    """
1890
    Set up workflows for business templates
1891 1892 1893
    """
    tool = getToolByName(p, 'portal_workflow', None)
    if tool is None:
Jérome Perrin's avatar
Jérome Perrin committed
1894
      return
1895
    for wf_id in ('business_template_building_workflow',
1896
                  'business_template_installation_workflow'):
1897 1898
      if wf_id in tool.objectIds():
        tool.manage_delObjects([wf_id])
1899
    bootstrap_dir = getBootstrapDirectory()
1900 1901 1902
    business_template_building_workflow = os.path.join(
                                 bootstrap_dir,
                                 'business_template_building_workflow.xml')
1903
    tool._importObjectFromFile(business_template_building_workflow)
1904 1905 1906
    business_template_installation_workflow = os.path.join(
                                 bootstrap_dir,
                                 'business_template_installation_workflow.xml')
1907 1908
    tool._importObjectFromFile(business_template_installation_workflow)
    tool.setChainForPortalTypes( ( 'Business Template', ),
1909 1910
                                 ( 'business_template_building_workflow',
                                   'business_template_installation_workflow' ) )
1911 1912 1913

  def setupIndex(self, p, **kw):
    # Make sure all tools and folders have been indexed
1914
    if not kw.get('reindex', 1):
1915 1916 1917 1918
      return
    skins_tool = getToolByName(p, 'portal_skins', None)
    if skins_tool is None:
      return
1919
    # When no SQL connection was define on the site,
1920 1921
    # we don't want to make it crash
    if p.erp5_sql_connection_type is not None:
1922
      setattr(p, 'isIndexable', ConstantGetter('isIndexable', value=True))
1923 1924
      # Clear portal ids sql table, like this we do not take
      # ids for a previously created web site
Sebastien Robin's avatar
Sebastien Robin committed
1925
      p.portal_ids.clearGenerator(all=True)
1926
      # Then clear the catalog and reindex it
1927
      p.portal_catalog.manage_catalogClear()
1928
      # Calling ERP5Site_reindexAll is useless.
1929

1930 1931 1932
  def setupUserFolder(self, p):
      # Use Pluggable Auth Service instead of the standard acl_users.
      p.manage_addProduct['PluggableAuthService'].addPluggableAuthService()
1933
      pas_dispatcher = p.acl_users.manage_addProduct['PluggableAuthService']
1934
      # Add legacy ZODB support
1935 1936 1937
      pas_dispatcher.addZODBUserManager('zodb_users')
      pas_dispatcher.addZODBGroupManager('zodb_groups')
      pas_dispatcher.addZODBRoleManager('zodb_roles')
1938 1939 1940 1941
      # Add CMF Portal Roles
      p.acl_users.zodb_roles.addRole('Member')
      p.acl_users.zodb_roles.addRole('Reviewer')
      # Register ZODB Interface
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
      p.acl_users.zodb_users.manage_activateInterfaces(
                                       ('IAuthenticationPlugin',
                                        'IUserEnumerationPlugin',
                                        'IUserAdderPlugin'))
      p.acl_users.zodb_groups.manage_activateInterfaces(
                                       ('IGroupsPlugin',
                                       'IGroupEnumerationPlugin'))
      p.acl_users.zodb_roles.manage_activateInterfaces(
                                       ('IRoleEnumerationPlugin',
                                        'IRolesPlugin',
                                        'IRoleAssignerPlugin'))
1953
      # Add ERP5UserManager
1954 1955 1956 1957 1958
      erp5security_dispatcher = p.acl_users.manage_addProduct['ERP5Security']
      erp5security_dispatcher.addERP5UserManager('erp5_users')
      erp5security_dispatcher.addERP5GroupManager('erp5_groups')
      erp5security_dispatcher.addERP5RoleManager('erp5_roles')
      erp5security_dispatcher.addERP5UserFactory('erp5_user_factory')
1959
      # Register ERP5UserManager Interface
1960 1961 1962
      p.acl_users.erp5_users.manage_activateInterfaces(
                                        ('IAuthenticationPlugin',
                                        'IUserEnumerationPlugin',))
1963 1964
      p.acl_users.erp5_groups.manage_activateInterfaces(('IGroupsPlugin',))
      p.acl_users.erp5_roles.manage_activateInterfaces(('IRolesPlugin',))
1965 1966
      p.acl_users.erp5_user_factory.manage_activateInterfaces(
                                        ('IUserFactoryPlugin',))
1967 1968 1969 1970 1971 1972 1973 1974

  def setupPermissions(self, p):
    permission_dict = {
      'Access Transient Objects'     : ('Manager', 'Anonymous'),
      'Access contents information'  : ('Manager', 'Member', 'Anonymous'),
      'Access future portal content' : ('Manager', 'Reviewer'),
      'Access session data'          : ('Manager', 'Anonymous'),
      'AccessContentsInformation'    : ('Manager', 'Member'),
1975
      'Change local roles'           : ('Manager', ),
1976 1977 1978 1979 1980 1981
      'Add portal content'           : ('Manager', 'Owner'),
      'Add portal folders'           : ('Manager', 'Owner'),
      'Delete objects'               : ('Manager', 'Owner'),
      'FTP access'                   : ('Manager', 'Owner'),
      'List folder contents'         : ('Manager', 'Member'),
      'List portal members'          : ('Manager', 'Member'),
1982
      'List undoable changes'        : ('Manager', ),
1983 1984 1985 1986 1987
      'Manage properties'            : ('Manager', 'Owner'),
      'Modify portal content'        : ('Manager', 'Owner'),
      'Reply to item'                : ('Manager', 'Member'),
      'Review portal content'        : ('Manager', 'Reviewer'),
      'Search ZCatalog'              : ('Manager', 'Member'),
1988
      'Set own password'             : ('Manager', ),
1989
      'Set own properties'           : ('Manager', 'Member'),
1990
      'Use mailhost services'        : ('Manager', 'Member'),
1991
      'Undo changes'                 : ('Manager', 'Owner'),
1992
      'View'                         : ('Manager', 'Member',
1993
                                        'Owner', 'Anonymous'),
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
      'View management screens'      : ('Manager', 'Owner')
    }

    for permission in p.ac_inherited_permissions(1):
      name = permission[0]
      role_list = permission_dict.get(name, ('Manager',))
      p.manage_permission(name, roles=role_list, acquire=0)

  def setup(self, p, create_userfolder, **kw):
    update = kw.get('update', 0)

2005 2006 2007
    if getattr(p, 'setDefaultSorting', None) is not None:
      p.setDefaultSorting('id', 0)

2008 2009 2010 2011 2012
    self.setupTools(p, **kw)

    if not p.hasObject('MailHost'):
      self.setupMailHost(p)

Jérome Perrin's avatar
Jérome Perrin committed
2013 2014
    if create_userfolder and not p.hasObject('acl_users'):
      self.setupUserFolder(p)
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026

    if not p.hasObject('cookie_authentication'):
      self.setupCookieAuth(p)

    if 'Member' not in getattr(p, '__ac_roles__', ()):
      self.setupRoles(p)
    if not update:
      self.setupPermissions(p)
      self.setupDefaultSkins(p)

    # ERP5 Design Choice is that all content should be user defined
    # Content is disseminated through business templates
2027
    self.setupPortalTypes(p)
2028 2029 2030 2031 2032 2033 2034 2035 2036

    if not p.hasObject('content_type_registry'):
      self.setupMimetypes(p)
    if not update:
      self.setupWorkflow(p)

    if not update:
      self.setupERP5Core(p,**kw)

2037 2038 2039
    # Make sure the cache is initialized
    p.portal_caches.updateCache()

2040 2041
    self.setupLastTools(p, **kw)

2042 2043 2044 2045 2046
    # Make sure tools are cleanly indexed with a uid before creating children
    # XXX for some strange reason, member was indexed 5 times
    if not update:
      self.setupIndex(p, **kw)

2047
  def setupPortalTypes(self, p):
2048
    """
2049
    Install the portal_type of Business Template
2050 2051 2052 2053
    """
    tool = getToolByName(p, 'portal_types', None)
    if tool is None:
      return
2054
    for t in (BusinessTemplate, ):
2055 2056
      t = t.factory_type_information
      if not tool.hasObject(t['id']):
2057
        tool._setObject(t['id'], ERP5TypeInformation(uid=None, **t))
2058

2059
  def setupERP5Core(self,p,**kw):
2060
    """
2061
    Install the core part of ERP5
2062 2063 2064 2065 2066
    """
    template_tool = getToolByName(p, 'portal_templates', None)
    if template_tool is None:
      return
    if template_tool.getInstalledBusinessTemplate('erp5_core') is None:
2067
      for bt in ('erp5_core', p.erp5_catalog_storage, 'erp5_xhtml_style'):
2068 2069
        if not bt:
          continue
2070 2071 2072
        url = getBootstrapBusinessTemplateUrl(bt)
        bt = template_tool.download(url)
        bt.install(**kw)