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

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

from zLOG import LOG

46 47
class TemplateConflictError(Exception): pass

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

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

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

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

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

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

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

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

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

97
  def _backupObject(self, container, object_id, **kw):
98
    container_ids = container.objectIds()
99 100 101 102 103 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
      # 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():
203
          raise TemplateConflictError, 'the category %s already exists' % category_id
204
        category = category_tool.newContent(portal_type='Base Category',id=category_id)
205 206 207 208
        property_list = self._light_archive[category_id]['property_list']
        for property,value in property_list.items():
          category.setProperty(property,value)

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

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(',')
230
      for relative_url, object in self._archive.items():
231
        skin_id = relative_url.split('/')[-1]
232 233 234 235
        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)
236 237 238 239 240 241 242 243 244 245 246 247 248 249
      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)
250

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    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
268
    This is only useful in order to use
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    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)
318 319


320 321
class CatalogMethodTemplateItem(ObjectTemplateItem):

322 323 324
  def __init__(self, id_list, **kw):
    ObjectTemplateItem.__init__(self, id_list, tool_id='portal_catalog', **kw)
    self._is_catalog_method_archive = PersistentMapping()
325
    self._is_catalog_list_method_archive = PersistentMapping()
326 327 328 329 330 331 332 333 334 335
    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)
336 337 338 339 340 341 342 343 344

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

    if catalog is None:
      return

345 346
    for object in self._archive.values():
      method_id = object.id
347 348 349 350 351
      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
352
      self._is_filtered_archive[method_id] = 0
353 354 355 356 357
      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']
358 359 360 361

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

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    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)
377 378 379 380

    for object in self._archive.values():
      method_id = object.id
      is_catalog_method = self._is_catalog_method_archive[method_id]
381
      is_catalog_list_method = self._is_catalog_list_method_archive[method_id]
382 383 384 385 386 387 388 389 390 391
      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)

392 393 394 395 396
      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)

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
      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]

417 418 419 420 421
        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
422
      elif method_id in catalog.filter_dict.keys():
423
        catalog.filter_dict[method_id]['filtered'] = 0
424 425

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

  def uninstall(self, context, **kw):
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    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)
452 453 454 455 456 457 458

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

      if method_id in sql_catalog_object:
        sql_catalog_object.remove(method_id)

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

462 463 464 465 466 467 468 469 470 471 472 473
      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]

474 475 476 477 478
    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)
479 480 481 482 483 484 485 486 487

    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
488

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

491
      into
492

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
      "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(
537 538 539 540 541 542
                    id = action.id
                  , name = action.title
                  , action = action.action
                  , condition = action.condition
                  , permission = action.permissions
                  , category = action.category
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
                  , 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():
568 569 570 571 572 573
      for property in p.propertyMap():
        if property['id'] == id:
          property['value'] = p.getProperty(id)
          break
      else:
        property = None
574 575
      if property is None:
        raise NotFound, 'the property %s is not found' % id
576 577
      #LOG('SitePropertyTemplateItem build', 0, 'property = %r' % (property,))
      self._archive[id] = property
578 579 580 581 582 583 584 585

  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
586
      p._setProperty(id, property['value'], type=property['type'])
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 617 618 619 620 621 622

  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():
623 624 625 626
        module = portal._getOb(id)
        module.portal_type = mapping['portal_type'] # XXX
      else:
        module = portal.newContent(id=id, portal_type=mapping['portal_type'])
627 628
      module.setTitle(mapping['title'])
      for name,role_list in mapping['permission_list']:
629 630 631 632 633 634 635
        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
636

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

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

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():
662
      writeLocalDocument(id, text, create=1) # This raises an exception if the file exists.
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
      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():
684
      writeLocalPropertySheet(id, text, create=1) # This raises an exception if the file exists.
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
      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():
706
      writeLocalExtension(id, text, create=1) # This raises an exception if the file exists.
