Form.py 50.3 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
#############################################################################
Jean-Paul Smets's avatar
Jean-Paul Smets committed
3 4
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#
# 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.
#
##############################################################################

30 31
from copy import deepcopy

Jérome Perrin's avatar
Jérome Perrin committed
32
from Products.Formulator.Form import BasicForm, ZMIForm
33
from Products.Formulator.Errors import FormValidationError, ValidationError
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34 35 36
from Products.Formulator.DummyField import fields
from Products.Formulator.XMLToForm import XMLToForm
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
37
from Products.CMFCore.utils import _checkPermission, getToolByName
38 39
from Products.CMFCore.exceptions import AccessControl_Unauthorized
from Products.ERP5Type import PropertySheet, Permissions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40 41

from urllib import quote
Jérome Perrin's avatar
Jérome Perrin committed
42 43
from Products.ERP5Type.Globals import DTMLFile, get_request
from AccessControl import Unauthorized, ClassSecurityInfo
Yoshinori Okuji's avatar
Yoshinori Okuji committed
44
from ZODB.POSException import ConflictError
45
from zExceptions import Redirect
46
from Acquisition import aq_base
47
from Products.PageTemplates.Expressions import SecureModuleImporter
Jean-Paul Smets's avatar
Jean-Paul Smets committed
48

49
from Products.ERP5Type.PsycoWrapper import psyco
50
from Products.ERP5Type.Base import Base
51
import sys
Jean-Paul Smets's avatar
Jean-Paul Smets committed
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
class FieldValueCacheDict(dict):
  _last_sync = -1

  def clear(self):
    super(FieldValueCacheDict, self).clear()

    from Products.ERP5.ERP5Site import getSite
    try:
      portal = getSite()
    except IndexError:
      pass
    else:
      portal.newCacheCookie('form_field_value_cache')
      self._last_sync = portal.getCacheCookie('form_field_value_cache')

  def __getitem__(self, cache_id):
    from Products.ERP5.ERP5Site import getSite
    try:
      portal = getSite()
    except IndexError:
      pass
    else:
      cookie = portal.getCacheCookie('form_field_value_cache')
      if cookie != self._last_sync:
        LOG("ERP5Form.Form", 0, "Resetting form field value cache")
        self._last_sync = cookie
79
        super(FieldValueCacheDict, self).clear()
80 81 82 83 84
        raise KeyError('Field cache is outdated and has been reset')

    return super(FieldValueCacheDict, self).__getitem__(cache_id)

field_value_cache = FieldValueCacheDict()
85

Jean-Paul Smets's avatar
Jean-Paul Smets committed
86 87 88
# Patch the fiels methods to provide improved namespace handling

from Products.Formulator.Field import Field
89
from Products.Formulator.MethodField import Method, BoundMethod
90
from Products.Formulator.TALESField import TALESMethod
Jean-Paul Smets's avatar
Jean-Paul Smets committed
91

92
from zLOG import LOG, PROBLEM
Jean-Paul Smets's avatar
Jean-Paul Smets committed
93

94

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
def isCacheable(value):
  value = aq_base(value)
  if type(value) is BoundMethod:
    return False

  jar = getattr(value, '_p_jar', None)
  if jar is not None:
    return False

  dic = getattr(value, '__dict__', None)
  if dic is not None:
    for i in dic.values():
      jar = getattr(i, '_p_jar', None)
      if jar is not None:
        return False
  return True


113 114 115 116 117 118 119
def copyMethod(value):
    if type(aq_base(value)) is Method:
      value = Method(value.method_name)
    elif type(aq_base(value)) is TALESMethod:
      value = TALESMethod(value._text)
    return value

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
def getFieldDict(field, value_type):
    result = {}
    if field.meta_type=='ProxyField':
        if value_type=='values':
            get_method = getattr(field, 'get_recursive_orig_value')
        elif value_type=='tales':
            get_method = getattr(field, 'get_recursive_tales')
        else:
            raise ValueError, 'value_type must be values or tales'
        template_field = field.getRecursiveTemplateField()
        for ui_field_id in template_field.form.fields.keys():
            result[ui_field_id] = get_method(ui_field_id)
    else:
        if value_type=='values':
            get_method = getattr(field, 'get_orig_value')
        elif value_type=='tales':
            get_method = getattr(field, 'get_tales')
        else:
            raise ValueError, 'value_type must be values or tales'
        for ui_field_id in field.form.fields.keys():
            result[ui_field_id] = get_method(ui_field_id)
    return result

143

144 145 146 147 148 149 150 151
class StaticValue:
  """
    Encapsulated a static value in a class
    (quite heavy, would be faster to store the
    value as is)
  """
  def __init__(self, value):
    self.value = value
152

153 154
  def __call__(self, field, id, **kw):
    return self.returnValue(field, id, self.value)
155

156
  def returnValue(self, field, id, value):
157 158
    # if normal value is a callable itself, wrap it
    if callable(value):
159 160
      value = value.__of__(field)
      #value=value() # Mising call ??? XXX Make sure compatible with listbox methods
161

162 163 164 165 166 167 168
    if id == 'default':
      # We make sure we convert values to empty strings
      # for most fields (so that we do not get a 'value'
      # message on screen)
      # This can be overriden by using TALES in the field
      if value is None: value = ''

169 170
    return value

171 172 173 174 175
class TALESValue(StaticValue):
  def __init__(self, tales_expr):
    self.tales_expr = tales_expr

  def __call__(self, field, id, **kw):
176
    REQUEST = kw.get('REQUEST', get_request())
177 178 179
    if REQUEST is not None:
      # Proxyfield stores the "real" field in the request. Look if the
      # corresponding field exists in request, and use it as field in the
180
      # TALES context
