ERP5Site.py 56.7 KB
Newer Older
1
##############################################################################
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2 3 4 5 6 7 8 9 10 11 12
#
# 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
#
##############################################################################
13 14
"""
  Portal class
Jean-Paul Smets's avatar
Jean-Paul Smets committed
15 16 17
"""

import Globals
18
import AccessControl
Jean-Paul Smets's avatar
Jean-Paul Smets committed
19
from Globals import package_home
20

21
from Products.SiteErrorLog.SiteErrorLog import manage_addErrorLog
22
from ZPublisher import BeforeTraverse
Jean-Paul Smets's avatar
Jean-Paul Smets committed
23 24 25 26
from AccessControl import ClassSecurityInfo
from Products.CMFDefault.Portal import CMFSite, PortalGenerator
from Products.CMFCore.utils import getToolByName, _getAuthenticatedUser
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
Jean-Paul Smets's avatar
Jean-Paul Smets committed
27
from Products.ERP5Type.Core.Folder import FolderMixIn
Jean-Paul Smets's avatar
Jean-Paul Smets committed
28
from Acquisition import aq_base, aq_parent, aq_inner, aq_acquire
29
from Products.ERP5Type import allowClassTool
30
from Products.ERP5Type.Cache import CachingMethod
31 32
from Products.ERP5Type.ERP5Type import ERP5TypeInformation
from Products.ERP5.Document.BusinessTemplate import BusinessTemplate
33
from Products.ERP5Type.Log import log as unrestrictedLog
34

35
import ERP5Defaults
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36

37
from zLOG import LOG, INFO
Sebastien Robin's avatar
Sebastien Robin committed
38
from string import join
39
import os, traceback
40
import warnings
41 42
MARKER = []

43

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

103 104 105 106 107 108 109 110 111 112 113 114
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()
  #import pdb; pdb.set_trace()
  for item in os.listdir(bootstrap_dir):
    #LOG('getCatalogStorageList', 0, item)
    if item == '.svn':
      continue
115
    if item.endswith('.bt5') and os.path.isfile(item):
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
      # 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
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

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

153 154 155 156 157 158 159
    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
160

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    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()

180
class ERP5Site(FolderMixIn, CMFSite):
181
  """
182 183
  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.
184
  """
185
  meta_type = 'ERP5 Site'
186
  constructors = (('addERP5Site', manage_addERP5SiteForm), manage_addERP5Site, )
187 188 189
  uid = 0
  last_id = 0
  icon = 'portal.gif'
190
  isIndexable = 1 # Default value, prevents error during upgrade
191 192

  _properties = (
193
      { 'id':'title',
194
        'type':'string'},
195
      { 'id':'description',
196 197
        'type':'text'},
      )
198 199 200 201 202 203 204 205 206
  title = ''
  description = ''

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

  security.declareProtected(Permissions.View, 'view')
  def view(self):
207 208 209 210 211
    """
      Returns the default view.
      Implemented for consistency
    """
    return self.index_html()
212

213 214 215 216 217 218 219
  security.declareProtected(Permissions.ManagePortal, 'enableRefererCheck')
  def enableRefererCheck(self):
    """Enable a ReferCheckerBeforeTraverseHook to check users have valid
    HTTP_REFERER
    """
    BeforeTraverse.registerBeforeTraverse(self,
                                        ReferCheckerBeforeTraverseHook(),
220 221 222
                                        ReferCheckerBeforeTraverseHook.handle,
                             # we want to be registered _after_ CookieCrumbler
                                        100)
223

224 225 226 227
  def _disableRefererCheck(self):
    """Disable the HTTP_REFERER check."""
    BeforeTraverse.unregisterBeforeTraverse(self,
                                        ReferCheckerBeforeTraverseHook.handle)
228

229
  def hasObject(self, id):
230
    """
231
    Check if the portal has an id.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
232
    """
233
    return id in self.objectIds()
234

235
  security.declareProtected(Permissions.AccessContentsInformation,
236
                            'getPortalObject')
237 238
  def getPortalObject(self):
    return self
Jean-Paul Smets's avatar
Jean-Paul Smets committed
239

240
  security.declareProtected(Permissions.AccessContentsInformation,
241
                            'getTitle')
242 243 244 245 246
  def getTitle(self):
    """
      Return the title.
    """
    return self.title
247

248 249 250 251 252 253
  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
254

