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

$Id$
"""

import Globals
from Globals import package_home
#from Products.ERP5 import content_classes
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
25
from Products.ERP5Type.Document.Folder import FolderMixIn
26
from Products.ERP5Type.Document import addFolder
Jean-Paul Smets's avatar
Jean-Paul Smets committed
27
from Acquisition import aq_base, aq_parent, aq_inner, aq_acquire
28
from Products.ERP5Type import allowClassTool
29
from Products.ERP5Type.Cache import CachingMethod
30

31
import ERP5Defaults
32
from os import path
Jean-Paul Smets's avatar
Jean-Paul Smets committed
33 34

from zLOG import LOG
Sebastien Robin's avatar
Sebastien Robin committed
35
from string import join
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36 37 38 39 40 41 42 43

import os

#factory_type_information = []
#for c in content_classes:
#  factory_type_information.append(getattr(c, 'factory_type_information', []))

# Site Creation DTML
44 45
manage_addERP5SiteForm = Globals.HTMLFile('dtml/addERP5Site', globals())
manage_addERP5SiteForm.__name__ = 'addERP5Site'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
46 47 48 49

# ERP5Site Constructor
def manage_addERP5Site(self, id, title='ERP5', description='',
                         create_userfolder=1,
50
                         create_activities=1,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
51 52
                         email_from_address='postmaster@localhost',
                         email_from_name='Portal Administrator',
53
                         validate_email=0,
54 55 56 57
                         erp5_sql_connection_type='Z MySQL Database Connection',
                         erp5_sql_connection_string='test test',
                         cmf_activity_sql_connection_type='Z MySQL Database Connection',
                         cmf_activity_sql_connection_string='test test',
Sebastien Robin's avatar
Sebastien Robin committed
58
                         light_install=0,reindex=1,
59
                         RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
60 61 62
    '''
    Adds a portal instance.
    '''
63 64
    #LOG('manage_addERP5Site, create_activities',0,create_activities)
    #LOG('manage_addERP5Site, create_activities==1',0,create_activities==1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
65 66 67
    gen = ERP5Generator()
    from string import strip
    id = strip(id)
68 69 70
    p = gen.create(self, id, create_userfolder,
                   erp5_sql_connection_type,erp5_sql_connection_string,
                   cmf_activity_sql_connection_type,cmf_activity_sql_connection_string,
Sebastien Robin's avatar
Sebastien Robin committed
71 72
                   create_activities=create_activities,light_install=light_install,
                   reindex=reindex)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
73 74 75 76
    gen.setupDefaultProperties(p, title, description,
                               email_from_address, email_from_name,
                               validate_email)
    if RESPONSE is not None:
77
        RESPONSE.redirect(p.absolute_url())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
78

Jean-Paul Smets's avatar
Jean-Paul Smets committed
79
class ERP5Site ( CMFSite, FolderMixIn ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    """
        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.
    """
    meta_type = 'ERP5 Site'
    constructors = (manage_addERP5SiteForm, manage_addERP5Site, )
    uid = 0
    last_id = 0
    icon = 'portal.gif'

    _properties = (
        {'id':'title', 'type':'string'},
        {'id':'description', 'type':'text'},
        )
    title = ''
    description = ''

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

Yoshinori Okuji's avatar
Yoshinori Okuji committed
101
    security.declareProtected(Permissions.View, 'view')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
102 103 104 105 106 107 108
    def view(self):
        """
          Returns the default view.
          Implemented for consistency
        """
        return self.index_html()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
109 110 111 112
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalObject')
    def getPortalObject(self):
      return self

113 114 115 116 117 118 119
    security.declareProtected(Permissions.AccessContentsInformation, 'getTitle')
    def getTitle(self):
      """
        Return the title.
      """
      return self.title

Jean-Paul Smets's avatar
Jean-Paul Smets committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    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).

        WARNING : must be updates for circular references issues
      """
      #if not hasattr(self, 'uid'):
      #  self.reindexObject()
      return getattr(self, 'uid', 0)

    security.declareProtected(Permissions.AccessContentsInformation, 'getParentUid')
    def getParentUid(self):
      """
        A portal has no parent
      """
      return self.getUid()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
140 141 142 143 144 145
    # Required to allow content creation outside folders
    security.declareProtected(Permissions.View, 'getIdGroup')
    def getIdGroup(self):
      return None

    # Required to allow content creation outside folders
Yoshinori Okuji's avatar
Yoshinori Okuji committed
146
    security.declareProtected(Permissions.View, 'setLastId')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
147 148 149
    def setLastId(self, id):
      self.last_id = id

