BusinessTemplate.py 58.1 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
30
from Acquisition import Implicit, aq_base
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

class SkinTemplateItem(ObjectTemplateItem):

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

261 262 263 264 265 266 267 268 269 270 271 272
  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)
      if hasattr(aq_base(object), 'objectValues'):
        for script in object.objectValues(spec=('Script (Python)',)):
          if getattr(aq_base(script), '_code', None) is not None:
            LOG('Business Template', 0, 'clear _code in %r' % (script,))
273 274
            # Disable this at the moment, until the unstability is solved.
            #script._code = None
275 276 277
      self._archive[relative_url] = object
      object.wl_clearLocks()

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
  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(',')
293
      for relative_url, object in self._archive.items():
294
        skin_id = relative_url.split('/')[-1]
295 296 297 298
        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)
299 300 301 302 303 304 305 306 307 308 309 310 311 312
      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)
313

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    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
331
    This is only useful in order to use
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    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)
381 382


383 384
class CatalogMethodTemplateItem(ObjectTemplateItem):

385 386 387
  def __init__(self, id_list, **kw):
    ObjectTemplateItem.__init__(self, id_list, tool_id='portal_catalog', **kw)
    self._is_catalog_method_archive = PersistentMapping()
388
    self._is_catalog_list_method_archive = PersistentMapping()
389 390 391 392 393 394 395 396 397 398
    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)
399 400 401 402 403 404 405 406 407

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

    if catalog is None:
      return

408 409
    for object in self._archive.values():
      method_id = object.id
410 411 412 413 414
      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
415
      self._is_filtered_archive[method_id] = 0
416 417 418 419 420
      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']
421 422 423 424

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

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    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)
440 441 442 443

    for object in self._archive.values():
      method_id = object.id
      is_catalog_method = self._is_catalog_method_archive[method_id]
444
      is_catalog_list_method = self._is_catalog_list_method_archive[method_id]
445 446 447 448 449 450 451 452 453 454
      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)

455 456 457 458 459
      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)

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
      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]

480 481 482 483 484
        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
485
      elif method_id in catalog.filter_dict.keys():
486
        catalog.filter_dict[method_id]['filtered'] = 0
487 488

    sql_catalog_object.sort()
489 490 491
    catalog.sql_catalog_object = tuple(sql_catalog_object)
    sql_catalog_object_list.sort()
    catalog.sql_catalog_object_list = tuple(sql_catalog_object_list)
492
    sql_uncatalog_object.sort()
493
    catalog.sql_uncatalog_object = tuple(sql_uncatalog_object)
494
    sql_update_object.sort()
495
    catalog.sql_update_object = tuple(sql_update_object)
496
    sql_clear_catalog.sort()
497
    catalog.sql_clear_catalog = tuple(sql_clear_catalog)
498 499

  def uninstall(self, context, **kw):
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    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)
515 516 517 518 519 520 521

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

      if method_id in sql_catalog_object:
        sql_catalog_object.remove(method_id)

522 523 524
      if method_id in sql_catalog_object_list:
        sql_catalog_object_list.remove(method_id)

525 526 527 528 529 530 531 532 533
      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)

Yoshinori Okuji's avatar
Yoshinori Okuji committed
534
      if catalog.filter_dict.has_key(method_id):
535
        del catalog.filter_dict[method_id]
536

537 538 539 540 541
    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)
542 543 544 545 546 547 548 549 550

    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
551

552
      "foo/bar[id=zoo]"
553

554
      into
555

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
      "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:
584
          #LOG('BusinessTemplate', 0, 'ai = %r, ai.action = %r, key = %r, value = %r' % (ai, ai.action, key, value))
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
          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(
601 602
                    id = action.id
                  , name = action.title
603
                  , action = action.action.text
604 605 606
                  , condition = action.condition
                  , permission = action.permissions
                  , category = action.category
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
                  , 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():
632 633 634 635 636 637
      for property in p.propertyMap():
        if property['id'] == id:
          property['value'] = p.getProperty(id)
          break
      else:
        property = None
638 639
      if property is None:
        raise NotFound, 'the property %s is not found' % id
640 641
      #LOG('SitePropertyTemplateItem build', 0, 'property = %r' % (property,))
      self._archive[id] = property
642 643 644 645 646 647 648 649

  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
650
      p._setProperty(id, property['value'], type=property['type'])
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686

  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():
687 688 689 690
        module = portal._getOb(id)
        module.portal_type = mapping['portal_type'] # XXX
      else:
        module = portal.newContent(id=id, portal_type=mapping['portal_type'])
691 692
      module.setTitle(mapping['title'])
      for name,role_list in mapping['permission_list']:
693 694 695 696 697 698 699
        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
700

701 702 703 704 705
  def uninstall(self, context, **kw):
    p = context.getPortalObject()
    id_list = p.objectIds()
    for id in self._archive.keys():
      if id in id_list:
706 707 708 709
        try:
          p.manage_delObjects([id])
        except:
          pass
710 711
    BaseTemplateItem.uninstall(self, context, **kw)

712 713 714
  def trash(self, context, new_item, **kw):
    # Do not remove any module for safety.
    pass
715 716 717 718 719 720 721 722 723 724 725

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():
726
      writeLocalDocument(id, text, create=1) # This raises an exception if the file exists.
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
      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():
748
      writeLocalPropertySheet(id, text, create=1) # This raises an exception if the file exists.
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
      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():
770
      writeLocalExtension(id, text, create=1) # This raises an exception if the file exists.
771 772 773 774 775 776 777 778 779 780
      importLocalPropertySheet(id)

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

781 782 783 784 785 786 787 788 789 790
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():
791
      writeLocalTest(id, text, create=1) # This raises an exception if the file exists.
792 793 794 795 796 797 798 799 800

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

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827

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)

828 829 830 831 832 833 834 835 836
  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
837
      if role in roles and role not in new_roles:
838 839 840
        del roles[role]
    p.__ac_roles__ = tuple(roles.keys())

841 842 843 844 845

class CatalogResultKeyTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
846 847 848 849 850 851 852 853 854 855

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

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

856
    sql_search_result_keys = list(catalog.sql_search_result_keys)
857
    for key in self._archive.keys():
858 859 860
      if key not in sql_search_result_keys:
        sql_search_result_keys.append(key)
    catalog.sql_search_result_keys = sql_search_result_keys
861 862

  def uninstall(self, context, **kw):
863 864 865 866 867 868 869 870 871 872
    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)
873 874 875
    for key in self._archive.keys():
      if key in sql_search_result_keys:
        sql_search_result_keys.remove(key)
876
    catalog.sql_search_result_keys = sql_search_result_keys
877 878 879
    BaseTemplateItem.uninstall(self, context, **kw)


880 881 882 883 884 885 886 887 888 889 890 891 892 893
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

894
    sql_catalog_related_keys = list(catalog.sql_catalog_related_keys)
895
    for key in self._archive.keys():
896 897 898
      if key not in sql_catalog_related_keys:
        sql_catalog_related_keys.append(key)
    catalog.sql_catalog_related_keys = sql_catalog_related_keys
899 900 901 902 903 904 905 906 907 908 909

  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

910
    sql_catalog_related_keys = list(catalog.sql_catalog_related_keys)
911 912 913 914 915 916 917
    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)


918 919 920 921
class CatalogResultTableTemplateItem(BaseTemplateItem):

  def install(self, context, **kw):
    BaseTemplateItem.install(self, context, **kw)
922 923 924 925 926 927 928 929 930 931

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

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

932 933 934 935 936
    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
937 938

  def uninstall(self, context, **kw):
939 940 941 942 943 944 945 946 947 948
    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)
949 950 951
    for key in self._archive.keys():
      if key in sql_search_tables:
        sql_search_tables.remove(key)
952
    catalog.sql_search_tables = sql_search_tables
953 954 955
    BaseTemplateItem.uninstall(self, context, **kw)


956 957 958 959 960 961 962
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()
963 964
      # Export only erp5_ui at the moment. This is safer against information leak.
      for catalog in ('erp5_ui', ):
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
        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
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 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
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'
1049
    add_permission = Permissions.AddPortalContent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    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
