BusinessTemplate.py 56.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
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
42 43
import fnmatch
import re
Yoshinori Okuji's avatar
Yoshinori Okuji committed
44
from Products.ERP5Type.Cache import clearCache
Jean-Paul Smets's avatar
Jean-Paul Smets committed
45 46 47

from zLOG import LOG

48 49
class TemplateConflictError(Exception): pass

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

55
  def __init__(self, id_list, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
56
    self.__dict__.update(kw)
57 58 59 60 61 62 63 64 65 66 67 68 69
    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
70

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

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

80 81 82 83
  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()
84
      self._archive.clear()
85 86 87 88 89 90 91 92 93 94 95 96 97 98
      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()

99
  def _backupObject(self, container, object_id, **kw):
100
    container_ids = container.objectIds()
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    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
118
        self._backupObject(container, object_id)
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
      # 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()
135
    trash = kw.get('trash', 0)
136 137 138
    for relative_url in self._archive.keys():
      container_path = relative_url.split('/')[0:-1]
      object_id = relative_url.split('/')[-1]
139 140 141 142 143 144 145 146 147 148
      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

149 150 151
    BaseTemplateItem.uninstall(self, context, **kw)


152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
class PathTemplateItem(ObjectTemplateItem):
  """
    This class is used to store objects with wildcards supported.
  """
  def __init__(self, id_list, tool_id=None, **kw):
    BaseTemplateItem.__init__(self, id_list, tool_id=tool_id, **kw)
    id_list = self._archive.keys()
    self._archive.clear()
    self._path_archive = PersistentMapping()
    for id in id_list:
      self._path_archive[id] = None

  def _resolvePath(self, folder, relative_url_list, id_list):
    """
      This method calls itself recursively.
      
      The folder is the current object which contains sub-objects.
      The list of ids are path components. If the list is empty,
      the current folder is valid.
    """
    if len(id_list) == 0:
      return ['/'.join(relative_url_list)]
      
    id = id_list[0]
    if re.search('[\*\?\[\]]', id) is None:
      # If the id has no meta character, do not have to check all objects.
      object = folder._getOb(id)
      return self._resolvePath(object, relative_url_list + [id], id_list[1:])
      
    path_list = []
    for object_id in fnmatch.filter(folder.objectIds(), id):
      path_list.extend(self._resolvePath(folder._getOb(object_id), relative_url_list + [object_id], id_list[1:]))
    return path_list
      
  def build(self, context, **kw):
    BaseTemplateItem.build(self, context, **kw)
    p = context.getPortalObject()
    for path in self._path_archive.keys():
      for relative_url in self._resolvePath(p, [], path.split('/')):
        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()
197 198 199 200 201


class CategoryTemplateItem(ObjectTemplateItem):

  def __init__(self, id_list, **kw):
202 203 204 205 206 207 208 209 210
    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
211

212 213 214 215 216 217 218 219 220
  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)
221
      category_copy = category._getCopy(context)
222 223 224 225 226
      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))
227 228
      self._archive[relative_url] = category_copy
      category_copy.wl_clearLocks()
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
      # 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():
249
          raise TemplateConflictError, 'the category %s already exists' % category_id
250
        category = category_tool.newContent(portal_type='Base Category',id=category_id)
251 252 253 254
        property_list = self._light_archive[category_id]['property_list']
        for property,value in property_list.items():
          category.setProperty(property,value)

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

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(',')
276
      for relative_url, object in self._archive.items():
277
        skin_id = relative_url.split('/')[-1]
278 279 280 281
        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)
282 283 284 285 286 287 288 289 290 291 292 293 294 295
      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)
296

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    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
314
    This is only useful in order to use
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    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)
364 365


366 367
class CatalogMethodTemplateItem(ObjectTemplateItem):

368 369 370
  def __init__(self, id_list, **kw):
    ObjectTemplateItem.__init__(self, id_list, tool_id='portal_catalog', **kw)
    self._is_catalog_method_archive = PersistentMapping()