Sebastien Robin's avatar
Sebastien Robin committed
150 151 152 153 154 155 156
    security.declareProtected(Permissions.AccessContentsInformation, 'getPath')
    def getPath(self, REQUEST=None):
      """
        Returns the absolute path of an object
      """
      return join(self.getPhysicalPath(),'/')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    security.declareProtected(Permissions.AccessContentsInformation, 'searchFolder')
    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 = {}
      # Remove useless matter before calling the
      # catalog. In particular, consider empty
      # strings as None values
      for cname in kw.keys():
        if kw[cname] != '' and kw[cname]!=None:
          kw2[cname] = kw[cname]
      # The method to call to search the folder
      # content has to be called z_search_folder
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
      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 = {}
      # Remove useless matter before calling the
      # catalog. In particular, consider empty
      # strings as None values
      for cname in kw.keys():
        if kw[cname] != '' and kw[cname]!=None:
          kw2[cname] = kw[cname]
      # The method to call to search the folder
      # content has to be called z_search_folder
      method = self.portal_catalog.countResults
Jean-Paul Smets's avatar
Jean-Paul Smets committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      return method(**kw2)

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

    # Make sure fixConsistency is recursive - ERROR - this creates recursion errors
    # checkConsistency = Folder.checkConsistency
    # fixConsistency = Folder.fixConsistency

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

      This should absolutely be rewritten by using clean concepts to separate worklists XXX
      """
      #LOG("getOrderedGlobalActionList", 0, str(action_list))
      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])
229
      sorted_global_actions.append({'title': 'Others', 'disabled': 1})
Jean-Paul Smets's avatar
Jean-Paul Smets committed
230 231 232
      sorted_global_actions.extend(other_global_actions)
      return sorted_global_actions

233 234 235 236 237 238 239 240
    def setupDefaultProperties(self, p, title, description,
                               email_from_address, email_from_name,
                               validate_email
                               ):
        CMFSite.setupDefaultProperties(self, p, title, description,
                               email_from_address, email_from_name,
                               validate_email)

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    # 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 to customize the settings for each portal site.
    def _getPortalConfiguration(self, id):
      """
        Get a portal-specific configuration.

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

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

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

260 261 262 263 264 265 266 267 268
    def _getPortalGroupedTypeList(self, group):
      """Return a list of portal types classified to a specific group.
      """
      def getTypeList(group):
        type_list = []
        for pt in self.portal_types.objectValues():
          if group in getattr(pt, 'group_list', ()):
            type_list.append(pt.getId())
        return tuple(type_list)
269

270 271
      getTypeList = CachingMethod(getTypeList, id=('_getPortalGroupedTypeList', group), cache_duration=3600)
      return getTypeList(group)
272

273 274 275 276 277 278 279 280 281
    def _getPortalGroupedCategoryList(self, group):
      """Return a list of base categories classified to a specific group.
      """
      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)
282

283 284
      getCategoryList = CachingMethod(getCategoryList, id=('_getPortalGroupedCategoryList', group), cache_duration=3600)
      return getCategoryList(group)
285 286 287 288 289 290 291

    def _getPortalGroupedStateList(self, group):
      """Return a list of workflow states classified to a specific group.
      """
      def getStateList(group):
        state_dict = {}
        for wf in self.portal_workflow.objectValues():
292
          if getattr(wf, 'states', None):
293 294 295 296
            for state in wf.states.objectValues():
              if group in getattr(state, 'type_list', ()):
                state_dict[state.getId()] = None
        return tuple(state_dict.keys())
297

298 299
      getStateList = CachingMethod(getStateList, id=('_getPortalGroupedStateList', group), cache_duration=3600)
      return getStateList(group)
300

301 302 303 304 305 306 307
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalDefaultSectionCategory')
    def getPortalDefaultSectionCategory(self):
      """
        Return a default section category. This method is deprecated.
      """
      LOG('ERP5Site', 0, 'getPortalDefaultSectionCategory is deprecated; use portal_preferences.getPreferredSectionCategory instead.')
      section_category = self.portal_preferences.getPreferredSectionCategory()
308

309 310 311
      # XXX This is only for backward-compatibility.
      if not section_category:
        section_category = self._getPortalConfiguration('portal_default_section_category')
312

313 314
      return section_category

315 316 317 318 319
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalResourceTypeList')
    def getPortalResourceTypeList(self):
      """
        Return resource types.
      """
320
      return self._getPortalGroupedTypeList('resource') or self._getPortalConfiguration('portal_resource_type_list')
321 322 323 324 325 326

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalVariationTypeList')
    def getPortalVariationTypeList(self):
      """
        Return variation types.
      """
327
      return self._getPortalGroupedTypeList('variation') or self._getPortalConfiguration('portal_variation_type_list')
328 329 330 331 332 333

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalNodeTypeList')
    def getPortalNodeTypeList(self):
      """
        Return node types.
      """
334
      return self._getPortalGroupedTypeList('node') or self._getPortalConfiguration('portal_node_type_list')
335 336 337 338 339 340

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalInvoiceTypeList')
    def getPortalInvoiceTypeList(self):
      """
        Return invoice types.
      """
341
      return self._getPortalGroupedTypeList('invoice') or self._getPortalConfiguration('portal_invoice_type_list')
342 343 344 345 346 347

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalOrderTypeList')
    def getPortalOrderTypeList(self):
      """
        Return order types.
      """
348
      return self._getPortalGroupedTypeList('order') or self._getPortalConfiguration('portal_order_type_list')