255 256 257
      WARNING : must be updates for circular references issues
    """
    return getattr(self, 'uid', 0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
258

259
  security.declareProtected(Permissions.AccessContentsInformation,
260
                            'getParentUid')
261 262 263 264 265
  def getParentUid(self):
    """
      A portal has no parent
    """
    return self.getUid()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
266

267 268 269 270
  # 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
271

272 273 274 275
  # 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
276

277 278
  security.declareProtected(Permissions.AccessContentsInformation, 'getUrl')
  def getUrl(self, REQUEST=None):
279 280 281 282
    """
      Returns the absolute path of an object
    """
    return join(self.getPhysicalPath(),'/')
Sebastien Robin's avatar
Sebastien Robin committed
283

284 285 286 287 288
  # Old name - for compatibility
  security.declareProtected(Permissions.AccessContentsInformation, 'getPath')
  getPath = getUrl

  security.declareProtected(Permissions.AccessContentsInformation, 'searchFolder')
289 290 291 292 293 294 295 296
  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
    kw2 = {}
297 298 299
    # Remove useless matter before calling the
    # catalog. In particular, consider empty
    # strings as None values
300
    for cname in kw.keys():
301
      if kw[cname] not in ('', None):
302
        kw2[cname] = kw[cname]
303 304
    # The method to call to search the folder
    # content has to be called z_search_folder
305 306 307 308 309 310 311 312 313 314 315 316
    method = self.portal_catalog.searchResults
    return method(**kw2)

  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
    kw2 = {}
317 318 319
    # Remove useless matter before calling the
    # catalog. In particular, consider empty
    # strings as None values
320
    for cname in kw.keys():
321
      if kw[cname] not in ('', None):
322
        kw2[cname] = kw[cname]
323 324
    # The method to call to search the folder
    # content has to be called z_search_folder
325 326 327 328 329 330 331 332 333 334
    method = self.portal_catalog.countResults
    return method(**kw2)

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

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

337
    This should absolutely be rewritten by using clean
338
    concepts to separate worklists XXX
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    """
    sorted_workflow_actions = {}
    sorted_global_actions = []
    other_global_actions = []
    for action in action_list:
      action['disabled'] = 0
      if action.has_key('workflow_title'):
        if not sorted_workflow_actions.has_key(action['workflow_title']):
          sorted_workflow_actions[action['workflow_title']] = []
        sorted_workflow_actions[action['workflow_title']].append(action)
      else:
        other_global_actions.append(action)
    workflow_title_list = sorted_workflow_actions.keys()
    workflow_title_list.sort()
    for key in workflow_title_list:
      sorted_global_actions.append({'title': key, 'disabled': 1})
      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,
361 362 363
                             email_from_address, email_from_name,
                             validate_email
                             ):
364
    CMFSite.setupDefaultProperties(self, p, title, description,
365 366
                           email_from_address, email_from_name,
                           validate_email)
367

368 369 370
  # 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
371
  # to customize the settings for each portal site.
372 373
  def _getPortalConfiguration(self, id):
    """
374
    Get a portal-specific configuration.
375

376 377
    Current implementation is using properties in a portal object.
    If not found, try to get a default value for backward compatibility.
378

379 380
    This implementation can be improved by gathering information
    from appropriate places, such as portal_types, portal_categories
381
    and portal_workflow.
382 383 384
    """
    if self.hasProperty(id):
      return self.getProperty(id)
385

386 387
    # Fall back to the default.
    return getattr(ERP5Defaults, id, None)
388

389
  def _getPortalGroupedTypeList(self, group):
390
    """
391
    Return a list of portal types classified to a specific group.
392 393
    The result is sorted by language (using the user language
    as default)
394 395 396 397 398 399
    """
    def getTypeList(group):
      type_list = []
      for pt in self.portal_types.objectValues():
        if group in getattr(pt, 'group_list', ()):
          type_list.append(pt.getId())
400 401 402 403 404 405

      def sortByTranslation(a, b):
        return cmp(localizer_tool.translate('ui', a),
                   localizer_tool.translate('ui', b))

      type_list.sort(sortByTranslation)
406 407
      return tuple(type_list)

408 409 410 411
    localizer_tool = getToolByName(self, 'Localizer')
    language = localizer_tool.get_selected_language()
    # language should be cached in Transaction Cache if performance issue

412
    getTypeList = CachingMethod(getTypeList,
413
                                id=(('_getPortalGroupedTypeList', language), group),
Aurel's avatar
Aurel committed
414
                                cache_factory='erp5_content_medium')
415 416 417

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

  def _getPortalGroupedCategoryList(self, group):
420
    """
421
    Return a list of base categories classified to a specific group.
422 423 424 425 426 427 428 429
    """
    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)

430 431
    getCategoryList = CachingMethod(
                            getCategoryList,
432
                            id=('_getPortalGroupedCategoryList', group),
Aurel's avatar
Aurel committed
433
                            cache_factory='erp5_content_medium')
434 435 436
    return getCategoryList(group)

  def _getPortalGroupedStateList(self, group):
437
    """
438
    Return a list of workflow states classified to a specific group.
439 440 441 442 443 444 445 446 447 448
    """
    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())

449
    getStateList = CachingMethod(getStateList,
450
                                 id=('_getPortalGroupedStateList', group),
Aurel's avatar
Aurel committed
451
                                 cache_factory='erp5_content_medium')
452 453
    return getStateList(group)

454 455
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDefaultSectionCategory')
456 457
  def getPortalDefaultSectionCategory(self):
    """
458
    Return a default section category. This method is deprecated.
459 460 461 462
    """
    LOG('ERP5Site', 0, 'getPortalDefaultSectionCategory is deprecated;'+
        ' use portal_preferences.getPreferredSectionCategory instead.')
    section_category = self.portal_preferences.getPreferredSectionCategory()
463

464 465 466 467
    # XXX This is only for backward-compatibility.
    if not section_category:
      section_category = self._getPortalConfiguration(
                                'portal_default_section_category')
468

469
    return section_category
470

471 472 473 474 475 476
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalResourceTypeList')
  def getPortalResourceTypeList(self):
    """
      Return resource types.
    """
477 478 479
    return self._getPortalGroupedTypeList('resource') or \
           self._getPortalConfiguration('portal_resource_type_list')

480 481 482 483 484 485 486
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSubVariationTypeList')
  def getPortalSubVariationTypeList(self):
    """
      Return resource types.
    """
    return self._getPortalGroupedTypeList('sub_variation')
487

488 489 490 491 492 493 494
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSubVariationBaseCategoryList')
  def getPortalSubVariationBaseCategoryList(self):
    """
      Return variation base categories.
    """
    return self._getPortalGroupedCategoryList('sub_variation')
