ERP5Site.py 83.9 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
from Products.ERP5Type import Permissions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
30
from Products.ERP5Type.Core.Folder import FolderMixIn
31
from Acquisition import aq_base
32
from Products.ERP5Type import allowClassTool
33 34
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
from Products.ERP5Type.Cache import caching_instance_method
35
from Products.ERP5Type.Cache import CachingMethod, CacheCookieMixin
36
from Products.ERP5Type.ERP5Type import ERP5TypeInformation
37
from Products.ERP5Type.Log import log as unrestrictedLog
38
from Products.CMFActivity.Errors import ActivityPendingError
39
import ERP5Defaults
40
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Nicolas Dumazet's avatar
Nicolas Dumazet committed
41
from Products.ERP5Type.dynamic.portal_type_class import synchronizeDynamicModules
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42

43
from zLOG import LOG, INFO, WARNING, ERROR
Sebastien Robin's avatar
Sebastien Robin committed
44
from string import join
45
import os
46
import warnings
47
from App.config import getConfiguration
48 49
MARKER = []

50

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

108 109 110 111 112 113 114 115 116 117
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
118
    if item.endswith('.bt5') and os.path.isfile(item):
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
      # 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
140

141 142 143 144 145 146 147 148
def addERP5Tool(portal, id, portal_type):
  if portal.hasObject(id):
    return
  import erp5.portal_type
  klass = getattr(erp5.portal_type, portal_type)
  obj = klass()
  portal._setObject(id, obj)

149 150 151 152 153 154 155 156 157 158 159 160 161 162
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()
163

164 165 166 167 168 169 170
    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
171

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    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()

191 192 193 194 195 196 197 198 199 200

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

201
  def __get(self, REQUEST=None):
202
    """Returns the currently processed site, optionally wrapped in a request
203
    """
204 205 206
    while True:
      app, site_id = self.site[-1]
      app = app()
207
      if app._p_jar.opened:
208 209 210 211
        if REQUEST is None:
          return getattr(app, site_id)
        return getattr(app.__of__(RequestContainer(REQUEST=REQUEST)), site_id)
      del self.site[-1]
212 213 214 215 216 217 218 219 220 221 222 223 224 225

  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()


226
class ERP5Site(FolderMixIn, CMFSite, CacheCookieMixin):
227
  """
228 229
  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.
230
  """
231
  meta_type = 'ERP5 Site'
232
  portal_type = 'ERP5 Site'
233
  constructors = (('addERP5Site', manage_addERP5SiteForm), manage_addERP5Site, )
234 235 236
  uid = 0
  last_id = 0
  icon = 'portal.gif'
237 238
  # Default value, prevents error during upgrade
  isIndexable = ConstantGetter('isIndexable', value=True)
239 240

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

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

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  def _createInitialSiteManager(self):
    # This section of code is inspired by
    # Products.CMFDefault.upgrade.to21.upgrade_root_site_manager(),
    # specificallythe 'except ComponentLookupError:' clause, and also
    # by Products.CMFDefault.PortalObjectBase.__init__
    from zope.component.globalregistry import base
    from five.localsitemanager import (PersistentComponents,
                                       find_next_sitemanager)
    next = find_next_sitemanager(self)
    if next is None:
      next = base
    name = '++etc++site'
    sm = PersistentComponents(name, (next,))
    sm.__parent__ = aq_base(self)
    self.setSiteManager(sm)
    LOG('ERP5Site', 0, "Site manager '%s' added." % name)

  def _doTranslationDomainRegistration(self):
    from zope.i18n.interfaces import ITranslationDomain
272
    from Products.Localizer.MessageCatalog import (
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
      message_catalog_alias_sources
    )
    sm = self.getSiteManager()
    for message_catalog in self.Localizer.objectValues():
      sm.registerUtility(message_catalog,
                         provided=ITranslationDomain,
                         name=message_catalog.getId())
      for alias in message_catalog_alias_sources.get(message_catalog.getId()):
        sm.registerUtility(message_catalog,
                           provided=ITranslationDomain,
                           name=alias)

  def _doInitialSiteManagerMigration(self):
    self._createInitialSiteManager()
    # Now that we have a sitemanager, se can do things that require
    # one. Including setting up ZTK style utilities and adapters. We
    # can even call setSite(self), as long as we roll back that later,
    # since we are actually in the middle of a setSite() call.
    from zope.site.hooks import getSite, setSite
    old_site = getSite()
    try:
      setSite(self)
      # setSite(self) is not really necessary for the migration below, but
      # could be needed by other migrations to be added here.
      self._doTranslationDomainRegistration()
    finally:
      setSite(old_site)

  # backward compatibility auto-migration
  def getSiteManager(self):
    # NOTE: do not add a docstring! This method is private by virtue of
    # not having it.

    # XXX-Leo: Consider moving this method and all methods that it calls
    # into a monkeypatch of an optional product. This product could have
    # its own tests for migration without actually cluttering the original
    # source code and would only need to be installed in sites needing
    # migration from Zope 2.8

    # This code is an alteration of
    # OFS.ObjectManager.ObjectManager.getSiteManager(), and is exactly
    # as cheap as it is on the case that self._components is already
    # set.
    _components = self._components
    if _components is not None:
      return _components
    # This method below can take as (reasonably) long as it pleases
    # since it will not be run ever again
    self._doInitialSiteManagerMigration()
    assert self._components is not None, 'Migration Failed!'
    return self._components