349 350 351 352 353 354

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalDeliveryTypeList')
    def getPortalDeliveryTypeList(self):
      """
        Return delivery types.
      """
355
      return self._getPortalGroupedTypeList('delivery') or self._getPortalConfiguration('portal_delivery_type_list')
356

357
    security.declareProtected(Permissions.AccessContentsInformation,
358 359 360 361 362
                              'getPortalTransformationTypeList')
    def getPortalTransformationTypeList(self):
      """
        Return transformation types.
      """
363
      return self._getPortalGroupedTypeList('transformation') or self._getPortalConfiguration('portal_transformation_type_list')
364

365 366 367 368 369
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalVariationBaseCategoryList')
    def getPortalVariationBaseCategoryList(self):
      """
        Return variation base categories.
      """
370
      return self._getPortalGroupedCategoryList('variation') or self._getPortalConfiguration('portal_variation_base_category_list')
371

372 373 374 375 376 377
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getPortalOptionBaseCategoryList')
    def getPortalOptionBaseCategoryList(self):
      """
        Return option base categories.
      """
378
      return self._getPortalGroupedCategoryList('option') or self._getPortalConfiguration('portal_option_base_category_list')
379

380 381 382 383 384
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalInvoiceMovementTypeList')
    def getPortalInvoiceMovementTypeList(self):
      """
        Return invoice movement types.
      """
385
      return self._getPortalGroupedTypeList('invoice_movement') or self._getPortalConfiguration('portal_invoice_movement_type_list')
386 387 388 389 390 391

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalOrderMovementTypeList')
    def getPortalOrderMovementTypeList(self):
      """
        Return order movement types.
      """
392
      return self._getPortalGroupedTypeList('order_movement') or self._getPortalConfiguration('portal_order_movement_type_list')
393 394 395 396 397 398

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalDeliveryMovementTypeList')
    def getPortalDeliveryMovementTypeList(self):
      """
        Return delivery movement types.
      """
399
      return self._getPortalGroupedTypeList('delivery_movement') or self._getPortalConfiguration('portal_delivery_movement_type_list')
400

401 402 403
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalDeliveryMovementTypeList')
    def getPortalSupplyTypeList(self):
      """
Sebastien Robin's avatar
Sebastien Robin committed
404
        Return supply types.
405
      """
406
      return self._getPortalGroupedTypeList('supply') or self._getPortalConfiguration('portal_supply_type_list')
407

408 409 410 411 412
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalAcquisitionMovementTypeList')
    def getPortalAcquisitionMovementTypeList(self):
      """
        Return acquisition movement types.
      """
413
      return tuple(list(self.getPortalOrderMovementTypeList()) + list(self.getPortalDeliveryMovementTypeList()) + list(self.getPortalInvoiceMovementTypeList()))
414 415 416 417 418 419

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalMovementTypeList')
    def getPortalMovementTypeList(self):
      """
        Return movement types.
      """
420
      return tuple(list(self.getPortalOrderMovementTypeList()) + list(self.getPortalDeliveryMovementTypeList()) + list(self.getPortalInvoiceMovementTypeList()) + ['Simulation Movement'])
421 422 423 424 425 426

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalSimulatedMovementTypeList')
    def getPortalSimulatedMovementTypeList(self):
      """
        Return simulated movement types.
      """
427
      return tuple([x for x in self.getPortalMovementTypeList() if x not in self.getPortalContainerTypeList()])
428 429 430 431 432 433

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalContainerTypeList')
    def getPortalContainerTypeList(self):
      """
        Return container types.
      """
434
      return self._getPortalGroupedTypeList('container') or self._getPortalConfiguration('portal_container_type_list')
435

436 437 438 439 440
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalContainerLineTypeList')
    def getPortalContainerLineTypeList(self):
      """
        Return container line types.
      """
441
      return self._getPortalGroupedTypeList('container_line') or self._getPortalConfiguration('portal_container_line_type_list')
442

443 444 445 446 447
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalItemTypeList')
    def getPortalItemTypeList(self):
      """
        Return item types.
      """
448
      return self._getPortalGroupedTypeList('item') or self._getPortalConfiguration('portal_item_type_list')
449 450 451 452 453 454

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalDiscountTypeList')
    def getPortalDiscountTypeList(self):
      """
        Return discount types.
      """
455
      return self._getPortalGroupedTypeList('discount') or self._getPortalConfiguration('portal_discount_type_list')
456 457 458 459 460 461

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalAlarmTypeList')
    def getPortalAlarmTypeList(self):
      """
        Return alarm types.
      """
462
      return self._getPortalGroupedTypeList('alarm') or self._getPortalConfiguration('portal_alarm_type_list')
463 464 465 466 467 468

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalPaymentConditionTypeList')
    def getPortalPaymentConditionTypeList(self):
      """
        Return payment condition types.
      """
469
      return self._getPortalGroupedTypeList('payment_condition') or self._getPortalConfiguration('portal_payment_condition_type_list')
