ERP5Site.py 19.2 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 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 28
from Acquisition import aq_base, aq_parent, aq_inner, aq_acquire
import ERP5Globals
29
from Products.ERP5Type.Cache import CachingMethod
Jean-Paul Smets's avatar
Jean-Paul Smets committed
30 31 32 33 34 35 36 37 38 39

from zLOG import LOG

import os

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

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

# ERP5Site Constructor
def manage_addERP5Site(self, id, title='ERP5', description='',
                         create_userfolder=1,
                         email_from_address='postmaster@localhost',
                         email_from_name='Portal Administrator',
48 49 50 51
                         validate_email=0,
                         sql_connection_type='Z MySQL Database Connection',
                         sql_connection_string='test test',
                         RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
52 53 54 55 56 57
    '''
    Adds a portal instance.
    '''
    gen = ERP5Generator()
    from string import strip
    id = strip(id)
58
    p = gen.create(self, id, create_userfolder,sql_connection_type,sql_connection_string)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
59 60 61 62 63 64
    gen.setupDefaultProperties(p, title, description,
                               email_from_address, email_from_name,
                               validate_email)
    if RESPONSE is not None:
        RESPONSE.redirect(p.absolute_url() + '/finish_portal_construction')

Jean-Paul Smets's avatar
Jean-Paul Smets committed
65
class ERP5Site ( CMFSite, FolderMixIn ):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    """
        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
87
    security.declareProtected(Permissions.View, 'view')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
88 89 90 91 92 93 94
    def view(self):
        """
          Returns the default view.
          Implemented for consistency
        """
        return self.index_html()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
95 96 97 98
    security.declareProtected(Permissions.AccessContentsInformation, 'getPortalObject')
    def getPortalObject(self):
      return self

Jean-Paul Smets's avatar
Jean-Paul Smets committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    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
119 120 121 122 123 124
    # 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
125
    security.declareProtected(Permissions.View, 'setLastId')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
126 127 128
    def setLastId(self, id):
      self.last_id = id

Jean-Paul Smets's avatar
Jean-Paul Smets committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    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
      method = self.portal_catalog.z_search_folder
      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.declareProtected(Permissions.AccessContentsInformation, 'getMovementTypeList')
    def getMovementTypeList(self):
      """
        Returns possible movements types
      """
      return ERP5Globals.movement_type_list

Yoshinori Okuji's avatar
Yoshinori Okuji committed
164
    security.declarePublic('getModuleList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
165 166 167 168 169
    def getModuleList(self):
      """
         Return a list of modules - result dependent on user - result is translated and cached
      """
      # Return Cache
170 171 172 173 174 175 176 177
      def getModuleListFor(user):
        result = []
        for module in self.objectValues('ERP5 Folder'):
          # XXX Restrict access to modules to valid users
          result.append({'url': module.absolute_url(), 'id': module.getId(), 'title': self.gettext(module.getTitle())})
        result.sort(lambda x,y: cmp(x['title'], y['title']))
        return result

Jean-Paul Smets's avatar
Jean-Paul Smets committed
178
      user = str(_getAuthenticatedUser(self))
179 180 181 182 183 184
      method = CachingMethod(getModuleListFor, id='getModuleList', cache_duration=300)
      return method(user)

    #getModuleList = CachingMethod(getModuleList, cache_duration=300, request_keys=('AUTHENTICATED_USER', 'time'))


Jean-Paul Smets's avatar
Jean-Paul Smets committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    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])
      sorted_global_actions.append({'title': 'Other', 'disabled': 1})
      sorted_global_actions.extend(other_global_actions)
      return sorted_global_actions

214 215 216 217 218 219 220 221
    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)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
222 223 224 225 226 227
Globals.InitializeClass(ERP5Site)

class ERP5Generator(PortalGenerator):

    klass = ERP5Site

228 229 230 231 232 233 234 235 236 237 238
    def create(self, parent, id, create_userfolder, sql_connection_type, sql_connection_string):
        id = str(id)
        portal = self.klass(id=id)
        parent._setObject(id, portal)
        # Return the fully wrapped object.
        p = parent.this()._getOb(id)
        p._setProperty('sql_connection_type', sql_connection_type, 'string')
        p._setProperty('sql_connection_string', sql_connection_string, 'string')
        self.setup(p, create_userfolder)
        return p

Jean-Paul Smets's avatar
Jean-Paul Smets committed
239 240 241 242 243 244 245 246 247 248 249 250
    def setupTools(self, p):
        """Set up initial tools"""

        PortalGenerator.setupTools(self, p)

        # Add ERP5 Tools
        addTool = p.manage_addProduct['ERP5'].manage_addTool
        #print "addTool = %s" % str(addTool)
        addTool('ERP5 Categories', None)
        addTool('ERP5 Rule Tool', None)
        addTool('ERP5 Id Tool', None)
        addTool('ERP5 Simulation Tool', None)
251 252 253 254
        addTool('ERP5 Template Tool', None)

        # Add Activity Tool
        addTool = p.manage_addProduct['CMFActivity'].manage_addTool
255
        addTool('CMF Activity Tool', None) # Allow user to select active/passive
Jean-Paul Smets's avatar
Jean-Paul Smets committed
256 257 258 259 260 261

        # Add ERP5 SQL Catalog Tool
        addTool = p.manage_addProduct['ERP5Catalog'].manage_addTool
        p._delObject('portal_catalog')
        addTool('ERP5 Catalog', None)
        # Add Default SQL connection
262 263 264 265 266
        if p.sql_connection_type == 'Z MySQL Database Connection':
          addSQLConnectioon = p.manage_addProduct['ZSQLMethods'].manage_addZMySQLConnection
          addSQLConnectioon('erp5_sql_connection', 'ERP5 SQL Server Connection', p.sql_connection_string)
        elif p.sql_connection_type == 'Z Gadfly':
          pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        # Create default methods in Catalog XXX
        portal_catalog = getToolByName(p, 'portal_catalog')
        addSQLMethod = portal_catalog.manage_addProduct['ZSQLMethods'].manage_addZSQLMethod
        product_path = package_home(globals())
        zsql_dir = os.path.join(product_path, 'sql')
        #print ("zsql_dir = %s" % str(zsql_dir))
        # Iterate over the sql directory. Add all sql methods in that directory.
        for entry in os.listdir(zsql_dir):
          if len(entry) > 5 and entry[-5:] == '.zsql':
            id = entry[:-5]
            # Create an empty SQL method first.
            addSQLMethod(id = id, title = '', connection_id = '', arguments = '', template = '')
            sql_method = getattr(portal_catalog, id)
            # Set parameters of the SQL method from the contents of a .zsql file.
            sql_method.fromFile(os.path.join(zsql_dir, entry))
        # Setup ZSQLCaralog properties
        portal_catalog.sql_catalog_object = ('z0_catalog_object', 'z_catalog_category', 'z_catalog_movement',
                                             'z_catalog_roles_and_users', 'z_catalog_stock', 'z_catalog_subject',)
        portal_catalog.sql_uncatalog_object = ('z0_uncatalog_category', 'z0_uncatalog_movement', 'z0_uncatalog_roles_and_users',
                                               'z0_uncatalog_stock', 'z0_uncatalog_subject', 'z_uncatalog_object', )
        portal_catalog.sql_update_object = ('z0_uncatalog_category', 'z0_uncatalog_movement', 'z0_uncatalog_roles_and_users',
                                            'z0_uncatalog_stock', 'z0_uncatalog_subject', 'z_catalog_category',
                                            'z_catalog_movement', 'z_catalog_roles_and_users', 'z_catalog_stock', 'z_catalog_subject',
                                            'z_update_object', )
        portal_catalog.sql_clear_catalog = ('z0_drop_catalog', 'z0_drop_category', 'z0_drop_movement', 'z0_drop_roles_and_users',
                                            'z0_drop_stock', 'z0_drop_subject', 'z_create_catalog',
                                            'z_create_category', 'z_create_movement', 'z_create_roles_and_users',
                                            'z_create_stock', 'z_create_subject', )
        portal_catalog.sql_search_results = 'z_search_results'
        portal_catalog.sql_count_results = 'z_count_results'
        portal_catalog.sql_getitem_by_path = 'z_getitem_by_path'
        portal_catalog.sql_getitem_by_uid = 'z_getitem_by_uid'
299
        portal_catalog.sql_catalog_schema = 'z_show_columns'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
300 301 302 303 304
        portal_catalog.sql_unique_values = 'z_unique_values'
        portal_catalog.sql_catalog_paths = 'z_catalog_paths'
        portal_catalog.sql_catalog_keyword_search_keys = ('Description', 'SearchableText', 'Title', )
        portal_catalog.sql_catalog_full_text_search_keys = ('Description', 'SearchableText', 'Title', )
        portal_catalog.sql_catalog_request_keys = ()
305 306 307 308 309 310
        portal_catalog.sql_search_result_keys = ('catalog.*',)
        portal_catalog.sql_search_tables = ('catalog', 'category', 'roles_and_users', 'movement', 'subject', )
        portal_catalog.sql_catalog_tables = 'z_show_tables'

        # Clear Catalog
        portal_catalog.manage_catalogClear()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
311 312 313 314 315 316 317 318 319

        # Add Selection Tool
        addTool = p.manage_addProduct['ERP5Form'].manage_addTool
        addTool('ERP5 Selections', None)

        # Add ERP5SyncML Tools
        addTool = p.manage_addProduct['ERP5SyncML'].manage_addTool
        addTool('ERP5 Synchronizations', None)

320 321 322 323 324 325
        # Add Message Catalog
        addMessageCatalog = p.manage_addProduct['Localizer'].manage_addMessageCatalog
        addMessageCatalog('gettext', 'ERP5 Localized Messages', ('en'))
        addMessageCatalog('translated_ui', 'ERP5 Localized Interface', ('en'))
        addMessageCatalog('translated_content', 'ERP5 Localized Content', ('en'))

Jean-Paul Smets's avatar
Jean-Paul Smets committed
326 327
        # Add Translation Service
        p.manage_addProduct['TranslationService'].addPlacefulTranslationService('translation_service')
328 329 330
        p.translation_service.manage_setDomainInfo(domain_0=None, path_0='gettext')
        p.translation_service.manage_addDomainInfo(domain='ui', path='translated_ui')
        p.translation_service.manage_addDomainInfo(domain='content', path='translated_content')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
331 332


333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    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):
        text = """<span  metal:define-macro="body">
<span tal:condition="python: not here.portal_membership.isAnonymousUser()">
<br/>
<br/>
<br/>
<br/>
<h3 align=center>Welcome to your new information system</h3>
<table border=1 align=center>
<tr tal:define="module_list python:here.objectValues('ERP5 Folder');
                dummy python:module_list.sort(lambda x,y: cmp(x.getTitle(), y.getTitle()));
                module_len python:len(module_list);
                col_size python:16;
                col_len python:module_len / col_size">
  <td>
   <img src="erp5_logo.png" alt="ERP5 Logo" />
  </td>
  <td tal:repeat="col_no python:range(col_len)" valign="top" class="ModuleShortcut">
    <p tal:repeat="module python:module_list[col_size*col_no:min(col_size*(col_no+1),module_len)] "><a href="composant"
       tal:content="module/title"
       tal:attributes="href module/id">Composants</a></p>
  </td>
</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>
</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')
        addDirectoryViews(ps, 'skins', globals())
        addDirectoryViews(ps, 'skins', cmfdefault_globals)
        addDirectoryViews(ps, 'skins', cmfactivity_globals)
        ps.manage_addProduct['OFSP'].manage_addFolder(id='external_method')
        ps.manage_addProduct['OFSP'].manage_addFolder(id='local_pro')
        ps.manage_addProduct['OFSP'].manage_addFolder(id='local_erp5')
389 390
        ps.manage_addProduct['OFSP'].manage_addFolder(id='local_trade')
        ps.manage_addProduct['OFSP'].manage_addFolder(id='local_mrp')
391 392
        ps.manage_addProduct['OFSP'].manage_addFolder(id='local_list_method')
        ps.addSkinSelection('ERP5', 'local_pro, local_erp5, local_list_method, '
393
                                  + 'external_method, local_trade, local_mrp, pro, erp5, activity, '
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
                                  + 'zpt_topic, zpt_content, zpt_generic,'
                                  + 'zpt_control, topic, content, generic, control, Images',
                            make_default=1)
        p.setupCurrentSkin()

    def setupWorkflow(self, p):
        """
          ERP5 has no default worklow
        """
        pass

    def setupIndex(self, p):
        from Products.CMFDefault.MembershipTool import MembershipTool
        # Make sure all tools and folders have been indexed
        portal_catalog = p.portal_catalog
        portal_catalog.manage_catalogClear()
        portal_catalog.reindexObject(p)
        portal_catalog.reindexObject(p.portal_templates)
        portal_catalog.reindexObject(p.portal_categories)
        # portal_catalog.reindexObject(p.portal_activities)
        #p[MembershipTool.membersfolder_id].immediateReindexObject()

416 417 418 419 420 421 422 423
    def setupUserFolder(self, p):
        try:
          # Use NuxUserGroups instead of the standard acl_users.
          p.manage_addProduct['NuxUserGroups'].manage_addUserFolderWithGroups()
        except:
          # No way.
          PortalGenerator.setupUserFolder(self, p)

424 425 426 427 428 429 430 431 432 433 434
    def setup(self, p, create_userfolder):
        self.setupTools(p)
        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
435 436 437 438 439 440 441 442
        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()
443 444 445 446 447 448 449

        # Finish setup
        self.setupMembersFolder(p)

        # ERP5 Design Choice is that all content should be user defined
        # Content is disseminated through business templates
        from Products.ERP5.Document.BusinessTemplate import BusinessTemplate
Jean-Paul Smets's avatar
Jean-Paul Smets committed
450
        from Products.ERP5Type.Document.Folder import Folder
451 452 453 454 455 456 457 458 459
        self.setupTypes(p, (BusinessTemplate.factory_type_information, Folder.factory_type_information))

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

        # Make sure tools are cleanly indexed with a uid before creating children
        # XXX for some strange reason, member was indexed 5 times
        self.setupIndex(p)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
460 461 462

# Patch the standard method
CMFSite.getPhysicalPath = ERP5Site.getPhysicalPath