325 326
  security.declareProtected(Permissions.View, 'view')
  def view(self):
327 328 329 330 331
    """
      Returns the default view.
      Implemented for consistency
    """
    return self.index_html()
332

333 334 335 336 337
  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()
338 339 340
    # 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:
341 342
      tv['ERP5Site.__of__'] = None
      setSite(self)
343 344

      try:
345
        component_tool = self.portal_components
346
      except AttributeError:
347 348 349 350 351
        # This should only happen before erp5_core is installed
        synchronizeDynamicModules(self)
      else:
        # If Components are reset, then portal type classes should be reset
        synchronizeDynamicModules(self, component_tool.reset())
352

353 354
    return self

355
  def manage_beforeDelete(self, item, container):
356
    # skin is setup during __before_publishing_traverse__, which
357 358 359 360 361 362 363 364
    # 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)

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
  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:
381
        portal_activities = self.portal_activities
382
      except AttributeError:
383 384
        pass
      else:
385 386 387 388 389 390 391 392 393 394 395 396 397 398
        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)

399

400 401 402 403 404 405 406
  def _getAcquireLocalRoles(self):
    """
      Prevent local roles from being acquired outside of Portal object.
      See ERP5Security/__init__.py:mergedLocalRoles .
    """
    return False

407 408 409 410 411 412 413
  security.declareProtected(Permissions.ManagePortal, 'enableRefererCheck')
  def enableRefererCheck(self):
    """Enable a ReferCheckerBeforeTraverseHook to check users have valid
    HTTP_REFERER
    """
    BeforeTraverse.registerBeforeTraverse(self,
                                        ReferCheckerBeforeTraverseHook(),
414 415 416
                                        ReferCheckerBeforeTraverseHook.handle,
                             # we want to be registered _after_ CookieCrumbler
                                        100)
417

418 419 420 421
  def _disableRefererCheck(self):
    """Disable the HTTP_REFERER check."""
    BeforeTraverse.unregisterBeforeTraverse(self,
                                        ReferCheckerBeforeTraverseHook.handle)
422

423
  def hasObject(self, id):
424
    """
425
    Check if the portal has an id.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
426
    """
427
    return id in self.objectIds()
428

429
  security.declareProtected(Permissions.AccessContentsInformation,
430
                            'getPortalObject')
431 432
  def getPortalObject(self):
    return self
Jean-Paul Smets's avatar
Jean-Paul Smets committed
433

434 435 436 437 438
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalType')
  def getPortalType(self):
    return self.portal_type

439
  security.declareProtected(Permissions.AccessContentsInformation,
440
                            'getTitle')
441 442 443 444 445
  def getTitle(self):
    """
      Return the title.
    """
    return self.title
446

447
  security.declareProtected(Permissions.AccessContentsInformation,
448 449
                            'getVersionPriorityList')
  def getVersionPriorityList(self):
Arnaud Fontaine's avatar
Arnaud Fontaine committed
450
    """
451
    Return the Component version priorities defined on the site in descending
452
    order. Whatever happens, erp5 version must always be returned otherwise it
453
    may render the site unusable when all Products will have been migrated
Arnaud Fontaine's avatar
Arnaud Fontaine committed
454
    """
455
    return getattr(self, '_version_priority_list', None) or ('erp5 | 0.0',)
456 457

  security.declareProtected(Permissions.ModifyPortalContent,
458
                            'setVersionPriorityList' )
459
  def setVersionPriorityList(self, version_priority_tuple):
460
    """
461 462 463
    Set Version Priority List and make sure that erp5 version is always
    defined whatever the given value is

464 465
    XXX-arnau: must be written through an interaction workflow when ERP5Site
               will become a real ERP5 object...
466
    """
467 468 469 470 471 472 473 474 475 476
    if not isinstance(version_priority_tuple, tuple):
      version_priority_tuple = tuple(version_priority_tuple)

    # erp5 version must always be present, thus add it at the end if it's not
    # already there
    for version_priority in version_priority_tuple:
      if version_priority.split('|')[0].strip() == 'erp5':
        break
    else:
      version_priority_tuple = version_priority_tuple + ('erp5 | 0.0',)
477

478
    self._version_priority_list = version_priority_tuple
479