470 471 472 473 474 475

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalBalanceTransactionLineTypeList')
    def getPortalBalanceTransactionLineTypeList(self):
      """
        Return balance transaction line types.
      """
476
      return self._getPortalGroupedTypeList('balance_transaction_line') or self._getPortalConfiguration('portal_balance_transaction_line_type_list')
477 478 479 480 481 482

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalCurrentInventoryStateList')
    def getPortalCurrentInventoryStateList(self):
      """
        Return current inventory states.
      """
483
      return self._getPortalGroupedStateList('current_inventory') or self._getPortalConfiguration('portal_current_inventory_state_list')
484 485 486 487 488 489

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalDraftOrderStateList')
    def getPortalDraftOrderStateList(self):
      """
        Return draft order states.
      """
490
      return self._getPortalGroupedStateList('draft_order') or self._getPortalConfiguration('portal_draft_order_state_list')
491 492 493 494 495 496

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalPlannedOrderStateList')
    def getPortalPlannedOrderStateList(self):
      """
        Return planned order states.
      """
497
      return self._getPortalGroupedStateList('planned_order') or self._getPortalConfiguration('portal_planned_order_state_list')
498 499 500 501 502 503

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalReservedInventoryStateList')
    def getPortalReservedInventoryStateList(self):
      """
        Return reserved inventory states.
      """
504
      return self._getPortalGroupedStateList('reserved_inventory') or self._getPortalConfiguration('portal_reserved_inventory_state_list')
505 506 507 508 509 510

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalFutureInventoryStateList')
    def getPortalFutureInventoryStateList(self):
      """
        Return future inventory states.
      """
511
      return self._getPortalGroupedStateList('future_inventory') or self._getPortalConfiguration('portal_future_inventory_state_list')
512 513 514 515 516 517

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalColumnBaseCategoryList')
    def getPortalColumnBaseCategoryList(self):
      """
        Return column base categories.
      """
518
      return self._getPortalGroupedCategoryList('column') or self._getPortalConfiguration('portal_column_base_category_list')
519 520 521 522 523 524

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalLineBaseCategoryList')
    def getPortalLineBaseCategoryList(self):
      """
        Return line base categories.
      """
525
      return self._getPortalGroupedCategoryList('line') or self._getPortalConfiguration('portal_line_base_category_list')
526 527 528 529 530 531

    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalTabBaseCategoryList')
    def getPortalTabBaseCategoryList(self):
      """
        Return tab base categories.
      """
532
      return self._getPortalGroupedCategoryList('tab') or self._getPortalConfiguration('portal_tab_base_category_list')
533

534 535 536 537
    def getPortalDefaultGapRoot(self):
      """
        Return the Accounting Plan to use by default (return the root node)
      """
538 539 540
      LOG('ERP5Site', 0, 'getPortalDefaultGapRoot is deprecated; use portal_preferences.getPreferredAccountingTransactionGap instead.')

      return self.portal_preferences.getPreferredAccountingTransactionGap() or self._getPortalConfiguration('portal_default_gap_root')
541

542
    def getPortalAccountingMovementTypeList(self) :
543 544 545
      """
        Return accounting movement type list.
      """
546
      return self._getPortalGroupedTypeList('accounting_movement') or self._getPortalConfiguration('portal_accounting_movement_type_list')
547

548
    def getPortalAssignmentBaseCategoryList(self):
549
      """
550 551
        Return List of category values to generate security groups.
      """
552 553 554 555 556 557 558
      ### Here is the filter patch waiting bug #124 to be corrected
      category_list = self._getPortalGroupedCategoryList('assignment') or self._getPortalConfiguration('portal_assignment_base_category_list')
      clean_list = []
      for cat in category_list:
        if cat.find("_btsave") == -1:
          clean_list.append(cat)
      return clean_list
559

560 561 562 563 564 565 566
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalReferenceCurrencyID')
    def getPortalReferenceCurrencyID(self):
      """
        Return the currency used as a reference for banking transaction.
      """
      return self._getPortalConfiguration('portal_reference_currency_id')

567 568 569
    security.declareProtected(Permissions.AccessContentsInformation, 'getDefaultModuleId')
    def getDefaultModuleId(self, portal_type):
      """
570
        Return default module id where a object with portal_type can
Romain Courteaud's avatar
Romain Courteaud committed
571
        be created.
572
      """
Romain Courteaud's avatar
Romain Courteaud committed
573
      # Very dummy method, but it works with today name convention.
574 575 576 577 578
      module_name = portal_type.lower().replace(' ','_')
      portal_object = self
      if not hasattr(portal_object, module_name):
        module_name += '_module'
        if not hasattr(portal_object, module_name):
Romain Courteaud's avatar
Romain Courteaud committed
579 580 581
          LOG('ERP5Site, getDefaultModuleId', 0,
              'Unable to find default module for portal_type: %s' % \
                  portal_type)
582 583
          raise ValueError, 'Unable to find module for portal_type: %s' % \
                            portal_type
584 585 586 587 588 589 590 591 592
      return module_name

    security.declareProtected(Permissions.AccessContentsInformation, 'getDefaultModule')
    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)