371
    self._is_catalog_list_method_archive = PersistentMapping()
372 373 374 375 376 377 378 379 380 381
    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)
382 383 384 385 386 387 388 389 390

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

    if catalog is None:
      return

391 392
    for object in self._archive.values():
      method_id = object.id
393 394 395 396 397
      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
398
      self._is_filtered_archive[method_id] = 0
399 400 401 402 403
      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']
404 405 406 407

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

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    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)
423 424 425 426

    for object in self._archive.values():
      method_id = object.id
      is_catalog_method = self._is_catalog_method_archive[method_id]
427
      is_catalog_list_method = self._is_catalog_list_method_archive[method_id]
428 429 430 431 432 433 434 435 436 437
      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)

438 439 440 441 442
      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)

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
      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]

463 464 465 466 467
        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
468
      elif method_id in catalog.filter_dict.keys():
469
        catalog.filter_dict[method_id]['filtered'] = 0
470 471

    sql_catalog_object.sort()
472 473 474
    catalog.sql_catalog_object = tuple(sql_catalog_object)
    sql_catalog_object_list.sort()
    catalog.sql_catalog_object_list = tuple(sql_catalog_object_list)
475
    sql_uncatalog_object.sort()
476
    catalog.sql_uncatalog_object = tuple(sql_uncatalog_object)
477
    sql_update_object.sort()
478
    catalog.sql_update_object = tuple(sql_update_object)
479
    sql_clear_catalog.sort()
480
    catalog.sql_clear_catalog = tuple(sql_clear_catalog)
481 482

  def uninstall(self, context, **kw):
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    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)
498 499 500 501 502 503 504

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

      if method_id in sql_catalog_object:
        sql_catalog_object.remove(method_id)

505 506 507
      if method_id in sql_catalog_object_list:
        sql_catalog_object_list.remove(method_id)

508 509 510 511 512 513 514 515 516 517 518 519
      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]

520 521 522 523 524
    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)
525 526 527 528 529 530 531 532 533

    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
534

535
      "foo/bar[id=zoo]"
536

537
      into
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
      "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(
583 584 585 586 587 588
                    id = action.id
                  , name = action.title
                  , action = action.action
                  , condition = action.condition
                  , permission = action.permissions
                  , category = action.category
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
                  , 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():
614 615 616 617 618 619
      for property in p.propertyMap():
        if property['id'] == id:
          property['value'] = p.getProperty(id)
          break
      else:
        property = None
620 621
      if property is None:
        raise NotFound, 'the property %s is not found' % id
622 623
      #LOG('SitePropertyTemplateItem build', 0, 'property = %r' % (property,))
      self._archive[id] = property
624 625 626 627 628 629 630 631

  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
632
      p._setProperty(id, property['value'], type=property['type'])
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668

  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():
669 670 671 672
        module = portal._getOb(id)
        module.portal_type = mapping['portal_type'] # XXX
      else:
        module = portal.newContent(id=id, portal_type=mapping['portal_type'])
673 674
      module.setTitle(mapping['title'])
      for name,role_list in mapping['permission_list']:
675 676 677 678 679 680 681
        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
682

683 684 685 686 687
  def uninstall(self, context, **kw):
    p = context.getPortalObject()
    id_list = p.objectIds()
    for id in self._archive.keys():
      if id in id_list:
688 689 690 691
        try:
          p.manage_delObjects([id])
        except:
          pass
692 693
    BaseTemplateItem.uninstall(self, context, **kw)

694 695 696
  def trash(self, context, new_item, **kw):
    # Do not remove any module for safety.
    pass
697 698 699 700 701 702 703 704 705 706 707

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():
708
      writeLocalDocument(id, text, create=1) # This raises an exception if the file exists.
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
      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():
730
      writeLocalPropertySheet(id, text, create=1) # This raises an exception if the file exists.
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
      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():
752
      writeLocalExtension(id, text, create=1) # This raises an exception if the file exists.
753 754 755 756 757 758 759 760 761 762
      importLocalPropertySheet(id)

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

