BusinessTemplate.py 54.4 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

29
from Globals import Persistent, PersistentMapping
Jean-Paul Smets's avatar
Jean-Paul Smets committed
30
from Acquisition import Implicit
31
from AccessControl.Permission import Permission
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32 33
from AccessControl import ClassSecurityInfo
from Products.CMFCore.utils import getToolByName
34
from Products.CMFCore.WorkflowCore import WorkflowMethod
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
36 37
from Products.ERP5Type.Utils import readLocalPropertySheet, writeLocalPropertySheet, importLocalPropertySheet, removeLocalPropertySheet
from Products.ERP5Type.Utils import readLocalExtension, writeLocalExtension, removeLocalExtension
38
from Products.ERP5Type.Utils import readLocalTest, writeLocalTest, removeLocalTest
39
from Products.ERP5Type.Utils import readLocalDocument, writeLocalDocument, importLocalDocument, removeLocalDocument
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40 41
from Products.ERP5Type.XMLObject import XMLObject
import cStringIO
Yoshinori Okuji's avatar
Yoshinori Okuji committed
42
from Products.ERP5Type.Cache import clearCache
Jean-Paul Smets's avatar
Jean-Paul Smets committed
43 44 45

from zLOG import LOG

46 47
class TemplateConflictError(Exception): pass

48
class BaseTemplateItem(Implicit, Persistent):
49
  """
50
    This class is the base class for all template items.
51
  """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
52