593 594 595 596 597 598 599
    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'
600
      if portal_type is None:
601 602 603 604 605 606 607 608 609 610
        raise ValueError, 'The portal_type should not be None'
      self.portal_types.constructContent(type_name=portal_type,
                                         container=self,
                                         id=id,
                                         ) # **kw) removed due to CMF bug
      new_instance = self[id]
      if kw is not None: new_instance._edit(force_update=1, **kw)
      if immediate_reindex: new_instance.immediateReindexObject()
      return new_instance

611 612 613 614 615 616
    def log(self,description,content):
      """
      Put a log message
      """
      LOG(description,0,content)

617

Jean-Paul Smets's avatar
Jean-Paul Smets committed
618 619 620 621 622 623
Globals.InitializeClass(ERP5Site)

class ERP5Generator(PortalGenerator):

    klass = ERP5Site

624 625 626 627 628 629 630
    def getBootstrapDirectory(self):
        """
          Return the name of the bootstrap directory
        """
        product_path = package_home(globals())
        return os.path.join(product_path, 'bootstrap')

631 632 633
    def create(self, parent, id, create_userfolder,
               erp5_sql_connection_type, erp5_sql_connection_string,
               cmf_activity_sql_connection_type,cmf_activity_sql_connection_string,
Sebastien Robin's avatar
Sebastien Robin committed
634
               reindex=1,**kw):
635
        LOG('setupTools, create',0,kw)
636 637
        id = str(id)
        portal = self.klass(id=id)
Sebastien Robin's avatar
Sebastien Robin committed
638 639
        if reindex==0:
          setattr(portal,'isIndexable',0)
640 641 642
        parent._setObject(id, portal)
        # Return the fully wrapped object.
        p = parent.this()._getOb(id)
643 644 645 646
        p._setProperty('erp5_sql_connection_type', erp5_sql_connection_type, 'string')
        p._setProperty('erp5_sql_connection_string', erp5_sql_connection_string, 'string')
        p._setProperty('cmf_activity_sql_connection_type', cmf_activity_sql_connection_type, 'string')
        p._setProperty('cmf_activity_sql_connection_string', cmf_activity_sql_connection_string, 'string')
647
        p._setProperty('management_page_charset', 'UTF-8', 'string') # XXX hardcoded charset
648
        self.setup(p, create_userfolder,**kw)
649 650
        return p

651 652 653 654 655 656 657 658 659 660 661
    def setupLastTools(self, p,**kw):
        """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
        """
        # Add Activity Tool
        LOG('setupTools, kw',0,kw)
        if kw.has_key('create_activities') and int(kw['create_activities'])==1:
          addTool = p.manage_addProduct['CMFActivity'].manage_addTool
          addTool('CMF Activity Tool', None) # Allow user to select active/passive