480 481 482 483 484 485
    # Reset cached value of getVersionPriorityNameList() if present
    try:
      del self._v_version_priority_name_list
    except AttributeError:
      pass

486
    # Make sure that reset is not performed when creating a new site
487 488 489
    if not getattr(self, '_v_bootstrapping', False):
      self.portal_components.resetOnceAtTransactionBoundary()

490 491
  version_priority_list = property(getVersionPriorityList,
                                   setVersionPriorityList)
492

493 494
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getVersionPriorityNameList')
495
  def getVersionPriorityNameList(self):
496 497 498 499 500 501 502 503 504
    """
    Get only the version names ordered by priority and cache it as it is used
    very often in Component import hooks
    """
    if getattr(self, '_v_version_priority_name_list', None) is None:
      self._v_version_priority_name_list = \
          [name.split('|')[0].strip() for name in self.getVersionPriorityList()]

    return self._v_version_priority_name_list
505

506 507 508 509 510 511
  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
512

513 514 515
      WARNING : must be updates for circular references issues
    """
    return getattr(self, 'uid', 0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
516

517
  security.declareProtected(Permissions.AccessContentsInformation,
518
                            'getParentUid')
519 520 521 522 523
  def getParentUid(self):
    """
      A portal has no parent
    """
    return self.getUid()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
524

525 526 527 528
  # 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
529

530 531 532 533
  # 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
534

535 536
  security.declareProtected(Permissions.AccessContentsInformation, 'getUrl')
  def getUrl(self, REQUEST=None):
537 538 539 540
    """
      Returns the absolute path of an object
    """
    return join(self.getPhysicalPath(),'/')
Sebastien Robin's avatar
Sebastien Robin committed
541

542 543 544 545 546 547 548
  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)

549 550 551 552
  # Old name - for compatibility
  security.declareProtected(Permissions.AccessContentsInformation, 'getPath')
  getPath = getUrl

553 554 555 556 557 558
  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 []

559
  security.declareProtected(Permissions.AccessContentsInformation, 'searchFolder')
560 561 562 563 564 565 566
  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
567
    return self.portal_catalog.searchResults(**kw)
568 569 570 571 572 573 574 575 576

  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
577
    return self.portal_catalog.countResults(**kw)
578 579 580 581 582 583 584 585

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

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

588
    This should absolutely be rewritten by using clean
589
    concepts to separate worklists XXX
590 591 592 593 594 595
    """
    sorted_workflow_actions = {}
    sorted_global_actions = []
    other_global_actions = []
    for action in action_list:
      action['disabled'] = 0
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
596 597 598 599 600 601 602 603 604 605
      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)
606 607
      else:
        other_global_actions.append(action)
608
    for key in sorted(sorted_workflow_actions):
609 610 611 612 613 614
      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,
615 616 617
                             email_from_address, email_from_name,
                             validate_email
                             ):
618
    CMFSite.setupDefaultProperties(self, p, title, description,
619 620
                           email_from_address, email_from_name,
                           validate_email)
621

622 623 624
  # 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
625
  # to customize the settings for each portal site.
626 627
  def _getPortalConfiguration(self, id):
    """
628
    Get a portal-specific configuration.
629

630 631
    Current implementation is using properties in a portal object.
    If not found, try to get a default value for backward compatibility.
632

633 634
    This implementation can be improved by gathering information
    from appropriate places, such as portal_types, portal_categories
635
    and portal_workflow.
636 637 638
    """
    if self.hasProperty(id):
      return self.getProperty(id)
639

640 641
    # Fall back to the default.
    return getattr(ERP5Defaults, id, None)
642

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
  security.declareProtected(Permissions.ManagePortal, 'getPromiseParameter')
  def getPromiseParameter(self, section, option):
    """
    Read external promise parameters.

    The parameters should be provided by an external configuration file.
    Location of this configuration file is defined in the zope configuration
    file in a product_config named as the path of the ERP5 site.
    Example if the site id is erp5:
      <product-config /erp5>
        promise_path /tmp/promise.cfg
      </product-config>

    The promise configuration is a simple ConfigParser readable file (a list of
    section containing a list of string parameters.

    getPromiseParameter returns None if the parameter isn't found.
    """
    config = getConfiguration()
    if getattr(config, 'product_config', None) is not None:
      parameter_dict = config.product_config.get(self.getPath())
      if 'promise_path' in parameter_dict:
        promise_path = parameter_dict['promise_path']
        import ConfigParser
        configuration = ConfigParser.ConfigParser()
        configuration.read(promise_path)
        try:
          return configuration.get(section, option)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
          pass
    return None

675
  def _getPortalGroupedTypeList(self, group, enable_sort=True):
676
    """
677
    Return a list of portal types classified to a specific group.
678 679
    The result is sorted by language (using the user language
    as default)
680 681 682

    Enable_sort parameter was added in order to allows looking groups
    of portal type without sorting. This is better for performance
683 684 685
    """
    def getTypeList(group):
      type_list = []