181 182 183
      field = REQUEST.get(
        'field__proxyfield_%s_%s_%s' % (field.id, field._p_oid, id),
        field)
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

    kw['field'] = field

    form = field.aq_parent # XXX (JPS) form for default is wrong apparently in listbox - double check
    obj = getattr(form, 'aq_parent', None)
    if obj is not None:
        container = obj.aq_inner.aq_parent
    else:
        container = None

    kw['form'] = form
    kw['request'] = REQUEST
    kw['here'] = obj
    kw['context'] = obj
    kw['modules'] = SecureModuleImporter
    kw['container'] = container
    try :
      kw['preferences'] = obj.getPortalObject().portal_preferences
    except AttributeError :
      LOG('ERP5Form', PROBLEM,
          'portal_preferences not put in TALES context (not installed?)')
    # This allows to pass some pointer to the local object
    # through the REQUEST parameter. Not very clean.
    # Used by ListBox to render different items in a list
Julien Muchembled's avatar
Julien Muchembled committed
208 209 210 211 212 213 214
    if kw.get('cell') is None:
      request = kw.get('REQUEST')
      if request is not None:
        if getattr(request, 'cell', None) is not None:
          kw['cell'] = request.cell
        else:
          kw['cell'] = request
215 216 217
        if 'cell_index' not in kw and\
            getattr(request, 'cell_index', None) is not None:
          kw['cell_index'] = request.cell_index
Julien Muchembled's avatar
Julien Muchembled committed
218
      elif getattr(REQUEST, 'cell', None) is not None:
219 220 221 222
        kw['cell'] = REQUEST.cell
    if 'cell_index' not in kw and \
      getattr(REQUEST, 'cell_index', None) is not None:
        kw['cell_index'] = REQUEST.cell_index
223 224 225 226 227
    # on Zope 2.12, only path expressions can access the CONTEXTS name
    # but ERP5 has many python expressions that try to access CONTEXTS, so
    # we try to keep backward compatibility
    if self.tales_expr._text.startswith("python:"):
      kw['CONTEXTS'] = kw
228 229
    try:
      value = self.tales_expr.__of__(field)(**kw)
230
    except (ConflictError, RuntimeError, Redirect):
231 232 233 234 235
      raise
    except:
      # We add this safety exception to make sure we always get
      # something reasonable rather than generate plenty of errors
      LOG('ERP5Form', PROBLEM,
236 237
          'Field.get_value %r [%s], exception on tales_expr: ' %
          (field, id), error=sys.exc_info())
238
      # field may be ProxyField
239 240 241 242 243 244
      # here we avoid calling field.get_recursive_orig_value
      # on all fields because it can be acquired from another
      # field in context. ie, from a listbox field.
      # So, test condition on meta_type attribute to avoid
      # non desirable side effects.
      if field.meta_type == 'ProxyField':
245
        value = field.get_recursive_orig_value(id)
246
      else:
247
        value = field.get_orig_value(id)
248 249 250 251 252 253 254 255 256 257 258 259

    return self.returnValue(field, id, value)

class OverrideValue(StaticValue):
  def __init__(self, override):
    self.override = override

  def __call__(self, field, id, **kw):
    return self.returnValue(field, id, self.override.__of__(field)())

class DefaultValue(StaticValue):
  def __init__(self, field_id, value):
260
    self.key = field_id.split('_', 1)[1]
261 262 263
    self.value = value

  def __call__(self, field, id, **kw):
264
    REQUEST = get_request()
265 266
    try:
      form = field.aq_parent
267
      ob = REQUEST.get('cell', getattr(form, 'aq_parent', None))
268
      value = self.value
269 270 271 272 273 274 275 276 277 278
      try:
        if value not in (None, ''):
          # If a default value is defined on the field, it has precedence
          value = ob.getProperty(self.key, d=value)
        else:
          # else we should give a chance to the accessor to provide
          # a default value (including None)
          value = ob.getProperty(self.key)
      except Unauthorized:
        value = ob.getProperty(self.key, d=value, checked_permission='View')
279
        REQUEST = kw.get('REQUEST', get_request())
280 281
        if REQUEST is not None:
          REQUEST.set('read_only_%s' % self.key, 1)
282 283 284 285
    except (KeyError, AttributeError):
      value = None
    return self.returnValue(field, id, value)

286 287 288 289 290 291 292 293 294 295
class DefaultCheckBoxValue(DefaultValue):
  def __call__(self, field, id, **kw):
    try:
      form = field.aq_parent
      ob = getattr(form, 'aq_parent', None)
      value = self.value
      try:
        value = ob.getProperty(self.key)
      except Unauthorized:
        value = ob.getProperty(self.key, d=value, checked_permission='View')
296
        REQUEST = kw.get('REQUEST', get_request())
297 298 299 300 301 302
        if REQUEST is not None:
          REQUEST.set('read_only_%s' % self.key, 1)
    except (KeyError, AttributeError):
      value = None
    return self.returnValue(field, id, value)

303 304 305 306 307 308 309 310 311 312
class EditableValue(StaticValue):

  def __call__(self, field, id, **kw):
    # By default, pages are editable and
    # fields are editable if they are set to editable mode
    # However, if the REQUEST defines editable_mode to 0
    # then all fields become read only.
    # This is useful to render ERP5 content as in a web site (ECommerce)
    # editable_mode should be set for example by the page template
    # which defines the current layout
313 314 315
    REQUEST = kw.get('REQUEST', get_request())
    if REQUEST is not None:
      if not REQUEST.get('editable_mode', 1):
316
        return 0
317 318 319 320
    return self.value

def getFieldValue(self, field, id, **kw):
  """
321
    Return a callable expression and cacheable boolean flag
322 323 324 325 326 327
  """
  tales_expr = self.tales.get(id, "")
  if tales_expr:
    # TALESMethod is persistent object, so that we cannot cache original one.
    # Becase if connection which original talesmethod uses is closed,
    # RuntimeError must occurs in __setstate__.
328 329
    tales_expr = copyMethod(tales_expr)
    return TALESValue(tales_expr), isCacheable(tales_expr)
330 331 332

  override = self.overrides.get(id, "")
  if override:
333 334
    override = copyMethod(override)
    return OverrideValue(override), isCacheable(override)
335 336 337

  # Get a normal value.
  value = self.get_orig_value(id)
338 339
  value = copyMethod(value)
  cacheable = isCacheable(value)
340 341 342

  field_id = field.id

343 344
  if id == 'default' and (field_id.startswith('my_') or
                          field_id.startswith('listbox_')):