662
    def setupTools(self, p,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
663
        """Set up initial tools"""
664

665 666
        if not 'portal_actions' in p.objectIds():
          PortalGenerator.setupTools(self, p)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
667

668 669 670 671
        # It is better to remove portal_catalog which is ZCatalog as soon as possible,
        # because the API is not the completely same as ERP5Catalog, and ZCatalog is
        # useless for ERP5 after all.
        p._delObject('portal_catalog')
672

Yoshinori Okuji's avatar
Yoshinori Okuji committed
673 674 675 676
        # Add CMF Report Tool
        addTool = p.manage_addProduct['CMFReportTool'].manage_addTool
        addTool('CMF Report Tool', None)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
677 678 679 680 681 682
        # Add ERP5 Tools
        addTool = p.manage_addProduct['ERP5'].manage_addTool
        addTool('ERP5 Categories', None)
        addTool('ERP5 Rule Tool', None)
        addTool('ERP5 Id Tool', None)
        addTool('ERP5 Simulation Tool', None)
683
        addTool('ERP5 Template Tool', None)
684
        addTool('ERP5 Alarm Tool', None)
685
        addTool('ERP5 Domain Tool', None)
686
        addTool('ERP5 Delivery Tool', None)
687
        addTool('ERP5 Order Tool', None)
688 689 690

        # Add ERP5Type Tools
        addTool = p.manage_addProduct['ERP5Type'].manage_addTool
691 692 693 694
        if allowClassTool():
          addTool('ERP5 Class Tool', None)
        else:
          addTool('ERP5 Dummy Class Tool', None)
695

Jean-Paul Smets's avatar
Jean-Paul Smets committed
696 697 698 699
        # Add ERP5 SQL Catalog Tool
        addTool = p.manage_addProduct['ERP5Catalog'].manage_addTool
        addTool('ERP5 Catalog', None)
        # Add Default SQL connection
700
        if p.erp5_sql_connection_type == 'Z MySQL Database Connection':
Sebastien Robin's avatar
Sebastien Robin committed
701
          addSQLConnection = p.manage_addProduct['ZSQLMethods'].manage_addZMySQLConnection
702 703 704 705 706 707 708
          addSQLConnection('erp5_sql_connection', 'ERP5 SQL Server Connection', p.erp5_sql_connection_string)
        elif p.erp5_sql_connection_type == 'Z Gadfly':
          pass
        if p.cmf_activity_sql_connection_type == 'Z MySQL Database Connection':
          addSQLConnection = p.manage_addProduct['ZSQLMethods'].manage_addZMySQLConnection
          addSQLConnection('cmf_activity_sql_connection', 'CMF Activity SQL Server Connection', p.cmf_activity_sql_connection_string)
        elif p.cmf_activity_sql_connection_type == 'Z Gadfly':
709
          pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
710 711
        # Create default methods in Catalog XXX
        portal_catalog = getToolByName(p, 'portal_catalog')
712
        portal_catalog.addDefaultSQLMethods('erp5_mysql')
713

714 715
        # Clear Catalog
        portal_catalog.manage_catalogClear()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
716

717
        # Add ERP5Form Tools
Jean-Paul Smets's avatar
Jean-Paul Smets committed
718 719
        addTool = p.manage_addProduct['ERP5Form'].manage_addTool
        addTool('ERP5 Selections', None)
720
        addTool('ERP5 Preference Tool', None)
721

Jean-Paul Smets's avatar
Jean-Paul Smets committed
722 723 724 725
        # Add ERP5SyncML Tools
        addTool = p.manage_addProduct['ERP5SyncML'].manage_addTool
        addTool('ERP5 Synchronizations', None)

726
        # Add Message Catalog
Sebastien Robin's avatar
Sebastien Robin committed
727 728 729 730 731 732
        #if 'Localizer' in p.objectIds():
          #p._delObject('Localizer') # Why delete it, we should keep for ERP5/CPS
        if not 'Localizer' in p.objectIds():
          #p._delObject('Localizer') # Why delete it, we should keep for ERP5/CPS
          addLocalizer = p.manage_addProduct['Localizer'].manage_addLocalizer
          addLocalizer('', ('en',))
733 734
        localizer = getToolByName(p, 'Localizer')
        addMessageCatalog = localizer.manage_addProduct['Localizer'].manage_addMessageCatalog
Sebastien Robin's avatar
Sebastien Robin committed
735 736
        if 'default' in localizer.objectIds():
          localizer.manage_delObjects('default')
737 738 739
        addMessageCatalog('default', 'ERP5 Localized Messages', ('en',))
        addMessageCatalog('erp5_ui', 'ERP5 Localized Interface', ('en',))
        addMessageCatalog('erp5_content', 'ERP5 Localized Content', ('en',))
740

Jean-Paul Smets's avatar
Jean-Paul Smets committed
741
        # Add Translation Service
742 743
        if 'translation_service' in p.objectIds():
          p._delObject('translation_service')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
744
        p.manage_addProduct['TranslationService'].addPlacefulTranslationService('translation_service')
745 746 747
        p.translation_service.manage_setDomainInfo(domain_0=None, path_0='Localizer/default')
        p.translation_service.manage_addDomainInfo(domain='ui', path='Localizer/erp5_ui')
        p.translation_service.manage_addDomainInfo(domain='content', path='Localizer/erp5_content')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
748 749


750 751 752 753 754 755 756 757 758 759 760 761
    def setupMembersFolder(self, p):
        """
          ERP5 is not a CMS
        """
        pass
        #from Products.CMFDefault.MembershipTool import MembershipTool
        #addFolder(p, id=MembershipTool.membersfolder_id, title='ERP5 Members')
        #member_folder = p[MembershipTool.membersfolder_id]
        #member_folder.manage_addProduct['OFSP'].manage_addDTMLMethod(
        #    'index_html', 'Member list', '<dtml-return roster>')

    def setupFrontPage(self, p):
762 763 764 765 766 767 768
        text = """<span metal:define-macro="body">

  <span tal:condition="python: not here.portal_membership.isAnonymousUser()">
    <br/>
    <br/>
    <br/>
    <br/>
769 770
    <h2 align="center" i18n:translate="" i18n:domain="ui">
      Welcome to ERP5
771 772 773 774 775 776 777
    </h2>
    <table border="1" align="center">
      <tr tal:define="module_list python:here.ERP5Site_getModuleItemList();
                      module_len python:len(module_list);
                      col_size python:16;
                      col_len python:(module_len + col_size) / col_size">
        <td>
778
          <a href="http://www.erp5.org"><img src="images/erp5_logo.png" alt="ERP5 Logo" /></a>
779 780 781 782 783 784
        </td>
        <tal:block tal:repeat="col_no python:range(col_len)">
          <td valign="top" class="ModuleShortcut">
            <tal:block tal:repeat="module python:module_list[col_size*col_no:min(col_size*(col_no+1),module_len)] ">
              <p>
                <a href="person"
785 786
                  tal:content="python: module[0]"
                  tal:attributes="href python: module[1] + '/view'">
787 788 789 790 791 792 793 794 795 796 797 798 799
                  Person
                </a>
              </p>
            </tal:block>
          </td>
        </tal:block>
      </tr>
    </table>
  </span>

  <span tal:condition="python: here.portal_membership.isAnonymousUser()">
    <p tal:define="dummy python:request.RESPONSE.redirect('%s/login_form' % here.absolute_url())"/>
  </span>
800 801 802 803 804 805 806 807 808 809 810

</span>
"""
        p.manage_addProduct['PageTemplates'].manage_addPageTemplate(
                  'local_pt', title='ERP5 Front Page', text=text)

    def setupDefaultSkins(self, p):
        from Products.CMFCore.DirectoryView import addDirectoryViews
        from Products.CMFDefault import cmfdefault_globals
        from Products.CMFActivity import cmfactivity_globals
        ps = getToolByName(p, 'portal_skins')
811 812 813
        # Do not use filesystem skins for ERP5 any longer.
        # addDirectoryViews(ps, 'skins', globals())
        # addDirectoryViews(ps, path.join('skins','pro'), globals())
814 815 816
        addDirectoryViews(ps, 'skins', cmfdefault_globals)
        addDirectoryViews(ps, 'skins', cmfactivity_globals)
        ps.manage_addProduct['OFSP'].manage_addFolder(id='external_method')
817
        ps.manage_addProduct['OFSP'].manage_addFolder(id='custom')
818
        # set the 'custom' layer a high priority, so it remains the first
819 820 821
        # layer when installing new business templates
        ps['custom'].manage_addProperty(
            "business_template_skin_layer_priority", 100.0, "float")
822
        ps.addSkinSelection('View', 'custom, external_method, activity, '
823
                                  + 'zpt_content, zpt_generic,'
824
                                  + 'zpt_control, content, generic, control, Images',
825
                            make_default=1)
826 827 828
        ps.addSkinSelection('Print', 'custom, external_method, activity, '
                                  + 'zpt_content, zpt_generic,'
                                  + 'zpt_control, content, generic, control, Images',
Romain Courteaud's avatar
Romain Courteaud committed
829 830 831 832
                            make_default=0)
        ps.addSkinSelection('CSV', 'custom, external_method, activity, '
                                  + 'zpt_content, zpt_generic,'
                                  + 'zpt_control, content, generic, control, Images',
833
                            make_default=0)
834 835 836 837
        p.setupCurrentSkin()

    def setupWorkflow(self, p):
        """
838
          Set up workflows for business templates
839
        """
840 841 842 843 844 845 846 847 848 849 850 851 852 853
        tool = getToolByName(p, 'portal_workflow', None)
        if tool is None:
            return
        bootstrap_dir = self.getBootstrapDirectory()
        business_template_building_workflow = os.path.join(bootstrap_dir,
                                                           'business_template_building_workflow.xml')
        tool._importObjectFromFile(business_template_building_workflow)
        business_template_installation_workflow = os.path.join(bootstrap_dir,
                                                               'business_template_installation_workflow.xml')
        tool._importObjectFromFile(business_template_installation_workflow)

        tool.setChainForPortalTypes( ( 'Business Template', ),
                                     ( 'business_template_building_workflow',
                                       'business_template_installation_workflow' ) )
854 855
        pass

Sebastien Robin's avatar
Sebastien Robin committed
856
    def setupIndex(self, p,**kw):
857 858 859 860
        from Products.CMFDefault.MembershipTool import MembershipTool
        # Make sure all tools and folders have been indexed
        portal_catalog = p.portal_catalog
        portal_catalog.manage_catalogClear()
Sebastien Robin's avatar
Sebastien Robin committed
861 862
        if kw.has_key('reindex') and kw['reindex']==0:
          return
863 864 865
        #portal_catalog.reindexObject(p)
        #portal_catalog.reindexObject(p.portal_templates)
        #portal_catalog.reindexObject(p.portal_categories)
866 867
        # portal_catalog.reindexObject(p.portal_activities)
        #p[MembershipTool.membersfolder_id].immediateReindexObject()
868 869 870 871
        skins_tool = getToolByName(p, 'portal_skins', None)
        if skins_tool is None:
          return
        skins_tool["erp5_core"].ERP5Site_reindexAll()
872

873
    def setupUserFolder(self, p):
874
        # We use if possible ERP5Security, then NuxUserGroups
875
        try:
876
          from Products import ERP5Security
877
          from Products import PluggableAuthService
878 879 880 881 882 883 884
        except ImportError:
          ERP5Security = None
          try:
            import Products.NuxUserGroups
            withnuxgroups = 1
          except:
            withnuxgroups = 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
885
        if ERP5Security is not None:
886 887
          # Use Pluggable Auth Service instead of the standard acl_users.
          p.manage_addProduct['PluggableAuthService'].addPluggableAuthService()
888 889 890 891
          # Add legacy ZODB support
          p.acl_users.manage_addProduct['PluggableAuthService'].addZODBUserManager('zodb_users')
          p.acl_users.manage_addProduct['PluggableAuthService'].addZODBGroupManager('zodb_groups')
          p.acl_users.manage_addProduct['PluggableAuthService'].addZODBRoleManager('zodb_roles')
892 893 894 895
          # Add CMF Portal Roles
          #XXX Maybe it will no longer be required once PAS is the standard
          p.acl_users.zodb_roles.addRole('Member')
          p.acl_users.zodb_roles.addRole('Reviewer')
896 897 898 899 900 901 902
          # Register ZODB Interface
          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'))
903 904 905 906
          # Add ERP5UserManager
          p.acl_users.manage_addProduct['ERP5Security'].addERP5UserManager('erp5_users')
          p.acl_users.manage_addProduct['ERP5Security'].addERP5GroupManager('erp5_groups')
          p.acl_users.manage_addProduct['ERP5Security'].addERP5RoleManager('erp5_roles')
907
          # Register ERP5UserManager Interface
908
          p.acl_users.erp5_users.manage_activateInterfaces(('IAuthenticationPlugin',
909 910 911
                                                            'IUserEnumerationPlugin',))
          p.acl_users.erp5_groups.manage_activateInterfaces(('IGroupsPlugin',))
          p.acl_users.erp5_roles.manage_activateInterfaces(('IRolesPlugin',))
912 913
        elif withnuxgroups:
          # NuxUserGroups user folder
914
          p.manage_addProduct['NuxUserGroups'].addUserFolderWithGroups()
915 916
        else:
          # Standard user folder
917 918
          PortalGenerator.setupUserFolder(self, p)

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
    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'),
        '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'),
        'List undoable changes'        : ('Manager', 'Member'),
        'Manage properties'            : ('Manager', 'Owner'),
        'Modify portal content'        : ('Manager', 'Owner'),
        'Reply to item'                : ('Manager', 'Member'),
        'Review portal content'        : ('Manager', 'Reviewer'),
        'Search ZCatalog'              : ('Manager', 'Member'),
        'Set own password'             : ('Manager', 'Member'),
        'Set own properties'           : ('Manager', 'Member'),
        'Undo changes'                 : ('Manager', 'Owner'),
        'View'                         : ('Manager', 'Member', 'Owner', 'Anonymous'),
        '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)