Sebastien Robin's avatar
Sebastien Robin committed
686
      for pt in self.portal_types.listTypeInfo():
687 688
        if group in getattr(pt, 'group_list', ()):
          type_list.append(pt.getId())
689

690 691 692 693
      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
694 695
        translate = localizer_tool.translate
        type_list.sort(key=lambda x:translate('ui', x))
696 697
      return tuple(type_list)

698 699
    if enable_sort:
      # language should be cached in Transaction Cache if performance issue
700
      localizer_tool = self.Localizer
701 702 703
      language = localizer_tool.get_selected_language()
    else:
      localizer_tool = language = None
704

705
    getTypeList = CachingMethod(getTypeList,
706 707 708 709
                                id=(('_getPortalGroupedTypeList', language), group,
                                    enable_sort),
                                cache_factory='erp5_content_medium',
                                )
710 711 712

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

714 715 716 717 718 719 720 721 722
  @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))

723
  def _getPortalGroupedCategoryList(self, group):
724
    """
725
    Return a list of base categories classified to a specific group.
726 727 728 729 730 731 732 733
    """
    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)

734 735
    getCategoryList = CachingMethod(
                            getCategoryList,
736
                            id=('_getPortalGroupedCategoryList', group),
Aurel's avatar
Aurel committed
737
                            cache_factory='erp5_content_medium')
738 739 740
    return getCategoryList(group)

  def _getPortalGroupedStateList(self, group):
741
    """
742
    Return a list of workflow states classified to a specific group.
743 744 745 746 747 748 749 750 751 752
    """
    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())

753
    getStateList = CachingMethod(getStateList,
754
                                 id=('_getPortalGroupedStateList', group),
Aurel's avatar
Aurel committed
755
                                 cache_factory='erp5_content_medium')
756 757
    return getStateList(group)

758 759
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDefaultSectionCategory')
760 761
  def getPortalDefaultSectionCategory(self):
    """
762
    Return a default section category. This method is deprecated.
763 764 765 766
    """
    LOG('ERP5Site', 0, 'getPortalDefaultSectionCategory is deprecated;'+
        ' use portal_preferences.getPreferredSectionCategory instead.')
    section_category = self.portal_preferences.getPreferredSectionCategory()
767

768 769 770 771
    # XXX This is only for backward-compatibility.
    if not section_category:
      section_category = self._getPortalConfiguration(
                                'portal_default_section_category')
772

773
    return section_category
774

775 776 777 778 779 780
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalResourceTypeList')
  def getPortalResourceTypeList(self):
    """
      Return resource types.
    """
781 782 783
    return self._getPortalGroupedTypeList('resource') or \
           self._getPortalConfiguration('portal_resource_type_list')

784 785 786 787 788 789 790
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSubVariationTypeList')
  def getPortalSubVariationTypeList(self):
    """
      Return resource types.
    """
    return self._getPortalGroupedTypeList('sub_variation')
791

792 793 794 795 796 797 798
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSubVariationBaseCategoryList')
  def getPortalSubVariationBaseCategoryList(self):
    """
      Return variation base categories.
    """
    return self._getPortalGroupedCategoryList('sub_variation')
799

800 801 802 803 804 805
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalVariationTypeList')
  def getPortalVariationTypeList(self):
    """
      Return variation types.
    """
806 807 808
    return self._getPortalGroupedTypeList('variation') or \
           self._getPortalConfiguration('portal_variation_type_list')

809 810 811 812 813 814
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalNodeTypeList')
  def getPortalNodeTypeList(self):
    """
      Return node types.
    """
815 816 817
    return self._getPortalGroupedTypeList('node') or \
           self._getPortalConfiguration('portal_node_type_list')

818 819 820 821 822 823
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPaymentNodeTypeList')
  def getPortalPaymentNodeTypeList(self):
    """
      Return payment node types.
    """
824 825 826
    return self._getPortalGroupedTypeList('payment_node') or \
           self._getPortalConfiguration('portal_payment_node_type_list')

827 828 829 830 831 832
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInvoiceTypeList')
  def getPortalInvoiceTypeList(self):
    """
      Return invoice types.
    """
833 834 835
    return self._getPortalGroupedTypeList('invoice') or \
           self._getPortalConfiguration('portal_invoice_type_list')

836 837 838 839 840 841
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOrderTypeList')
  def getPortalOrderTypeList(self):
    """
      Return order types.
    """
842 843 844
    return self._getPortalGroupedTypeList('order') or \
           self._getPortalConfiguration('portal_order_type_list')

845 846 847 848 849 850 851 852 853
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOpenOrderTypeList')
  def getPortalOpenOrderTypeList(self):
    """
      Return open order types.
    """
    return self._getPortalGroupedTypeList('open_order') or \
           self._getPortalConfiguration('portal_open_order_type_list')