53
  def __init__(self, id_list, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
54
    self.__dict__.update(kw)
55 56 57 58 59 60 61 62 63 64 65 66 67
    self._archive = PersistentMapping()
    for id in id_list:
      if not id: continue
      self._archive[id] = None

  def build(self, context, **kw):
    pass

  def install(self, context, **kw):
    pass

  def uninstall(self, context, **kw):
    pass
68

69 70 71 72
  def trash(self, context, new_item, **kw):
    # trash is quite similar to uninstall.
    return self.uninstall(context, new_item=new_item, trash=1, **kw)

73 74 75
class ObjectTemplateItem(BaseTemplateItem):
  """
    This class is used for generic objects and as a subclass.
76 77
  """

78 79 80 81
  def __init__(self, id_list, tool_id=None, **kw):
    BaseTemplateItem.__init__(self, id_list, tool_id=tool_id, **kw)
    if tool_id is not None:
      id_list = self._archive.keys()
82
      self._archive.clear()
83 84 85 86 87 88 89 90 91 92 93 94 95 96
      for id in id_list:
        self._archive["%s/%s" % (tool_id, id)] = None

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    p = context.getPortalObject()
    for relative_url in self._archive.keys():
      object = p.unrestrictedTraverse(relative_url)
      #if not object.cb_isCopyable():
      #  raise CopyError, eNotSupported % escape(relative_url)
      object = object._getCopy(context)
      self._archive[relative_url] = object
      object.wl_clearLocks()

97
  def _backupObject(self, container, object_id, **kw):
98
    container_ids = container.objectIds()
99 100 101 102 103
    n = 0
    new_object_id = object_id
    while new_object_id in container_ids:
      n = n + 1
      new_object_id = '%s_btsave_%s' % (object_id, n)
104
    LOG('_backupObject', 0, repr((container, object_id, new_object_id)))
105 106 107 108 109 110 111 112 113 114 115 116
    container.manage_renameObject(object_id, new_object_id)

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    portal = context.getPortalObject()
    for relative_url,object in self._archive.items():
      container_path = relative_url.split('/')[0:-1]
      object_id = relative_url.split('/')[-1]
      container = portal.unrestrictedTraverse(container_path)
      #LOG('Installing' , 0, '%s in %s with %s' % (self.id, container.getPhysicalPath(), self.export_string))
      container_ids = container.objectIds()
      if object_id in container_ids:    # Object already exists
117
        self._backupObject(container, object_id)
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
      # Set a hard link
      #if not object.cb_isCopyable():
      #    raise CopyError, eNotSupported % escape(relative_url)
      object = object._getCopy(container)
      container._setObject(object_id, object)
      object = container._getOb(object_id)
      object.manage_afterClone(object)
      object.wl_clearLocks()
      if object.meta_type in ('Z SQL Method',):
        # It is necessary to make sure that the sql connection in this method is valid.
        sql_connection_list = portal.objectIds(spec=('Z MySQL Database Connection',))
        if object.connection_id not in sql_connection_list:
          object.connection_id = sql_connection_list[0]

  def uninstall(self, context, **kw):
    portal = context.getPortalObject()
134
    trash = kw.get('trash', 0)
135 136 137
    for relative_url in self._archive.keys():
      container_path = relative_url.split('/')[0:-1]
      object_id = relative_url.split('/')[-1]
138 139 140 141 142 143 144 145 146 147
      try:
        container = portal.unrestrictedTraverse(container_path)
        if trash:
          self._backupObject(container, object_id)
        else:
          if object_id in container.objectIds():
            container.manage_delObjects([object_id])
      except:
        pass

148 149 150 151 152 153 154 155 156
    BaseTemplateItem.uninstall(self, context, **kw)


class PathTemplateItem(ObjectTemplateItem): pass


class CategoryTemplateItem(ObjectTemplateItem):

  def __init__(self, id_list, **kw):
157 158 159 160 161 162 163 164 165
    ObjectTemplateItem.__init__(self, id_list, **kw)
    self._light_archive = PersistentMapping()
    for id in id_list:
      self._light_archive[id] = None
    tool_id = 'portal_categories'
    id_list = self._archive.keys()
    self._archive.clear()
    for id in id_list:
      self._archive["%s/%s" % (tool_id, id)] = None
166

167 168 169 170 171 172 173 174 175
  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    p = context.getPortalObject()
    category_tool = p.portal_categories
    for relative_url in self._archive.keys():
      category = p.unrestrictedTraverse(relative_url)
      category_id = relative_url.split('/')[-1]
      #if not object.cb_isCopyable():
      #  raise CopyError, eNotSupported % escape(relative_url)
176
      category_copy = category._getCopy(context)
177 178 179 180 181
      include_sub_categories = category.getProperty('business_template_include_sub_categories', 1)
      if not include_sub_categories:
        id_list = category_copy.objectIds()
        if len(id_list) > 0:
          category_copy.manage_delObjects(list(id_list))
182 183
      self._archive[relative_url] = category_copy
      category_copy.wl_clearLocks()
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
      # No store attributes for light install
      mapping = PersistentMapping()
      mapping['id'] = category.getId()
      property_list = PersistentMapping()
      for property in [x for x in category.propertyIds() if x not in ('id','uid')]:
        property_list[property] = category.getProperty(property,evaluate=0)
      mapping['property_list'] = property_list
      #mapping['title'] = category.getTitle()
      self._light_archive[category_id] = mapping

  def install(self, context, light_install = 0, **kw):
    BaseTemplateItem.install(self, context, **kw)
    portal = context.getPortalObject()
    category_tool = portal.portal_categories
    tool_id = self.tool_id
    if light_install==0:
      ObjectTemplateItem.install(self, context, **kw)
    else:
      for category_id in self._light_archive.keys():
        if category_id in category_tool.objectIds():
204
          raise TemplateConflictError, 'the category %s already exists' % category_id
205
        category = category_tool.newContent(portal_type='Base Category',id=category_id)
206 207 208 209
        property_list = self._light_archive[category_id]['property_list']
        for property,value in property_list.items():
          category.setProperty(property,value)

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

class SkinTemplateItem(ObjectTemplateItem):

  def __init__(self, id_list, **kw):
    ObjectTemplateItem.__init__(self, id_list, tool_id='portal_skins', **kw)

  def install(self, context, **kw):
    ObjectTemplateItem.install(self, context, **kw)
    p = context.getPortalObject()
    # It is necessary to make sure that the sql connections in Z SQL Methods are valid.
    sql_connection_list = p.objectIds(spec=('Z MySQL Database Connection',))
    for relative_url in self._archive.keys():
      folder = p.unrestrictedTraverse(relative_url)
      for object in folder.objectValues(spec=('Z SQL Method',)):
        if object.connection_id not in sql_connection_list:
          object.connection_id = sql_connection_list[0]
    # Add new folders into skin paths.
    ps = p.portal_skins
    for skin_name, selection in ps.getSkinPaths():
      new_selection = []
      selection = selection.split(',')
231
      for relative_url, object in self._archive.items():
232
        skin_id = relative_url.split('/')[-1]
233 234 235 236
        selection_list = object.getProperty('business_template_registered_skin_selections', None)
        if selection_list is None or skin_name in selection_list:
          if skin_id not in selection:
            new_selection.append(skin_id)
237 238 239 240 241 242 243 244 245 246 247 248 249 250
      new_selection.extend(selection)
      ps.manage_skinLayers(skinpath = tuple(new_selection), skinname = skin_name, add_skin = 1)

  def uninstall(self, context, **kw):
    # Remove folders from skin paths.
    ps = context.portal_skins
    skin_id_list = [relative_url.split('/')[-1] for relative_url in self._archive.keys()]
    for skin_name, selection in ps.getSkinPaths():
      new_selection = []
      selection = selection.split(',')
      for skin_id in selection:
        if skin_id not in skin_id_list:
          new_selection.append(skin_id)
      ps.manage_skinLayers(skinpath = tuple(new_selection), skinname = skin_name, add_skin = 1)
251

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    ObjectTemplateItem.uninstall(self, context, **kw)


class WorkflowTemplateItem(ObjectTemplateItem):

  def __init__(self, id_list, **kw):
    ObjectTemplateItem.__init__(self, id_list, tool_id='portal_workflow', **kw)


class PortalTypeTemplateItem(ObjectTemplateItem):

  workflow_chain = None

  def _getChainByType(self, context):
    """
    This is used in order to construct the full list
    of mapping between type and list of workflow associated
269
    This is only useful in order to use
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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    portal_workflow.manage_changeWorkflows
    """
    pw = context.portal_workflow
    cbt = pw._chains_by_type
    ti = pw._listTypeInfo()
    types_info = []
    for t in ti:
      id = t.getId()
      title = t.Title()
      if title == id:
        title = None
      if cbt is not None and cbt.has_key(id):
        chain = ', '.join(cbt[id])
      else:
        chain = '(Default)'
      types_info.append({'id': id,
                        'title': title,
                        'chain': chain})
    new_dict = {}
    for item in types_info:
      new_dict['chain_%s' % item['id']] = item['chain']
    default_chain=', '.join(pw._default_chain)
    return (default_chain, new_dict)

  def __init__(self, id_list, **kw):
    kw['tool_id'] = 'portal_types'
    ObjectTemplateItem.__init__(self, id_list, **kw)
    self._workflow_chain_archive = PersistentMapping()

  def build(self, context, **kw):
    ObjectTemplateItem.build(self, context, **kw)
    (default_chain, chain_dict) = self._getChainByType(context)
    for object in self._archive.values():
      portal_type = object.id
      self._workflow_chain_archive[portal_type] = chain_dict['chain_%s' % portal_type]

  def install(self, context, **kw):
    ObjectTemplateItem.install(self, context, **kw)
    # We now need to setup the list of workflows corresponding to
    # each portal type
    (default_chain, chain_dict) = self._getChainByType(context)
    # Set the default chain to the empty string is probably the
    # best solution, by default it is 'default_workflow', wich is
    # not very usefull
    default_chain = ''
    for object in self._archive.values():
      portal_type = object.id
      chain_dict['chain_%s' % portal_type] = self._workflow_chain_archive[portal_type]
    context.portal_workflow.manage_changeWorkflows(default_chain,props=chain_dict)
319 320


321 322
class CatalogMethodTemplateItem(ObjectTemplateItem):

323 324 325
  def __init__(self, id_list, **kw):
    ObjectTemplateItem.__init__(self, id_list, tool_id='portal_catalog', **kw)
    self._is_catalog_method_archive = PersistentMapping()
326
    self._is_catalog_list_method_archive = PersistentMapping()
327 328 329 330 331 332 333 334 335 336
    self._is_uncatalog_method_archive = PersistentMapping()
    self._is_update_method_archive = PersistentMapping()
    self._is_clear_method_archive = PersistentMapping()
    self._is_filtered_archive = PersistentMapping()
    self._filter_expression_archive = PersistentMapping()
    self._filter_expression_instance_archive = PersistentMapping()
    self._filter_type_archive = PersistentMapping()

  def build(self, context, **kw):
    ObjectTemplateItem.build(self, context, **kw)
337 338 339 340 341 342 343 344 345

    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      return

    if catalog is None:
      return

346 347
    for object in self._archive.values():
      method_id = object.id
348 349 350 351 352
      self._is_catalog_method_archive[method_id] = method_id in catalog.sql_catalog_object
      self._is_catalog_list_method_archive[method_id] = method_id in catalog.sql_catalog_object_list
      self._is_uncatalog_method_archive[method_id] = method_id in catalog.sql_uncatalog_object
      self._is_update_method_archive[method_id] = method_id in catalog.sql_update_object
      self._is_clear_method_archive[method_id] = method_id in catalog.sql_clear_catalog
353
      self._is_filtered_archive[method_id] = 0
354 355 356 357 358
      if catalog.filter_dict.has_key(method_id):
        self._is_filtered_archive[method_id] = catalog.filter_dict[method_id]['filtered']
        self._filter_expression_archive[method_id] = catalog.filter_dict[method_id]['expression']
        self._filter_expression_instance_archive[method_id] = catalog.filter_dict[method_id]['expression_instance']
        self._filter_type_archive[method_id] = catalog.filter_dict[method_id]['type']
359 360 361 362

  def install(self, context, **kw):
    ObjectTemplateItem.install(self, context, **kw)

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      catalog = None

    if catalog is None:
      LOG('BusinessTemplate', 0, 'no SQL catalog was available')
      return

    # Make copies of attributes of the default catalog of portal_catalog.
    sql_catalog_object = list(catalog.sql_catalog_object)
    sql_catalog_object_list = list(catalog.sql_catalog_object_list)
    sql_uncatalog_object = list(catalog.sql_uncatalog_object)
    sql_update_object = list(catalog.sql_update_object)
    sql_clear_catalog = list(catalog.sql_clear_catalog)
378 379 380 381

    for object in self._archive.values():
      method_id = object.id
      is_catalog_method = self._is_catalog_method_archive[method_id]
382
      is_catalog_list_method = self._is_catalog_list_method_archive[method_id]
383 384 385 386 387 388 389 390 391 392
      is_uncatalog_method = self._is_uncatalog_method_archive[method_id]
      is_update_method = self._is_update_method_archive[method_id]
      is_clear_method = self._is_clear_method_archive[method_id]
      is_filtered = self._is_filtered_archive[method_id]

      if is_catalog_method and method_id not in sql_catalog_object:
        sql_catalog_object.append(method_id)
      elif not is_catalog_method and method_id in sql_catalog_object:
        sql_catalog_object.remove(method_id)

393 394 395 396 397
      if is_catalog_list_method and method_id not in sql_catalog_object_list:
        sql_catalog_object_list.append(method_id)
      elif not is_catalog_list_method and method_id in sql_catalog_object_list:
        sql_catalog_object_list.remove(method_id)

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
      if is_update_method and method_id not in sql_uncatalog_object:
        sql_uncatalog_object.append(method_id)
      elif not is_update_method and method_id in sql_uncatalog_object:
        sql_uncatalog_object.remove(method_id)

      if is_uncatalog_method and method_id not in sql_update_object:
        sql_update_object.append(method_id)
      elif not is_uncatalog_method and method_id in sql_update_object:
        sql_update_object.remove(method_id)

      if is_clear_method and method_id not in sql_clear_catalog:
        sql_clear_catalog.append(method_id)
      elif not is_clear_method and method_id in sql_clear_catalog:
        sql_clear_catalog.remove(method_id)

      if is_filtered:
        expression = self._filter_expression_archive[method_id]
        expression_instance = self._filter_expression_instance_archive[method_id]
        type = self._filter_type_archive[method_id]

418 419 420 421 422
        catalog.filter_dict[method_id] = PersistentMapping()
        catalog.filter_dict[method_id]['filtered'] = 1
        catalog.filter_dict[method_id]['expression'] = expression
        catalog.filter_dict[method_id]['expression_instance'] = expression_instance
        catalog.filter_dict[method_id]['type'] = type
423
      elif method_id in catalog.filter_dict.keys():
424
        catalog.filter_dict[method_id]['filtered'] = 0
425 426

    sql_catalog_object.sort()
427 428 429
    catalog.sql_catalog_object = tuple(sql_catalog_object)
    sql_catalog_object_list.sort()
    catalog.sql_catalog_object_list = tuple(sql_catalog_object_list)
430
    sql_uncatalog_object.sort()
431
    catalog.sql_uncatalog_object = tuple(sql_uncatalog_object)
432
    sql_update_object.sort()
433
    catalog.sql_update_object = tuple(sql_update_object)
434
    sql_clear_catalog.sort()
435
    catalog.sql_clear_catalog = tuple(sql_clear_catalog)
436 437

  def uninstall(self, context, **kw):
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      catalog = None

    if catalog is None:
      LOG('BusinessTemplate', 0, 'no SQL catalog was available')
      return

    # Make copies of attributes of the default catalog of portal_catalog.
    sql_catalog_object = list(catalog.sql_catalog_object)
    sql_catalog_object_list = list(catalog.sql_catalog_object_list)
    sql_uncatalog_object = list(catalog.sql_uncatalog_object)
    sql_update_object = list(catalog.sql_update_object)
    sql_clear_catalog = list(catalog.sql_clear_catalog)
453 454 455 456 457 458 459

    for object in self._archive.values():
      method_id = object.id

      if method_id in sql_catalog_object:
        sql_catalog_object.remove(method_id)

460 461 462
      if method_id in sql_catalog_object_list:
        sql_catalog_object_list.remove(method_id)

463 464 465 466 467 468 469 470 471 472 473 474
      if method_id in sql_uncatalog_object:
        sql_uncatalog_object.remove(method_id)

      if method_id in sql_update_object:
        sql_update_object.remove(method_id)

      if method_id in sql_clear_catalog:
        sql_clear_catalog.remove(method_id)

      if method_id in portal_catalog.filter_dict:
        del portal_catalog.filter_dict[method_id]

475 476 477 478 479
    catalog.sql_catalog_object = tuple(sql_catalog_object)
    catalog.sql_catalog_object_list = tuple(sql_catalog_object_list)
    catalog.sql_uncatalog_object = tuple(sql_uncatalog_object)
    catalog.sql_update_object = tuple(sql_update_object)
    catalog.sql_clear_catalog = tuple(sql_clear_catalog)
480 481 482 483 484 485 486 487 488

    ObjectTemplateItem.uninstall(self, context, **kw)


class ActionTemplateItem(BaseTemplateItem):

  def _splitPath(self, path):
    """
      Split path tries to split a complexe path such as:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
489

490
      "foo/bar[id=zoo]"
491

492
      into
493

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
      "foo/bar", "id", "zoo"

      This is used mostly for generic objects
    """
    # Add error checking here
    if path.find('[') >= 0 and path.find(']') > path.find('=') and path.find('=') > path.find('['):
      relative_url = path[0:path.find('[')]
      id_block = path[path.find('[')+1:path.find(']')]
      key = id_block.split('=')[0]
      value = id_block.split('=')[1]
      return relative_url, key, value
    return path, None, None

  def __init__(self, id_list, **kw):
    BaseTemplateItem.__init__(self, id_list, **kw)
    id_list = self._archive.keys()
    self._archive.clear()
    for id in id_list:
      self._archive["%s/%s" % ('portal_types', id)] = None

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    p = context.getPortalObject()
    for id in self._archive.keys():
      relative_url, key, value = self._splitPath(id)
      object = p.unrestrictedTraverse(relative_url)
      for ai in object.listActions():
        if getattr(ai, key) == value:
          self._archive[id] = ai._getCopy(context)
          self._archive[id].wl_clearLocks()
          break
      else:
        raise NotFound, 'no action has %s as %s' % (value, key)

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    p = context.getPortalObject()
    for id,action in self._archive.items():
      relative_url, key, value = self._splitPath(id)
      object = p.unrestrictedTraverse(relative_url)
      for ai in object.listActions():
        if getattr(ai, key) == value:
          raise TemplateConflictError, 'the portal type %s already has the action %s' % (object.id, value)
      object.addAction(
538 539 540 541 542 543
                    id = action.id
                  , name = action.title
                  , action = action.action
                  , condition = action.condition
                  , permission = action.permissions
                  , category = action.category
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
                  , visible=action.visible
                  )

  def uninstall(self, context, **kw):
    p = context.getPortalObject()
    for id,action in self._archive.items():
      relative_url, key, value = self._splitPath(id)
      object = p.unrestrictedTraverse(relative_url)
      action_list = object.listActions()
      for index in range(len(action_list)):
        if getattr(ai, key) == value:
          object.deleteActions(selections=(index,))
          break
    BaseTemplateItem.uninstall(self, context, **kw)


class SitePropertyTemplateItem(BaseTemplateItem):

  def __init__(self, id_list, **kw):
    BaseTemplateItem.__init__(self, id_list, **kw)

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    p = context.getPortalObject()
    for id in self._archive.keys():
569 570 571 572 573 574
      for property in p.propertyMap():
        if property['id'] == id:
          property['value'] = p.getProperty(id)
          break
      else:
        property = None
575 576
      if property is None:
        raise NotFound, 'the property %s is not found' % id
577 578
      #LOG('SitePropertyTemplateItem build', 0, 'property = %r' % (property,))
      self._archive[id] = property
579 580 581 582 583 584 585 586

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    p = context.getPortalObject()
    for id,property in self._archive.items():
      if p.hasProperty(id):
        # Too much???
        raise TemplateConflictError, 'the property %s already exists' % id
Romain Courteaud's avatar
Romain Courteaud committed
587
      p._setProperty(id, property['value'], type=property['type'])
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623

  def uninstall(self, context, **kw):
    p = context.getPortalObject()
    for id in self._archive.keys():
      if p.hasProperty(id):
        p._delProperty(id)
    BaseTemplateItem.uninstall(self, context, **kw)


class ModuleTemplateItem(BaseTemplateItem):

  def __init__(self, id_list, **kw):
    BaseTemplateItem.__init__(self, id_list, **kw)

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    p = context.getPortalObject()
    for id in self._archive.keys():
      module = p.unrestrictedTraverse(id)
      mapping = PersistentMapping()
      mapping['id'] = module.getId()
      mapping['title'] = module.getTitle()
      mapping['portal_type'] = module.getPortalType()
      permission_list = []
      for permission in module.ac_inherited_permissions(1):
        name, value = permission[:2]
        role_list = Permission(name, value, module).getRoles()
        permission_list.append((name, role_list))
      mapping['permission_list'] = permission_list
      self._archive[id] = mapping

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    portal = context.getPortalObject()
    for id,mapping in self._archive.items():
      if id in portal.objectIds():
624 625 626 627
        module = portal._getOb(id)
        module.portal_type = mapping['portal_type'] # XXX
      else:
        module = portal.newContent(id=id, portal_type=mapping['portal_type'])
628 629
      module.setTitle(mapping['title'])
      for name,role_list in mapping['permission_list']:
630 631 632 633 634 635 636
        acquire = (type(role_list) == type([]))
        try:
          module.manage_permission(name, roles=role_list, acquire=acquire)
        except:
          # Normally, an exception is raised when you don't install any Product which
          # has been in use when this business template is created.
          pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
637

638 639 640 641 642
  def uninstall(self, context, **kw):
    p = context.getPortalObject()
    id_list = p.objectIds()
    for id in self._archive.keys():
      if id in id_list:
643 644 645 646
        try:
          p.manage_delObjects([id])
        except:
          pass
647 648
    BaseTemplateItem.uninstall(self, context, **kw)

649 650 651
  def trash(self, context, new_item, **kw):
    # Do not remove any module for safety.
    pass
652 653 654 655 656 657 658 659 660 661 662

class DocumentTemplateItem(BaseTemplateItem):

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    for id in self._archive.keys():
      self._archive[id] = readLocalDocument(id)

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    for id,text in self._archive.items():
663
      writeLocalDocument(id, text, create=1) # This raises an exception if the file exists.
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
      importLocalDocument(id)

  def uninstall(self, context, **kw):
    for id in self._archive.keys():
      try:
        removeLocalDocument(id)
      except OSError:
        pass
    BaseTemplateItem.uninstall(self, context, **kw)


class PropertySheetTemplateItem(BaseTemplateItem):

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    for id in self._archive.keys():
      self._archive[id] = readLocalPropertySheet(id)

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    for id,text in self._archive.items():
685
      writeLocalPropertySheet(id, text, create=1) # This raises an exception if the file exists.
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
      importLocalPropertySheet(id)

  def uninstall(self, context, **kw):
    for id in self._archive.keys():
      try:
        removeLocalPropertySheet(id)
      except OSError:
        pass
    BaseTemplateItem.uninstall(self, context, **kw)


class ExtensionTemplateItem(BaseTemplateItem):

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    for id in self._archive.keys():
      self._archive[id] = readLocalExtension(id)

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    for id,text in self._archive.items():
707
      writeLocalExtension(id, text, create=1) # This raises an exception if the file exists.
708 709 710 711 712 713 714 715 716 717
      importLocalPropertySheet(id)

  def uninstall(self, context, **kw):
    for id in self._archive.keys():
      try:
        removeLocalExtension(id)
      except OSError:
        pass
    BaseTemplateItem.uninstall(self, context, **kw)

718 719 720 721 722 723 724 725 726 727
class TestTemplateItem(BaseTemplateItem):

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    for id in self._archive.keys():
      self._archive[id] = readLocalTest(id)

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    for id,text in self._archive.items():
728
      writeLocalTest(id, text, create=1) # This raises an exception if the file exists.
729 730 731 732 733 734 735 736 737

  def uninstall(self, context, **kw):
    for id in self._archive.keys():
      try:
        removeLocalTest(id)
      except OSError:
        pass
    BaseTemplateItem.uninstall(self, context, **kw)

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764

class ProductTemplateItem(BaseTemplateItem): pass # Not implemented yet


class RoleTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
    p = context.getPortalObject()
    roles = {}
    for role in p.__ac_roles__:
      roles[role] = 1
    for role in self._archive.keys():
      roles[role] = 1
    p.__ac_roles__ = tuple(roles.keys())

  def uninstall(self, context, **kw):
    p = context.getPortalObject()
    roles = {}
    for role in p.__ac_roles__:
      roles[role] = 1
    for role in self._archive.keys():
      if role in roles:
        del roles[role]
    p.__ac_roles__ = tuple(roles.keys())
    BaseTemplateItem.uninstall(self, context, **kw)

765 766 767 768 769 770 771 772 773
  def trash(self, context, new_item, **kw):
    p = context.getPortalObject()
    new_roles = {}
    for role in new_item._archive.keys():
      new_roles[role] = 1
    roles = {}
    for role in p.__ac_roles__:
      roles[role] = 1
    for role in self._archive.keys():
Yoshinori Okuji's avatar
Yoshinori Okuji committed
774
      if role in roles and role not in new_roles:
775 776 777
        del roles[role]
    p.__ac_roles__ = tuple(roles.keys())

778 779 780 781 782

class CatalogResultKeyTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
783 784 785 786 787 788 789 790 791 792

    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      catalog = None

    if catalog is None:
      LOG('BusinessTemplate', 0, 'no SQL catalog was available')
      return

793
    for key in self._archive.keys():
794 795
      if key not in catalog.sql_search_result_keys:
        catalog.sql_search_result_keys = (key,) + catalog.sql_search_result_keys
796 797

  def uninstall(self, context, **kw):
798 799 800 801 802 803 804 805 806 807
    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      catalog = None

    if catalog is None:
      LOG('BusinessTemplate', 0, 'no SQL catalog was available')
      return

    sql_search_result_keys = list(catalog.sql_search_result_keys)
808 809 810
    for key in self._archive.keys():
      if key in sql_search_result_keys:
        sql_search_result_keys.remove(key)
811
    catalog.sql_search_result_keys = sql_search_result_keys
812 813 814
    BaseTemplateItem.uninstall(self, context, **kw)


815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
class CatalogRelatedKeyTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)

    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      catalog = None

    if catalog is None:
      LOG('BusinessTemplate', 0, 'no SQL catalog was available')
      return

    for key in self._archive.keys():
      if key not in catalog.sql_catalog_related_keys:
        catalog.sql_catalog_related_keys = (key,) + catalog.sql_catalog_related_keys

  def uninstall(self, context, **kw):
    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      catalog = None

    if catalog is None:
      LOG('BusinessTemplate', 0, 'no SQL catalog was available')
      return