1063
                      , PropertySheet.SimpleItem
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1064 1065 1066 1067 1068 1069 1070 1071 1072
                      , PropertySheet.CategoryCore
                      , PropertySheet.BusinessTemplate
                      )

    # Factory Type Information
    factory_type_information = \
      {    'id'             : portal_type
         , 'meta_type'      : meta_type
         , 'description'    : """\
1073
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
1074
         , 'icon'           : 'order_line_icon.gif'
1075
         , 'product'        : 'ERP5Type'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1076 1077 1078
         , 'factory'        : 'addBusinessTemplate'
         , 'immediate_view' : 'BusinessTemplate_view'
         , 'allow_discussion'     : 1
1079
         , 'allowed_content_types': (
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
                                      )
         , 'filter_content_types' : 1
         , 'global_allow'   : 1
         , 'actions'        :
        ( { 'id'            : 'view'
          , 'name'          : 'View'
          , 'category'      : 'object_view'
          , 'action'        : 'BusinessTemplate_view'
          , 'permissions'   : (
              Permissions.View, )
          }
1091 1092 1093
        , { 'id'            : 'history'
          , 'name'          : 'History'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1094
          , 'action'        : 'Base_viewHistory'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1095 1096 1097 1098 1099 1100
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'metadata'
          , 'name'          : 'Metadata'
          , 'category'      : 'object_view'
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1101
          , 'action'        : 'Base_viewMetadata'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1102
          , 'permissions'   : (
1103
              Permissions.ManageProperties, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1104 1105 1106
          }
        , { 'id'            : 'translate'
          , 'name'          : 'Translate'
1107
          , 'category'      : 'object_exchange'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1108 1109 1110 1111
          , 'action'        : 'translation_template_view'
          , 'permissions'   : (
              Permissions.TranslateContent, )
          }
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
        , { '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
1133 1134 1135
        )
      }

1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    _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
1148
    _test_item = None
1149 1150 1151
    _product_item = None
    _role_item = None
    _catalog_result_key_item = None
1152
    _catalog_related_key_item = None
1153
    _catalog_result_table_item = None
1154
    _message_translation_item = None
1155

1156 1157 1158 1159 1160 1161 1162 1163
    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:
1164 1165
          # 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
1166

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1167 1168 1169 1170
    def build(self):
      """
        Copy existing portal objects to self
      """
1171 1172
      # Make sure that everything is sane.
      self.clean()
1173

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
      # XXX Trim down the history to prevent it from bloating the bt5 file.
      # XXX Is there any better way to shrink the size???
      portal_workflow = getToolByName(self, 'portal_workflow')
      wf_id_list = portal_workflow.getChainFor(self)
      original_history_dict = {}
      for wf_id in wf_id_list:
        history = portal_workflow.getHistoryOf(wf_id, self)
        if history is not None and len(history) > 30:
          original_history_dict[wf_id] = history
          LOG('Business Template', 0, 'trim down the history of %s' % (wf_id,))
          self.workflow_history[wf_id] = history[-30:]
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1186
      # Copy portal_types
1187 1188 1189
      self._portal_type_item = PortalTypeTemplateItem(self.getTemplatePortalTypeIdList())
      self._portal_type_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1190
      # Copy workflows
1191 1192 1193
      self._workflow_item = WorkflowTemplateItem(self.getTemplateWorkflowIdList())
      self._workflow_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1194
      # Copy skins
1195 1196 1197
      self._skin_item = SkinTemplateItem(self.getTemplateSkinIdList())
      self._skin_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1198
      # Copy categories
1199 1200 1201
      self._category_item = CategoryTemplateItem(self.getTemplateBaseCategoryList())
      self._category_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1202
      # Copy catalog methods
1203 1204 1205
      self._catalog_method_item = CatalogMethodTemplateItem(self.getTemplateCatalogMethodIdList())
      self._catalog_method_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1206
      # Copy actions
1207 1208 1209
      self._action_item = ActionTemplateItem(self.getTemplateActionPathList())
      self._action_item.build(self)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1210
      # Copy properties
1211 1212 1213
      self._site_property_item = SitePropertyTemplateItem(self.getTemplateSitePropertyIdList())
      self._site_property_item.build(self)

1214
      # Copy modules
1215 1216
      self._module_item = ModuleTemplateItem(self.getTemplateModuleIdList())
      self._module_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1217

1218
      # Copy Document Classes
1219 1220
      self._document_item = DocumentTemplateItem(self.getTemplateDocumentIdList())
      self._document_item.build(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1221

1222
      # Copy Propertysheet Classes
1223 1224
      self._property_sheet_item = PropertySheetTemplateItem(self.getTemplatePropertySheetIdList())
      self._property_sheet_item.build(self)
1225 1226

      # Copy Extensions Classes (useful for catalog)
1227 1228
      self._extension_item = ExtensionTemplateItem(self.getTemplateExtensionIdList())
      self._extension_item.build(self)
1229

1230 1231 1232 1233
      # Copy Test Classes
      self._test_item = TestTemplateItem(self.getTemplateTestIdList())
      self._test_item.build(self)

1234
      # Copy Products
1235 1236
      self._product_item = ProductTemplateItem(self.getTemplateProductIdList())
      self._product_item.build(self)
1237 1238

      # Copy roles
1239 1240
      self._role_item = RoleTemplateItem(self.getTemplateRoleList())
      self._role_item.build(self)
1241

1242 1243 1244
      # Copy catalog result keys
      self._catalog_result_key_item = CatalogResultKeyTemplateItem(self.getTemplateCatalogResultKeyList())
      self._catalog_result_key_item.build(self)
1245

1246 1247 1248 1249
      # Copy catalog related keys
      self._catalog_related_key_item = CatalogRelatedKeyTemplateItem(self.getTemplateCatalogRelatedKeyList())
      self._catalog_related_key_item.build(self)

1250
      # Copy catalog result tables
1251 1252
      self._catalog_result_table_item = CatalogResultTableTemplateItem(self.getTemplateCatalogResultTableList())
      self._catalog_result_table_item.build(self)
1253

1254 1255 1256 1257
      # Copy message translations
      self._message_translation_item = MessageTranslationTemplateItem(self.getTemplateMessageTranslationList())
      self._message_translation_item.build(self)

1258 1259 1260
      # Other objects
      self._path_item = PathTemplateItem(self.getTemplatePathList())
      self._path_item.build(self)
1261

1262
    build = WorkflowMethod(build)
1263 1264

    def publish(self, url, username=None, password=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1265 1266 1267
      """
        Publish in a format or another
      """
1268
      return self.portal_templates.publish(self, url, username=username, password=password)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1269

1270
    def update(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1271
      """
1272
        Update template: download new template defition
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1273
      """
1274
      return self.portal_templates.update(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1275

1276
    def install(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1277 1278 1279
      """
        For install based on paramaters provided in **kw
      """
1280 1281
      installed_bt = self.portal_templates.getInstalledBusinessTemplate(self.getTitle())
      if installed_bt is not None:
1282
        installed_bt.trash(self)
1283
        installed_bt.replace(self)
1284

1285
      # Update local dictionary containing all setup parameters
1286 1287 1288 1289 1290
      # This may include mappings
      self.portal_templates.updateLocalConfiguration(self, **kw)
      local_configuration = self.portal_templates.getLocalConfiguration(self)

      # Classes and security information
1291 1292 1293 1294
      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)
1295
      if self._test_item is not None: self._test_item.install(local_configuration)
1296
      if self._role_item is not None: self._role_item.install(local_configuration)
1297

1298
      # Message translations
1299
      if self._message_translation_item is not None: self._message_translation_item.install(local_configuration)
1300

1301
      # Objects and properties
1302 1303 1304
      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)
1305

1306
      # Portal Types
1307
      if self._portal_type_item is not None: self._portal_type_item.install(local_configuration)
1308

1309
      # Categories
1310
      if self._category_item is not None: self._category_item.install(local_configuration,**kw)
1311

1312
      # Modules.
1313
      if self._module_item is not None: self._module_item.install(local_configuration)
1314

1315 1316 1317
      # 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)

1318
      # Skins
1319
      if self._skin_item is not None: self._skin_item.install(local_configuration)
1320

1321
      # Actions, catalog
1322 1323
      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)
1324
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.install(local_configuration)
1325
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.install(local_configuration)
1326

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1327 1328 1329
      # It is better to clear cache because the installation of a template
      # adds many new things into the portal.
      clearCache()
1330

1331
    install = WorkflowMethod(install)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1332

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    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
1345 1346
      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)
1347
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.trash(local_configuration, new_bt._catalog_related_key_item)
1348
      if self._catalog_result_table_item is not None: self._catalog_result_table_item.trash(local_configuration, new_bt._catalog_result_table_item)
1349 1350

      # Skins
1351
      if self._skin_item is not None: self._skin_item.trash(local_configuration, new_bt._skin_item)
1352 1353

      # Portal Types
1354
      if self._portal_type_item is not None: self._portal_type_item.trash(local_configuration, new_bt._portal_type_item)
1355 1356

      # Modules.
1357
      if self._module_item is not None: self._module_item.trash(local_configuration, new_bt._module_item)
1358 1359

      # Objects and properties
1360 1361 1362 1363 1364
      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)
1365

1366
      # Message translations
1367
      if self._message_translation_item is not None: self._message_translation_item.trash(local_configuration, new_bt._message_translation_item)
1368

1369
      # Classes and security information
1370 1371 1372 1373
      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)
1374
      if self._test_item is not None: self._test_item.trash(local_configuration, new_bt._test_item)
1375
      if self._role_item is not None: self._role_item.trash(local_configuration, new_bt._role_item)
1376

1377
    def uninstall(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1378
      """
1379
        For uninstall based on paramaters provided in **kw
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1380
      """
1381 1382 1383 1384
      # 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
1385

1386
      # Actions, catalog
1387 1388
      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)
1389
      if self._catalog_related_key_item is not None: self._catalog_related_key_item.uninstall(local_configuration)
1390
      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
1391

1392
      # Skins
1393
      if self._skin_item is not None: self._skin_item.uninstall(local_configuration)
1394 1395

      # Portal Types
1396
      if self._portal_type_item is not None: self._portal_type_item.uninstall(local_configuration)
1397 1398

      # Modules.
1399
      if self._module_item is not None: self._module_item.uninstall(local_configuration)
1400 1401

      # Objects and properties
1402 1403 1404 1405 1406
      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)
1407

1408
      # Message translations
1409
      if self._message_translation_item is not None: self._message_translation_item.uninstall(local_configuration)
1410

1411
      # Classes and security information
1412 1413 1414 1415
      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)
1416
      if self._test_item is not None: self._test_item.uninstall(local_configuration)
1417
      if self._role_item is not None: self._role_item.uninstall(local_configuration)
1418 1419 1420 1421

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

1423 1424 1425
    uninstall = WorkflowMethod(uninstall)

    def clean(self):
1426
      """
1427
        Clean built information.
1428
      """
1429
      # First, remove obsolete attributes if present.
1430
      for attr in ('_action_archive', '_document_archive', '_extension_archive', '_test_archive', '_module_archive',
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
                   '_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
1447
      self._test_item = None
1448 1449 1450
      self._product_item = None
      self._role_item = None
      self._catalog_result_key_item = None
1451
      self._catalog_related_key_item = None
1452
      self._catalog_result_table_item = None
1453
      self._message_translation_item = None
1454 1455

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

1457 1458
    security.declareProtected(Permissions.AccessContentsInformation, 'getBuildingState')
    def getBuildingState(self, id_only=1):
1459
      """
1460
        Returns the current state in building
1461
      """
1462 1463 1464
      portal_workflow = getToolByName(self, 'portal_workflow')
      wf = portal_workflow.getWorkflowById('business_template_building_workflow')
      return wf._getWorkflowStateOf(self, id_only=id_only )
1465

1466 1467
    security.declareProtected(Permissions.AccessContentsInformation, 'getInstallationState')
    def getInstallationState(self, id_only=1):
1468
      """
1469
        Returns the current state in installation
1470
      """
1471 1472 1473
      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
1474

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1475 1476 1477 1478 1479 1480 1481 1482 1483
    security.declareProtected(Permissions.AccessContentsInformation, 'toxml')
    def toxml(self):
      """
        Return this Business Template in XML
      """
      portal_templates = getToolByName(self, 'portal_templates')
      export_string = portal_templates.manage_exportObject(id=self.getId(), toxml=1, download=1)
      return export_string
      
1484
    def _getOrderedList(self, id):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1485
      """
1486 1487
        We have to set this method because we want an
        ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1488
      """
1489 1490 1491 1492 1493 1494 1495 1496
      #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
1497

1498
    def getTemplateCatalogMethodIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1499
      """
1500 1501
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1502
      """
1503
      return self._getOrderedList('template_catalog_method_id')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1504

1505
    def getTemplateBaseCategoryList(self):
1506
      """
1507 1508
      We have to set this method because we want an
      ordered list
1509
      """
1510
      return self._getOrderedList('template_base_category')
1511

1512
    def getTemplateWorkflowIdList(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1513
      """
1514 1515
      We have to set this method because we want an
      ordered list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1516
      """
1517
      return self._getOrderedList('template_workflow_id')
1518

1519
    def getTemplatePortalTypeIdList(self):
1520
      """
1521 1522
      We have to set this method because we want an
      ordered list
1523
      """
1524
      return self._getOrderedList('template_portal_type_id')
1525

1526
    def getTemplateActionPathList(self):
1527
      """
1528 1529
      We have to set this method because we want an
      ordered list
1530
      """
1531
      return self._getOrderedList('template_action_path')
1532

1533
    def getTemplateSkinIdList(self):
1534
      """
1535 1536
      We have to set this method because we want an
      ordered list
1537
      """
1538
      return self._getOrderedList('template_skin_id')
1539

1540
    def getTemplateModuleIdList(self):
1541
      """
1542 1543
      We have to set this method because we want an
      ordered list
1544
      """
1545
      return self._getOrderedList('template_module_id')
1546 1547 1548 1549 1550 1551 1552

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