950 951
    def setup(self, p, create_userfolder,**kw):
        self.setupTools(p,**kw)
952 953 954 955 956 957 958 959 960
        self.setupMailHost(p)
        if int(create_userfolder) != 0:
            self.setupUserFolder(p)
        self.setupCookieAuth(p)
        self.setupRoles(p)
        self.setupPermissions(p)
        self.setupDefaultSkins(p)

        # Initialize Activities
961 962 963 964 965 966 967 968
        portal_skins = p.portal_skins
        try:
          portal_skins.activity.SQLDict_dropMessageTable()
          portal_skins.activity.SQLQueue_dropMessageTable()
        except:
          pass
        portal_skins.activity.SQLDict_createMessageTable()
        portal_skins.activity.SQLQueue_createMessageTable()
969

970 971
        self.setupLastTools(p,**kw)

972 973 974 975 976
        # Finish setup
        self.setupMembersFolder(p)

        # ERP5 Design Choice is that all content should be user defined
        # Content is disseminated through business templates
977
        self.setupBusinessTemplate(p)
978 979 980 981 982

        self.setupMimetypes(p)
        self.setupWorkflow(p)
        self.setupFrontPage(p)

Sebastien Robin's avatar
Sebastien Robin committed
983
        self.setupERP5Core(p,**kw)
