ProxyField.py 27.9 KB
Newer Older
1
# -*- coding: utf-8 -*-
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2 3
##############################################################################
#
4
# Copyright (c) 2006 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5
#                    Jean-Paul Smets <jp@nexedi.com>
6
#                    Romain Courteaud <romain@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 34
#
# 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
35
from Products.Formulator import MethodField
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36
from Products.ERP5Type.Utils import convertToUpperCase
37
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38 39 40

from Products.PageTemplates.PageTemplateFile import PageTemplateFile

41
from Products.ERP5Type.Globals import get_request
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42 43 44 45
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 Products.ERP5Type.Globals import DTMLFile
Jean-Paul Smets's avatar
Jean-Paul Smets committed
52

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

Romain Courteaud's avatar
Romain Courteaud committed
58 59 60
from Products.CMFCore.Skinnable import SKINDATA
from thread import get_ident

61 62
_USE_ORIGINAL_GET_VALUE_MARKER = []

63 64 65
_field_value_cache = {}
def purgeFieldValueCache():
  _field_value_cache.clear()
66 67 68 69

class WidgetDelegatedMethod(Method):
  """Method delegated to the proxied field's widget.
  """
70 71
  func_code = None

72 73 74 75 76 77 78 79 80
  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)
81 82 83 84
      try:
        return proxied_method(field, *args, **kw)
      finally:
        self.func_code = getattr(proxied_method, 'func_code', None)
85 86 87
    return self._default


Jean-Paul Smets's avatar
Jean-Paul Smets committed
88 89
class ProxyWidget(Widget.Widget):
  """
90 91 92 93
  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
94 95
  """

96
  property_names = [
97 98
    'form_id',
    'field_id',
99
    'target',
Jean-Paul Smets's avatar
Jean-Paul Smets committed
100 101 102 103 104
  ]

  form_id = fields.StringField(
                                'form_id',
                                title='Form ID',
105 106
                                description= \
                                  "ID of the master form.",
Jean-Paul Smets's avatar
Jean-Paul Smets committed
107 108 109 110 111 112
                                default="",
                                required=1)

  field_id = fields.StringField(
                                'field_id',
                                title='Field ID',
113 114
                                description= \
                                  "ID of the field in the master form.",
Jean-Paul Smets's avatar
Jean-Paul Smets committed
115 116 117
                                default="",
                                required=1)

118 119 120 121 122 123 124 125
  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)

126 127 128 129 130 131
  # 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='')
132
  render_dict = WidgetDelegatedMethod('render_dict', default=None)
133
  render_odf = WidgetDelegatedMethod('render_odf', default='')
134 135
  render_odt = WidgetDelegatedMethod('render_odt', default=None)
  render_odt_view = WidgetDelegatedMethod('render_odt_view', default=None)
136 137
  render_odt_variable = WidgetDelegatedMethod('render_odt_variable',
                                              default=None)
138
  render_odg = WidgetDelegatedMethod('render_odg', default=None)
139 140
  get_javascript_list = WidgetDelegatedMethod(
                            'get_javascript_list', default=[])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
141

142

Jean-Paul Smets's avatar
Jean-Paul Smets committed
143 144 145 146
class ProxyValidator(Validator.Validator):
  """
    Validation of entered value through proxy field
  """
147
  property_names = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
148 149

  def validate(self, field, key, REQUEST):
150
    proxy_field = field.getRecursiveTemplateField()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
151
    try:
152
      result = proxy_field.validator.validate(field, key, REQUEST)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
153 154 155 156 157 158 159 160 161 162
    except ValidationError, error:
      error.field_id = field.id
      raise error
    return result

ProxyWidgetInstance = ProxyWidget()
ProxyValidatorInstance = ProxyValidator()

class ProxyField(ZMIField):
  meta_type = "ProxyField"
163
  security = ClassSecurityInfo()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
164 165 166

  widget = ProxyWidgetInstance
  validator = ProxyValidatorInstance
167
  delegated_list = tuple()
168
  delegated_message_list = tuple()
169

170 171 172 173 174 175 176 177 178 179
  # 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())

180 181 182 183
  # messages screen
  security.declareProtected('View management screens', 'manage_messagesForm')
  manage_messagesForm = DTMLFile('dtml/proxyFieldMessages', globals())

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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  # 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)

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  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())