854 855 856 857 858 859
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDeliveryTypeList')
  def getPortalDeliveryTypeList(self):
    """
      Return delivery types.
    """
860 861 862
    return self._getPortalGroupedTypeList('delivery') or \
           self._getPortalConfiguration('portal_delivery_type_list')

863 864 865 866 867 868
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTransformationTypeList')
  def getPortalTransformationTypeList(self):
    """
      Return transformation types.
    """
869 870 871
    return self._getPortalGroupedTypeList('transformation') or \
           self._getPortalConfiguration('portal_transformation_type_list')

872 873 874 875 876 877 878 879 880
  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')

881 882 883 884 885 886
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalVariationBaseCategoryList')
  def getPortalVariationBaseCategoryList(self):
    """
      Return variation base categories.
    """
887 888 889
    return self._getPortalGroupedCategoryList('variation') or \
           self._getPortalConfiguration('portal_variation_base_category_list')

890 891 892 893 894 895
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOptionBaseCategoryList')
  def getPortalOptionBaseCategoryList(self):
    """
      Return option base categories.
    """
896 897 898
    return self._getPortalGroupedCategoryList('option') or \
           self._getPortalConfiguration('portal_option_base_category_list')

899 900 901 902 903 904
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInvoiceMovementTypeList')
  def getPortalInvoiceMovementTypeList(self):
    """
      Return invoice movement types.
    """
905 906 907
    return self._getPortalGroupedTypeList('invoice_movement') or \
           self._getPortalConfiguration('portal_invoice_movement_type_list')

908 909 910 911 912 913 914 915 916 917
  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')


918 919 920 921 922 923
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOrderMovementTypeList')
  def getPortalOrderMovementTypeList(self):
    """
      Return order movement types.
    """
924 925 926
    return self._getPortalGroupedTypeList('order_movement') or \
           self._getPortalConfiguration('portal_order_movement_type_list')

927 928 929 930 931 932
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDeliveryMovementTypeList')
  def getPortalDeliveryMovementTypeList(self):
    """
      Return delivery movement types.
    """
933 934 935
    return self._getPortalGroupedTypeList('delivery_movement') or \
           self._getPortalConfiguration('portal_delivery_movement_type_list')

936
  security.declareProtected(Permissions.AccessContentsInformation,
937
                            'getPortalSupplyTypeList')
938 939 940 941
  def getPortalSupplyTypeList(self):
    """
      Return supply types.
    """
942 943 944
    return self._getPortalGroupedTypeList('supply') or \
           self._getPortalConfiguration('portal_supply_type_list')

945 946 947 948 949 950 951 952
  security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalConstraintTypeList')
  def getPortalConstraintTypeList(self):
    """
      Return rule types.
    """
    return self._getPortalGroupedTypeList('constraint')

953 954 955 956 957 958 959 960
  security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalRuleTypeList')
  def getPortalRuleTypeList(self):
    """
      Return rule types.
    """
    return self._getPortalGroupedTypeList('rule')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
961 962 963 964
  security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalProjectTypeList')
  def getPortalProjectTypeList(self):
    """
965
      Return project types.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
966 967 968
    """
    return self._getPortalGroupedTypeList('project')

969
  security.declareProtected(Permissions.AccessContentsInformation,
970 971 972 973 974
                              'getPortalDocumentTypeList')
  def getPortalDocumentTypeList(self):
    """
      Return document types.
    """
975
    return self._getPortalGroupedTypeList('document')
976

977 978 979 980 981 982 983 984
  security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalEmbeddedDocumentTypeList')
  def getPortalEmbeddedDocumentTypeList(self):
    """
      Return embedded document types.
    """
    return self._getPortalGroupedTypeList('embedded_document')

985 986 987 988 989 990 991 992
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalWebDocumentTypeList')
  def getPortalWebDocumentTypeList(self):
    """
      Return web page types.
    """
    return self._getPortalGroupedTypeList('web_document')

993 994 995 996
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalFileDocumentTypeList')
  def getPortalFileDocumentTypeList(self):
    """
997
      Return file document types.
998 999 1000 1001 1002 1003 1004
    """
    return self._getPortalGroupedTypeList('file_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalRecentDocumentTypeList')
  def getPortalRecentDocumentTypeList(self):
    """
1005
      Return recent document types.
1006 1007 1008 1009 1010 1011 1012
    """
    return self._getPortalGroupedTypeList('recent_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTemplateDocumentTypeList')
  def getPortalTemplateDocumentTypeList(self):
    """
1013
      Return template document types.
1014 1015 1016 1017 1018 1019 1020
    """
    return self._getPortalGroupedTypeList('template_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalMyDocumentTypeList')
  def getPortalMyDocumentTypeList(self):
    """
1021
      Return my document types.
1022 1023 1024
    """
    return self._getPortalGroupedTypeList('my_document')

