ProxyField.py 22.4 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2
##############################################################################
#
3
# Copyright (c) 2006 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets <jp@nexedi.com>
5
#                    Romain Courteaud <romain@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 30 31 32 33
#
# 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.
#
##############################################################################

from Products.Formulator import Widget, Validator
from Products.Formulator.Field import ZMIField
from Products.Formulator.DummyField import fields
from Products.Formulator.Errors import ValidationError
34
from Products.Formulator import MethodField
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35
from Products.ERP5Type.Utils import convertToUpperCase
36
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37 38 39 40 41 42 43 44 45
from Products.CMFCore.utils import getToolByName

from Products.PageTemplates.PageTemplateFile import PageTemplateFile

from Globals import get_request
from Products.PythonScripts.Utility import allow_class

from Products.PythonScripts.standard import url_quote_plus

46
from AccessControl import ClassSecurityInfo
47
from MethodObject import Method
Jean-Paul Smets's avatar
Jean-Paul Smets committed
48

49
from zLOG import LOG, WARNING, DEBUG, PROBLEM
50
from Acquisition import aq_base, aq_inner, aq_acquire, aq_chain
51
from Globals import DTMLFile
Jean-Paul Smets's avatar
Jean-Paul Smets committed
52

53 54
from Products.Formulator.TALESField import TALESMethod
from Products.ERP5Form.Form import StaticValue, TALESValue, OverrideValue, DefaultValue, EditableValue
55
from Products.ERP5Form.Form import copyMethod, isCacheable
56

57 58
_USE_ORIGINAL_GET_VALUE_MARKER = []

59 60 61
_field_value_cache = {}
def purgeFieldValueCache():
  _field_value_cache.clear()
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

class WidgetDelegatedMethod(Method):
  """Method delegated to the proxied field's widget.
  """
  def __init__(self, method_id, default=''):
    self._method_id = method_id
    self._default = default

  def __call__(self, instance, *args, **kw):
    field = instance
    proxied_field = field.getRecursiveTemplateField()
    if proxied_field:
      proxied_method = getattr(proxied_field.widget, self._method_id)
      return proxied_method(field, *args, **kw)
    return self._default


Jean-Paul Smets's avatar
Jean-Paul Smets committed
79 80
class ProxyWidget(Widget.Widget):
  """
81 82 83 84
  A widget that renders itself as a field from another form
  after changing its title and id. It is recommended to define
  a master form on which complex fields with a lot of TALES
  are defined in order to minimize code duplication.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
85 86
  """

87
  property_names = [
88 89
    'form_id',
    'field_id',
90
    'target',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
91 92 93 94 95
  ]

  form_id = fields.StringField(
                                'form_id',
                                title='Form ID',
96 97
                                description= \
                                  "ID of the master form.",
Jean-Paul Smets's avatar
Jean-Paul Smets committed
98 99 100 101 102 103
                                default="",
                                required=1)

  field_id = fields.StringField(
                                'field_id',
                                title='Field ID',
104 105
                                description= \
                                  "ID of the field in the master form.",
Jean-Paul Smets's avatar
Jean-Paul Smets committed
106 107 108
                                default="",
                                required=1)

109 110 111 112 113 114 115 116
  target = fields.HyperLinkField(
                                'target',
                                title='Proxy Target',
                                description="Link to the master field edit form",
                                default='Click to edit the target',
                                href='manage_edit_target',
                                required=0)

117 118 119 120 121 122
  # Field API Methods, delegated to the template field widget
  render = WidgetDelegatedMethod('render', default='')
  render_htmlgrid = WidgetDelegatedMethod('render_htmlgrid', default='')
  render_view = WidgetDelegatedMethod('render_view', default='')
  render_pdf = WidgetDelegatedMethod('render_pdf', default='')
  render_css = WidgetDelegatedMethod('render_css', default='')
123
  render_dict = WidgetDelegatedMethod('render_dict', default=None)
124 125
  get_javascript_list = WidgetDelegatedMethod(
                            'get_javascript_list', default=[])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
126

127

Jean-Paul Smets's avatar
Jean-Paul Smets committed
128 129 130 131
class ProxyValidator(Validator.Validator):
  """
    Validation of entered value through proxy field
  """
132
  property_names = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
133 134

  def validate(self, field, key, REQUEST):