707 708 709 710 711 712 713 714 715 716
      importLocalPropertySheet(id)

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

717 718 719 720 721 722 723 724 725 726
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():
727
      writeLocalTest(id, text, create=1) # This raises an exception if the file exists.
728 729 730 731 732 733 734 735 736

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

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

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)

764 765 766 767 768 769 770 771 772
  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
773
      if role in roles and role not in new_roles:
774 775 776
        del roles[role]
    p.__ac_roles__ = tuple(roles.keys())

777 778 779 780 781

class CatalogResultKeyTemplateItem(BaseTemplateItem):

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

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

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

792
    sql_search_result_keys = list(catalog.sql_search_result_keys)
793
    for key in self._archive.keys():
794 795 796
      if key not in sql_search_result_keys:
        sql_search_result_keys.append(key)
    catalog.sql_search_result_keys = sql_search_result_keys
797 798

  def uninstall(self, context, **kw):
799 800 801 802 803 804 805 806 807 808
    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)
809 810 811
    for key in self._archive.keys():
      if key in sql_search_result_keys:
        sql_search_result_keys.remove(key)
812
    catalog.sql_search_result_keys = sql_search_result_keys
813 814 815
    BaseTemplateItem.uninstall(self, context, **kw)


816 817 818 819 820 821 822 823 824 825 826 827 828 829
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

830
    sql_catalog_related_keys = list(catalog.sql_catalog_related_keys)
831
    for key in self._archive.keys():
832 833 834
      if key not in sql_catalog_related_keys:
        sql_catalog_related_keys.append(key)
    catalog.sql_catalog_related_keys = sql_catalog_related_keys
835 836 837 838 839 840 841 842 843 844 845

  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

846
    sql_catalog_related_keys = list(catalog.sql_catalog_related_keys)
847 848 849 850 851 852 853
    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)


854 855 856 857
class CatalogResultTableTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
858 859 860 861 862 863 864 865 866 867

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

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

868 869 870 871 872
    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
873 874

  def uninstall(self, context, **kw):
875 876 877 878 879 880 881 882 883 884
    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)
885 886 887
    for key in self._archive.keys():
      if key in sql_search_tables:
        sql_search_tables.remove(key)
888
    catalog.sql_search_tables = sql_search_tables
889 890 891
    BaseTemplateItem.uninstall(self, context, **kw)


892 893 894 895 896 897 898
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()
899 900
      # Export only erp5_ui at the moment. This is safer against information leak.
      for catalog in ('erp5_ui', ):
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
        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
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
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'
985
    add_permission = Permissions.AddPortalContent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
986 987 988 989 990 991 992 993 994 995 996 997 998
    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