1025 1026 1027 1028
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalCrawlerIndexTypeList')
  def getPortalCrawlerIndexTypeList(self):
    """
1029
      Return crawler index types.
1030 1031 1032
    """
    return self._getPortalGroupedTypeList('crawler_index')

1033 1034 1035 1036 1037 1038 1039 1040
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalBudgetVariationTypeList')
  def getPortalBudgetVariationTypeList(self):
    """
      Return budget variation types.
    """
    return self._getPortalGroupedTypeList('budget_variation')

1041
  security.declareProtected(Permissions.AccessContentsInformation,
1042
                            'getPortalSupplyPathTypeList')
1043 1044
  def getPortalSupplyPathTypeList(self):
    """
1045
      Return supply path types.
1046
    """
1047 1048 1049
    return self._getPortalGroupedTypeList('supply_path') or \
           self._getPortalConfiguration('portal_supply_path_type_list')

1050 1051 1052 1053 1054 1055 1056
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAcquisitionMovementTypeList')
  def getPortalAcquisitionMovementTypeList(self):
    """
      Return acquisition movement types.
    """
    return tuple(list(self.getPortalOrderMovementTypeList()) +
1057
                 list(self.getPortalDeliveryMovementTypeList()) +
1058
                 list(self.getPortalTaxMovementTypeList()) +
1059 1060
                 list(self.getPortalInvoiceMovementTypeList()))

1061 1062 1063 1064 1065 1066 1067
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalMovementTypeList')
  def getPortalMovementTypeList(self):
    """
      Return movement types.
    """
    return tuple(list(self.getPortalOrderMovementTypeList()) +
1068 1069
                 list(self.getPortalDeliveryMovementTypeList()) +
                 list(self.getPortalInvoiceMovementTypeList()) +
1070
                 list(self.getPortalTaxMovementTypeList()) +
1071
                 list(self.getPortalAccountingMovementTypeList()) +
1072
                 ['Simulation Movement'])
1073

1074 1075 1076 1077 1078 1079
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSimulatedMovementTypeList')
  def getPortalSimulatedMovementTypeList(self):
    """
      Return simulated movement types.
    """
1080
    return tuple([x for x in self.getPortalMovementTypeList() \
1081
                  if x not in self.getPortalContainerTypeList()])
1082

1083 1084 1085 1086 1087 1088
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalContainerTypeList')
  def getPortalContainerTypeList(self):
    """
      Return container types.
    """
1089 1090 1091
    return self._getPortalGroupedTypeList('container') or \
           self._getPortalConfiguration('portal_container_type_list')

1092 1093 1094 1095 1096 1097
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalContainerLineTypeList')
  def getPortalContainerLineTypeList(self):
    """
      Return container line types.
    """
1098 1099 1100
    return self._getPortalGroupedTypeList('container_line') or \
           self._getPortalConfiguration('portal_container_line_type_list')

1101 1102 1103 1104 1105 1106
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalItemTypeList')
  def getPortalItemTypeList(self):
    """
      Return item types.
    """
1107 1108 1109
    return self._getPortalGroupedTypeList('item') or \
           self._getPortalConfiguration('portal_item_type_list')

1110 1111 1112 1113 1114 1115
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDiscountTypeList')
  def getPortalDiscountTypeList(self):
    """
      Return discount types.
    """
1116 1117 1118
    return self._getPortalGroupedTypeList('discount') or \
           self._getPortalConfiguration('portal_discount_type_list')

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  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')

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
  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')

1161 1162 1163 1164 1165 1166
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAlarmTypeList')
  def getPortalAlarmTypeList(self):
    """
      Return alarm types.
    """
1167 1168 1169
    return self._getPortalGroupedTypeList('alarm') or \
           self._getPortalConfiguration('portal_alarm_type_list')

1170 1171 1172 1173 1174 1175
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPaymentConditionTypeList')
  def getPortalPaymentConditionTypeList(self):
    """
      Return payment condition types.
    """
1176 1177 1178
    return self._getPortalGroupedTypeList('payment_condition') or \
           self._getPortalConfiguration('portal_payment_condition_type_list')

1179 1180 1181 1182 1183 1184
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalBalanceTransactionLineTypeList')
  def getPortalBalanceTransactionLineTypeList(self):
    """
      Return balance transaction line types.
    """
1185
    return self._getPortalGroupedTypeList('balance_transaction_line') or \
1186 1187
           self._getPortalConfiguration(
                  'portal_balance_transaction_line_type_list')
1188

1189 1190 1191 1192 1193 1194
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalCurrentInventoryStateList')
  def getPortalCurrentInventoryStateList(self):
    """
      Return current inventory states.
    """
1195 1196 1197
    return self._getPortalGroupedStateList('current_inventory') or \
           self._getPortalConfiguration('portal_current_inventory_state_list')

1198 1199 1200 1201 1202 1203 1204 1205 1206
  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')