763 764 765 766 767 768 769 770 771 772
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():
773
      writeLocalTest(id, text, create=1) # This raises an exception if the file exists.
774 775 776 777 778 779 780 781 782

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

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

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)

810 811 812 813 814 815 816 817 818
  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
819
      if role in roles and role not in new_roles:
820 821 822
        del roles[role]
    p.__ac_roles__ = tuple(roles.keys())

823 824 825 826 827

class CatalogResultKeyTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
828 829 830 831 832 833 834 835 836 837

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

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

838
    sql_search_result_keys = list(catalog.sql_search_result_keys)
839
    for key in self._archive.keys():
840 841 842
      if key not in sql_search_result_keys:
        sql_search_result_keys.append(key)
    catalog.sql_search_result_keys = sql_search_result_keys
843 844

  def uninstall(self, context, **kw):
845 846 847 848 849 850 851 852 853 854
    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)
855 856 857
    for key in self._archive.keys():
      if key in sql_search_result_keys:
        sql_search_result_keys.remove(key)
858
    catalog.sql_search_result_keys = sql_search_result_keys
859 860 861
    BaseTemplateItem.uninstall(self, context, **kw)


862 863 864 865 866 867 868 869 870 871 872 873 874 875
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

876
    sql_catalog_related_keys = list(catalog.sql_catalog_related_keys)
877
    for key in self._archive.keys():
878 879 880
      if key not in sql_catalog_related_keys:
        sql_catalog_related_keys.append(key)
    catalog.sql_catalog_related_keys = sql_catalog_related_keys
881 882 883 884 885 886 887 888 889 890 891

  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

892
    sql_catalog_related_keys = list(catalog.sql_catalog_related_keys)
893 894 895 896 897 898 899
    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)


900 901 902 903
class CatalogResultTableTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
904 905 906 907 908 909 910 911 912 913

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

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

914 915 916 917 918
    sql_search_tables = list(catalog.sql_search_tables)
    for key in self._archive.keys():
      if key not in sql_search_tables:
        sql_search_tables.append(key)
    catalog.sql_search_tables = sql_search_tables
919 920

  def uninstall(self, context, **kw):
921 922 923 924 925 926 927 928 929 930
    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)
931 932 933
    for key in self._archive.keys():
      if key in sql_search_tables:
        sql_search_tables.remove(key)
934
    catalog.sql_search_tables = sql_search_tables
935 936 937
    BaseTemplateItem.uninstall(self, context, **kw)


938 939 940 941 942 943 944
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()
945 946
      # Export only erp5_ui at the moment. This is safer against information leak.
      for catalog in ('erp5_ui', ):
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
        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
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
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'
1031
    add_permission = Permissions.AddPortalContent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    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