999
                      , PropertySheet.SimpleItem
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1000 1001 1002 1003 1004 1005 1006 1007 1008
                      , PropertySheet.CategoryCore
                      , PropertySheet.BusinessTemplate
                      )

    # Factory Type Information
    factory_type_information = \
      {    'id'             : portal_type
         , 'meta_type'      : meta_type
         , 'description'    : """\
1009
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
1010
         , 'icon'           : 'order_line_icon.gif'
1011
         , 'product'        : 'ERP5Type'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1012 1013 1014
         , 'factory'        : 'addBusinessTemplate'
         , 'immediate_view' : 'BusinessTemplate_view'
         , 'allow_discussion'     : 1
1015
         , 'allowed_content_types': (
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
                                      )
         , 'filter_content_types' : 1
         , 'global_allow'   : 1
         , 'actions'        :
        ( { 'id'            : 'view'
          , 'name'          : 'View'
          , 'category'      : 'object_view'
          , 'action'        : 'BusinessTemplate_view'
          , 'permissions'   : (
              Permissions.View, )
          }
1027 1028 1029
        , { 'id'            : 'history'
          , 'name'          : 'History'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1030
          , 'action'        : 'Base_viewHistory'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1031 1032 1033 1034 1035 1036
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'metadata'
          , 'name'          : 'Metadata'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1037
          , 'action'        : 'Base_viewMetadata'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1038
          , 'permissions'   : (
1039
              Permissions.ManageProperties, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1040 1041 1042
          }
        , { 'id'            : 'translate'
          , 'name'          : 'Translate'
1043
          , 'category'      : 'object_exchange'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1044 1045 1046 1047
          , 'action'        : 'translation_template_view'
          , 'permissions'   : (
              Permissions.TranslateContent, )
          }
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        , { '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
1069 1070 1071
        )
      }

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    _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
1084
    _test_item = None
1085 1086 1087
    _product_item = None
    _role_item = None
    _catalog_result_key_item = None
1088
    _catalog_related_key_item = None
1089
    _catalog_result_table_item = None
1090
    _message_translation_item = None
1091

1092 1093 1094 1095 1096 1097 1098 1099
    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:
1100 1101
          # 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
1102

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1103 1104 1105 1106
    def build(self):
      """
        Copy existing portal objects to self
      """
1107 1108
      # Make sure that everything is sane.
      self.clean()
1109

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1110
      # Copy portal_types
1111 1112 1113
      self._portal_type_item = PortalTypeTemplateItem(self.getTemplatePortalTypeIdList())
      self._portal_type_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1114
      # Copy workflows
1115 1116 1117
      self._workflow_item = WorkflowTemplateItem(self.getTemplateWorkflowIdList())
      self._workflow_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1118
      # Copy skins
1119 1120 1121
      self._skin_item = SkinTemplateItem(self.getTemplateSkinIdList())
      self._skin_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1122
      # Copy categories
1123 1124 1125
      self._category_item = CategoryTemplateItem(self.getTemplateBaseCategoryList())
      self._category_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1126
      # Copy catalog methods
1127 1128 1129
      self._catalog_method_item = CatalogMethodTemplateItem(self.getTemplateCatalogMethodIdList())
      self._catalog_method_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1130
      # Copy actions
1131 1132 1133
      self._action_item = ActionTemplateItem(self.getTemplateActionPathList())
      self._action_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1134
      # Copy properties
1135 1136 1137
      self._site_property_item = SitePropertyTemplateItem(self.getTemplateSitePropertyIdList())
      self._site_property_item.build(self)

1138
      # Copy modules
1139 1140
      self._module_item = ModuleTemplateItem(self.getTemplateModuleIdList())
      self._module_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1141

1142
      # Copy Document Classes
1143 1144
      self._document_item = DocumentTemplateItem(self.getTemplateDocumentIdList())
      self._document_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1145

1146
      # Copy Propertysheet Classes
1147 1148
      self._property_sheet_item = PropertySheetTemplateItem(self.getTemplatePropertySheetIdList())
      self._property_sheet_item.build(self)
1149 1150

      # Copy Extensions Classes (useful for catalog)
1151 1152
      self._extension_item = ExtensionTemplateItem(self.getTemplateExtensionIdList())
      self._extension_item.build(self)
1153

1154 1155 1156 1157
      # Copy Test Classes
      self._test_item = TestTemplateItem(self.getTemplateTestIdList())
      self._test_item.build(self)

1158
      # Copy Products
1159 1160
      self._product_item = ProductTemplateItem(self.getTemplateProductIdList())
      self._product_item.build(self)
1161 1162

      # Copy roles
1163 1164
      self._role_item = RoleTemplateItem(self.getTemplateRoleList())
      self._role_item.build(self)
1165

1166 1167 1168
      # Copy catalog result keys
      self._catalog_result_key_item = CatalogResultKeyTemplateItem(self.getTemplateCatalogResultKeyList())
      self._catalog_result_key_item.build(self)
1169

1170 1171 1172 1173
      # Copy catalog related keys
      self._catalog_related_key_item = CatalogRelatedKeyTemplateItem(self.getTemplateCatalogRelatedKeyList())
      self._catalog_related_key_item.build(self)

1174
      # Copy catalog result tables
1175 1176
      self._catalog_result_table_item = CatalogResultTableTemplateItem(self.getTemplateCatalogResultTableList())
      self._catalog_result_table_item.build(self)
1177

1178 1179 1180 1181
      # Copy message translations
      self._message_translation_item = MessageTranslationTemplateItem(self.getTemplateMessageTranslationList())
      self._message_translation_item.build(self)

1182 1183 1184
      # Other objects
      self._path_item = PathTemplateItem(self.getTemplatePathList())
      self._path_item.build(self)
1185

1186
    build = WorkflowMethod(build)
1187 1188

    def publish(self, url, username=None, password=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1189 1190 1191
      """
        Publish in a format or another
      """
1192
      return self.portal_templates.publish(self, url, username=username, password=password)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1193

1194
    def update(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1195
      """
1196
        Update template: download new template defition
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1197
      """
1198
      return self.portal_templates.update(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1199

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

1209
      # Update local dictionary containing all setup parameters
1210 1211 1212 1213 1214
      # This may include mappings
      self.portal_templates.updateLocalConfiguration(self, **kw)
      local_configuration = self.portal_templates.getLocalConfiguration(self)

      # Classes and security information
1215 1216 1217 1218
      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)
1219
      if self._test_item is not None: self._test_item.install(local_configuration)
1220
      if self._role_item is not None: self._role_item.install(local_configuration)
1221

1222
      # Message translations
1223
      if self._message_translation_item is not None: self._message_translation_item.install(local_configuration)
1224

1225
      # Objects and properties
1226 1227 1228
      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)
1229

1230
      # Portal Types
1231
      if self._portal_type_item is not None: self._portal_type_item.install(local_configuration)
1232

1233
      # Categories
1234
      if self._category_item is not None: self._category_item.install(local_configuration,**kw)
1235

1236
      # Modules.
1237
      if self._module_item is not None: self._module_item.install(local_configuration)
1238

1239 1240 1241
      # 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)

1242
      # Skins
1243
      if self._skin_item is not None: self._skin_item.install(local_configuration)
1244

1245
      # Actions, catalog
1246 1247
      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)
1248
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.install(local_configuration)
1249
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.install(local_configuration)
1250

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1251 1252 1253
      # It is better to clear cache because the installation of a template
      # adds many new things into the portal.
      clearCache()
1254

1255
    install = WorkflowMethod(install)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1256

1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
    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
1269 1270
      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)
1271
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.trash(local_configuration, new_bt._catalog_related_key_item)
1272
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.trash(local_configuration, new_bt._catalog_result_table_item)
1273 1274

      # Skins
1275
      if self._skin_item is not None: self._skin_item.trash(local_configuration, new_bt._skin_item)
1276 1277

      # Portal Types
1278
      if self._portal_type_item is not None: self._portal_type_item.trash(local_configuration, new_bt._portal_type_item)
1279 1280

      # Modules.
1281
      if self._module_item is not None: self._module_item.trash(local_configuration, new_bt._module_item)
1282 1283

      # Objects and properties
1284 1285 1286 1287 1288
      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)
1289

1290
      # Message translations
1291
      if self._message_translation_item is not None: self._message_translation_item.trash(local_configuration, new_bt._message_translation_item)
1292

1293
      # Classes and security information
1294 1295 1296 1297
      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)
1298
      if self._test_item is not None: self._test_item.trash(local_configuration, new_bt._test_item)
1299
      if self._role_item is not None: self._role_item.trash(local_configuration, new_bt._role_item)
1300

1301
    def uninstall(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1302
      """
1303
        For uninstall based on paramaters provided in **kw
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1304
      """
1305 1306 1307 1308
      # 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
1309

1310
      # Actions, catalog
1311 1312
      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)
1313
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.uninstall(local_configuration)
1314
      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
1315

1316
      # Skins
1317
      if self._skin_item is not None: self._skin_item.uninstall(local_configuration)
1318 1319

      # Portal Types
1320
      if self._portal_type_item is not None: self._portal_type_item.uninstall(local_configuration)
1321 1322

      # Modules.
1323
      if self._module_item is not None: self._module_item.uninstall(local_configuration)
1324 1325

      # Objects and properties
1326 1327 1328 1329 1330
      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)
1331

1332
      # Message translations
1333
      if self._message_translation_item is not None: self._message_translation_item.uninstall(local_configuration)
1334

1335
      # Classes and security information
1336 1337 1338 1339
      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)
1340
      if self._test_item is not None: self._test_item.uninstall(local_configuration)
1341
      if self._role_item is not None: self._role_item.uninstall(local_configuration)
1342 1343 1344 1345

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

1347 1348 1349
    uninstall = WorkflowMethod(uninstall)

    def clean(self):
1350
      """
1351
        Clean built information.
1352
      """
1353
      # First, remove obsolete attributes if present.
1354
      for attr in ('_action_archive', '_document_archive', '_extension_archive', '_test_archive', '_module_archive',
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
                   '_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
1371
      self._test_item = None
1372 1373 1374
      self._product_item = None
      self._role_item = None
      self._catalog_result_key_item = None
1375
      self._catalog_related_key_item = None
1376
      self._catalog_result_table_item = None
1377
      self._message_translation_item = None
1378 1379

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

1381 1382
    security.declareProtected(Permissions.AccessContentsInformation, 'getBuildingState')
    def getBuildingState(self, id_only=1):
1383
      """
1384
        Returns the current state in building
1385
      """
1386 1387 1388
      portal_workflow = getToolByName(self, 'portal_workflow')
      wf = portal_workflow.getWorkflowById('business_template_building_workflow')
      return wf._getWorkflowStateOf(self, id_only=id_only )
1389

1390 1391
    security.declareProtected(Permissions.AccessContentsInformation, 'getInstallationState')
    def getInstallationState(self, id_only=1):
1392
      """
1393
        Returns the current state in installation
1394
      """
1395 1396 1397
      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
1398

1399
    def _getOrderedList(self, id):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1400
      """
1401 1402
        We have to set this method because we want an
        ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1403
      """
1404 1405 1406 1407 1408 1409 1410 1411
      #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
1412

1413
    def getTemplateCatalogMethodIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1414
      """
1415 1416
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1417
      """
1418
      return self._getOrderedList('template_catalog_method_id')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1419

1420
    def getTemplateBaseCategoryList(self):
1421
      """
1422 1423
      We have to set this method because we want an
      ordered list
1424
      """
1425
      return self._getOrderedList('template_base_category')
1426

1427
    def getTemplateWorkflowIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1428
      """
1429 1430
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1431
      """
1432
      return self._getOrderedList('template_workflow_id')
1433

1434
    def getTemplatePortalTypeIdList(self):
1435
      """
1436 1437
      We have to set this method because we want an
      ordered list
1438
      """
1439
      return self._getOrderedList('template_portal_type_id')
1440

1441
    def getTemplateActionPathList(self):
1442
      """
1443 1444
      We have to set this method because we want an
      ordered list
1445
      """
1446
      return self._getOrderedList('template_action_path')
1447

1448
    def getTemplateSkinIdList(self):
1449
      """
1450 1451
      We have to set this method because we want an
      ordered list
1452
      """
1453
      return self._getOrderedList('template_skin_id')
1454

1455
    def getTemplateModuleIdList(self):
1456
      """
1457 1458
      We have to set this method because we want an
      ordered list
1459
      """
1460
      return self._getOrderedList('template_module_id')
1461 1462 1463 1464 1465 1466 1467

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