495

496 497 498 499 500 501
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalVariationTypeList')
  def getPortalVariationTypeList(self):
    """
      Return variation types.
    """
502 503 504
    return self._getPortalGroupedTypeList('variation') or \
           self._getPortalConfiguration('portal_variation_type_list')

505 506 507 508 509 510
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalNodeTypeList')
  def getPortalNodeTypeList(self):
    """
      Return node types.
    """
511 512 513
    return self._getPortalGroupedTypeList('node') or \
           self._getPortalConfiguration('portal_node_type_list')

514 515 516 517 518 519
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPaymentNodeTypeList')
  def getPortalPaymentNodeTypeList(self):
    """
      Return payment node types.
    """
520 521 522
    return self._getPortalGroupedTypeList('payment_node') or \
           self._getPortalConfiguration('portal_payment_node_type_list')

523 524 525 526 527 528
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInvoiceTypeList')
  def getPortalInvoiceTypeList(self):
    """
      Return invoice types.
    """
529 530 531
    return self._getPortalGroupedTypeList('invoice') or \
           self._getPortalConfiguration('portal_invoice_type_list')

532 533 534 535 536 537
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOrderTypeList')
  def getPortalOrderTypeList(self):
    """
      Return order types.
    """
538 539 540
    return self._getPortalGroupedTypeList('order') or \
           self._getPortalConfiguration('portal_order_type_list')

541 542 543 544 545 546
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDeliveryTypeList')
  def getPortalDeliveryTypeList(self):
    """
      Return delivery types.
    """
547 548 549
    return self._getPortalGroupedTypeList('delivery') or \
           self._getPortalConfiguration('portal_delivery_type_list')

550 551 552 553 554 555
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTransformationTypeList')
  def getPortalTransformationTypeList(self):
    """
      Return transformation types.
    """
556 557 558
    return self._getPortalGroupedTypeList('transformation') or \
           self._getPortalConfiguration('portal_transformation_type_list')

559 560 561 562 563 564
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalVariationBaseCategoryList')
  def getPortalVariationBaseCategoryList(self):
    """
      Return variation base categories.
    """
565 566 567
    return self._getPortalGroupedCategoryList('variation') or \
           self._getPortalConfiguration('portal_variation_base_category_list')

568 569 570 571 572 573
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOptionBaseCategoryList')
  def getPortalOptionBaseCategoryList(self):
    """
      Return option base categories.
    """
574 575 576
    return self._getPortalGroupedCategoryList('option') or \
           self._getPortalConfiguration('portal_option_base_category_list')

577 578 579 580 581 582
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalInvoiceMovementTypeList')
  def getPortalInvoiceMovementTypeList(self):
    """
      Return invoice movement types.
    """
583 584 585
    return self._getPortalGroupedTypeList('invoice_movement') or \
           self._getPortalConfiguration('portal_invoice_movement_type_list')

586 587 588 589 590 591
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalOrderMovementTypeList')
  def getPortalOrderMovementTypeList(self):
    """
      Return order movement types.
    """
592 593 594
    return self._getPortalGroupedTypeList('order_movement') or \
           self._getPortalConfiguration('portal_order_movement_type_list')

595 596 597 598 599 600
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDeliveryMovementTypeList')
  def getPortalDeliveryMovementTypeList(self):
    """
      Return delivery movement types.
    """
601 602 603
    return self._getPortalGroupedTypeList('delivery_movement') or \
           self._getPortalConfiguration('portal_delivery_movement_type_list')

604
  security.declareProtected(Permissions.AccessContentsInformation,
605
                            'getPortalSupplyTypeList')
606 607 608 609
  def getPortalSupplyTypeList(self):
    """
      Return supply types.
    """
610 611 612
    return self._getPortalGroupedTypeList('supply') or \
           self._getPortalConfiguration('portal_supply_type_list')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
613 614 615 616 617 618 619 620
  security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalProjectTypeList')
  def getPortalProjectTypeList(self):
    """
      Return document types.
    """
    return self._getPortalGroupedTypeList('project')

621
  security.declareProtected(Permissions.AccessContentsInformation,
622 623 624 625 626
                              'getPortalDocumentTypeList')
  def getPortalDocumentTypeList(self):
    """
      Return document types.
    """
627
    return self._getPortalGroupedTypeList('document')
628 629 630 631 632 633 634 635 636

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalWebDocumentTypeList')
  def getPortalWebDocumentTypeList(self):
    """
      Return web page types.
    """
    return self._getPortalGroupedTypeList('web_document')

637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalFileDocumentTypeList')
  def getPortalFileDocumentTypeList(self):
    """
      Return web page types.
    """
    return self._getPortalGroupedTypeList('file_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalRecentDocumentTypeList')
  def getPortalRecentDocumentTypeList(self):
    """
      Return web page types.
    """
    return self._getPortalGroupedTypeList('recent_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTemplateDocumentTypeList')
  def getPortalTemplateDocumentTypeList(self):
    """
      Return web page types.
    """
    return self._getPortalGroupedTypeList('template_document')

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalMyDocumentTypeList')
  def getPortalMyDocumentTypeList(self):
    """
      Return web page types.
    """
    return self._getPortalGroupedTypeList('my_document')

669
  security.declareProtected(Permissions.AccessContentsInformation,
670
                            'getPortalSupplyPathTypeList')
671 672 673 674
  def getPortalSupplyPathTypeList(self):
    """
      Return supply movement types.
    """