1045
                      , PropertySheet.SimpleItem
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1046 1047 1048 1049 1050 1051 1052 1053 1054
                      , PropertySheet.CategoryCore
                      , PropertySheet.BusinessTemplate
                      )

    # Factory Type Information
    factory_type_information = \
      {    'id'             : portal_type
         , 'meta_type'      : meta_type
         , 'description'    : """\
1055
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
1056
         , 'icon'           : 'order_line_icon.gif'
1057
         , 'product'        : 'ERP5Type'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1058 1059 1060
         , 'factory'        : 'addBusinessTemplate'
         , 'immediate_view' : 'BusinessTemplate_view'
         , 'allow_discussion'     : 1
1061
         , 'allowed_content_types': (
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
                                      )
         , 'filter_content_types' : 1
         , 'global_allow'   : 1
         , 'actions'        :
        ( { 'id'            : 'view'
          , 'name'          : 'View'
          , 'category'      : 'object_view'
          , 'action'        : 'BusinessTemplate_view'
          , 'permissions'   : (
              Permissions.View, )
          }
1073 1074 1075
        , { 'id'            : 'history'
          , 'name'          : 'History'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1076
          , 'action'        : 'Base_viewHistory'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1077 1078 1079 1080 1081 1082
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'metadata'
          , 'name'          : 'Metadata'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1083
          , 'action'        : 'Base_viewMetadata'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1084
          , 'permissions'   : (
1085
              Permissions.ManageProperties, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1086 1087 1088
          }
        , { 'id'            : 'translate'
          , 'name'          : 'Translate'
1089
          , 'category'      : 'object_exchange'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1090 1091 1092 1093
          , 'action'        : 'translation_template_view'
          , 'permissions'   : (
              Permissions.TranslateContent, )
          }
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
        , { '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
1115 1116 1117
        )
      }

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    _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
1130
    _test_item = None
1131 1132 1133
    _product_item = None
    _role_item = None
    _catalog_result_key_item = None
1134
    _catalog_related_key_item = None
1135
    _catalog_result_table_item = None
1136
    _message_translation_item = None
1137

1138 1139 1140 1141 1142 1143 1144 1145
    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:
1146 1147
          # 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
1148

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1149 1150 1151 1152
    def build(self):
      """
        Copy existing portal objects to self
      """
1153 1154
      # Make sure that everything is sane.
      self.clean()
1155

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1156
      # Copy portal_types
1157 1158 1159
      self._portal_type_item = PortalTypeTemplateItem(self.getTemplatePortalTypeIdList())
      self._portal_type_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1160
      # Copy workflows
1161 1162 1163
      self._workflow_item = WorkflowTemplateItem(self.getTemplateWorkflowIdList())
      self._workflow_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1164
      # Copy skins
1165 1166 1167
      self._skin_item = SkinTemplateItem(self.getTemplateSkinIdList())
      self._skin_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1168
      # Copy categories
1169 1170 1171
      self._category_item = CategoryTemplateItem(self.getTemplateBaseCategoryList())
      self._category_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1172
      # Copy catalog methods
1173 1174 1175
      self._catalog_method_item = CatalogMethodTemplateItem(self.getTemplateCatalogMethodIdList())
      self._catalog_method_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1176
      # Copy actions
1177 1178 1179
      self._action_item = ActionTemplateItem(self.getTemplateActionPathList())
      self._action_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1180
      # Copy properties
1181 1182 1183
      self._site_property_item = SitePropertyTemplateItem(self.getTemplateSitePropertyIdList())
      self._site_property_item.build(self)

1184
      # Copy modules
1185 1186
      self._module_item = ModuleTemplateItem(self.getTemplateModuleIdList())
      self._module_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1187

1188
      # Copy Document Classes
1189 1190
      self._document_item = DocumentTemplateItem(self.getTemplateDocumentIdList())
      self._document_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1191

1192
      # Copy Propertysheet Classes
1193 1194
      self._property_sheet_item = PropertySheetTemplateItem(self.getTemplatePropertySheetIdList())
      self._property_sheet_item.build(self)
1195 1196

      # Copy Extensions Classes (useful for catalog)
1197 1198
      self._extension_item = ExtensionTemplateItem(self.getTemplateExtensionIdList())
      self._extension_item.build(self)
1199

1200 1201 1202 1203
      # Copy Test Classes
      self._test_item = TestTemplateItem(self.getTemplateTestIdList())
      self._test_item.build(self)

1204
      # Copy Products
1205 1206
      self._product_item = ProductTemplateItem(self.getTemplateProductIdList())
      self._product_item.build(self)
1207 1208

      # Copy roles
1209 1210
      self._role_item = RoleTemplateItem(self.getTemplateRoleList())
      self._role_item.build(self)
1211

1212 1213 1214
      # Copy catalog result keys
      self._catalog_result_key_item = CatalogResultKeyTemplateItem(self.getTemplateCatalogResultKeyList())
      self._catalog_result_key_item.build(self)
1215

1216 1217 1218 1219
      # Copy catalog related keys
      self._catalog_related_key_item = CatalogRelatedKeyTemplateItem(self.getTemplateCatalogRelatedKeyList())
      self._catalog_related_key_item.build(self)

1220
      # Copy catalog result tables
1221 1222
      self._catalog_result_table_item = CatalogResultTableTemplateItem(self.getTemplateCatalogResultTableList())
      self._catalog_result_table_item.build(self)
1223

1224 1225 1226 1227
      # Copy message translations
      self._message_translation_item = MessageTranslationTemplateItem(self.getTemplateMessageTranslationList())
      self._message_translation_item.build(self)

1228 1229 1230
      # Other objects
      self._path_item = PathTemplateItem(self.getTemplatePathList())
      self._path_item.build(self)
1231

1232
    build = WorkflowMethod(build)
1233 1234

    def publish(self, url, username=None, password=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1235 1236 1237
      """
        Publish in a format or another
      """
1238
      return self.portal_templates.publish(self, url, username=username, password=password)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1239

1240
    def update(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1241
      """
1242
        Update template: download new template defition
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1243
      """
1244
      return self.portal_templates.update(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1245

1246
    def install(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1247 1248 1249
      """
        For install based on paramaters provided in **kw
      """
1250 1251
      installed_bt = self.portal_templates.getInstalledBusinessTemplate(self.getTitle())
      if installed_bt is not None:
1252 1253
        installed_bt.trash(self)
        installed_bt.replace()
1254

1255
      # Update local dictionary containing all setup parameters
1256 1257 1258 1259 1260
      # This may include mappings
      self.portal_templates.updateLocalConfiguration(self, **kw)
      local_configuration = self.portal_templates.getLocalConfiguration(self)

      # Classes and security information
1261 1262 1263 1264
      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)
1265
      if self._test_item is not None: self._test_item.install(local_configuration)
1266
      if self._role_item is not None: self._role_item.install(local_configuration)
1267

1268
      # Message translations
1269
      if self._message_translation_item is not None: self._message_translation_item.install(local_configuration)
1270

1271
      # Objects and properties
1272 1273 1274
      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)
1275

1276
      # Portal Types
1277
      if self._portal_type_item is not None: self._portal_type_item.install(local_configuration)
1278

1279
      # Categories
1280
      if self._category_item is not None: self._category_item.install(local_configuration,**kw)
1281

1282
      # Modules.
1283
      if self._module_item is not None: self._module_item.install(local_configuration)
1284

1285 1286 1287
      # 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)

1288
      # Skins
1289
      if self._skin_item is not None: self._skin_item.install(local_configuration)
1290

1291
      # Actions, catalog
1292 1293
      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)
1294
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.install(local_configuration)
1295
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.install(local_configuration)
1296

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1297 1298 1299
      # It is better to clear cache because the installation of a template
      # adds many new things into the portal.
      clearCache()
1300

1301
    install = WorkflowMethod(install)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1302

1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
    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
1315 1316
      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)
1317
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.trash(local_configuration, new_bt._catalog_related_key_item)
1318
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.trash(local_configuration, new_bt._catalog_result_table_item)
1319 1320

      # Skins
1321
      if self._skin_item is not None: self._skin_item.trash(local_configuration, new_bt._skin_item)
1322 1323

      # Portal Types
1324
      if self._portal_type_item is not None: self._portal_type_item.trash(local_configuration, new_bt._portal_type_item)
1325 1326

      # Modules.
1327
      if self._module_item is not None: self._module_item.trash(local_configuration, new_bt._module_item)
1328 1329

      # Objects and properties
1330 1331 1332 1333 1334
      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)
1335

1336
      # Message translations
1337
      if self._message_translation_item is not None: self._message_translation_item.trash(local_configuration, new_bt._message_translation_item)
1338

1339
      # Classes and security information
1340 1341 1342 1343
      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)
1344
      if self._test_item is not None: self._test_item.trash(local_configuration, new_bt._test_item)
1345
      if self._role_item is not None: self._role_item.trash(local_configuration, new_bt._role_item)
1346

1347
    def uninstall(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1348
      """
1349
        For uninstall based on paramaters provided in **kw
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1350
      """
1351 1352 1353 1354
      # 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
1355

1356
      # Actions, catalog
1357 1358
      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)
1359
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.uninstall(local_configuration)
1360
      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
1361

1362
      # Skins
1363
      if self._skin_item is not None: self._skin_item.uninstall(local_configuration)
1364 1365

      # Portal Types
1366
      if self._portal_type_item is not None: self._portal_type_item.uninstall(local_configuration)
1367 1368

      # Modules.
1369
      if self._module_item is not None: self._module_item.uninstall(local_configuration)
1370 1371

      # Objects and properties
1372 1373 1374 1375 1376
      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)
1377

1378
      # Message translations
1379
      if self._message_translation_item is not None: self._message_translation_item.uninstall(local_configuration)
1380

1381
      # Classes and security information
1382 1383 1384 1385
      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)
1386
      if self._test_item is not None: self._test_item.uninstall(local_configuration)
1387
      if self._role_item is not None: self._role_item.uninstall(local_configuration)
1388 1389 1390 1391

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

1393 1394 1395
    uninstall = WorkflowMethod(uninstall)

    def clean(self):
1396
      """
1397
        Clean built information.
1398
      """
1399
      # First, remove obsolete attributes if present.
1400
      for attr in ('_action_archive', '_document_archive', '_extension_archive', '_test_archive', '_module_archive',
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
                   '_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
1417
      self._test_item = None
1418 1419 1420
      self._product_item = None
      self._role_item = None
      self._catalog_result_key_item = None
1421
      self._catalog_related_key_item = None
1422
      self._catalog_result_table_item = None
1423
      self._message_translation_item = None
1424 1425

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

1427 1428
    security.declareProtected(Permissions.AccessContentsInformation, 'getBuildingState')
    def getBuildingState(self, id_only=1):
1429
      """
1430
        Returns the current state in building
1431
      """
1432 1433 1434
      portal_workflow = getToolByName(self, 'portal_workflow')
      wf = portal_workflow.getWorkflowById('business_template_building_workflow')
      return wf._getWorkflowStateOf(self, id_only=id_only )
1435

1436 1437
    security.declareProtected(Permissions.AccessContentsInformation, 'getInstallationState')
    def getInstallationState(self, id_only=1):
1438
      """
1439
        Returns the current state in installation
1440
      """
1441 1442 1443
      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
1444

1445
    def _getOrderedList(self, id):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1446
      """
1447 1448
        We have to set this method because we want an
        ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1449
      """
1450 1451 1452 1453 1454 1455 1456 1457
      #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
1458

1459
    def getTemplateCatalogMethodIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1460
      """
1461 1462
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1463
      """
1464
      return self._getOrderedList('template_catalog_method_id')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1465

1466
    def getTemplateBaseCategoryList(self):
1467
      """
1468 1469
      We have to set this method because we want an
      ordered list
1470
      """
1471
      return self._getOrderedList('template_base_category')
1472

1473
    def getTemplateWorkflowIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1474
      """
1475 1476
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1477
      """
1478
      return self._getOrderedList('template_workflow_id')
1479

1480
    def getTemplatePortalTypeIdList(self):
1481
      """
1482 1483
      We have to set this method because we want an
      ordered list
1484
      """
1485
      return self._getOrderedList('template_portal_type_id')
1486

1487
    def getTemplateActionPathList(self):
1488
      """
1489 1490
      We have to set this method because we want an
      ordered list
1491
      """
1492
      return self._getOrderedList('template_action_path')
1493

1494
    def getTemplateSkinIdList(self):
1495
      """
1496 1497
      We have to set this method because we want an
      ordered list
1498
      """
1499
      return self._getOrderedList('template_skin_id')
1500

1501
    def getTemplateModuleIdList(self):
1502
      """
1503 1504
      We have to set this method because we want an
      ordered list
1505
      """
1506
      return self._getOrderedList('template_module_id')
1507 1508 1509 1510 1511 1512 1513

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