345 346 347 348
    if field.meta_type == 'ProxyField' and \
        field.getRecursiveTemplateField().meta_type == 'CheckBoxField' or \
        self.meta_type == 'CheckBoxField':
      return DefaultCheckBoxValue(field_id, value), cacheable
349
    return DefaultValue(field_id, value), cacheable
350 351 352

  # For the 'editable' value, we try to get a default value
  if id == 'editable':
353
    return EditableValue(value), cacheable
354

Jean-Paul Smets's avatar
Jean-Paul Smets committed
355
  # Return default value in callable mode
356
  if callable(value):
357
    return StaticValue(value), cacheable
358 359

  # Return default value in non callable mode
360 361
  return_value = StaticValue(value)(field, id, **kw)
  return return_value, isCacheable(return_value)
362

363 364 365
def get_value(self, id, REQUEST=None, **kw):
  if REQUEST is None:
    REQUEST = get_request()
366
  if REQUEST is not None:
367 368 369
    field = REQUEST.get(
      'field__proxyfield_%s_%s_%s' % (self.id, self._p_oid, id),
      self)
370 371 372
  else:
    field = self

373 374 375 376
  cache_id = ('Form.get_value',
              self._p_oid,
              field._p_oid,
              id)
377

378
  try:
379
    value = field_value_cache[cache_id]
380 381 382 383
  except KeyError:
    # either returns non callable value (ex. "Title")
    # or a FieldValue instance of appropriate class
    value, cacheable = getFieldValue(self, field, id, **kw)
384 385 386 387 388
    # Do not cache if the field is not stored in zodb,
    # because such field must be used for editing field in ZMI
    # and caching sometimes break these field settings at initialization.
    # As the result, we would see broken field editing screen in ZMI.
    if cacheable and self._p_oid:
389
      field_value_cache[cache_id] = value
390 391 392 393 394

  if callable(value):
    return value(field, id, **kw)
  return value

395 396 397 398 399 400 401 402 403 404 405 406 407
psyco.bind(get_value)

def om_icons(self):
    """Return a list of icon URLs to be displayed by an ObjectManager"""
    icons = ({'path': self.icon,
              'alt': self.meta_type, 'title': self.meta_type},)
    return icons


def _get_default(self, key, value, REQUEST):
    if value is not None:
        return value
    try:
408
        value = self._get_user_input_value(key, REQUEST)
409 410
    except (KeyError, AttributeError):
        # fall back on default
411
        return self.get_value('default', REQUEST=REQUEST) # It was missing on Formulator
412

413 414 415 416 417 418 419 420 421
    # if we enter a string value while the field expects unicode,
    # convert to unicode first
    # this solves a problem when re-rendering a sticky form with
    # values from request
    if (self.has_value('unicode') and self.get_value('unicode') and
        type(value) == type('')):
        return unicode(value, self.get_form_encoding())
    else:
        return value
422 423


Jean-Paul Smets's avatar
Jean-Paul Smets committed
424
# Dynamic Patch
425
Field.get_value = get_value
426 427
Field._get_default = _get_default
Field.om_icons = om_icons
Jean-Paul Smets's avatar
Jean-Paul Smets committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453

# Constructors

manage_addForm = DTMLFile("dtml/form_add", globals())

def addERP5Form(self, id, title="", REQUEST=None):
    """Add form to folder.
    id     -- the id of the new form to add
    title  -- the title of the form to add
    Result -- empty string
    """
    # add actual object
    id = self._setObject(id, ERP5Form(id, title))
    # respond to the add_and_edit button if necessary
    add_and_edit(self, id, REQUEST)
    return ''

def add_and_edit(self, id, REQUEST):
    """Helper method to point to the object's management screen if
    'Add and Edit' button is pressed.
    id -- id of the object we just added
    """
    if REQUEST is None:
        return
    try:
        u = self.DestinationURL()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
454
    except AttributeError:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
455 456 457 458 459
        u = REQUEST['URL1']
    if REQUEST['submit'] == " Add and Edit ":
        u = "%s/%s" % (u, quote(id))
    REQUEST.RESPONSE.redirect(u+'/manage_main')