258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  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)
284 285
        if key in self.tales:
          self.tales.pop(key)
286 287 288 289

    # now do actual update of values
    values.update(result)
    self.values = values
290
    self.delegated_list = sorted(surcharge_list)
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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362

    # 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)
363 364
        if key in self.values:
          self.values.pop(key)
365 366 367 368

    # now do actual update of values
    tales.update(result)
    self.tales = tales
369
    self.delegated_list = sorted(surcharge_list)
370 371 372 373
    # 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)
374

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
  security.declareProtected('Change Formulator Fields', 'manage_messages')
  def manage_messages(self, REQUEST):
    """Change message texts.
    """
    surcharge_list = []
    messages = self.message_values
    unicode_mode = self.get_unicode_mode()
    for message_key in self.get_error_names():
      checkbox_key = "surcharge_%s" % message_key
      if not REQUEST.has_key(checkbox_key):
        surcharge_list.append(message_key)
        message = REQUEST[message_key]
        if unicode_mode:
          message = unicode(message, 'UTF-8')
        messages[message_key] = message
      else:
        if message_key in messages:
          messages.pop(message_key)
    self.message_values = messages
394
    self.delegated_message_list = sorted(surcharge_list)
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    if REQUEST:
      message="Content changed."
      return self.manage_messagesForm(self,REQUEST,
                                      manage_tabs_message=message)

  security.declareProtected('View management screens', 'get_error_message') 
  def get_error_message(self, name): 
    if not self.is_message_delegated(name):
      try: 
        return self.message_values[name] 
      except KeyError: 
        if name in self.validator.message_names: 
          return getattr(self.validator, name) 
        else: 
          return "Unknown error: %s" % name 
    else:
      return self.getTemplateField().get_error_message(name)

  security.declareProtected('View management screens', 'get_error_names') 
  def get_error_names(self): 
    """Get error messages. 
    """ 
    return self.getTemplateField().get_error_names()

419
  def getTemplateField(self, cache=True):
420 421
    """
    Return template field of the proxy field.
422
    """
423
    if cache is True:
424 425 426 427
      tales = self.tales
      if self._p_oid is None or tales['field_id'] or tales['form_id']:
        cache = False
      else:
428 429 430 431
        try:
          return self._getTemplateFieldCache()
        except KeyError:
          pass
432

433
    portal = self.getPortalObject()
Nicolas Delaby's avatar
Nicolas Delaby committed
434
    portal_skins = portal.portal_skins
435 436
    form = self.aq_parent
    object = form.aq_parent
Romain Courteaud's avatar
Romain Courteaud committed
437 438 439 440 441 442 443 444

    form_id = self.get_value('form_id')
    proxy_field = None
    form_id_with_skin_folder_name_flag = False
    if '/' in form_id:
      # If a / is in the form_id, it means that skin_folder is explicitly
      # defined. If so, prevent acquisition to get the form.
      form_id_with_skin_folder_name_flag = True
445 446 447
      proxy_form = aq_base(portal_skins).unrestrictedTraverse(form_id, None)
      if proxy_form is not None:
        proxy_form = portal_skins.unrestrictedTraverse(form_id)
Romain Courteaud's avatar
Romain Courteaud committed
448 449 450 451 452
    else:
      proxy_form = getattr(object, form_id, None)

    if (proxy_form is not None):
      field_id = self.get_value('field_id')
453 454
      proxy_field = proxy_form._getOb(field_id, None)
      if proxy_field is None:
Romain Courteaud's avatar
Romain Courteaud committed
455 456 457 458 459 460 461 462 463 464 465 466 467 468
        if form_id_with_skin_folder_name_flag is False:
          # Try to get the field from another field library with a lower
          # priority.
          # This should return no field if the skin folder name is defined in
          # form_id.
          skin_info = SKINDATA.get(get_ident())

          if skin_info is not None:
            skin_selection_name, ignore, resolve = skin_info

            selection_dict = portal_skins._getSelections()
            candidate_folder_id_list = selection_dict[skin_selection_name].split(',')

            for candidate_folder_id in candidate_folder_id_list:
469
              candidate_folder = portal_skins._getOb(candidate_folder_id, None)
Romain Courteaud's avatar
Romain Courteaud committed
470
              if candidate_folder is not None:
471
                proxy_form = candidate_folder._getOb(form_id, None)
Romain Courteaud's avatar
Romain Courteaud committed
472
                if proxy_form is not None:
473
                  proxy_field = proxy_form._getOb(field_id, None)
Romain Courteaud's avatar
Romain Courteaud committed
474 475 476
                  if proxy_field is not None:
                    break

477
    if proxy_field is None:
478 479 480
      LOG('ProxyField', WARNING, 
          'Could not get a field from a proxy field %s in %s' % \
              (self.id, object.id))
481 482
    if cache is True:
      self._setTemplateFieldCache(proxy_field)
483 484
    return proxy_field

485
  def getRecursiveTemplateField(self):
486
    """
487 488
    Return template field of the proxy field.
    This result must not be a ProxyField.
489
    """
490
    field = self
491
    chain = []
492 493 494 495
    while True:
      template_field = field.getTemplateField()
      if template_field.__class__ != ProxyField:
        break
496 497
      template_field_base = aq_base(template_field)
      if template_field_base in chain:
498 499 500
        LOG('ProxyField', WARNING, 'Infinite loop detected in %s.' %
            '/'.join(self.getPhysicalPath()))
        return
501
      chain.append(template_field_base)
502 503
      field = template_field
    return template_field
504

505 506 507 508 509
  def _aq_dynamic(self, name):
    if name == 'sub_form':
      return self.getTemplateField().sub_form
    return None

510 511 512 513 514 515 516
  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.
    """
517
    return id not in self.delegated_list
518

519 520 521 522 523 524 525 526 527
  security.declareProtected('Access contents information', 
                            'is_message_delegated')
  def is_message_delegated(self, id):
    """
    Return true if we get the message from the proxied field.
    No, if we surcharged the message on the proxy field.
    """
    return id not in self.delegated_message_list

528 529 530 531 532 533 534 535
  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 \
536 537
       ((not self.is_delegated(id)) and \
       (self.values.has_key(id)))):
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
      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()
557 558
      if proxied_field is None:
        raise AttributeError('The proxy field %r cannot find a template field' % self)
559 560 561 562 563 564 565 566 567 568 569 570 571
      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, "")

572 573
  security.declareProtected('Edit target', 'manage_edit_target')
  def manage_edit_target(self, REQUEST):
574 575 576 577 578
    """ 
    Edit target field of this proxy
    """
    proxy_field = self.getTemplateField()
    if proxy_field:
579
      url = "%s/manage_main" % proxy_field.absolute_url() 
580 581 582 583 584
      REQUEST.RESPONSE.redirect(url)
    else:
      # FIXME: should show some error message 
      # ("form_id and field_id don't define a valid template")
      pass
585

586 587 588 589 590 591
  security.declareProtected('Access contents information', 'has_value')
  def has_value(self, id):
    """
    Return true if the field defines such a value.
    """
    result = None
592 593
    if (id in self.widget.property_names) or \
       (not self.is_delegated(id)):
594 595 596 597 598 599
      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
600 601 602 603 604 605 606 607 608 609

  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:
610 611
      result = ZMIField._get_user_input_value(self, key, REQUEST)
    return result
612

613 614 615 616 617 618 619
  security.declareProtected('Access contents information', 'get_orig_value')
  def get_orig_value(self, id):
    """Get value for id; don't do any override calculation.
    """
    if id not in self.widget.property_names and self.is_delegated(id):
      return self.getTemplateField().get_orig_value(id)
    return ZMIField.get_orig_value(self, id)
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

  #
  # 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):
    """
648
      Return a callable expression and cacheable boolean flag