675 676 677
    return self._getPortalGroupedTypeList('supply_path') or \
           self._getPortalConfiguration('portal_supply_path_type_list')

678 679 680 681 682 683 684
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAcquisitionMovementTypeList')
  def getPortalAcquisitionMovementTypeList(self):
    """
      Return acquisition movement types.
    """
    return tuple(list(self.getPortalOrderMovementTypeList()) +
685 686 687
                 list(self.getPortalDeliveryMovementTypeList()) +
                 list(self.getPortalInvoiceMovementTypeList()))

688 689 690 691 692 693 694
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalMovementTypeList')
  def getPortalMovementTypeList(self):
    """
      Return movement types.
    """
    return tuple(list(self.getPortalOrderMovementTypeList()) +
695 696
                 list(self.getPortalDeliveryMovementTypeList()) +
                 list(self.getPortalInvoiceMovementTypeList()) +
697
                 ['Simulation Movement'])
698

699 700 701 702 703 704
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalSimulatedMovementTypeList')
  def getPortalSimulatedMovementTypeList(self):
    """
      Return simulated movement types.
    """
705
    return tuple([x for x in self.getPortalMovementTypeList() \
706
                  if x not in self.getPortalContainerTypeList()])
707

708 709 710 711 712 713
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalContainerTypeList')
  def getPortalContainerTypeList(self):
    """
      Return container types.
    """
714 715 716
    return self._getPortalGroupedTypeList('container') or \
           self._getPortalConfiguration('portal_container_type_list')

717 718 719 720 721 722
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalContainerLineTypeList')
  def getPortalContainerLineTypeList(self):
    """
      Return container line types.
    """
723 724 725
    return self._getPortalGroupedTypeList('container_line') or \
           self._getPortalConfiguration('portal_container_line_type_list')

726 727 728 729 730 731
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalItemTypeList')
  def getPortalItemTypeList(self):
    """
      Return item types.
    """
732 733 734
    return self._getPortalGroupedTypeList('item') or \
           self._getPortalConfiguration('portal_item_type_list')

735 736 737 738 739 740
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDiscountTypeList')
  def getPortalDiscountTypeList(self):
    """
      Return discount types.
    """
741 742 743
    return self._getPortalGroupedTypeList('discount') or \
           self._getPortalConfiguration('portal_discount_type_list')

744 745 746 747 748 749
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalAlarmTypeList')
  def getPortalAlarmTypeList(self):
    """
      Return alarm types.
    """
750 751 752
    return self._getPortalGroupedTypeList('alarm') or \
           self._getPortalConfiguration('portal_alarm_type_list')

753 754 755 756 757 758
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPaymentConditionTypeList')
  def getPortalPaymentConditionTypeList(self):
    """
      Return payment condition types.
    """
759 760 761
    return self._getPortalGroupedTypeList('payment_condition') or \
           self._getPortalConfiguration('portal_payment_condition_type_list')

762 763 764 765 766 767
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalBalanceTransactionLineTypeList')
  def getPortalBalanceTransactionLineTypeList(self):
    """
      Return balance transaction line types.
    """
768
    return self._getPortalGroupedTypeList('balance_transaction_line') or \
769 770
           self._getPortalConfiguration(
                  'portal_balance_transaction_line_type_list')
771

772 773 774 775 776 777
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalCurrentInventoryStateList')
  def getPortalCurrentInventoryStateList(self):
    """
      Return current inventory states.
    """
778 779 780
    return self._getPortalGroupedStateList('current_inventory') or \
           self._getPortalConfiguration('portal_current_inventory_state_list')

781 782 783 784 785 786 787 788 789
  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')

790 791 792 793 794 795
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDraftOrderStateList')
  def getPortalDraftOrderStateList(self):
    """
      Return draft order states.
    """
796 797 798
    return self._getPortalGroupedStateList('draft_order') or \
           self._getPortalConfiguration('portal_draft_order_state_list')

799 800 801 802 803 804
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalPlannedOrderStateList')
  def getPortalPlannedOrderStateList(self):
    """
      Return planned order states.
    """
805 806 807
    return self._getPortalGroupedStateList('planned_order') or \
           self._getPortalConfiguration('portal_planned_order_state_list')

808 809 810 811 812 813
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalReservedInventoryStateList')
  def getPortalReservedInventoryStateList(self):
    """
      Return reserved inventory states.
    """
814
    return self._getPortalGroupedStateList('reserved_inventory') or \
815
        self._getPortalConfiguration('portal_reserved_inventory_state_list')
816

817 818 819 820 821 822
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalFutureInventoryStateList')
  def getPortalFutureInventoryStateList(self):
    """
      Return future inventory states.
    """
823 824 825
    return self._getPortalGroupedStateList('future_inventory') or \
           self._getPortalConfiguration('portal_future_inventory_state_list')

826
  security.declareProtected(Permissions.AccessContentsInformation,
827
                          'getPortalUpdatableAmortisationTransactionStateList')
828 829
  def getPortalUpdatableAmortisationTransactionStateList(self):
    """
830
      Return states when Amortisation Transaction can be updated
831
      by amortisation_transaction_builder.
832
    """
833 834
    return self._getPortalConfiguration(
        'portal_updatable_amortisation_transaction_state_list')
835

836 837 838 839 840 841
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalColumnBaseCategoryList')
  def getPortalColumnBaseCategoryList(self):
    """
      Return column base categories.
    """
842 843 844
    return self._getPortalGroupedCategoryList('column') or \
           self._getPortalConfiguration('portal_column_base_category_list')