1207 1208 1209 1210 1211 1212
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDraftOrderStateList')
  def getPortalDraftOrderStateList(self):
    """
      Return draft order states.
    """
1213 1214 1215
    return self._getPortalGroupedStateList('draft_order') or \
           self._getPortalConfiguration('portal_draft_order_state_list')

1216 1217 1218 1219 1220 1221
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPlannedOrderStateList')
  def getPortalPlannedOrderStateList(self):
    """
      Return planned order states.
    """
1222 1223 1224
    return self._getPortalGroupedStateList('planned_order') or \
           self._getPortalConfiguration('portal_planned_order_state_list')

1225 1226 1227 1228 1229 1230
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalReservedInventoryStateList')
  def getPortalReservedInventoryStateList(self):
    """
      Return reserved inventory states.
    """
1231
    return self._getPortalGroupedStateList('reserved_inventory') or \
1232
        self._getPortalConfiguration('portal_reserved_inventory_state_list')
1233

1234 1235 1236 1237 1238 1239
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalFutureInventoryStateList')
  def getPortalFutureInventoryStateList(self):
    """
      Return future inventory states.
    """
1240 1241 1242
    return self._getPortalGroupedStateList('future_inventory') or \
           self._getPortalConfiguration('portal_future_inventory_state_list')

1243
  security.declareProtected(Permissions.AccessContentsInformation,
1244
                          'getPortalUpdatableAmortisationTransactionStateList')
1245 1246
  def getPortalUpdatableAmortisationTransactionStateList(self):
    """
1247
      Return states when Amortisation Transaction can be updated
1248
      by amortisation_transaction_builder.
1249
    """
1250 1251
    return self._getPortalConfiguration(
        'portal_updatable_amortisation_transaction_state_list')
1252

1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  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()

1275 1276 1277 1278 1279 1280
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalColumnBaseCategoryList')
  def getPortalColumnBaseCategoryList(self):
    """
      Return column base categories.
    """
1281 1282 1283
    return self._getPortalGroupedCategoryList('column') or \
           self._getPortalConfiguration('portal_column_base_category_list')

1284 1285 1286 1287 1288 1289
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalLineBaseCategoryList')
  def getPortalLineBaseCategoryList(self):
    """
      Return line base categories.
    """
1290 1291 1292
    return self._getPortalGroupedCategoryList('line') or \
           self._getPortalConfiguration('portal_line_base_category_list')

1293 1294 1295 1296 1297 1298
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTabBaseCategoryList')
  def getPortalTabBaseCategoryList(self):
    """
      Return tab base categories.
    """
1299 1300 1301
    return self._getPortalGroupedCategoryList('tab') or \
           self._getPortalConfiguration('portal_tab_base_category_list')

1302 1303 1304 1305
  def getPortalDefaultGapRoot(self):
    """
      Return the Accounting Plan to use by default (return the root node)
    """
1306
    LOG('ERP5Site', 0,
1307 1308 1309
        'getPortalDefaultGapRoot is deprecated; ' \
        'use portal_preferences.getPreferredAccountingTransactionGap instead.')

1310 1311
    return self.portal_preferences.getPreferredAccountingTransactionGap() or \
           self._getPortalConfiguration('portal_default_gap_root')
1312

1313 1314 1315 1316
  def getPortalAccountingMovementTypeList(self) :
    """
      Return accounting movement type list.
    """
1317
    return self._getPortalGroupedTypeList('accounting_movement') or \
1318
        self._getPortalConfiguration('portal_accounting_movement_type_list')
1319

1320 1321 1322 1323
  def getPortalAccountingTransactionTypeList(self) :
    """
      Return accounting transaction movement type list.
    """
1324
    return self._getPortalGroupedTypeList('accounting_transaction') or \
1325
      self._getPortalConfiguration('portal_accounting_transaction_type_list')
1326

1327 1328 1329 1330
  def getPortalAssignmentBaseCategoryList(self):
    """
      Return List of category values to generate security groups.
    """
1331
    return self._getPortalGroupedCategoryList('assignment') or \
1332
        self._getPortalConfiguration('portal_assignment_base_category_list')
1333

1334 1335
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTicketTypeList')
1336 1337 1338 1339 1340
  def getPortalTicketTypeList(self):
    """
    Return ticket types.
    """
    return self._getPortalGroupedTypeList('ticket')
1341

1342 1343
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalEventTypeList')
1344 1345 1346 1347 1348
  def getPortalEventTypeList(self):
    """
    Return event types.
    """
    return self._getPortalGroupedTypeList('event')
1349

1350 1351 1352 1353 1354 1355 1356 1357
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDivergenceTesterTypeList')
  def getPortalDivergenceTesterTypeList(self):
    """
    Return divergence tester types.
    """
    return self._getPortalGroupedTypeList('divergence_tester')