460
def initializeForm(field_registry, form_class=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
461 462
    """Sets up ZMIForm with fields from field_registry.
    """
463
    if form_class is None: form_class = ERP5Form
464

Jean-Paul Smets's avatar
Jean-Paul Smets committed
465 466 467 468 469 470 471 472
    meta_types = []
    for meta_type, field in field_registry.get_field_classes().items():
        # don't set up in form if this is a field for internal use only
        if field.internal_field:
            continue

        # set up individual add dictionaries for meta_types
        dict = { 'name': field.meta_type,
473
                 'permission': 'Add Formulator Fields',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
                 'action':
                 'manage_addProduct/Formulator/manage_add%sForm' % meta_type }
        meta_types.append(dict)
        # set up add method
        setattr(form_class,
                'manage_add%sForm' % meta_type,
                DTMLFile('dtml/fieldAdd', globals(), fieldname=meta_type))

    # set up meta_types that can be added to form
    form_class._meta_types = tuple(meta_types)

    # set up settings form
    form_class.settings_form._realize_fields()

# Special Settings

def create_settings_form():
    """Create settings form for ZMIForm.
    """
    form = BasicForm('manage_settings')

    title = fields.StringField('title',
                               title="Title",
                               required=0,
                               default="")
499 500 501 502
    description = fields.TextAreaField('description',
                               title="Description",
                               required=0,
                               default="")
Jean-Paul Smets's avatar
Jean-Paul Smets committed
503
    row_length = fields.IntegerField('row_length',
504 505 506
                                     title='Number of groups in row (in order tab)',
                                     required=1,
                                     default=4)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
507 508 509 510 511 512 513 514 515 516 517 518
    name = fields.StringField('name',
                              title="Form name",
                              required=0,
                              default="")
    pt = fields.StringField('pt',
                              title="Page Template",
                              required=0,
                              default="")
    action = fields.StringField('action',
                                title='Form action',
                                required=0,
                                default="")
519 520 521 522
    update_action = fields.StringField('update_action',
                                title='Form update action',
                                required=0,
                                default="")
523 524 525 526
    update_action_title = fields.StringField('update_action_title',
                               title="Update Action Title",
                               required=0,
                               default="")
Jean-Paul Smets's avatar
Jean-Paul Smets committed
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    method = fields.ListField('method',
                              title='Form method',
                              items=[('POST', 'POST'),
                                     ('GET', 'GET')],
                              required=1,
                              size=1,
                              default='POST')
    enctype = fields.ListField('enctype',
                               title='Form enctype',
                               items=[('No enctype', ""),
                                      ('application/x-www-form-urlencoded',
                                       'application/x-www-form-urlencoded'),
                                      ('multipart/form-data',
                                       'multipart/form-data')],
                               required=0,
                               size=1,
                               default=None)
544 545 546 547 548 549
    encoding = fields.StringField('encoding',
                                  title='Encoding of pages the form is in',
                                  default="UTF-8",
                                  required=1)
    stored_encoding = fields.StringField('stored_encoding',
                                      title='Encoding of form properties',
550
                                      default='UTF-8',
551
                                      required=1)
552 553 554 555
    unicode_mode = fields.CheckBoxField('unicode_mode',
                                        title='Form properties are unicode',
                                        default=0,
                                        required=1)
556 557 558
    edit_order = fields.LinesField('edit_order',
                                   title='Setters for these properties should be'
                                   '<br /> called by edit() in the defined order')
559

560 561
    form.add_fields([title, description, row_length, name, pt, action, update_action, update_action_title,
                     method, enctype, encoding, stored_encoding, unicode_mode, edit_order])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
562 563
    return form

564 565 566

from OFS.Cache import filterCacheTab

567
class ERP5Form(Base, ZMIForm, ZopePageTemplate):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
568 569 570 571 572
    """
        A Formulator form with a built-in rendering parameter based
        on page templates or DTML.
    """
    meta_type = "ERP5 Form"
573
    portal_type = "ERP5 Form"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
574 575 576 577 578
    icon = "www/Form.png"

    # Declarative Security
    security = ClassSecurityInfo()

579 580
    # Tabs in ZMI
    manage_options = (ZMIForm.manage_options[:5] +
581
                      ({'label':'Proxify', 'action':'formProxify'},
582
                       {'label':'UnProxify', 'action':'formUnProxify'},
583
                       {'label':'RelatedProxy',
584 585 586 587 588
                         'action':'formShowRelatedProxyFields'},
                       {'label': 'Cache',
                        'action': 'ZCacheable_manage',
                        'filter': filterCacheTab,
                        'help': ('OFSP', 'Cacheable-properties.stx')}
589
                      )+
590 591
                      ZMIForm.manage_options[5:])

Jean-Paul Smets's avatar
Jean-Paul Smets committed
592 593
    # Declarative properties
    property_sheets = ( PropertySheet.Base
594 595 596 597
                      , PropertySheet.SimpleItem
                      , PropertySheet.Folder
                      , PropertySheet.CategoryCore
                      )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
598 599 600 601

    # Constructors
    constructors =   (manage_addForm, addERP5Form)

602 603 604 605
    # This is a patched dtml formOrder
    security.declareProtected('View management screens', 'formOrder')
    formOrder = DTMLFile('dtml/formOrder', globals())

606 607 608 609
    # Proxify form
    security.declareProtected('View management screens', 'formProxify')
    formProxify = DTMLFile('dtml/formProxify', globals())

610 611 612 613
    # Proxify form
    security.declareProtected('View management screens', 'formUnProxify')
    formUnProxify = DTMLFile('dtml/formUnProxify', globals())

614 615 616
    # Related Proxy Fields
    security.declareProtected('View management screens',
        'formShowRelatedProxyFields')
617
    formShowRelatedProxyFields = DTMLFile('dtml/formShowRelatedProxyFields',
618 619
        globals())

Jean-Paul Smets's avatar
Jean-Paul Smets committed
620 621
    # Default Attributes
    pt = 'form_view'
622
    update_action = ''
623
    update_action_title = ''
624
    edit_order = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
625 626 627 628

    # Special Settings
    settings_form = create_settings_form()

629 630 631 632 633
    manage_main = ZMIForm.manage_main
    objectIds = ZMIForm.objectIds
    objectItems = ZMIForm.objectItems
    objectValues = ZMIForm.objectValues

634
    def __init__(self, id, title, unicode_mode=0, encoding='UTF-8',
Romain Courteaud's avatar
Romain Courteaud committed
635
                 stored_encoding='UTF-8'):
636 637 638 639 640 641 642 643 644 645
        """Initialize form.
        id    -- id of form
        title -- the title of the form
        """
        ZMIForm.inheritedAttribute('__init__')(self, "", "POST", "", id,
                                               encoding, stored_encoding,
                                               unicode_mode)
        self.id = id
        self.title = title
        self.row_length = 4
646
        self.group_list = ["left", "right", "center", "bottom", "hidden"]
647 648 649 650
        groups = {}
        for group in self.group_list:
          groups[group] = []
        self.groups = groups
651

Jean-Paul Smets's avatar
Jean-Paul Smets committed
652 653
    # Proxy method to PageTemplate
    def __call__(self, *args, **kwargs):
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
        # Security
        #
        # The minimal action consists in checking that
        # we have View permission on the current object
        # before rendering a form. Otherwise, object with
        # AccessContentInformation can be viewed by invoking
        # a form directly.
        #
        # What would be better is to prevent calling certain
        # forms to render objects. This can not be done
        # through actions since we are using sometimes forms
        # to render the results of a report dialog form.
        # An a appropriate solutions could consist in adding
        # a permission field to the form. Another solutions
        # is the use of REFERER in the rendering process.
        #
        # Both solutions are not perfect if the goal is, for
        # example, to prevent displaying private information of
        # staff. The only real solution is to use a special
        # permission (ex. AccessPrivateInformation) for those
        # properties which are sensitive.
Julien Muchembled's avatar
Julien Muchembled committed
675 676 677
        kwargs.setdefault('args', args)
        key_prefix = kwargs.pop('key_prefix', None)
        obj = getattr(self, 'aq_parent', None)
678 679 680 681
        if obj is not None:
          container = obj.aq_inner.aq_parent
          if not _checkPermission(Permissions.View, obj):
            raise AccessControl_Unauthorized('This document is not authorized for view.')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
682 683 684
        else:
          container = None
        pt = getattr(self,self.pt)
685 686 687
        extra_context = dict( container=container,
                              template=self,
                              form=self,
688
                              key_prefix=key_prefix,
689
                              options=kwargs,
690 691 692
                              here=obj,
                              context=obj,
                            )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
693 694 695 696 697 698
        return pt.pt_render(extra_context=extra_context)

    def _exec(self, bound_names, args, kw):
        pt = getattr(self,self.pt)
        return pt._exec(self, bound_names, args, kw)

699 700 701 702 703 704 705 706 707 708 709 710 711
    def manage_renameObject(self, id, new_id, REQUEST=None):
      # overriden to keep the order of a field after rename
      groups = deepcopy(self.groups)
      ret = ZMIForm.manage_renameObject(self, id, new_id, REQUEST=REQUEST)
      for group_id, field_id_list in groups.items():
        if id in field_id_list:
          index = field_id_list.index(id)
          field_id_list.pop(index)
          field_id_list.insert(index, new_id)
          groups[group_id] = field_id_list
      self.groups = groups
      return ret

Jean-Paul Smets's avatar
Jean-Paul Smets committed
712
    # Utilities
713
    security.declareProtected('View', 'ErrorFields')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
    def ErrorFields(self, validation_errors):
        """
            Create a dictionnary of validation_errors
            with field id as key
        """
        ef = {}
        for e in validation_errors.errors:
            ef[e.field_id] = e
        return ef

    def om_icons(self):
        """Return a list of icon URLs to be displayed by an ObjectManager"""
        icons = ({'path': 'misc_/ERP5Form/Form.png',
                  'alt': self.meta_type, 'title': self.meta_type},)
        return icons

730 731
    # Pached validate_all to support ListBox validation
    security.declareProtected('View', 'validate_all')
732
    def validate_all(self, REQUEST, key_prefix=None):
733 734 735 736 737 738
        """Validate all enabled fields in this form, catch any ValidationErrors
        if they occur and raise a FormValidationError in the end if any
        Validation Errors occured.
        """
        result = {}
        errors = []
739 740
        for group in self.get_groups():
            if group.lower() == 'hidden':
741
                continue
742 743
            for field in self.get_fields_in_group(group):
                # skip any field we don't need to validate
744
                if not field.need_validate(REQUEST, key_prefix=key_prefix):
745 746 747 748
                    continue
                if not (field.get_value('editable',REQUEST=REQUEST)):
                    continue
                try:
749
                    value = field.validate(REQUEST, key_prefix=key_prefix)
750 751 752 753 754 755 756 757 758 759 760 761 762
                    # store under id
                    result[field.id] = value
                    # store as alternate name as well if necessary
                    alternate_name = field.get_value('alternate_name')
                    if alternate_name:
                        result[alternate_name] = value
                except FormValidationError, e: # XXX JPS Patch for listbox
                    errors.extend(e.errors)
                    result.update(e.result)
                except ValidationError, err:
                    errors.append(err)
                except KeyError, err:
                    LOG('ERP5Form/Form.py:validate_all', 0, 'KeyError : %s' % (err, ))
763

764 765 766 767
        if len(errors) > 0:
            raise FormValidationError(errors, result)
        return result

Jean-Paul Smets's avatar
Jean-Paul Smets committed
768 769 770 771 772 773 774 775 776 777 778 779
    # FTP/DAV Access
    manage_FTPget = ZMIForm.get_xml

    def PUT(self, REQUEST, RESPONSE):
        """Handle HTTP PUT requests."""
        self.dav__init(REQUEST, RESPONSE)
        self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
        body=REQUEST.get('BODY', '')
        # Empty the form (XMLToForm is unable to empty things before reopening)
        for k in self.get_field_ids():
          try:
            self._delObject(k)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
780
          except AttributeError:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
781 782 783 784 785 786 787 788 789 790 791
            pass
        self.groups = {}
        self.group_list = []
        # And reimport
        XMLToForm(body, self)
        self.ZCacheable_invalidate()
        RESPONSE.setStatus(204)
        return RESPONSE

    manage_FTPput = PUT

792
    security.declarePrivate('getSimilarSkinFolderIdList')
793 794 795 796
    def getSimilarSkinFolderIdList(self):
      """
      Find other skins id installed in the same time
      """
797
      portal = self.getPortalObject()
798 799
      folder_id = self.aq_parent.id
      # Find a business template which manages the context skin folder.
800
      folder_id_set = {folder_id}
801
      for template in portal.portal_templates.getInstalledBusinessTemplateList():
802 803
        template_skin_id_list = template.getTemplateSkinIdList()
        if folder_id in template_skin_id_list:
804
          folder_id_set.update(template_skin_id_list)
805 806 807 808 809

          # Find folders which can be surcharged by this skin folder
          if '_' in folder_id:
            surcharged_folder_id = 'erp5_%s' % folder_id.split('_')[-1]
            if (surcharged_folder_id != folder_id) and \
810
              (getattr(portal.portal_skins, surcharged_folder_id, None) \
811 812 813
                                                             is not None):
              folder_id_set.add(surcharged_folder_id)

814
          break
815
      return list(folder_id_set)
816

817
    #Methods for Proxify tab.
818 819 820 821
    security.declareProtected('View management screens', 'getFormFieldList')
    def getFormFieldList(self):
        """
        find fields and forms which name ends with 'FieldLibrary' in
822
        the same business template or in erp5_core.
823
        """
824 825 826
        form_list = []
        def iterate(obj):
            for i in obj.objectValues():
827
                if (i.meta_type=='ERP5 Form' and
828
                    i.id.startswith('Base_view') and
829
                    i.id.endswith('FieldLibrary') and
830
                    '_view' in i.getId()):
831 832 833 834 835 836 837
                    form_id = i.getId()
                    form_path = '%s.%s' % (obj.getId(), form_id)
                    field_list = []
                    form_list.append({'form_path':form_path,
                                      'form_id':form_id,
                                      'field_list':field_list})
                    for field in i.objectValues():
838 839 840
                        field_type, proxy_flag = get_field_meta_type_and_proxy_flag(field)
                        if proxy_flag:
                            field_type = '%s(Proxy)' % field_type
841 842 843 844 845
                        field_list.append({'field_object':field,
                                           'field_type':field_type,
                                           'proxy_flag':proxy_flag})
                if i.meta_type=='Folder':
                    iterate(i)
846 847 848

        skins_tool = self.portal_skins
        folder_id = self.aq_parent.id
849 850
        for skin_folder_id in self.getSimilarSkinFolderIdList():
          iterate(getattr(skins_tool, skin_folder_id))
851
        iterate(skins_tool.erp5_core)
852 853 854 855 856
        return form_list

    security.declareProtected('View management screens', 'getProxyableFieldList')
    def getProxyableFieldList(self, field, form_field_list=None):
        """"""
857
        def extract_keyword(name):
858
            keyword_list = [i for i in name.split('_') if not i in \
859
                    ('my', 'default', 'listbox', 'your')]
860 861 862 863 864
            if len(keyword_list) == 0:
              # This means that the name is one of the exception keywords,
              # so we have to keep it
              keyword_list = [name]
            return keyword_list
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

        def check_keyword_list(name, keyword_list):
            count = 0
            for i in keyword_list:
                if i in name:
                    count += 1
            return count/float(len(keyword_list))

        def match(field_data):
            if not field_data['field_type'].startswith(field.meta_type):
                return 0
            field_object = field_data['field_object']
            if field_object.aq_base is field.aq_base:
                return 0
            field_id = field_object.getId()
880 881 882 883 884 885 886
            # All proxy fields in field libraries should define their
            # technical context
            # XXX Theses 3 following lines will need to be uncommented
            # as soon as proxy guideline is fully validated on erp5_trade
            #if field.meta_type == 'ProxyField' and \
            #    re.match('my_.*_mode', field_id) is None:
            #  return 0
887 888
            # XXX keyword match is not useful anymore.Need different approach.
            keyword_match_rate = check_keyword_list(field_id, extract_keyword(id_))
889
            if keyword_match_rate>0.3:
890 891
                return keyword_match_rate
            else:
Yusei Tahara's avatar
Yusei Tahara committed
892 893
                def split(string):
                    result = []
894
                    temporary = []
Yusei Tahara's avatar
Yusei Tahara committed
895 896 897 898 899 900 901 902 903 904 905 906 907
                    for char in string:
                        if char.isupper():
                            if temporary:
                                result.append(''.join(temporary))
                            temporary = []
                        temporary.append(char)
                    result.append(''.join(temporary))
                    return result

                if ''.join(field_id.split('_')[1:]).startswith(
                    split(field.meta_type)[0].lower()):
                    # At least it seems a generic template field of the meta_type.
                    return 0.1
908 909 910 911 912 913 914 915 916 917 918 919 920 921

        def make_dict_list_append_function(dic, order_list):
            def append(key, item):
                if not key in order_list:
                    order_list.append(key)
                    dic[key] = []
                dic[key].append(item)
            return append

        def add_default_field_library():
            portal_url = getToolByName(self, 'portal_url')
            portal = portal_url.getPortalObject()
            portal_skins = getToolByName(self, 'portal_skins')

Jérome Perrin's avatar
Jérome Perrin committed
922 923 924
            default_field_library_path = portal.getProperty(
                                  'erp5_default_field_library_path',
                                  'erp5_core.Base_viewFieldLibrary')
925 926 927 928 929 930 931 932 933 934
            if (not default_field_library_path or
                len(default_field_library_path.split('.'))!=2):
                return

            skinfolder_id, form_id = default_field_library_path.split('.')

            skinfolder = getattr(portal_skins, skinfolder_id, None)
            default_field_library = getattr(skinfolder, form_id, None)
            if default_field_library is None:
                return
Jérome Perrin's avatar
Jérome Perrin committed
935 936 937 938 939 940 941 942 943 944 945
            for i in default_field_library.objectValues():
                field_meta_type, proxy_flag = get_field_meta_type_and_proxy_flag(i)
                if meta_type==field_meta_type:
                    if proxy_flag:
                        field_meta_type = '%s(Proxy)' % field_meta_type
                    matched_item = {'form_id':form_id,
                                    'field_type':field_meta_type,
                                    'field_object':i,
                                    'proxy_flag':proxy_flag,
                                    'matched_rate':0
                                    }
946 947 948 949 950 951 952

                    if not i in [item['field_object']
                                 for item in matched.get(default_field_library_path, ())]:
                      matched_append(default_field_library_path, matched_item)
                    if not i in [item['field_object']
                                 for item in perfect_matched.get(default_field_library_path, ())]:
                      perfect_matched_append(default_field_library_path, matched_item)
953 954

        id_ = field.getId()
955
        meta_type = field.meta_type
956

957 958
        matched = {}
        form_order = []
959 960 961 962 963
        matched_append = make_dict_list_append_function(matched, form_order)

        perfect_matched = {}
        perfect_matched_form_order = []
        perfect_matched_append = make_dict_list_append_function(perfect_matched, perfect_matched_form_order)
964 965

        if form_field_list is None:
966
            form_field_list = self.getFormFieldList()
967 968 969

        for i in form_field_list:
            for data in i['field_list']:
970 971
                tmp = []
                matched_rate = match(data)
972
                if matched_rate>0:
973 974 975 976 977
                    form_path = i['form_path']
                    form_id = i['form_id']
                    field_type = data['field_type']
                    field_object = data['field_object']
                    proxy_flag = data['proxy_flag']
978 979 980 981 982 983 984 985 986 987 988 989 990 991

                    matched_item = {'form_id':form_id,
                                    'field_type':field_type,
                                    'field_object':field_object,
                                    'proxy_flag':proxy_flag,
                                    'matched_rate':matched_rate
                                    }
                    if matched_rate==1:
                        perfect_matched_append(form_path, matched_item)
                    elif not perfect_matched:
                        matched_append(form_path, matched_item)

        if perfect_matched:
            perfect_matched_form_order.sort()
Jérome Perrin's avatar
Jérome Perrin committed
992
            add_default_field_library()
993 994
            return perfect_matched_form_order, perfect_matched

995
        form_order.sort()
996
        add_default_field_library()
997 998
        return form_order, matched

999 1000 1001 1002 1003
    security.declareProtected('View management screens', 'getUnProxyableFieldList')
    def getUnProxyableFieldList(self):
      """
      Return ProxyFields
      """
1004 1005
      return sorted([f for f in self.objectValues() \
          if f.meta_type == 'ProxyField'], key = lambda x: x.id)
1006

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    security.declareProtected('View management screens',
        'getRelatedProxyFieldDictList')
    def getRelatedProxyFieldDictList(self, **kw):
      """
      Retrieve all proxy using proxy in this form
      """
      form_id = self.id
      proxy_dict = {}
      for document in self.objectValues():
        if document.meta_type == 'ProxyField':
          short_path = "%s.%s" % (form_id, document.id)
          proxy_dict[short_path] = {'proxy': document,
                                    'short_path': short_path,
                                    'related_proxy_list': []}
      def iterate(document):
        for i in document.objectValues():
1023
          if i.meta_type == 'ERP5 Form':
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
            for field in i.objectValues():
              if field.meta_type == 'ProxyField':
                key = "%s.%s" % (field.get_value('form_id'),
                                 field.get_value('field_id'))
                if proxy_dict.has_key(key):
                  proxy_dict[key]['related_proxy_list'].append(
                      {'short_path': "%s.%s" % \
                      (field.aq_parent.id, field.id),
                       'proxy': field})
          if i.meta_type == 'Folder':
            iterate(i)

      skins_tool = self.portal_skins
      proxy_dict_list = []
      if len(proxy_dict):
        for skin_folder_id in self.getSimilarSkinFolderIdList():
          iterate(getattr(skins_tool, skin_folder_id))
        proxy_dict_list = proxy_dict.values()
        proxy_dict_list.sort(key=lambda x: x['short_path'])
        for item in proxy_dict_list:
          item['related_proxy_list'].sort(key=lambda x: x['short_path'])

      return proxy_dict_list

1048
    security.declareProtected('Change Formulator Forms', 'proxifyField')
1049 1050
    def proxifyField(self, field_dict=None, force_delegate=False,
                     keep_empty_value=False, REQUEST=None):
1051
        """Convert fields to proxy fields
1052 1053 1054 1055 1056
        If the field value is not empty and different from the proxyfield
        value, the value is kept on the proxyfield, otherwise it is delegated.
        If you specify force_delegate, values will be delegated even if they
        are different. And if you specify keep_empty_value, then empty values
        will not be delegated(force_delegate option is high priority).
1057
        """
1058
        def copy(field, value_type):
1059
            new_dict = {}
1060 1061 1062 1063 1064 1065 1066
            for key, value in getFieldDict(field, value_type).iteritems():
                if (keep_empty_value is False and
                    (value=='' or
                     value==0 or
                     (isinstance(value, (tuple, list)) and len(value)==0)
                     )
                    ):
1067
                    continue
1068 1069
                if isinstance(aq_base(value), (Method, TALESMethod)):
                    value = copyMethod(value)
Jérome Perrin's avatar
Jérome Perrin committed
1070
                elif value is not None and not isinstance(value,
1071 1072
                        (str, unicode, int, long, float, bool, list, tuple, dict)):
                    raise ValueError, '%s:%s' % (type(value), repr(value))
1073 1074 1075 1076 1077 1078 1079 1080
                new_dict[key] = value
            return new_dict

        def is_equal(a, b):
            type_a = type(a)
            type_b = type(b)
            if type_a is not type_b:
                return False
1081
            elif type_a is Method:
1082 1083 1084 1085 1086 1087 1088 1089 1090
                return a.method_name==b.method_name
            elif type_a is TALESMethod:
                return a._text==b._text
            else:
                return a==b

        def remove_same_value(new_dict, target_dict):
            for key, value in new_dict.items():
                target_value = target_dict.get(key)
1091
                if force_delegate or is_equal(value, target_value):
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
                    del new_dict[key]
            return new_dict

        def get_group_and_position(field_id):
            for i in self.groups.keys():
                if field_id in self.groups[i]:
                    return i, self.groups[i].index(field_id)

        def set_group_and_position(group, position, field_id):
            self.field_removed(field_id)
            self.groups[group].insert(position, field_id)
            # Notify changes explicitly.
            self.groups = self.groups

        if field_dict is None:
            return

        for field_id in field_dict.keys():
            target = field_dict[field_id]
            target_form_id, target_field_id = target.split('.')

            # keep current group and position.
            group, position = get_group_and_position(field_id)

            # create proxy field
            old_field = getattr(self, field_id)
            self.manage_delObjects(field_id)
            self.manage_addField(id=field_id, title='', fieldname='ProxyField')
            proxy_field = getattr(self, field_id)
            proxy_field.values['form_id'] = target_form_id
            proxy_field.values['field_id'] = target_field_id

1124
            target_field = proxy_field.getTemplateField()
1125 1126 1127
            if target_field is None:
              raise ValueError("Unable to find template : %s.%s" % (
                               target_form_id, target_field_id))
1128 1129

            # copy data
1130 1131 1132 1133
            new_values = remove_same_value(copy(old_field, 'values'),
                                           getFieldDict(target_field, 'values'))
            new_tales = remove_same_value(copy(old_field, 'tales'),
                                          getFieldDict(target_field, 'tales'))
1134

1135 1136
            if target_field.meta_type=='ProxyField':
                for i in new_values.keys():
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
                    if not i in target_field.delegated_list:
                        # obsolete variable check
                        try:
                            target_field.get_recursive_orig_value(i)
                        except KeyError:
                            # then `i` is obsolete!
                            del new_values[i]
                        else:
                            if is_equal(target_field.get_recursive_orig_value(i),
                                        new_values[i]):
                                del new_values[i]
Jérome Perrin's avatar
Jérome Perrin committed
1148
                for i in new_tales.keys():
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
                    if not i in target_field.delegated_list:
                        # obsolete variable check
                        try:
                            target_field.get_recursive_tales(i)
                        except KeyError:
                            # then `i` is obsolete!
                            del new_tales[i]
                        else:
                            if is_equal(target_field.get_recursive_tales(i),
                                        new_tales[i]):
                                del new_tales[i]
1160

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
            delegated_list = []
            for i in (new_values.keys()+new_tales.keys()):
                if not i in delegated_list:
                    delegated_list.append(i)
            proxy_field.values.update(new_values)
            proxy_field.tales.update(new_tales)
            proxy_field.delegated_list = delegated_list

            # move back to the original group and position.
            set_group_and_position(group, position, field_id)

1172 1173
        if REQUEST is not None:
            return self.formProxify(manage_tabs_message='Changed')
1174

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1175 1176 1177
    psyco.bind(__call__)
    psyco.bind(_exec)

1178
    security.declareProtected('Change Formulator Forms', 'unProxifyField')
1179 1180
    def unProxifyField(self, field_dict=None, copy_delegated_values=False,
                       REQUEST=None):
1181 1182 1183
        """
        Convert proxy fields to fields
        """
Nicolas Delaby's avatar
Nicolas Delaby committed
1184
        def copy(field, value_type):
1185
            new_dict = {}
1186
            for key, value in getFieldDict(field, value_type).iteritems():
1187 1188 1189
                if isinstance(aq_base(value), (Method, TALESMethod)):
                    value = copyMethod(value)
                elif value is not None and not isinstance(value,
1190 1191
                        (str, unicode, int, long, float, bool, list, tuple, dict)):
                    raise ValueError, '%s:%s' % (type(value), repr(value))
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
                new_dict[key] = value
            return new_dict

        def is_equal(a, b):
            type_a = type(a)
            type_b = type(b)
            if type_a is not type_b:
                return False
            elif type_a is Method:
                return a.method_name==b.method_name
            elif type_a is TALESMethod:
                return a._text==b._text
            else:
                return a==b

        def remove_same_value(new_dict, target_dict):
            for key, value in new_dict.items():
                target_value = target_dict.get(key)
                if is_equal(value, target_value):
                    del new_dict[key]
            return new_dict

        def get_group_and_position(field_id):
            for i in self.groups.keys():
                if field_id in self.groups[i]:
                    return i, self.groups[i].index(field_id)

        def set_group_and_position(group, position, field_id):
            self.field_removed(field_id)
            self.groups[group].insert(position, field_id)
            # Notify changes explicitly.
            self.groups = self.groups

        if field_dict is None:
            return

        for field_id in field_dict.keys():
            # keep current group and position.
            group, position = get_group_and_position(field_id)

            # create field
            old_proxy_field = getattr(self, field_id)
            delegated_field = old_proxy_field.getRecursiveTemplateField()
            if delegated_field is None:
              break
            self.manage_delObjects(field_id)
            self.manage_addField(id=field_id,
                                 title='',
                                 fieldname=delegated_field.meta_type)
            field = getattr(self, field_id)
            # copy data
Nicolas Delaby's avatar
Nicolas Delaby committed
1243
            new_values = remove_same_value(copy(old_proxy_field, 'values'),
1244
                                           field.values)
Nicolas Delaby's avatar
Nicolas Delaby committed
1245
            new_tales = remove_same_value(copy(old_proxy_field, 'tales'),
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
                                          field.tales)

            field.values.update(new_values)
            field.tales.update(new_tales)

            # move back to the original group and position.
            set_group_and_position(group, position, field_id)

        if REQUEST is not None:
            return self.formUnProxify(manage_tabs_message='Changed')

1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    # Overload of the Form method
    #   Use the include_disabled parameter since
    #   we should consider all fields to render the group tab
    #   moreoever, listbox rendering fails whenever enabled
    #   is based on the cell parameter.
    security.declareProtected('View', 'get_largest_group_length')
    def get_largest_group_length(self):
        """Get the largest group length available; necessary for
        'order' screen user interface.
        XXX - Copyright issue
        """
        max = 0
        for group in self.get_groups(include_empty=1):
            fields = self.get_fields_in_group(group, include_disabled=1)
            if len(fields) > max:
                max = len(fields)
        return max

    security.declareProtected('View', 'get_groups')
    def get_groups(self, include_empty=0):
        """Get a list of all groups, in display order.

        If include_empty is false, suppress groups that do not have
        enabled fields.
        XXX - Copyright issue
        """
        if include_empty:
            return self.group_list
        return [group for group in self.group_list
                if self.get_fields_in_group(group, include_disabled=1)]

1288 1289 1290 1291
    # Find support in ZMI. This is useful for development.
    def PrincipiaSearchSource(self):
      return str((self.pt, self.name, self.action, self.update_action,
                  self.encoding, self.stored_encoding, self.enctype))
1292 1293 1294 1295

# utility function
def get_field_meta_type_and_proxy_flag(field):
    if field.meta_type=='ProxyField':
1296 1297 1298
        try:
            return field.getRecursiveTemplateField().meta_type, True
        except AttributeError:
1299 1300 1301
            raise AttributeError, 'The proxy target of %s.%s field does not '\
                  'exists. Please check the field setting.' % \
                  (field.aq_parent.id, field.getId())
1302 1303 1304 1305
    else:
        return field.meta_type, False


Jean-Paul Smets's avatar
Jean-Paul Smets committed
1306 1307
# More optimizations
#psyco.bind(ERP5Field)
1308
# XXX Not useful, as we patch those methods in FormulatorPatch
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
psyco.bind(Field.render)
psyco.bind(Field._render_helper)
psyco.bind(Field.get_value)

#from Products.PageTemplates.PageTemplate import PageTemplate
#from TAL import TALInterpreter
#psyco.bind(TALInterpreter.TALInterpreter)
#psyco.bind(TALInterpreter.TALInterpreter.interpret)
#psyco.bind(PageTemplate.pt_render)
#psyco.bind(PageTemplate.pt_macros)

#from Products.CMFCore.ActionsTool import ActionsTool
1321
#psyco.bind(ActionsTool.listFilteredActionsFor)
1322