845 846 847 848 849 850
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalLineBaseCategoryList')
  def getPortalLineBaseCategoryList(self):
    """
      Return line base categories.
    """
851 852 853
    return self._getPortalGroupedCategoryList('line') or \
           self._getPortalConfiguration('portal_line_base_category_list')

854 855 856 857 858 859
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTabBaseCategoryList')
  def getPortalTabBaseCategoryList(self):
    """
      Return tab base categories.
    """
860 861 862
    return self._getPortalGroupedCategoryList('tab') or \
           self._getPortalConfiguration('portal_tab_base_category_list')

863 864 865 866
  def getPortalDefaultGapRoot(self):
    """
      Return the Accounting Plan to use by default (return the root node)
    """
867
    LOG('ERP5Site', 0,
868 869 870
        'getPortalDefaultGapRoot is deprecated; ' \
        'use portal_preferences.getPreferredAccountingTransactionGap instead.')

871 872
    return self.portal_preferences.getPreferredAccountingTransactionGap() or \
           self._getPortalConfiguration('portal_default_gap_root')
873

874 875 876 877
  def getPortalAccountingMovementTypeList(self) :
    """
      Return accounting movement type list.
    """
878
    return self._getPortalGroupedTypeList('accounting_movement') or \
879
        self._getPortalConfiguration('portal_accounting_movement_type_list')
880

881 882 883 884
  def getPortalAccountingTransactionTypeList(self) :
    """
      Return accounting transaction movement type list.
    """
885
    return self._getPortalGroupedTypeList('accounting_transaction') or \
886
      self._getPortalConfiguration('portal_accounting_transaction_type_list')
887

888 889 890 891
  def getPortalAssignmentBaseCategoryList(self):
    """
      Return List of category values to generate security groups.
    """
892
    return self._getPortalGroupedCategoryList('assignment') or \
893
        self._getPortalConfiguration('portal_assignment_base_category_list')
894

895 896
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalTicketTypeList')
897 898 899 900 901
  def getPortalTicketTypeList(self):
    """
    Return ticket types.
    """
    return self._getPortalGroupedTypeList('ticket')
902

903 904
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalEventTypeList')
905 906 907 908 909
  def getPortalEventTypeList(self):
    """
    Return event types.
    """
    return self._getPortalGroupedTypeList('event')
910

911 912 913 914 915 916 917 918
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalDivergenceTesterTypeList')
  def getPortalDivergenceTesterTypeList(self):
    """
    Return divergence tester types.
    """
    return self._getPortalGroupedTypeList('divergence_tester')

919 920 921 922 923 924 925 926
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getPortalCalendarPeriodTypeList')
  def getPortalCalendarPeriodTypeList(self):
    """
    Return calendar period types.
    """
    return self._getPortalGroupedTypeList('calendar_period')

927 928
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getDefaultModuleId')
929 930
  def getDefaultModuleId(self, portal_type, default=MARKER):
    """
Romain Courteaud's avatar
Romain Courteaud committed
931 932
    Return default module id where a object with portal_type can
    be created.
933 934
    """
    portal_object = self
Romain Courteaud's avatar
Romain Courteaud committed
935 936 937 938 939 940 941 942
    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
    expected_module_id += '_module'
    if portal_object._getOb(expected_module_id, None) is not None:
      module_id = expected_module_id
943
    # then look for module where the type is allowed
Romain Courteaud's avatar
Romain Courteaud committed
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    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

    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
964

965 966
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getDefaultModule')
967 968 969 970 971
  def getDefaultModule(self, portal_type):
    """
      Return default module where a object with portal_type can be created
    """
    return getattr(self, self.getDefaultModuleId(portal_type), None)
972

973 974 975 976 977 978 979 980 981
  security.declareProtected(Permissions.AddPortalContent, 'newContent')
  def newContent(self, id=None, portal_type=None, immediate_reindex=0, **kw):
    """
      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'
982 983 984 985
    self.portal_types.constructContent(type_name=portal_type,
                                       container=self,
                                       id=id,
                                       ) # **kw) removed due to CMF bug
986
    new_instance = self[id]
987 988 989 990
    if kw is not None:
      new_instance._edit(force_update=1, **kw)
    if immediate_reindex:
      new_instance.immediateReindexObject()
991 992
    return new_instance

993 994 995 996 997 998
  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)
999

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1000 1001
Globals.InitializeClass(ERP5Site)

1002 1003 1004 1005 1006 1007 1008
def getBootstrapDirectory():
  """
    Return the name of the bootstrap directory
  """
  product_path = package_home(globals())
  return os.path.join(product_path, 'bootstrap')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1009 1010
class ERP5Generator(PortalGenerator):

1011
  klass = ERP5Site
1012

1013
  def getBootstrapDirectory(self):
1014
    return getBootstrapDirectory()
1015

1016 1017 1018
  def create(self,
             parent,
             id,
1019
             create_userfolder,
1020
             erp5_catalog_storage,
1021
             erp5_sql_connection_type,
1022 1023 1024 1025 1026 1027 1028 1029
             erp5_sql_connection_string,
             erp5_sql_deferred_connection_type,
             erp5_sql_deferred_connection_string,
             cmf_activity_sql_connection_type,
             cmf_activity_sql_connection_string,
             create_activities=1,
             reindex=1,
             **kw):
1030 1031
    id = str(id)
    portal = self.klass(id=id)
1032 1033
    # Make sure reindex will not be called until business templates
    # will be installed
1034
    setattr(portal, 'isIndexable', 0)
1035 1036 1037
    parent._setObject(id, portal)
    # Return the fully wrapped object.
    p = parent.this()._getOb(id)
1038 1039
    p._setProperty('erp5_catalog_storage',
                   erp5_catalog_storage, 'string')
1040
    p._setProperty('erp5_sql_connection_type',
1041
                   erp5_sql_connection_type, 'string')
1042
    p._setProperty('erp5_sql_connection_string',
1043
                   erp5_sql_connection_string, 'string')
1044
    p._setProperty('erp5_sql_deferred_connection_type',
1045
                   erp5_sql_deferred_connection_type, 'string')
1046
    p._setProperty('erp5_sql_deferred_connection_string',
1047
                   erp5_sql_deferred_connection_string, 'string')
1048
    p._setProperty('cmf_activity_sql_connection_type',
1049
                   cmf_activity_sql_connection_type, 'string')
1050
    p._setProperty('cmf_activity_sql_connection_string',
1051 1052
                   cmf_activity_sql_connection_string, 'string')
    # XXX hardcoded charset
1053
    p._setProperty('management_page_charset', 'UTF-8', 'string')
1054 1055
    self.setup(p, create_userfolder, create_activities=create_activities,
        reindex=reindex, **kw)
1056 1057 1058 1059
    return p

  def setupLastTools(self, p, **kw):
    """