843
    sql_catalog_related_keys = list(catalog.sql_catalog_related_keys)
844 845 846 847 848 849 850
    for key in self._archive.keys():
      if key in sql_catalog_related_keys:
        sql_catalog_related_keys.remove(key)
    catalog.sql_catalog_related_keys = sql_catalog_related_keys
    BaseTemplateItem.uninstall(self, context, **kw)


851 852 853 854
class CatalogResultTableTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
855 856 857 858 859 860 861 862 863 864

    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      catalog = None

    if catalog is None:
      LOG('BusinessTemplate', 0, 'no SQL catalog was available')
      return

865
    for table in self._archive.keys():
866 867
      if table not in catalog.sql_search_tables:
        catalog.sql_search_tables = (table,) + catalog.sql_search_tables
868 869

  def uninstall(self, context, **kw):
870 871 872 873 874 875 876 877 878 879
    try:
      catalog = context.portal_catalog.getSQLCatalog()
    except:
      catalog = None

    if catalog is None:
      LOG('BusinessTemplate', 0, 'no SQL catalog was available')
      return

    sql_search_tables = list(catalog.sql_search_tables)
880 881 882
    for key in self._archive.keys():
      if key in sql_search_tables:
        sql_search_tables.remove(key)
883
    catalog.sql_search_tables = sql_search_tables
