BusinessTemplate.py 51.2 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 38
from Products.ERP5Type.Utils import readLocalPropertySheet, writeLocalPropertySheet, importLocalPropertySheet, removeLocalPropertySheet
from Products.ERP5Type.Utils import readLocalExtension, writeLocalExtension, removeLocalExtension
from Products.ERP5Type.Utils import readLocalDocument, writeLocalDocument, importLocalDocument, removeLocalDocument
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39 40
from Products.ERP5Type.XMLObject import XMLObject
import cStringIO
Yoshinori Okuji's avatar
Yoshinori Okuji committed
41
from Products.ERP5Type.Cache import clearCache
42
from Products.ERP5.Tool.Category import addBaseCategory
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 104 105 106 107 108 109 110 111 112 113 114 115
    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)
    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
116
        self._backupObject(container, object_id)
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
      # 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()
133
    trash = kw.get('trash', 0)
134 135 136
    for relative_url in self._archive.keys():
      container_path = relative_url.split('/')[0:-1]
      object_id = relative_url.split('/')[-1]
137 138 139 140 141 142 143 144 145 146
      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

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


class PathTemplateItem(ObjectTemplateItem): pass


class CategoryTemplateItem(ObjectTemplateItem):

  def __init__(self, id_list, **kw):
156 157 158 159 160 161 162 163 164
    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
165

166 167 168 169 170 171 172 173 174
  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)
175
      category_copy = category._getCopy(context)
176 177 178 179 180
      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))
181 182
      self._archive[relative_url] = category_copy
      category_copy.wl_clearLocks()
183 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():
          raise TemplateConflictError, 'the category %s already exists' % id
204
        addBaseCategory(category_tool, category_id)
205 206 207 208 209
        category = category_tool[category_id]
        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 423 424
        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
      elif method_id in catalog.filter_dict:
        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 538 539 540 541 542 543 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 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 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
      "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(
                    action.id
                  , action.title
                  , action.action
                  , action.permission
                  , action.category
                  , 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():
      property = p.getProperty(id)
      if property is None:
        raise NotFound, 'the property %s is not found' % id
      self._archive[id] = property.copy()

  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
      object._setProperty(id, pi['value'], type=pi['type'])

  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():
617 618 619 620
        module = portal._getOb(id)
        module.portal_type = mapping['portal_type'] # XXX
      else:
        module = portal.newContent(id=id, portal_type=mapping['portal_type'])
621 622
      module.setTitle(mapping['title'])
      for name,role_list in mapping['permission_list']:
623 624 625 626 627 628 629
        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
630

631 632 633 634 635
  def uninstall(self, context, **kw):
    p = context.getPortalObject()
    id_list = p.objectIds()
    for id in self._archive.keys():
      if id in id_list:
636 637 638 639
        try:
          p.manage_delObjects([id])
        except:
          pass
640 641
    BaseTemplateItem.uninstall(self, context, **kw)

642 643 644
  def trash(self, context, new_item, **kw):
    # Do not remove any module for safety.
    pass
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739

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():
      writeLocalDocument(id, text, create=1) # This raises an exception if the file exists.
      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():
      writeLocalPropertySheet(id, text, create=1) # This raises an exception if the file exists.
      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():
      writeLocalExtension(id, text, create=1) # This raises an exception if the file exists.
      importLocalPropertySheet(id)

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


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():
      if role in roles:
        raise TemplateConflictError, 'the role %s already exists' % role
      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)

740 741 742 743 744 745 746 747 748 749 750 751 752
  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():
      if role in roles and role not in new_role:
        del roles[role]
    p.__ac_roles__ = tuple(roles.keys())

753 754 755 756 757

class CatalogResultKeyTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
758 759 760 761 762 763 764 765 766 767

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

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

768
    for key in self._archive.keys():
769 770
      if key not in catalog.sql_search_result_keys:
        catalog.sql_search_result_keys = (key,) + catalog.sql_search_result_keys
771 772

  def uninstall(self, context, **kw):
773 774 775 776 777 778 779 780 781 782
    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)
783 784 785
    for key in self._archive.keys():
      if key in sql_search_result_keys:
        sql_search_result_keys.remove(key)
786
    catalog.sql_search_result_keys = sql_search_result_keys
787 788 789 790 791 792 793
    BaseTemplateItem.uninstall(self, context, **kw)


class CatalogResultTableTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
794 795 796 797 798 799 800 801 802 803

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

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

804
    for table in self._archive.keys():
805 806
      if table not in catalog.sql_search_tables:
        catalog.sql_search_tables = (table,) + catalog.sql_search_tables
807 808

  def uninstall(self, context, **kw):
809 810 811 812 813 814 815 816 817 818
    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)
819 820 821
    for key in self._archive.keys():
      if key in sql_search_tables:
        sql_search_tables.remove(key)
822
    catalog.sql_search_tables = sql_search_tables
823 824 825
    BaseTemplateItem.uninstall(self, context, **kw)


826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
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()
      # Is it a good idea to include erp5_content?
      for catalog in ('erp5_ui', 'erp5_content'):
        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
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
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'
919
    add_permission = Permissions.AddPortalContent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
920 921 922 923 924 925 926 927 928 929 930 931 932
    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
933
                      , PropertySheet.SimpleItem
Jean-Paul Smets's avatar
Jean-Paul Smets committed
934 935 936 937 938 939 940 941 942
                      , PropertySheet.CategoryCore
                      , PropertySheet.BusinessTemplate
                      )

    # Factory Type Information
    factory_type_information = \
      {    'id'             : portal_type
         , 'meta_type'      : meta_type
         , 'description'    : """\
943
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
944
         , 'icon'           : 'order_line_icon.gif'
945
         , 'product'        : 'ERP5Type'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
946 947 948
         , 'factory'        : 'addBusinessTemplate'
         , 'immediate_view' : 'BusinessTemplate_view'
         , 'allow_discussion'     : 1
949
         , 'allowed_content_types': (
Jean-Paul Smets's avatar
Jean-Paul Smets committed
950 951 952 953 954 955 956 957 958 959 960
                                      )
         , 'filter_content_types' : 1
         , 'global_allow'   : 1
         , 'actions'        :
        ( { 'id'            : 'view'
          , 'name'          : 'View'
          , 'category'      : 'object_view'
          , 'action'        : 'BusinessTemplate_view'
          , 'permissions'   : (
              Permissions.View, )
          }
961 962 963
        , { 'id'            : 'history'
          , 'name'          : 'History'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
964
          , 'action'        : 'Base_viewHistory'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
965 966 967 968 969 970
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'metadata'
          , 'name'          : 'Metadata'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
971
          , 'action'        : 'Base_viewMetadata'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
972
          , 'permissions'   : (
973
              Permissions.ManageProperties, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
974 975 976
          }
        , { 'id'            : 'translate'
          , 'name'          : 'Translate'
977
          , 'category'      : 'object_exchange'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
978 979 980 981
          , 'action'        : 'translation_template_view'
          , 'permissions'   : (
              Permissions.TranslateContent, )
          }
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        , { '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
1003 1004 1005
        )
      }

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    _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
    _product_item = None
    _role_item = None
    _catalog_result_key_item = None
    _catalog_result_table_item = None
1022
    _message_translation_item = None
1023

1024 1025 1026 1027 1028 1029 1030 1031
    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:
1032 1033
          # 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
1034

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1035 1036 1037 1038
    def build(self):
      """
        Copy existing portal objects to self
      """
1039 1040
      # Make sure that everything is sane.
      self.clean()
1041

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1042
      # Copy portal_types
1043 1044 1045
      self._portal_type_item = PortalTypeTemplateItem(self.getTemplatePortalTypeIdList())
      self._portal_type_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1046
      # Copy workflows
1047 1048 1049
      self._workflow_item = WorkflowTemplateItem(self.getTemplateWorkflowIdList())
      self._workflow_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1050
      # Copy skins
1051 1052 1053
      self._skin_item = SkinTemplateItem(self.getTemplateSkinIdList())
      self._skin_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1054
      # Copy categories
1055 1056 1057
      self._category_item = CategoryTemplateItem(self.getTemplateBaseCategoryList())
      self._category_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1058
      # Copy catalog methods
1059 1060 1061
      self._catalog_method_item = CatalogMethodTemplateItem(self.getTemplateCatalogMethodIdList())
      self._catalog_method_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1062
      # Copy actions
1063 1064 1065
      self._action_item = ActionTemplateItem(self.getTemplateActionPathList())
      self._action_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1066
      # Copy properties
1067 1068 1069
      self._site_property_item = SitePropertyTemplateItem(self.getTemplateSitePropertyIdList())
      self._site_property_item.build(self)

1070
      # Copy modules
1071 1072
      self._module_item = ModuleTemplateItem(self.getTemplateModuleIdList())
      self._module_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1073

1074
      # Copy Document Classes
1075 1076
      self._document_item = DocumentTemplateItem(self.getTemplateDocumentIdList())
      self._document_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1077

1078
      # Copy Propertysheet Classes
1079 1080
      self._property_sheet_item = PropertySheetTemplateItem(self.getTemplatePropertySheetIdList())
      self._property_sheet_item.build(self)
1081 1082

      # Copy Extensions Classes (useful for catalog)
1083 1084
      self._extension_item = ExtensionTemplateItem(self.getTemplateExtensionIdList())
      self._extension_item.build(self)
1085 1086

      # Copy Products
1087 1088
      self._product_item = ProductTemplateItem(self.getTemplateProductIdList())
      self._product_item.build(self)
1089 1090

      # Copy roles
1091 1092
      self._role_item = RoleTemplateItem(self.getTemplateRoleList())
      self._role_item.build(self)
1093

1094 1095 1096
      # Copy catalog result keys
      self._catalog_result_key_item = CatalogResultKeyTemplateItem(self.getTemplateCatalogResultKeyList())
      self._catalog_result_key_item.build(self)
1097 1098

      # Copy catalog result tables
1099 1100
      self._catalog_result_table_item = CatalogResultTableTemplateItem(self.getTemplateCatalogResultTableList())
      self._catalog_result_table_item.build(self)
1101

1102 1103 1104 1105
      # Copy message translations
      self._message_translation_item = MessageTranslationTemplateItem(self.getTemplateMessageTranslationList())
      self._message_translation_item.build(self)

1106 1107 1108
      # Other objects
      self._path_item = PathTemplateItem(self.getTemplatePathList())
      self._path_item.build(self)
1109

1110
    build = WorkflowMethod(build)
1111 1112

    def publish(self, url, username=None, password=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1113 1114 1115
      """
        Publish in a format or another
      """
1116
      return self.portal_templates.publish(self, url, username=username, password=password)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1117

1118
    def update(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1119
      """
1120
        Update template: download new template defition
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1121
      """
1122
      return self.portal_templates.update(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1123

1124
    def install(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1125 1126 1127
      """
        For install based on paramaters provided in **kw
      """
1128 1129
      installed_bt = self.portal_templates.getInstalledBusinessTemplate(self.getTitle())
      if installed_bt is not None:
1130 1131
        installed_bt.trash(self)
        installed_bt.replace()
1132

1133
      # Update local dictionary containing all setup parameters
1134 1135 1136 1137 1138
      # This may include mappings
      self.portal_templates.updateLocalConfiguration(self, **kw)
      local_configuration = self.portal_templates.getLocalConfiguration(self)

      # Classes and security information
1139 1140 1141 1142 1143
      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)
      if self._role_item is not None: self._role_item.install(local_configuration)
1144

1145
      # Message translations
1146
      if self._message_translation_item is not None: self._message_translation_item.install(local_configuration)
1147

1148
      # Objects and properties
1149 1150 1151 1152
      if self._path_item is not None: self._path_item.install(local_configuration)
      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)
1153

1154
      # Portal Types
1155
      if self._portal_type_item is not None: self._portal_type_item.install(local_configuration)
1156

1157
      # Categories
1158
      if self._category_item is not None: self._category_item.install(local_configuration,**kw)
1159

1160
      # Modules.
1161
      if self._module_item is not None: self._module_item.install(local_configuration)
1162

1163
      # Skins
1164
      if self._skin_item is not None: self._skin_item.install(local_configuration)
1165

1166
      # Actions, catalog
1167 1168 1169
      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)
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.install(local_configuration)
1170

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1171 1172 1173
      # It is better to clear cache because the installation of a template
      # adds many new things into the portal.
      clearCache()
1174

1175
    install = WorkflowMethod(install)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1176

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    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
1189 1190 1191
      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)
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.trash(local_configuration, new_bt._catalog_result_table_item)
1192 1193

      # Skins
1194
      if self._skin_item is not None: self._skin_item.trash(local_configuration, new_bt._skin_item)
1195 1196

      # Portal Types
1197
      if self._portal_type_item is not None: self._portal_type_item.trash(local_configuration, new_bt._portal_type_item)
1198 1199

      # Modules.
1200
      if self._module_item is not None: self._module_item.trash(local_configuration, new_bt._module_item)
1201 1202

      # Objects and properties
1203 1204 1205 1206 1207
      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)
1208

1209
      # Message translations
1210
      if self._message_translation_item is not None: self._message_translation_item.trash(local_configuration, new_bt._message_translation_item)
1211

1212
      # Classes and security information
1213 1214 1215 1216 1217
      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)
      if self._role_item is not None: self._role_item.trash(local_configuration, new_bt._role_item)
1218

1219
    def uninstall(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1220
      """
1221
        For uninstall based on paramaters provided in **kw
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1222
      """
1223 1224 1225 1226
      # 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
1227

1228
      # Actions, catalog
1229 1230 1231
      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)
      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
1232

1233
      # Skins
1234
      if self._skin_item is not None: self._skin_item.uninstall(local_configuration)
1235 1236

      # Portal Types
1237
      if self._portal_type_item is not None: self._portal_type_item.uninstall(local_configuration)
1238 1239

      # Modules.
1240
      if self._module_item is not None: self._module_item.uninstall(local_configuration)
1241 1242

      # Objects and properties
1243 1244 1245 1246 1247
      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)
1248

1249
      # Message translations
1250
      if self._message_translation_item is not None: self._message_translation_item.uninstall(local_configuration)
1251

1252
      # Classes and security information
1253 1254 1255 1256 1257
      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)
      if self._role_item is not None: self._role_item.uninstall(local_configuration)
1258 1259 1260 1261

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

1263 1264 1265
    uninstall = WorkflowMethod(uninstall)

    def clean(self):
1266
      """
1267
        Clean built information.
1268
      """
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
      # First, remove obsolete attributes if present.
      for attr in ('_action_archive', '_document_archive', '_extension_archive', '_module_archive',
                   '_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
      self._product_item = None
      self._role_item = None
      self._catalog_result_key_item = None
      self._catalog_result_table_item = None
1291
      self._message_translation_item = None
1292 1293

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

1295 1296
    security.declareProtected(Permissions.AccessContentsInformation, 'getBuildingState')
    def getBuildingState(self, id_only=1):
1297
      """
1298
        Returns the current state in building
1299
      """
1300 1301 1302
      portal_workflow = getToolByName(self, 'portal_workflow')
      wf = portal_workflow.getWorkflowById('business_template_building_workflow')
      return wf._getWorkflowStateOf(self, id_only=id_only )
1303

1304 1305
    security.declareProtected(Permissions.AccessContentsInformation, 'getInstallationState')
    def getInstallationState(self, id_only=1):
1306
      """
1307
        Returns the current state in installation
1308
      """
1309 1310 1311
      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
1312

1313
    def _getOrderedList(self, id):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1314
      """
1315 1316
        We have to set this method because we want an
        ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1317
      """
1318 1319 1320 1321 1322 1323 1324 1325
      #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
1326

1327
    def getTemplateCatalogMethodIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1328
      """
1329 1330
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1331
      """
1332
      return self._getOrderedList('template_catalog_method_id')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1333

1334
    def getTemplateBaseCategoryList(self):
1335
      """
1336 1337
      We have to set this method because we want an
      ordered list
1338
      """
1339
      return self._getOrderedList('template_base_category')
1340

1341
    def getTemplateWorkflowIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1342
      """
1343 1344
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1345
      """
1346
      return self._getOrderedList('template_workflow_id')
1347

1348
    def getTemplatePortalTypeIdList(self):
1349
      """
1350 1351
      We have to set this method because we want an
      ordered list
1352
      """
1353
      return self._getOrderedList('template_portal_type_id')
1354

1355
    def getTemplateActionPathList(self):
1356
      """
1357 1358
      We have to set this method because we want an
      ordered list
1359
      """
1360
      return self._getOrderedList('template_action_path')
1361

1362
    def getTemplateSkinIdList(self):
1363
      """
1364 1365
      We have to set this method because we want an
      ordered list
1366
      """
1367
      return self._getOrderedList('template_skin_id')
1368

1369
    def getTemplateModuleIdList(self):
1370
      """
1371 1372
      We have to set this method because we want an
      ordered list
1373
      """
1374
      return self._getOrderedList('template_module_id')
1375 1376 1377 1378 1379 1380 1381

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