984

985 986
        # Make sure tools are cleanly indexed with a uid before creating children
        # XXX for some strange reason, member was indexed 5 times
Sebastien Robin's avatar
Sebastien Robin committed
987
        self.setupIndex(p,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
988

989 990 991 992
    def setupBusinessTemplate(self,p):
        """
        Install the portal_type of Business Template
        """
993
        from Products.ERP5Type.ERP5Type import ERP5TypeInformation
994
        from Products.ERP5.Document.BusinessTemplate import BusinessTemplate
995 996 997 998 999 1000 1001
        tool = getToolByName(p, 'portal_types', None)
        if tool is None:
          return
        t = BusinessTemplate.factory_type_information
        ti = apply(ERP5TypeInformation, (), t)
        tool._setObject(t['id'], ti)

Sebastien Robin's avatar
Sebastien Robin committed
1002
    def setupERP5Core(self,p,**kw):
1003 1004 1005 1006 1007 1008 1009
        """
        Install the core part of ERP5
        """
        template_tool = getToolByName(p, 'portal_templates', None)
        if template_tool is None:
          return
        bootstrap_dir = self.getBootstrapDirectory()
1010 1011 1012
        template = os.path.join(bootstrap_dir, 'erp5_core')
        if not os.path.exists(template):
          template = os.path.join(bootstrap_dir, 'erp5_core.bt5')
1013

1014 1015
        id = template_tool.generateNewId()
        template_tool.download(template, id=id)
Sebastien Robin's avatar
Sebastien Robin committed
1016
        template_tool[id].install(**kw)
1017

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1018
# Patch the standard method
Sebastien Robin's avatar
Sebastien Robin committed
1019
CMFSite.getPhysicalPath = ERP5Site.getPhysicalPath