884 885 886
    BaseTemplateItem.uninstall(self, context, **kw)


887 888 889 890 891 892 893
class MessageTranslationTemplateItem(BaseTemplateItem):

  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    localizer = context.getPortalObject().Localizer
    for lang in self._archive.keys():
      self._archive[lang] = PersistentMapping()
894 895
      # Export only erp5_ui at the moment. This is safer against information leak.
      for catalog in ('erp5_ui', ):
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
        LOG('MessageTranslationTemplateItem build', 0, 'catalog = %r' % (catalog,))
        mc = localizer._getOb(catalog)
        LOG('MessageTranslationTemplateItem build', 0, 'mc = %r' % (mc,))
        self._archive[lang][catalog] = mc.manage_export(lang)

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)

    localizer = context.getPortalObject().Localizer
    for lang, catalogs in self._archive.items():
      if lang not in localizer.get_languages():
        localizer.manage_addLanguage(lang)
      for catalog, po in catalogs.items():
        mc = localizer._getOb(catalog)
        if lang not in mc.get_languages():
          mc.manage_addLanguage(lang)
        mc.manage_import(lang, po)


Jean-Paul Smets's avatar
Jean-Paul Smets committed
915 916 917 918 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 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
class BusinessTemplate(XMLObject):
    """
    A business template allows to construct ERP5 modules
    in part or completely. It may include:

    - dependency

    - conflicts

    - catalog definition ( -> formal definition + sql files )
      - SQL methods including:
        - purpose (catalog, uncatalog, etc.)
        - filter definition
      - Mapping definition
        - id (ex. getTitle)
        - column_id (ex. title)
        - indexed
        - preferred table (ex. catalog)

    - portal_types definition ( -> zexp/xml file)
      - id
      - actions

    - module definition ( -> zexp/xml file)
      - id
      - relative_url
      - menus
      - roles/security

    - workflow definitions ( -> zexp/xml file)
      - workflow_id
      - XML/XMI definition
      - relevant portal_types

    - tool definition ( -> formal definition)

    - categories definition

    Each definition should be usable in both import and update mode.

    Technology:

    - download a zip file (from the web, from a CVS repository)

    - install files to the right location (publish / update) (in the ZODB)

    - PUBLISH: publish method allows to publish an application (and share code)
      publication in a CVS repository allows to develop

      THIS IS THE MOST IMPORTANT CONCEPT

    Use case:

    - install core ERP5 (the minimum)

    - go to "BT" menu. Refresh list. Select BT. Click register.

    - go to "BT" menu. Select register BT. Define params. Click install / update.

    - go to "BT" menu. Create new BT. Define BT elements (workflow, methods, attributes, etc.). Click publish. Provide URL.
      Done.
    """

    meta_type = 'ERP5 Business Template'
    portal_type = 'Business Template'