1060 1061 1062
    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
1063 1064
    """
    # Add Activity Tool
1065
    if kw.has_key('create_activities') and int(kw['create_activities'])==1:
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
      if not p.hasObject('portal_activities'):
        addTool = p.manage_addProduct['CMFActivity'].manage_addTool
        addTool('CMF Activity Tool', None) # Allow user to select active/passive
      # Initialize Activities
      portal_activities = getToolByName(p, 'portal_activities', None)
      if portal_activities is not None:
        if kw.get('update', 0):
          keep = 1
        else:
          keep = 0
        portal_activities.manageClearActivities(keep=keep)
1077

1078 1079
  def setupTemplateTool(self, p, **kw):
    """
1080
    Setup the Template Tool. Security must be set strictly.
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    """
    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):
    """
1091
    Set up initial tools.
1092 1093 1094 1095
    """
    if not 'portal_actions' in p.objectIds():
      PortalGenerator.setupTools(self, p)

1096
    # It is better to remove portal_catalog
1097
    # which is ZCatalog as soon as possible,
1098
    # because the API is not the completely same as ERP5Catalog,
1099
    # and ZCatalog is useless for ERP5 after all.
1100 1101
    update = kw.get('update', 0)
    portal_catalog = getToolByName(p, 'portal_catalog', None)
1102 1103 1104
    if portal_catalog is not None and \
       portal_catalog.meta_type != 'ZSQLCatalog' and \
       not update:
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
      p._delObject('portal_catalog')

    # Add CMF Report Tool
    if not p.hasObject('portal_report'):
      addTool = p.manage_addProduct['CMFReportTool'].manage_addTool
      addTool('CMF Report Tool', None)

    # 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_rules'):
      addTool('ERP5 Rule Tool', None)
    if not p.hasObject('portal_ids'):
      addTool('ERP5 Id Tool', None)
    if not p.hasObject('portal_simulation'):
      addTool('ERP5 Simulation 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)
    if not p.hasObject('portal_deliveries'):
      addTool('ERP5 Delivery Tool', None)
    if not p.hasObject('portal_orders'):
      addTool('ERP5 Order Tool', None)
1134 1135
    if not p.hasObject('portal_tests'):
      addTool('ERP5 Test Tool', None)
Aurel's avatar
Aurel committed
1136

1137 1138
    # Add ERP5Type Tool
    addTool = p.manage_addProduct['ERP5Type'].manage_addTool
1139 1140
    if not p.hasObject('portal_caches'):
      addTool('ERP5 Cache Tool', None)
1141 1142
    if not p.hasObject('portal_memcached'):
      addTool('ERP5 Memcached Tool', None)
1143

1144 1145 1146 1147 1148 1149
    try:
      addTool = p.manage_addProduct['ERP5Subversion'].manage_addTool
      if not p.hasObject('portal_subversion'):
        addTool('ERP5 Subversion Tool', None)
    except AttributeError:
      pass
1150

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    # 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)
    # Add Default SQL connection
    if p.erp5_sql_connection_type == 'Z MySQL Database Connection':
      if not p.hasObject('erp5_sql_connection'):
1166 1167
        addSQLConnection = p.manage_addProduct['ZMySQLDA'].\
                                     manage_addZMySQLConnection
1168 1169
        addSQLConnection('erp5_sql_connection',
                         'ERP5 SQL Server Connection',
1170
                         p.erp5_sql_connection_string)
1171 1172
    elif p.erp5_sql_connection_type == 'Z Gadfly':
      pass
1173 1174

    # Add Deferred SQL Connections
1175 1176
    if p.erp5_sql_deferred_connection_type == \
        'Z MySQL Deferred Database Connection':
1177
      if not p.hasObject('erp5_sql_deferred_connection'):
1178 1179
        addSQLConnection = p.manage_addProduct['ZMySQLDDA'].\
            manage_addZMySQLDeferredConnection
1180 1181
        addSQLConnection('erp5_sql_deferred_connection',
                         'ERP5 SQL Server Deferred Connection',
1182
                         p.erp5_sql_deferred_connection_string)
1183 1184 1185 1186
    elif p.erp5_sql_deferred_connection_type == 'Z Gadfly':
      pass

    # Add Activity SQL Connections
1187 1188
    if p.cmf_activity_sql_connection_type == 'Z MySQL Database Connection':
      if not p.hasObject('cmf_activity_sql_connection'):
1189 1190
        addSQLConnection = p.manage_addProduct['ZMySQLDA'].\
                                     manage_addZMySQLConnection
1191 1192
        addSQLConnection('cmf_activity_sql_connection',
                         'CMF Activity SQL Server Connection',
1193
                         p.cmf_activity_sql_connection_string)
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
      # 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
      # minux prepended to the conneciton string.
      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
1205
                         '-%s' % p.cmf_activity_sql_connection_string)
1206 1207
    elif p.cmf_activity_sql_connection_type == 'Z Gadfly':
      pass
1208

1209 1210 1211 1212 1213 1214 1215
    # 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)

1216 1217 1218 1219 1220 1221 1222
    try:
      # Add ERP5SyncML Tools
      addTool = p.manage_addProduct['ERP5SyncML'].manage_addTool
      if not p.hasObject('portal_synchronizations'):
        addTool('ERP5 Synchronizations', None)
    except AttributeError:
      pass
1223 1224 1225 1226 1227 1228

    # Add Message Catalog
    if not 'Localizer' in p.objectIds():
      addLocalizer = p.manage_addProduct['Localizer'].manage_addLocalizer
      addLocalizer('', ('en',))
    localizer = getToolByName(p, 'Localizer')
1229 1230
    addMessageCatalog = localizer.manage_addProduct['Localizer']\
                                      .manage_addMessageCatalog
1231 1232 1233
    if 'erp5_ui' not in localizer.objectIds():
      if 'default' in localizer.objectIds():
        localizer.manage_delObjects('default')
1234 1235 1236
      addMessageCatalog('default', 'ERP5 Localized Messages', ('en',))
      addMessageCatalog('erp5_ui', 'ERP5 Localized Interface', ('en',))
      addMessageCatalog('erp5_content', 'ERP5 Localized Content', ('en',))
1237 1238 1239 1240
    
    # Add an error_log
    if 'error_log' not in p.objectIds():
      manage_addErrorLog(p)
1241 1242 1243

  def setupMembersFolder(self, p):
    """