649
    """
650 651 652 653 654 655 656
    # Some field types have their own get_value implementation,
    # then we must use it always. This check must be done at first.
    template_field = self.getRecursiveTemplateField()
    # Old ListBox instance might have default attribute. so we need to check it.
    if checkOriginalGetValue(template_field, id):
      return _USE_ORIGINAL_GET_VALUE_MARKER, True

657 658 659
    try:
      tales_expr = self.get_tales_expression(id)
    except ValueError:
660
      return None, False
661
    if tales_expr:
662 663
      tales_expr = copyMethod(tales_expr)
      return TALESValue(tales_expr), isCacheable(tales_expr)
664 665 666 667 668 669 670

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

    override = self.overrides.get(id, "")
    if override:
671 672
      override = copyMethod(override)
      return OverrideValue(override), isCacheable(override)
673 674 675 676 677

    # Get a normal value.
    try:
      value = self.get_recursive_orig_value(id)
    except KeyError:
678
      # For ListBox and other exceptional fields.
679
      return self._get_value(id, **kw), False
680 681 682

    field_id = field.id

683 684 685
    value = copyMethod(value)
    cacheable = isCacheable(value)

686
    if id == 'default' and field_id.startswith('my_'):
687 688 689
      # XXX far from object-oriented programming
      if template_field.meta_type == 'CheckBoxField':
        return DefaultCheckBoxValue(field_id, value), cacheable
690
      return DefaultValue(field_id, value), cacheable
691 692 693

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

696
    # Return default value in callable mode
697
    if callable(value):
698
      return StaticValue(value), cacheable
699 700

    # Return default value in non callable mode
701 702
    return_value = StaticValue(value)(field, id, **kw)
    return return_value, isCacheable(return_value)
703 704 705

  security.declareProtected('Access contents information', 'get_value')
  def get_value(self, id, **kw):
706
    if id in self.widget.property_names:
707
      return ZMIField.get_value(self, id, **kw)
708 709 710 711 712 713 714
    if not self.is_delegated(id):
      original_template_field = self.getRecursiveTemplateField()
      function = getOriginalGetValueFunction(original_template_field, id)
      if function is not None:
        return function(self, id, **kw)
      else:
        return ZMIField.get_value(self, id, **kw)
715 716

    field = self
717
    proxy_field = self.getTemplateField()
718
    REQUEST = get_request()
719
    if proxy_field is not None and REQUEST is not None:
720 721 722 723 724 725
      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)
726

727 728 729 730
    # 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']:
      return self._get_value(id, **kw)
731
      # XXX: Are these disabled?
732 733 734 735 736 737
      proxy_field = self.getTemplateField(cache=False)
      if proxy_field is not None:
        return proxy_field.get_value(id, **kw)
      else:
        return None

738
    cache_id = ('ProxyField.get_value',
739 740
                self._p_oid,
                field._p_oid,
741 742 743 744 745 746 747
                id)

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

752
    if value is _USE_ORIGINAL_GET_VALUE_MARKER:
753
      return proxy_field.get_value(id, **kw)
754

755 756 757 758 759
    if callable(value):
      return value(field, id, **kw)
    return value

  def _get_value(self, id, **kw):
760
    proxy_field = self.getTemplateField(cache=False)
761 762 763 764 765 766 767
    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):
768
    getTransactionalVariable()[self._getCacheId()] = field
769 770

  def _getTemplateFieldCache(self):
771 772
    parent = self.aq_parent
    if parent is not None:
773
      cache = getTransactionalVariable()[self._getCacheId()]
774 775 776
      if cache is not None:
        return cache.__of__(parent)
    raise KeyError
777 778 779 780 781 782 783


#
# get_value exception dict
#
_get_value_exception_dict = {}

784
def registerOriginalGetValueClassAndArgument(class_, argument_name_list=(), get_value_function=None):
785 786 787 788 789 790 791 792 793
  """
  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,)
794 795 796 797
  if get_value_function is None:
    get_value_function = ZMIField.get_value
  _get_value_exception_dict[class_] = {'argument_name_list':argument_name_list,
                                       'get_value_function':get_value_function}
798 799 800 801 802 803

def checkOriginalGetValue(instance, argument_name):
  """
  if exception data is registered, then return True
  """
  class_ = aq_base(instance).__class__
804 805
  dict_ = _get_value_exception_dict.get(class_, {})
  argument_name_list = dict_.get('argument_name_list')
806 807 808 809 810 811 812 813 814 815

  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
816 817 818 819 820

def getOriginalGetValueFunction(instance, argument_name):
  class_ = aq_base(instance).__class__
  dict_ = _get_value_exception_dict.get(class_, {})
  return dict_.get('get_value_function')