1358 1359 1360 1361 1362 1363 1364 1365
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTargetSolverTypeList')
  def getPortalTargetSolverTypeList(self):
    """
    Return target solver types.
    """
    return self._getPortalGroupedTypeList('target_solver')

Sebastien Robin's avatar
Sebastien Robin committed
1366 1367 1368 1369 1370 1371 1372 1373
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTargetSolverTypeList')
  def getPortalDeliverySolverTypeList(self):
    """
    Return delivery solver types.
    """
    return self._getPortalGroupedTypeList('delivery_solver')

1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
  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')

1398 1399 1400 1401 1402 1403 1404 1405
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalBusinessProcessTypeList')
  def getPortalBusinessProcessTypeList(self):
    """
    Return amount generator types.
    """
    return self._getPortalGroupedTypeList('business_process')

1406

1407
  security.declareProtected(Permissions.AccessContentsInformation,
1408 1409
                            'getPortalBusinessLinkTypeList')
  def getPortalBusinessLinkTypeList(self):
1410
    """
1411 1412 1413 1414 1415 1416 1417 1418 1419
      Return business link types.
    """
    return self._getPortalGroupedTypeList('business_link')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTradeModelPathTypeList')
  def getPortalTradeModelPathTypeList(self):
    """
      Return trade model path types.
1420
    """
1421
    return self._getPortalGroupedTypeList('trade_model_path')
1422

1423 1424 1425 1426 1427 1428 1429 1430
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalCalendarPeriodTypeList')
  def getPortalCalendarPeriodTypeList(self):
    """
    Return calendar period types.
    """
    return self._getPortalGroupedTypeList('calendar_period')

1431 1432 1433 1434 1435 1436 1437 1438
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalModuleTypeList')
  def getPortalModuleTypeList(self):
    """
    Return module types.
    """
    return self._getPortalGroupedTypeList('module')

1439 1440 1441 1442 1443 1444 1445 1446
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInventoryMovementTypeList')
  def getPortalInventoryMovementTypeList(self):
    """
    Return inventory movement types.
    """
    return self._getPortalGroupedTypeList('inventory_movement')

Sebastien Robin's avatar
Sebastien Robin committed
1447 1448 1449 1450 1451 1452 1453 1454
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInventoryTypeList')
  def getPortalInventoryTypeList(self):
    """
    Return inventory types.
    """
    return self._getPortalGroupedTypeList('inventory')

1455 1456 1457 1458 1459 1460 1461 1462
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalMovementGroupTypeList')
  def getPortalMovementGroupTypeList(self):
    """
    Return movement group types.
    """
    return self._getPortalGroupedTypeList('movement_group')

1463 1464 1465 1466 1467 1468 1469 1470 1471
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalEntityTypeList')
  def getPortalEntityTypeList(self):
    """
    Returns Entity types.
    """
    return self._getPortalGroupedTypeList('entity') or\
           self._getPortalConfiguration('portal_entity_type_list')

1472 1473
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getDefaultModuleId')
1474 1475
  def getDefaultModuleId(self, portal_type, default=MARKER):
    """
Romain Courteaud's avatar
Romain Courteaud committed
1476 1477
    Return default module id where a object with portal_type can
    be created.
1478 1479
    """
    portal_object = self
Romain Courteaud's avatar
Romain Courteaud committed
1480 1481 1482 1483 1484
    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
1485 1486 1487 1488 1489 1490
    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:
1491
        for expected_module_id in portal_object.objectIds(('ERP5 Folder',)):
1492 1493 1494 1495 1496 1497
          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
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510

    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
1511

1512 1513
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getDefaultModule')
1514
  def getDefaultModule(self, portal_type, default=MARKER):
1515 1516 1517
    """
      Return default module where a object with portal_type can be created
    """
1518 1519 1520 1521
    module_id = self.getDefaultModuleId(portal_type, default)
    if module_id:
      return getattr(self, module_id, None)
    return None
1522

1523
  security.declareProtected(Permissions.AddPortalContent, 'newContent')
1524
  def newContent(self, id=None, portal_type=None, **kw):
1525 1526 1527 1528 1529 1530 1531
    """
      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'
1532 1533 1534 1535
    self.portal_types.constructContent(type_name=portal_type,
                                       container=self,
                                       id=id,
                                       ) # **kw) removed due to CMF bug
1536
    new_instance = self[id]
1537

1538
    if kw:
1539
      new_instance._edit(force_update=1, **kw)
1540 1541
    return new_instance

1542 1543 1544 1545 1546 1547
  security.declarePublic('getVisibleAllowedContentTypeList')
  def getVisibleAllowedContentTypeList(self):
    """Users cannot add anything in an ERP5Site using standard interface.
    """
    return ()

1548 1549 1550 1551 1552 1553
  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)
1554

1555 1556 1557 1558 1559
  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.
1560
    tv = getTransactionalVariable()
1561 1562 1563 1564 1565 1566 1567