1244
    ERP5 is not a CMS
1245 1246 1247 1248 1249
    """
    pass

  def setupDefaultSkins(self, p):
    from Products.CMFCore.DirectoryView import addDirectoryViews
1250
    from Products.CMFDefault  import cmfdefault_globals
1251
    from Products.CMFActivity import cmfactivity_globals
Jérome Perrin's avatar
Jérome Perrin committed
1252 1253 1254 1255 1256
    try:
      from Products.FCKeditor   import fckeditor_globals
      have_fckeditor = 1
    except:
      have_fckeditor = 0
1257 1258 1259
    ps = getToolByName(p, 'portal_skins')
    addDirectoryViews(ps, 'skins', cmfdefault_globals)
    addDirectoryViews(ps, 'skins', cmfactivity_globals)
Jérome Perrin's avatar
Jérome Perrin committed
1260 1261
    if have_fckeditor:
      addDirectoryViews(ps, 'skins', fckeditor_globals)
1262 1263
    ps.manage_addProduct['OFSP'].manage_addFolder(id='external_method')
    ps.manage_addProduct['OFSP'].manage_addFolder(id='custom')
1264
    # Set the 'custom' layer a high priority, so it remains the first
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    #   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'
                       , 'zpt_content'
                       , 'zpt_generic'
                       , 'zpt_control'
                       , 'content'
                       , 'generic'
                       , 'control'
                       , 'Images'
                       ]
Jérome Perrin's avatar
Jérome Perrin committed
1278 1279
    if have_fckeditor:
      skin_folder_list.insert(1, 'fckeditor')
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    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
                       )
1293 1294 1295 1296
    p.setupCurrentSkin()

  def setupWorkflow(self, p):
    """
1297
    Set up workflows for business templates