135
    proxy_field = field.getRecursiveTemplateField()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
136
    try:
137
      result = proxy_field.validator.validate(field, key, REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
138 139 140 141 142 143 144 145 146 147
    except ValidationError, error:
      error.field_id = field.id
      raise error
    return result

ProxyWidgetInstance = ProxyWidget()
ProxyValidatorInstance = ProxyValidator()

class ProxyField(ZMIField):
  meta_type = "ProxyField"
148
  security = ClassSecurityInfo()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
149 150 151

  widget = ProxyWidgetInstance
  validator = ProxyValidatorInstance
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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
  # methods screen
  security.declareProtected('View management screens',
                            'manage_main')
  manage_main = DTMLFile('dtml/proxyFieldEdit', globals())

  # tales screen
  security.declareProtected('View management screens',
                            'manage_talesForm')
  manage_talesForm = DTMLFile('dtml/proxyFieldTales', globals())

  # proxy field list header
  security.declareProtected('View management screens', 'proxyFieldListHeader')
  proxyFieldListHeader = DTMLFile('dtml/proxyFieldListHeader', globals())

  security.declareProtected('Change Formulator Forms', 'manage_edit')
  def manage_edit(self, REQUEST):
    """
    Surcharged values from proxied field.
    """
    # Edit template field attributes
    template_field = self.getRecursiveTemplateField()
    if template_field is not None:

      # Check the surcharged checkboxes
      surcharge_list = []
      for group in template_field.form.get_groups():
        for field in template_field.form.get_fields_in_group(group):
          field_id = field.id
          checkbox_key = "surcharge_%s" % field_id
          if not REQUEST.has_key(checkbox_key):
            surcharge_list.append(field_id)

      try:
        # validate the form and get results
        result = template_field.form.validate(REQUEST)
      except ValidationError, err:
        if REQUEST:
          message = "Error: %s - %s" % (err.field.get_value('title'),
                                        err.error_text)
          return self.manage_main(self, REQUEST,
                                  manage_tabs_message=message)
        else:
          raise

      self._surcharged_edit(result, surcharge_list)
    
    # Edit standards attributes
    # XXX It is not possible to call ZMIField.manage_edit because
    # it returns at the end...
    # we need to had a parameter to the method
    try:
      # validate the form and get results
      result = self.form.validate(REQUEST)
    except ValidationError, err:
      if REQUEST:
        message = "Error: %s - %s" % (err.field.get_value('title'),
                                      err.error_text)
        return self.manage_main(self,REQUEST,
                                manage_tabs_message=message)
      else:
        raise

    self._edit(result)
        
    if REQUEST:
      message="Content changed."
      return self.manage_main(self, REQUEST,
                              manage_tabs_message=message)

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  def manage_edit_surcharged_xmlrpc(self, mapping):
    """Edit surcharged properties
    This method is similar to manage_edit_xmlrpc, and it marks the properties
    as not delegated.
    """
    self._surcharged_edit(mapping, mapping.keys())

  def manage_tales_surcharged_xmlrpc(self, mapping):
    """Edit surcharged TALES
    This method is similar to manage_tales_xmlrpc, and it marks the TALES
    properties as not delegated.
    """
    self._surcharged_tales(mapping, mapping.keys())


237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
  def _surcharged_edit(self, result, surcharge_list):
    # first check for any changes  
    values = self.values
    # if we are in unicode mode, convert result to unicode
    # acquire get_unicode_mode and get_stored_encoding from form..
    if self.get_unicode_mode():
      new_result = {}
      for key, value in result.items():
        if type(value) == type(''):
          # in unicode mode, Formulator UI always uses UTF-8
          value = unicode(value, 'UTF-8')
        new_result[key] = value
      result = new_result

    changed = []
    for key, value in result.items():
      # XXX Remove old values
      values.pop(key, None)
      # store keys for which we want to notify change
      if not values.has_key(key) or values[key] != value:
        changed.append(key)

    proxied_field = self.getTemplateField()
    for key, value in result.items():
      if key not in surcharge_list:
        result.pop(key)
263 264
        if key in self.tales:
          self.tales.pop(key)
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341

    # now do actual update of values
    values.update(result)
    self.values = values
    self.delegated_list = surcharge_list

    # finally notify field of all changed values if necessary
    for key in changed:
      method_name = "on_value_%s_changed" % key
      if hasattr(self, method_name):
        getattr(self, method_name)(values[key])

  security.declareProtected('Change Formulator Forms', 'manage_tales')
  def manage_tales(self, REQUEST):
    """
    Surcharged talesfrom proxied field.
    """
    template_field = self.getRecursiveTemplateField()
    if template_field is not None:

      # Check the surcharged checkboxes
      surcharge_list = []
      for group in template_field.tales_form.get_groups():
        for field in template_field.tales_form.get_fields_in_group(group):
          field_id = field.id
          checkbox_key = "surcharge_%s" % field_id
          if not REQUEST.has_key(checkbox_key):
            surcharge_list.append(field_id)


      try:
        # validate the form and get results
        result = template_field.tales_form.validate(REQUEST)
      except ValidationError, err:
        if REQUEST:
          message = "Error: %s - %s" % (err.field.get_value('title'),
                                        err.error_text)
          return self.manage_talesForm(self, REQUEST,
                                       manage_tabs_message=message)
        else:
          raise

      self._surcharged_tales(result, surcharge_list)

    try:
      # validate the form and get results
      result = self.tales_form.validate(REQUEST)
    except ValidationError, err:
      if REQUEST:
        message = "Error: %s - %s" % (err.field.get_value('title'),
                                      err.error_text)
        return self.manage_talesForm(self,REQUEST,
                                     manage_tabs_message=message)
      else:
        raise

    self._edit_tales(result)

    
    if REQUEST:
      message="Content changed."
      return self.manage_talesForm(self, REQUEST,
                                            manage_tabs_message=message)

  def _surcharged_tales(self, result, surcharge_list):
    # first check for any changes  
    tales = self.tales

    changed = []
    for key, value in result.items():
      # XXX Remove old values
      tales.pop(key, None)

    proxied_field = self.getTemplateField()
    for key, value in result.items():
      if key not in surcharge_list:
        result.pop(key)
342 343
        if key in self.values:
          self.values.pop(key)
344 345 346 347 348

    # now do actual update of values
    tales.update(result)
    self.tales = tales
    self.delegated_list = surcharge_list
349 350 351 352
    # Put a default value on not delegated parameter
    for key in result.keys():
      if not self.values.has_key(key):
        self.values[key] = self.get_recursive_orig_value(key, include=0)
353

354 355 356
  def getTemplateField(self):
    """
    Return template field of the proxy field.
357
    """
358 359 360 361 362
    try:
      return self._getTemplateFieldCache()
    except KeyError:
      pass

363 364 365 366 367 368 369 370 371 372 373
    form = self.aq_parent
    object = form.aq_parent
    try:
      proxy_form = getattr(object, self.get_value('form_id'))
      proxy_field = aq_base(getattr(proxy_form, self.get_value('field_id')))
      proxy_field = proxy_field.__of__(form)
    except AttributeError:
      LOG('ProxyField', WARNING, 
          'Could not get a field from a proxy field %s in %s' % \
              (self.id, object.id))
      proxy_field = None
374
    self._setTemplateFieldCache(proxy_field)
375 376
    return proxy_field

377
  def getRecursiveTemplateField(self):
378
    """
379 380
    Return template field of the proxy field.
    This result must not be a ProxyField.
381
    """
382
    field = self
383
    chain = []
384 385 386 387
    while True:
      template_field = field.getTemplateField()
      if template_field.__class__ != ProxyField:
        break
388 389 390 391 392
      if aq_base(template_field) in chain:
        LOG('ProxyField', WARNING, 'Infinite loop detected in %s.' %
            '/'.join(self.getPhysicalPath()))
        return
      chain.append(aq_base(template_field))
393 394
      field = template_field
    return template_field
395

396 397 398 399 400
  def _aq_dynamic(self, name):
    if name == 'sub_form':
      return self.getTemplateField().sub_form
    return None

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
  security.declareProtected('Access contents information', 
                            'is_delegated')
  def is_delegated(self, id):
    """
    Return true if we get the value from the proxied field.
    No, if we surcharged the value on the proxy field.
    """
    # Update old proxied field
    try:
      if id in self.delegated_list:
        return False
      else:
        return True
    except AttributeError:
      # Update old proxied field
      self.delegated_list = []
      return True

  security.declareProtected('Access contents information', 
                            'get_recursive_orig_value')
  def get_recursive_orig_value(self, id, include=1):
    """
    Get value for id recursively.
    """
    if include and \
      ((id in self.widget.property_names) or \
427 428
       ((not self.is_delegated(id)) and \
       (self.values.has_key(id)))):
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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
      return self.get_orig_value(id)
    else:
      proxied_field = self.getTemplateField()
      if proxied_field.__class__ == ProxyField:
        return proxied_field.get_recursive_orig_value(id)
      else:
        return proxied_field.get_orig_value(id)

  security.declareProtected('View management screens', 'get_recursive_tales')
  def get_recursive_tales(self, id, include=1):
    """
    Get tales expression method for id.
    """
    if include and \
      ((id in self.widget.property_names) or \
       not self.is_delegated(id)):
      return self.get_tales(id)
    else:
      proxied_field = self.getTemplateField()
      if proxied_field.__class__ == ProxyField:
        return proxied_field.get_recursive_tales(id)
      else:
        return proxied_field.get_tales(id)
    
  # XXX Not implemented
  security.declareProtected('View management screens', 'get_recursive_override')
  def get_recursive_override(self, id):
    """
    Get override method for id (not wrapped).
    """
    return self.overrides.get(id, "")

  security.declareProtected('View management screens', 'get_error_message')
  def get_error_message(self, name):
    """
    """
    try:
      return self.message_values[name]
    except KeyError:
      proxied_field = self.getTemplateField()
      if proxied_field is not None:
        return proxied_field.get_error_message(name)
      else:
        return ZMIField.get_error_message(self, name)
473

474

475 476
  security.declareProtected('Edit target', 'manage_edit_target')
  def manage_edit_target(self, REQUEST):
477 478 479 480 481 482 483 484 485 486 487 488 489 490
    """ 
    Edit target field of this proxy
    """
    proxy_field = self.getTemplateField()
    if proxy_field:
      url='/'.join((self.absolute_url(),
                    self.get_value('form_id'),
                    self.get_value('field_id'),
                    'manage_main'))
      REQUEST.RESPONSE.redirect(url)
    else:
      # FIXME: should show some error message 
      # ("form_id and field_id don't define a valid template")
      pass
491

492 493 494 495 496 497
  security.declareProtected('Access contents information', 'has_value')
  def has_value(self, id):
    """
    Return true if the field defines such a value.
    """
    result = None
498 499
    if (id in self.widget.property_names) or \
       (not self.is_delegated(id)):
500 501 502 503 504 505
      result = ZMIField.has_value(self, id)
    else:
      proxy_field = self.getTemplateField()
      if proxy_field is not None:
        result = proxy_field.has_value(id)
    return result
506 507 508 509 510 511 512 513 514 515

  security.declareProtected('Access contents information', '_get_user_input_value')
  def _get_user_input_value(self, key, REQUEST):
    """
    Try to get a value of the field from the REQUEST
    """
    proxy_field = self.getTemplateField()
    if proxy_field is not None:
      result = proxy_field._get_user_input_value(key, REQUEST)
    else:
516 517
      result = ZMIField._get_user_input_value(self, key, REQUEST)
    return result
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546


  #
  # Performance improvement
  #
  def get_tales_expression(self, id):
    field = self
    while True:
      if (id in field.widget.property_names or
          not field.is_delegated(id)):
        tales = field.get_tales(id)
        if tales:
          return TALESMethod(tales._text)
        else:
          return None
      proxied_field = field.getTemplateField()
      if proxied_field.__class__ == ProxyField:
        field = proxied_field
      elif proxied_field is None:
        raise ValueError, "Can't find the template field of %s" % self.id
      else:
        tales = proxied_field.get_tales(id)
        if tales:
          return TALESMethod(tales._text)
        else:
          return None

  def getFieldValue(self, field, id, **kw):
    """
547
      Return a callable expression and cacheable boolean flag
548
    """
549 550 551
    try:
      tales_expr = self.get_tales_expression(id)
    except ValueError:
552
      return None, False
553
    if tales_expr:
554 555
      tales_expr = copyMethod(tales_expr)
      return TALESValue(tales_expr), isCacheable(tales_expr)
556 557 558 559 560 561 562

    # FIXME: backwards compat hack to make sure overrides dict exists
    if not hasattr(self, 'overrides'):
        self.overrides = {}

    override = self.overrides.get(id, "")
    if override:
563 564
      override = copyMethod(override)
      return OverrideValue(override), isCacheable(override)
565 566 567 568 569

    # Get a normal value.
    try:
      template_field = self.getRecursiveTemplateField()
      # Old ListBox instance might have default attribute. so we need to check it.
570
      if checkOriginalGetValue(template_field, id):
571
        return _USE_ORIGINAL_GET_VALUE_MARKER, True
572 573
      value = self.get_recursive_orig_value(id)
    except KeyError:
574
      # For ListBox and other exceptional fields.
575
      return self._get_value(id, **kw), False
576 577 578

    field_id = field.id

579 580 581
    value = copyMethod(value)
    cacheable = isCacheable(value)

582
    if id == 'default' and field_id.startswith('my_'):
583
      return DefaultValue(field_id, value), cacheable
584 585 586

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

589
    # Return default value in callable mode
590
    if callable(value):
591
      return StaticValue(value), cacheable
592 593

    # Return default value in non callable mode
594 595
    return_value = StaticValue(value)(field, id, **kw)
    return return_value, isCacheable(return_value)
596 597 598 599 600 601 602 603 604 605 606

  security.declareProtected('Access contents information', 'get_value')
  def get_value(self, id, **kw):
    REQUEST = get_request()
    if ((id in self.widget.property_names) or
        (not self.is_delegated(id))):
      return ZMIField.get_value(self, id, **kw)

    field = self
    proxy_field = self.getTemplateField()
    if proxy_field is not None and REQUEST is not None:
607 608 609 610 611 612
      field = REQUEST.get(
        'field__proxyfield_%s_%s_%s' % (self.id, self._p_oid, id),
        self)
      REQUEST.set(
        'field__proxyfield_%s_%s_%s' % (proxy_field.id, proxy_field._p_oid, id),
        field)
613

614 615 616
    # Don't use cache if field is not stored in zodb, or if target field is
    # defined by a TALES
    if self._p_oid is None or self.tales['field_id'] or self.tales['form_id']:
617 618
      return self._get_value(id, **kw)

619
    cache_id = ('ProxyField.get_value',
620 621
                self._p_oid,
                field._p_oid,
622 623 624 625 626 627 628
                id)

    try:
      value = _field_value_cache[cache_id]
    except KeyError:
      # either returns non callable value (ex. "Title")
      # or a FieldValue instance of appropriate class
629 630 631
      value, cacheable = self.getFieldValue(field, id, **kw)
      if cacheable:
        _field_value_cache[cache_id] = value
632

633 634 635
    if value is _USE_ORIGINAL_GET_VALUE_MARKER:
      return self.getTemplateField().get_value(id, **kw)

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    if callable(value):
      return value(field, id, **kw)
    return value

  def _get_value(self, id, **kw):
    proxy_field = self.getTemplateField()
    if proxy_field is not None:
      return proxy_field.get_value(id, **kw)

  def _getCacheId(self):
    return '%s%s' % ('ProxyField', self._p_oid or repr(self))

  def _setTemplateFieldCache(self, field):
    getTransactionalVariable(self)[self._getCacheId()] = field

  def _getTemplateFieldCache(self):
652 653
    if self.aq_parent:
      raise KeyError
654
    return getTransactionalVariable(self)[self._getCacheId()].__of__(self.aq_parent)
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689


#
# get_value exception dict
#
_get_value_exception_dict = {}

def registerOriginalGetValueClassAndArgument(class_, argument_name_list=()):
  """
  if field class has its own get_value implementation and
  must use it rather than ProxyField's one, then register it.

  if argument_name_list is '*' , original get_value is
  applied for all arguments.
  """
  if not isinstance(argument_name_list, (list, tuple)):
    argument_name_list = (argument_name_list,)
  _get_value_exception_dict[class_] = argument_name_list

def checkOriginalGetValue(instance, argument_name):
  """
  if exception data is registered, then return True
  """
  class_ = aq_base(instance).__class__
  argument_name_list = _get_value_exception_dict.get(class_)

  if argument_name_list is None:
    return False
  
  if len(argument_name_list)==1 and argument_name_list[0]=='*':
    return True

  if argument_name in argument_name_list:
    return True
  return False