980
    add_permission = Permissions.AddPortalContent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
981 982 983 984 985 986 987 988 989 990 991 992 993
    isPortalContent = 1
    isRADContent = 1

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

    # Declarative interfaces
    __implements__ = ( Interface.Variated, )

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
994
                      , PropertySheet.SimpleItem
Jean-Paul Smets's avatar
Jean-Paul Smets committed
995 996 997 998 999 1000 1001 1002 1003
                      , PropertySheet.CategoryCore
                      , PropertySheet.BusinessTemplate
                      )

    # Factory Type Information
    factory_type_information = \
      {    'id'             : portal_type
         , 'meta_type'      : meta_type
         , 'description'    : """\
1004
Business Template is a set of definitions, such as skins, portal types and categories. This is used to set up a new ERP5 site very efficiently."""
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1005
         , 'icon'           : 'order_line_icon.gif'
1006
         , 'product'        : 'ERP5Type'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1007 1008 1009
         , 'factory'        : 'addBusinessTemplate'
         , 'immediate_view' : 'BusinessTemplate_view'
         , 'allow_discussion'     : 1
1010
         , 'allowed_content_types': (
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
                                      )
         , 'filter_content_types' : 1
         , 'global_allow'   : 1
         , 'actions'        :
        ( { 'id'            : 'view'
          , 'name'          : 'View'
          , 'category'      : 'object_view'
          , 'action'        : 'BusinessTemplate_view'
          , 'permissions'   : (
              Permissions.View, )
          }
1022 1023 1024
        , { 'id'            : 'history'
          , 'name'          : 'History'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1025
          , 'action'        : 'Base_viewHistory'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1026 1027 1028 1029 1030 1031
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'metadata'
          , 'name'          : 'Metadata'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1032
          , 'action'        : 'Base_viewMetadata'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1033
          , 'permissions'   : (
1034
              Permissions.ManageProperties, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1035 1036 1037
          }
        , { 'id'            : 'translate'
          , 'name'          : 'Translate'
1038
          , 'category'      : 'object_exchange'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1039 1040 1041 1042
          , 'action'        : 'translation_template_view'
          , 'permissions'   : (
              Permissions.TranslateContent, )
          }
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
        , { 'id'            : 'update'
          , 'name'          : 'Update Business Template'
          , 'category'      : 'object_action'
          , 'action'        : 'BusinessTemplate_update'
          , 'permissions'   : (
              Permissions.ModifyPortalContent, )
          }
        , { 'id'            : 'save'
          , 'name'          : 'Save Business Template'
          , 'category'      : 'object_action'
          , 'action'        : 'BusinessTemplate_save'
          , 'permissions'   : (
              Permissions.ManagePortal, )
          }
        , { 'id'            : 'export'
          , 'name'          : 'Export Business Template'
          , 'category'      : 'object_action'
          , 'action'        : 'BusinessTemplate_export'
          , 'permissions'   : (
              Permissions.ManagePortal, )
          }
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1064 1065 1066
        )
      }

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    _workflow_item = None
    _skin_item = None
    _category_item = None
    _catalog_method_item = None
    _path_item = None
    _portal_type_item = None
    _action_item = None
    _site_property_item = None
    _module_item = None
    _document_item = None
    _property_sheet_item = None
    _extension_item = None
1079
    _test_item = None
1080 1081 1082
    _product_item = None
    _role_item = None
    _catalog_result_key_item = None
1083
    _catalog_related_key_item = None
1084
    _catalog_result_table_item = None
1085
    _message_translation_item = None
1086

1087 1088 1089 1090 1091 1092 1093 1094
    def manage_afterAdd(self, item, container):
      """
        This is called when a new business template is added or imported.
      """
      portal_workflow = getToolByName(self, 'portal_workflow')
      if portal_workflow is not None:
        # Make sure that the installation state is "not installed".
        if portal_workflow.getStatusOf('business_template_installation_workflow', self) is not None:
1095 1096
          # XXX Not good to access the attribute directly, but there is no API for clearing the history.
          self.workflow_history['business_template_installation_workflow'] = None
1097

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1098 1099 1100 1101
    def build(self):
      """
        Copy existing portal objects to self
      """
1102 1103
      # Make sure that everything is sane.
      self.clean()
1104

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1105
      # Copy portal_types
1106 1107 1108
      self._portal_type_item = PortalTypeTemplateItem(self.getTemplatePortalTypeIdList())
      self._portal_type_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1109
      # Copy workflows
1110 1111 1112
      self._workflow_item = WorkflowTemplateItem(self.getTemplateWorkflowIdList())
      self._workflow_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1113
      # Copy skins
1114 1115 1116
      self._skin_item = SkinTemplateItem(self.getTemplateSkinIdList())
      self._skin_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1117
      # Copy categories
1118 1119 1120
      self._category_item = CategoryTemplateItem(self.getTemplateBaseCategoryList())
      self._category_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1121
      # Copy catalog methods
1122 1123 1124
      self._catalog_method_item = CatalogMethodTemplateItem(self.getTemplateCatalogMethodIdList())
      self._catalog_method_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1125
      # Copy actions
1126 1127 1128
      self._action_item = ActionTemplateItem(self.getTemplateActionPathList())
      self._action_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1129
      # Copy properties
1130 1131 1132
      self._site_property_item = SitePropertyTemplateItem(self.getTemplateSitePropertyIdList())
      self._site_property_item.build(self)

1133
      # Copy modules
1134 1135
      self._module_item = ModuleTemplateItem(self.getTemplateModuleIdList())
      self._module_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1136

1137
      # Copy Document Classes
1138 1139
      self._document_item = DocumentTemplateItem(self.getTemplateDocumentIdList())
      self._document_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1140

1141
      # Copy Propertysheet Classes
1142 1143
      self._property_sheet_item = PropertySheetTemplateItem(self.getTemplatePropertySheetIdList())
      self._property_sheet_item.build(self)
1144 1145

      # Copy Extensions Classes (useful for catalog)
1146 1147
      self._extension_item = ExtensionTemplateItem(self.getTemplateExtensionIdList())
      self._extension_item.build(self)
1148

1149 1150 1151 1152
      # Copy Test Classes
      self._test_item = TestTemplateItem(self.getTemplateTestIdList())
      self._test_item.build(self)

1153
      # Copy Products
1154 1155
      self._product_item = ProductTemplateItem(self.getTemplateProductIdList())
      self._product_item.build(self)
1156 1157

      # Copy roles
1158 1159
      self._role_item = RoleTemplateItem(self.getTemplateRoleList())
      self._role_item.build(self)
1160

1161 1162 1163
      # Copy catalog result keys
      self._catalog_result_key_item = CatalogResultKeyTemplateItem(self.getTemplateCatalogResultKeyList())
      self._catalog_result_key_item.build(self)
1164

1165 1166 1167 1168
      # Copy catalog related keys
      self._catalog_related_key_item = CatalogRelatedKeyTemplateItem(self.getTemplateCatalogRelatedKeyList())
      self._catalog_related_key_item.build(self)

1169
      # Copy catalog result tables
1170 1171
      self._catalog_result_table_item = CatalogResultTableTemplateItem(self.getTemplateCatalogResultTableList())
      self._catalog_result_table_item.build(self)
1172

1173 1174 1175 1176
      # Copy message translations
      self._message_translation_item = MessageTranslationTemplateItem(self.getTemplateMessageTranslationList())
      self._message_translation_item.build(self)

1177 1178 1179
      # Other objects
      self._path_item = PathTemplateItem(self.getTemplatePathList())
      self._path_item.build(self)
1180

1181
    build = WorkflowMethod(build)
1182 1183

    def publish(self, url, username=None, password=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1184 1185 1186
      """
        Publish in a format or another
      """
1187
      return self.portal_templates.publish(self, url, username=username, password=password)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1188

1189
    def update(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1190
      """
1191
        Update template: download new template defition
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1192
      """
1193
      return self.portal_templates.update(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1194

1195
    def install(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1196 1197 1198
      """
        For install based on paramaters provided in **kw
      """
1199 1200
      installed_bt = self.portal_templates.getInstalledBusinessTemplate(self.getTitle())
      if installed_bt is not None:
1201 1202
        installed_bt.trash(self)
        installed_bt.replace()
1203

1204
      # Update local dictionary containing all setup parameters
1205 1206 1207 1208 1209
      # This may include mappings
      self.portal_templates.updateLocalConfiguration(self, **kw)
      local_configuration = self.portal_templates.getLocalConfiguration(self)

      # Classes and security information
1210 1211 1212 1213
      if self._product_item is not None: self._product_item.install(local_configuration)
      if self._property_sheet_item is not None: self._property_sheet_item.install(local_configuration)
      if self._document_item is not None: self._document_item.install(local_configuration)
      if self._extension_item is not None: self._extension_item.install(local_configuration)
1214
      if self._test_item is not None: self._test_item.install(local_configuration)
1215
      if self._role_item is not None: self._role_item.install(local_configuration)
1216

1217
      # Message translations
1218
      if self._message_translation_item is not None: self._message_translation_item.install(local_configuration)
1219

1220
      # Objects and properties
1221 1222 1223
      if self._workflow_item is not None: self._workflow_item.install(local_configuration)
      if self._catalog_method_item is not None: self._catalog_method_item.install(local_configuration)
      if self._site_property_item is not None: self._site_property_item.install(local_configuration)
1224

1225
      # Portal Types
1226
      if self._portal_type_item is not None: self._portal_type_item.install(local_configuration)
1227

1228
      # Categories
1229
      if self._category_item is not None: self._category_item.install(local_configuration,**kw)
1230

1231
      # Modules.
1232
      if self._module_item is not None: self._module_item.install(local_configuration)
1233

1234 1235 1236
      # Install Paths after Modules, as we may want to keep static objects in some modules defined in the BT.
      if self._path_item is not None: self._path_item.install(local_configuration)

1237
      # Skins
1238
      if self._skin_item is not None: self._skin_item.install(local_configuration)
1239

1240
      # Actions, catalog
1241 1242
      if self._action_item is not None: self._action_item.install(local_configuration)
      if self._catalog_result_key_item is not None: self._catalog_result_key_item.install(local_configuration)
1243
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.install(local_configuration)
1244
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.install(local_configuration)
1245

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1246 1247 1248
      # It is better to clear cache because the installation of a template
      # adds many new things into the portal.
      clearCache()
1249

1250
    install = WorkflowMethod(install)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1251

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    def trash(self, new_bt, **kw):
      """
        Trash unnecessary items before upograding to a new business template.
        This is similar to uninstall, but different in that this does not remove
        all items.
      """
      # Update local dictionary containing all setup parameters
      # This may include mappings
      self.portal_templates.updateLocalConfiguration(self, **kw)
      local_configuration = self.portal_templates.getLocalConfiguration(self)

      # Actions, catalog
1264 1265
      if self._action_item is not None: self._action_item.trash(local_configuration, new_bt._action_item)
      if self._catalog_result_key_item is not None: self._catalog_result_key_item.trash(local_configuration, new_bt._catalog_result_key_item)
1266
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.trash(local_configuration, new_bt._catalog_related_key_item)
1267
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.trash(local_configuration, new_bt._catalog_result_table_item)
1268 1269

      # Skins
1270
      if self._skin_item is not None: self._skin_item.trash(local_configuration, new_bt._skin_item)
1271 1272

      # Portal Types
1273
      if self._portal_type_item is not None: self._portal_type_item.trash(local_configuration, new_bt._portal_type_item)
1274 1275

      # Modules.
1276
      if self._module_item is not None: self._module_item.trash(local_configuration, new_bt._module_item)
1277 1278

      # Objects and properties
1279 1280 1281 1282 1283
      if self._path_item is not None: self._path_item.trash(local_configuration, new_bt._path_item)
      if self._workflow_item is not None: self._workflow_item.trash(local_configuration, new_bt._workflow_item)
      if self._category_item is not None: self._category_item.trash(local_configuration, new_bt._category_item)
      if self._catalog_method_item is not None: self._catalog_method_item.trash(local_configuration, new_bt._catalog_method_item)
      if self._site_property_item is not None: self._site_property_item.trash(local_configuration, new_bt._site_property_item)
1284

1285
      # Message translations
1286
      if self._message_translation_item is not None: self._message_translation_item.trash(local_configuration, new_bt._message_translation_item)
1287

1288
      # Classes and security information
1289 1290 1291 1292
      if self._product_item is not None: self._product_item.trash(local_configuration, new_bt._product_item)
      if self._property_sheet_item is not None: self._property_sheet_item.trash(local_configuration, new_bt._property_sheet_item)
      if self._document_item is not None: self._document_item.trash(local_configuration, new_bt._document_item)
      if self._extension_item is not None: self._extension_item.trash(local_configuration, new_bt._extension_item)
1293
      if self._test_item is not None: self._test_item.trash(local_configuration, new_bt._test_item)
1294
      if self._role_item is not None: self._role_item.trash(local_configuration, new_bt._role_item)
1295

1296
    def uninstall(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1297
      """
1298
        For uninstall based on paramaters provided in **kw
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1299
      """
1300 1301 1302 1303
      # Update local dictionary containing all setup parameters
      # This may include mappings
      self.portal_templates.updateLocalConfiguration(self, **kw)
      local_configuration = self.portal_templates.getLocalConfiguration(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1304

1305
      # Actions, catalog
1306 1307
      if self._action_item is not None: self._action_item.uninstall(local_configuration)
      if self._catalog_result_key_item is not None: self._catalog_result_key_item.uninstall(local_configuration)
1308
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.uninstall(local_configuration)
1309
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.uninstall(local_configuration)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1310

1311
      # Skins
1312
      if self._skin_item is not None: self._skin_item.uninstall(local_configuration)
1313 1314

      # Portal Types
1315
      if self._portal_type_item is not None: self._portal_type_item.uninstall(local_configuration)
1316 1317

      # Modules.
1318
      if self._module_item is not None: self._module_item.uninstall(local_configuration)
1319 1320

      # Objects and properties
1321 1322 1323 1324 1325
      if self._path_item is not None: self._path_item.uninstall(local_configuration)
      if self._workflow_item is not None: self._workflow_item.uninstall(local_configuration)
      if self._category_item is not None: self._category_item.uninstall(local_configuration)
      if self._catalog_method_item is not None: self._catalog_method_item.uninstall(local_configuration)
      if self._site_property_item is not None: self._site_property_item.uninstall(local_configuration)
1326

1327
      # Message translations
1328
      if self._message_translation_item is not None: self._message_translation_item.uninstall(local_configuration)
1329

1330
      # Classes and security information
1331 1332 1333 1334
      if self._product_item is not None: self._product_item.uninstall(local_configuration)
      if self._property_sheet_item is not None: self._property_sheet_item.uninstall(local_configuration)
      if self._document_item is not None: self._document_item.uninstall(local_configuration)
      if self._extension_item is not None: self._extension_item.uninstall(local_configuration)
1335
      if self._test_item is not None: self._test_item.uninstall(local_configuration)
1336
      if self._role_item is not None: self._role_item.uninstall(local_configuration)
1337 1338 1339 1340

      # It is better to clear cache because the uninstallation of a template
      # deletes many things from the portal.
      clearCache()
1341

1342 1343 1344
    uninstall = WorkflowMethod(uninstall)

    def clean(self):
1345
      """
1346
        Clean built information.
1347
      """
1348
      # First, remove obsolete attributes if present.
1349
      for attr in ('_action_archive', '_document_archive', '_extension_archive', '_test_archive', '_module_archive',
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
                   '_object_archive', '_portal_type_archive', '_property_archive', '_property_sheet_archive'):
        if hasattr(self, attr):
          delattr(self, attr)
      # Secondly, make attributes empty.
      self._workflow_item = None
      self._skin_item = None
      self._category_item = None
      self._catalog_method_item = None
      self._path_item = None
      self._portal_type_item = None
      self._action_item = None
      self._site_property_item = None
      self._module_item = None
      self._document_item = None
      self._property_sheet_item = None
      self._extension_item = None
1366
      self._test_item = None
1367 1368 1369
      self._product_item = None
      self._role_item = None
      self._catalog_result_key_item = None
1370
      self._catalog_related_key_item = None
1371
      self._catalog_result_table_item = None
1372
      self._message_translation_item = None
1373 1374

    clean = WorkflowMethod(clean)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1375

1376 1377
    security.declareProtected(Permissions.AccessContentsInformation, 'getBuildingState')
    def getBuildingState(self, id_only=1):
1378
      """
1379
        Returns the current state in building
1380
      """
1381 1382 1383
      portal_workflow = getToolByName(self, 'portal_workflow')
      wf = portal_workflow.getWorkflowById('business_template_building_workflow')
      return wf._getWorkflowStateOf(self, id_only=id_only )
1384

1385 1386
    security.declareProtected(Permissions.AccessContentsInformation, 'getInstallationState')
    def getInstallationState(self, id_only=1):
1387
      """
1388
        Returns the current state in installation
1389
      """
1390 1391 1392
      portal_workflow = getToolByName(self, 'portal_workflow')
      wf = portal_workflow.getWorkflowById('business_template_installation_workflow')
      return wf._getWorkflowStateOf(self, id_only=id_only )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1393

1394
    def _getOrderedList(self, id):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1395
      """
1396 1397
        We have to set this method because we want an
        ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1398
      """
1399 1400 1401 1402 1403 1404 1405 1406
      #LOG('BuisinessTemplate _getOrderedList', 0, 'id = %s' % repr(id))
      result = getattr(self,id,())
      if result is None: result = ()
      if result != ():
        result = list(result)
        result.sort()
        result = tuple(result)
      return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1407

1408
    def getTemplateCatalogMethodIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1409
      """
1410 1411
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1412
      """
1413
      return self._getOrderedList('template_catalog_method_id')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1414

1415
    def getTemplateBaseCategoryList(self):
1416
      """
1417 1418
      We have to set this method because we want an
      ordered list
1419
      """
1420
      return self._getOrderedList('template_base_category')
1421

1422
    def getTemplateWorkflowIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1423
      """
1424 1425
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1426
      """
1427
      return self._getOrderedList('template_workflow_id')
1428

1429
    def getTemplatePortalTypeIdList(self):
1430
      """
1431 1432
      We have to set this method because we want an
      ordered list
1433
      """
1434
      return self._getOrderedList('template_portal_type_id')
1435

1436
    def getTemplateActionPathList(self):
1437
      """
1438 1439
      We have to set this method because we want an
      ordered list
1440
      """
1441
      return self._getOrderedList('template_action_path')
1442

1443
    def getTemplateSkinIdList(self):
1444
      """
1445 1446
      We have to set this method because we want an
      ordered list
1447
      """
1448
      return self._getOrderedList('template_skin_id')
1449

1450
    def getTemplateModuleIdList(self):
1451
      """
1452 1453
      We have to set this method because we want an
      ordered list
1454
      """
1455
      return self._getOrderedList('template_module_id')
1456 1457 1458 1459 1460 1461 1462

    def getTemplateMessageTranslationList(self):
      """
      We have to set this method because we want an
      ordered list
      """
      return self._getOrderedList('template_message_translation')