1298 1299 1300
    """
    tool = getToolByName(p, 'portal_workflow', None)
    if tool is None:
Jérome Perrin's avatar
Jérome Perrin committed
1301
      return
1302
    for wf_id in ('business_template_building_workflow',
1303
                  'business_template_installation_workflow'):
1304 1305 1306
      if wf_id in tool.objectIds():
        tool.manage_delObjects([wf_id])
    bootstrap_dir = self.getBootstrapDirectory()
1307 1308 1309
    business_template_building_workflow = os.path.join(
                                 bootstrap_dir,
                                 'business_template_building_workflow.xml')
1310
    tool._importObjectFromFile(business_template_building_workflow)
1311 1312 1313
    business_template_installation_workflow = os.path.join(
                                 bootstrap_dir,
                                 'business_template_installation_workflow.xml')
1314 1315
    tool._importObjectFromFile(business_template_installation_workflow)
    tool.setChainForPortalTypes( ( 'Business Template', ),
1316 1317
                                 ( 'business_template_building_workflow',
                                   'business_template_installation_workflow' ) )
1318 1319 1320

  def setupIndex(self, p, **kw):
    # Make sure all tools and folders have been indexed
1321
    if not kw.get('reindex', 1):
1322 1323 1324 1325
      return
    skins_tool = getToolByName(p, 'portal_skins', None)
    if skins_tool is None:
      return
1326
    # When no SQL connection was define on the site,
1327 1328 1329 1330 1331 1332
    # we don't want to make it crash
    if p.erp5_sql_connection_type is not None:
      setattr(p, 'isIndexable', 1)
      portal_catalog = p.portal_catalog
      portal_catalog.manage_catalogClear()
      skins_tool["erp5_core"].ERP5Site_reindexAll()
1333

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
  def setupUserFolder(self, p):
    # We use if possible ERP5Security, then NuxUserGroups
    try:
      from Products import ERP5Security
      from Products import PluggableAuthService
    except ImportError:
      ERP5Security = None
      try:
        import Products.NuxUserGroups
        withnuxgroups = 1
      except ImportError:
        withnuxgroups = 0
    if ERP5Security is not None:
      # Use Pluggable Auth Service instead of the standard acl_users.
      p.manage_addProduct['PluggableAuthService'].addPluggableAuthService()
1349
      pas_dispatcher = p.acl_users.manage_addProduct['PluggableAuthService']
1350
      # Add legacy ZODB support
1351 1352 1353
      pas_dispatcher.addZODBUserManager('zodb_users')
      pas_dispatcher.addZODBGroupManager('zodb_groups')
      pas_dispatcher.addZODBRoleManager('zodb_roles')
1354
      # Add CMF Portal Roles
1355
      #XXX Maybe it will be no longer required once PAS is the standard
1356 1357 1358
      p.acl_users.zodb_roles.addRole('Member')
      p.acl_users.zodb_roles.addRole('Reviewer')
      # Register ZODB Interface
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
      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'))
1370
      # Add ERP5UserManager
1371 1372 1373 1374 1375
      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')
1376
      # Register ERP5UserManager Interface
1377 1378 1379
      p.acl_users.erp5_users.manage_activateInterfaces(
                                        ('IAuthenticationPlugin',
                                        'IUserEnumerationPlugin',))
1380 1381
      p.acl_users.erp5_groups.manage_activateInterfaces(('IGroupsPlugin',))
      p.acl_users.erp5_roles.manage_activateInterfaces(('IRolesPlugin',))
1382 1383
      p.acl_users.erp5_user_factory.manage_activateInterfaces(
                                        ('IUserFactoryPlugin',))
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    elif withnuxgroups:
      # NuxUserGroups user folder
      p.manage_addProduct['NuxUserGroups'].addUserFolderWithGroups()
    else:
      # Standard user folder
      PortalGenerator.setupUserFolder(self, p)

  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'),
1398
      'Change local roles'           : ('Manager', ),
1399 1400 1401 1402 1403 1404
      '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'),
1405
      'List undoable changes'        : ('Manager', ),
1406 1407 1408 1409 1410
      'Manage properties'            : ('Manager', 'Owner'),
      'Modify portal content'        : ('Manager', 'Owner'),
      'Reply to item'                : ('Manager', 'Member'),
      'Review portal content'        : ('Manager', 'Reviewer'),
      'Search ZCatalog'              : ('Manager', 'Member'),
1411
      'Set own password'             : ('Manager', ),
1412
      'Set own properties'           : ('Manager', 'Member'),
1413
      'Use mailhost services'        : ('Manager', 'Member'),
1414
      'Undo changes'                 : ('Manager', 'Owner'),
1415
      'View'                         : ('Manager', 'Member',
1416
                                        'Owner', 'Anonymous'),
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
      '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)

1428 1429 1430
    if getattr(p, 'setDefaultSorting', None) is not None:
      p.setDefaultSorting('id', 0)

1431 1432 1433 1434 1435
    self.setupTools(p, **kw)

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

Jérome Perrin's avatar
Jérome Perrin committed
1436 1437
    if create_userfolder and not p.hasObject('acl_users'):
      self.setupUserFolder(p)
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464

    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)

    # Finish setup
    if not p.hasObject('Members'):
      self.setupMembersFolder(p)

    # ERP5 Design Choice is that all content should be user defined
    # Content is disseminated through business templates
    self.setupBusinessTemplate(p)

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

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

1465 1466 1467
    # Make sure the cache is initialized
    p.portal_caches.updateCache()

1468 1469
    self.setupLastTools(p, **kw)

1470 1471 1472 1473 1474 1475 1476
    # 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)

  def setupBusinessTemplate(self,p):
    """
1477
    Install the portal_type of Business Template
1478 1479 1480 1481 1482 1483 1484 1485 1486
    """
    tool = getToolByName(p, 'portal_types', None)
    if tool is None:
      return
    if 'Business Template' not in tool.objectIds():
      t = BusinessTemplate.factory_type_information
      ti = apply(ERP5TypeInformation, (), t)
      tool._setObject(t['id'], ti)

1487
  def setupERP5Core(self,p,**kw):
1488
    """
1489
    Install the core part of ERP5
1490 1491 1492 1493 1494 1495
    """
    template_tool = getToolByName(p, 'portal_templates', None)
    if template_tool is None:
      return
    if template_tool.getInstalledBusinessTemplate('erp5_core') is None:
      bootstrap_dir = self.getBootstrapDirectory()
1496 1497 1498 1499 1500
      if p.erp5_catalog_storage is not '':
        business_template_list = ('erp5_core', p.erp5_catalog_storage, 'erp5_xhtml_style')
      else:
        business_template_list = ('erp5_core', 'erp5_xhtml_style')
      for bt in business_template_list:
1501 1502 1503 1504 1505 1506 1507
        template = os.path.join(bootstrap_dir, bt)
        if not os.path.exists(template):
          template = os.path.join(bootstrap_dir, '%s.bt5' % bt)

        id = template_tool.generateNewId()
        template_tool.download(template, id=id)
        template_tool[id].install(**kw)