FormulatorPatch.py 62.8 KB
Newer Older
Sebastien Robin's avatar
Sebastien Robin committed
1 2 3 4 5
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# Copyright (c) 2003 Nexedi SARL and Contributors. All Rights Reserved.
#          Sebastien Robin <seb@nexedi.com>
6
#          Jean-Paul Smets-Solanes <jp@nexedi.com>
Sebastien Robin's avatar
Sebastien Robin committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#
# 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 software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################

from Products.Formulator.Field import Field
25
from Products.Formulator.Widget import Widget
26
from Products.Formulator.Widget import render_element
27
from Products.Formulator.FieldRegistry import FieldRegistry
28 29
from Products.Formulator import TALESField
from Products.Formulator import MethodField
30 31 32
from Products.Formulator.Widget import ListWidget
from Products.Formulator.Widget import RadioWidget
from Products.Formulator.Widget import MultiItemsWidget
33
from ProxyField import ProxyField
34
from MultiLinkField import MultiLinkFieldWidget
Sebastien Robin's avatar
Sebastien Robin committed
35
from AccessControl import ClassSecurityInfo
36
from DocumentTemplate.ustr import ustr
37 38
from cgi import escape
import types
Sebastien Robin's avatar
Sebastien Robin committed
39
from zLOG import LOG
Sebastien Robin's avatar
Sebastien Robin committed
40

41 42 43 44 45 46 47
def noop(*args, **kw):
  pass

# XXX: this is a quick fix to avoid bloating the ZODB.
# Proper fix should only add FieldHelp when it's missing.
FieldRegistry.registerFieldHelp = noop

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
def Field_generate_field_key(self, validation=0, key=None):
    """Generate the key Silva uses to render the field in the form.
    """
    # Patched by JPS for ERP5 in order to
    # dynamically change the name
    if key is not None:
      return 'field_%s' % key
    if self.field_record is None:
        return 'field_%s' % self.id
    elif validation:
        return self.id
    elif isinstance(self.widget, MultiItemsWidget):
        return "%s.%s:record:list" % (self.field_record, self.id)
    else:
        return '%s.%s:record' % (self.field_record, self.id)

64
def Field_render(self, value=None, REQUEST=None, key=None, render_prefix=None):
65 66 67 68 69 70 71 72 73 74 75
    """Render the field widget.
    value -- the value the field should have (for instance
              from validation).
    REQUEST -- REQUEST can contain raw (unvalidated) field
              information. If value is None, REQUEST is searched
              for this value.
    if value and REQUEST are both None, the 'default' property of
    the field will be used for the value.
    """
    return self._render_helper(self.generate_field_key(key=key), value, REQUEST)

76
def Field_render_view(self, value=None, REQUEST=None, render_prefix=None):
77 78
    """Render value to be viewed.
    """
79
    return self.widget.render_view(self, value, REQUEST=REQUEST)
80

81
def Field_render_sub_field(self, id, value=None, REQUEST=None, key=None, render_prefix=None):
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    """Render a sub field, as part of complete rendering of widget in
    a form. Works like render() but for sub field.
        Added key parameter for ERP5 in order to be compatible with listbox/matrixbox
    """
    return self.sub_form.get_field(id)._render_helper(
        self.generate_subfield_key(id, key=key), value, REQUEST)

def Field_generate_subfield_key(self, id, validation=0, key=None):
    """Generate the key Silva uses to render a sub field.
        Added key parameter for ERP5
        Added key parameter for ERP5 in order to be compatible with listbox/matrixbox
    """
    if key is None: key = self.id
    if self.field_record is None or validation:
        return 'subfield_%s_%s'%(key, id)
97
    return '%s.subfield_%s_%s:record' % (self.field_record, key, id)
98 99 100 101 102 103 104

def Field_validate_sub_field(self, id, REQUEST, key=None):
    """Validates a subfield (as part of field validation).
    """
    return self.sub_form.get_field(id)._validate_helper(
        self.generate_subfield_key(id, validation=1, key=key), REQUEST)

105
def Field_render_helper(self, key, value, REQUEST, render_prefix=None):
106
    value = self._get_default(key, value, REQUEST)
107
    __traceback_info__ = ('key=%s value=%r' % (key, value))
108
    if self.get_value('hidden', REQUEST=REQUEST):
109
        return self.widget.render_hidden(self, key, value, REQUEST)
110
    elif (not self.get_value('editable', REQUEST=REQUEST)):
111 112 113 114 115 116
      # XXX: API transition try..except..log..raise. Remove after a while.
      try:
        return self.widget.render_view(self, value, REQUEST=REQUEST, render_prefix=render_prefix)
      except TypeError:
        LOG('FormulatorPatch', 0, 'To update: %r (%r)' % (self.widget.render_view, getattr(self.widget.render_view, 'func_code', None)))
        raise
117
    else:
118 119 120 121 122 123
      # XXX: API transition try..except..log..raise. Remove after a while.
      try:
        return self.widget.render(self, key, value, REQUEST, render_prefix=render_prefix)
      except TypeError:
        LOG('FormulatorPatch', 0, 'To update: %r (%r)' % (self.widget.render, getattr(self.widget.render, 'func_code', None)))
        raise
124

125 126 127 128 129 130
def Field_get_user_input_value(self, key, REQUEST):
  """
  Try to get a value of the field from the REQUEST
  """
  return REQUEST.form[key]

131 132 133
def Field_render_odf(self, field=None, key=None, value=None, REQUEST=None, render_format='ooo'):
  return self.widget.render_odf(self, key, value, REQUEST, render_format)

134 135
Field.generate_field_key = Field_generate_field_key
Field.render = Field_render
136
Field.render_view = Field_render_view
137 138 139
Field.render_sub_field = Field_render_sub_field
Field.generate_subfield_key = Field_generate_subfield_key
Field.validate_sub_field = Field_validate_sub_field
140
Field._render_helper = Field_render_helper
141
Field._get_user_input_value = Field_get_user_input_value
142
Field.render_odf = Field_render_odf
Sebastien Robin's avatar
Sebastien Robin committed
143

144 145
ProxyField._render_helper = Field_render_helper

Sebastien Robin's avatar
Sebastien Robin committed
146 147
from Products.Formulator.Validator import SelectionValidator
from Products.Formulator.Validator import StringBaseValidator
148 149 150 151 152 153 154 155 156 157 158
# The required field should have a default value to 0
from Products.Formulator.DummyField import fields

StringBaseValidator_required = fields.CheckBoxField('required',
                                title='Required',
                                description=(
    "Checked if the field is required; the user has to fill in some "
    "data."),
                                default=0)
StringBaseValidator.required = StringBaseValidator_required

159 160 161 162 163 164 165
def SelectionValidator_validate(self, field, key, REQUEST):
    value = StringBaseValidator.validate(self, field, key, REQUEST)

    if value == "" and not field.get_value('required'):
        return value

    # get the text and the value from the list of items
166
    for item in list(field.get_value('items', cell=getattr(REQUEST,'cell',None))) + [field.get_value('default', cell=getattr(REQUEST,'cell',None))]:
167 168
        try:
            item_text, item_value = item
169
        except (ValueError, TypeError):
170 171 172 173 174 175 176 177 178
            item_text = item
            item_value = item

        # check if the value is equal to the string/unicode version of
        # item_value; if that's the case, we can return the *original*
        # value in the list (not the submitted value). This way, integers
        # will remain integers.
        # XXX it is impossible with the UI currently to fill in unicode
        # items, but it's possible to do it with the TALES tab
179
        if field.get_value('unicode') and isinstance(item_value, unicode):
180 181 182 183 184 185 186 187 188 189 190 191
            str_value = item_value.encode(field.get_form_encoding())
        else:
            str_value = str(item_value)

        if str_value == value:
            return item_value

    # if we didn't find the value, return error
    self.raise_error('unknown_selection', field)

SelectionValidator.validate = SelectionValidator_validate

Sebastien Robin's avatar
Sebastien Robin committed
192 193 194
from Products.Formulator.Validator import MultiSelectionValidator

def MultiSelectionValidator_validate(self, field, key, REQUEST):
195 196 197 198
    if REQUEST.get('default_%s' % (key, )) is None:
      LOG('MultiSelectionValidator_validate', 0, 'Field %s is not present in request object (marker field default_%s not found).' % (repr(field.id), key))
      raise KeyError, 'Field %s is not present in request object (marker field default_%s not found).' % (repr(field.id), key)
    values = REQUEST.get(key, [])
Sebastien Robin's avatar
Sebastien Robin committed
199
    # NOTE: a hack to deal with single item selections
Romain Courteaud's avatar
Romain Courteaud committed
200
    if not isinstance(values, list):
Sebastien Robin's avatar
Sebastien Robin committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        # put whatever we got in a list
        values = [values]
    # if we selected nothing and entry is required, give error, otherwise
    # give entry list
    if len(values) == 0:
        if field.get_value('required'):
            self.raise_error('required_not_found', field)
        else:
            return values
    # convert everything to unicode if necessary
    if field.get_value('unicode'):
        values = [unicode(value, field.get_form_encoding())
                  for value in values]

    # create a dictionary of possible values
    value_dict = {}
    for item in field.get_value('items', cell=getattr(REQUEST,'cell',None)): # Patch by JPS for Listbox
        try:
            item_text, item_value = item
        except ValueError:
            item_text = item
            item_value = item
        value_dict[item_value] = 0
224
    default_value = field.get_value('default', cell=getattr(REQUEST,'cell',None))
225
    if isinstance(default_value, (list, tuple)):
226 227 228 229
      for v in default_value:
        value_dict[v] = 0
    else:
      value_dict[default_value] = 0
230

Sebastien Robin's avatar
Sebastien Robin committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

    # check whether all values are in dictionary
    result = []
    for value in values:
        # FIXME: hack to accept int values as well
        try:
            int_value = int(value)
        except ValueError:
            int_value = None
        if int_value is not None and value_dict.has_key(int_value):
            result.append(int_value)
            continue
        if value_dict.has_key(value):
            result.append(value)
            continue
        self.raise_error('unknown_selection', field)
    # everything checks out
    return result

MultiSelectionValidator.validate = MultiSelectionValidator_validate

from Products.Formulator.Validator import BooleanValidator

def BooleanValidator_validate(self, field, key, REQUEST):
255 256
    result = REQUEST.get(key, REQUEST.get('default_%s' % (key, )))
    if result is None:
257
       raise KeyError, 'Field %s is not present in request object.' % (repr(field.id), )
258
    if (not not result)==True:
Sebastien Robin's avatar
Sebastien Robin committed
259 260 261 262
       return 1
    else:
       return 0

263
BooleanValidator.validate = BooleanValidator_validate
Sebastien Robin's avatar
Sebastien Robin committed
264

265
from Products.Formulator.Widget import CheckBoxWidget
266
def CheckBoxWidget_render(self, field, key, value, REQUEST, render_prefix=None):
267 268 269 270 271 272 273
  """Render checkbox.
  """
  rendered = [render_element("input",
                             type="hidden",
                             name="default_%s:int" % (key, ),
                             value="0")
             ]
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  if value:
    rendered.append(render_element("input",
                                   type="checkbox",
                                   name=key,
                                   css_class=field.get_value('css_class'),
                                   checked=None,
                                   extra=field.get_value('extra'))
                   )
  else:
    rendered.append(render_element("input",
                                   type="checkbox",
                                   name=key,
                                   css_class=field.get_value('css_class'),
                                   extra=field.get_value('extra'))
                   )
  return "".join(rendered)

CheckBoxWidget.render = CheckBoxWidget_render

294
def CheckBoxWidget_render_view(self, field, value, REQUEST=None, render_prefix=None):
295 296 297 298
  """Render checkbox in view mode.
  """
  if value:
    return render_element("input",
Nicolas Delaby's avatar
Nicolas Delaby committed
299 300 301 302 303
                          type="checkbox",
                          css_class=field.get_value('css_class'),
                          checked=1,
                          extra=field.get_value('extra'),
                          disabled='disabled')
304 305
  else:
    return render_element("input",
Nicolas Delaby's avatar
Nicolas Delaby committed
306 307 308 309
                          type="checkbox",
                          css_class=field.get_value('css_class'),
                          extra=field.get_value('extra'),
                          disabled='disabled')
310 311 312

CheckBoxWidget.render_view = CheckBoxWidget_render_view

313 314 315 316 317 318
# Patch the render_view of LinkField so that it is clickable in read-only mode.
from Products.Formulator.Widget import TextWidget
from Products.Formulator.StandardFields import LinkField
from Globals import get_request
from urlparse import urljoin

319
class PatchedLinkWidget(TextWidget):
320
  def render_view(self, field, value, REQUEST=None, render_prefix=None):
321 322
    """Render link.
    """
323 324 325
    link_type = field.get_value('link_type', REQUEST=REQUEST)
    if REQUEST is None:
      REQUEST = get_request()
326 327 328 329 330 331

    if link_type == 'internal':
      value = urljoin(REQUEST['BASE0'], value)
    elif link_type == 'relative':
      value = urljoin(REQUEST['URL1'], value)

332 333
    return '<a href="%s">%s</a>' % (value,
        field.get_value('title', cell=getattr(REQUEST,'cell',None)))
334 335 336 337

PatchedLinkWidgetInstance = PatchedLinkWidget()
LinkField.widget = PatchedLinkWidgetInstance

338 339

# Patch the render_view of TextField to enclose the value within <span> html tags if css class defined
340
def TextWidget_patched_render_view(self, field, value, REQUEST=None, render_prefix=None):
341
  """Render text as non-editable.
342 343 344
     This renderer is designed to be type error resistant.
     in we get a non string value. It does escape the result
     and produces clean xhtml.
345 346 347
  """
  if value is None:
    return ''
348 349 350 351 352 353 354 355
  if isinstance(value, types.ListType) or isinstance(value, types.TupleType):
    old_value = value
  else:
    old_value = [str(value)]
  value = []
  for line in old_value:
    value.append(escape(line))
  value = '<br/>'.join(value)
356 357
  css_class = field.get_value('css_class')
  if css_class not in ('', None):
358 359
    # All strings should be escaped before rendering in HTML
    # except for editor field
360 361 362 363 364
    return "<span class='%s'>%s</span>" % (css_class, value)
  return value

from Products.Formulator.Widget import TextWidget
TextWidget.render_view = TextWidget_patched_render_view
365 366 367 368 369 370

original_TextWidget_render = TextWidget.render
def TextWidget_render(self, field, key, value, REQUEST, render_prefix=None):
  return original_TextWidget_render(self, field, key, value, REQUEST)
TextWidget.render = TextWidget_render

371 372 373
from Products.Formulator.Widget import TextAreaWidget
# Use a standard span rendering
TextAreaWidget.render_view = TextWidget_patched_render_view
374

375 376 377 378 379
original_TextAreaWidget_render = TextAreaWidget.render
def TextAreaWidget_render(self, field, key, value, REQUEST, render_prefix=None):
  return original_TextAreaWidget_render(self, field, key, value, REQUEST)
TextAreaWidget.render = TextAreaWidget_render

380
class IntegerWidget(TextWidget) :
381
  def render(self, field, key, value, REQUEST, render_prefix=None) :
382
    """Render an editable integer.
383
    """
384
    if isinstance(value, float):
385 386 387 388 389 390 391 392 393 394 395
      value = int(value)
    display_maxwidth = field.get_value('display_maxwidth') or 0
    if display_maxwidth > 0:
        return render_element("input",
                              type="text",
                              name=key,
                              css_class=field.get_value('css_class'),
                              value=value,
                              size=field.get_value('display_width'),
                              maxlength=display_maxwidth,
                              extra=field.get_value('extra'))
396
    else:
397 398 399 400 401 402 403 404
        return render_element("input",
                              type="text",
                              name=key,
                              css_class=field.get_value('css_class'),
                              value=value,
                              size=field.get_value('display_width'),
                              extra=field.get_value('extra'))

405
  def render_view(self, field, value, REQUEST=None, render_prefix=None):
406 407 408
      """Render a non-editable interger."""
      if isinstance(value, float):
          value = int(value)
409
      return TextWidget.render_view(self, field, value, REQUEST=REQUEST)
410

411 412

from Products.Formulator.StandardFields import IntegerField
413
from Products.Formulator.Validator import IntegerValidator
414 415 416
IntegerFieldWidgetInstance = IntegerWidget()
IntegerField.widget = IntegerFieldWidgetInstance

Sebastien Robin's avatar
Sebastien Robin committed
417
import string
418

419 420 421 422 423 424
def IntegerValidator_validate(self, field, key, REQUEST):
    value = StringBaseValidator.validate(self, field, key, REQUEST)
    # we need to add this check again
    if value == "" and not field.get_value('required'):
        return value

425
    try:
426 427 428 429 430
        if value.find(' ')>0:
          value = value.replace(' ','')
        value = int(value)
    except ValueError:
        self.raise_error('not_integer', field)
431

432 433 434 435
    start = field.get_value('start')
    end = field.get_value('end')
    if start != "" and value < start:
        self.raise_error('integer_out_of_range', field)
436
    if end != "" and value >= end:
437 438 439 440 441
        self.raise_error('integer_out_of_range', field)
    return value

IntegerValidator.validate = IntegerValidator_validate

442 443
def StringBaseValidator_validate(self, field, key, REQUEST):
  # We had to add this patch for hidden fields of type "list"
444
  value = REQUEST.get(key, REQUEST.get('default_%s' % (key, )))
445 446 447 448 449
  if value is None:
    if field.get_value('required'):
      raise Exception, 'Required field %s has not been transmitted. Check that all required fields are in visible groups.' % (repr(field.id), )
    else:
      raise KeyError, 'Field %s is not present in request object.' % (repr(field.id), )
450
  if isinstance(value, str):
451 452 453
    value = string.strip(value)
  if field.get_value('required') and value == "":
      self.raise_error('required_not_found', field)
454 455 456
  #if field.get_value('uppercase'):
  #    value = value.upper()

457 458 459
  return value

StringBaseValidator.validate = StringBaseValidator_validate
Sebastien Robin's avatar
Sebastien Robin committed
460

461
def Widget_render_hidden(self, field, key, value, REQUEST, render_prefix=None):
Sebastien Robin's avatar
Sebastien Robin committed
462 463 464 465 466 467 468 469 470 471
    """Renders this widget as a hidden field.
    """
    try:
        extra = field.get_value('extra')
    except KeyError:
    # In case extra is not defined as in DateTimeWidget
        extra = ''
    result = ''
    # We must adapt the rendering to the type of the value
    # in order to get the correct type back
472
    if isinstance(value, (tuple, list)):
Sebastien Robin's avatar
Sebastien Robin committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486
      for v in value:
        result += render_element("input",
                          type="hidden",
                          name="%s:list" % key,
                          value=v,
                          extra=extra)
    else:
      result = render_element("input",
                          type="hidden",
                          name=key,
                          value=value,
                          extra=extra)
    return result

487
def Widget_render_view(self, field, value, REQUEST=None, render_prefix=None):
488 489 490 491 492 493 494
    """Renders this widget for public viewing.
    """
    # default implementation
    if value is None:
        return ''
    return value

495 496
Widget.render_hidden = Widget_render_hidden
# default render_pdf for a Widget
497
Widget.render_pdf = Widget.render_view = Widget_render_view
Sebastien Robin's avatar
Sebastien Robin committed
498

499 500
def Widget_render_css(self, field, REQUEST):
  """
Bartek Górny's avatar
Bartek Górny committed
501 502 503
    Default render css for widget - to be overwritten in field classes.
    Should return valid css code as string.
    The value returned by this method will be used as inline style for a field.
504 505 506 507
  """
  pass
Widget.render_css = Widget_render_css

508 509 510 511 512 513 514 515 516
def Widget_get_css_list(self, field, REQUEST):
  """
    Return CSS needed by the widget - to be overwritten in field classes.
    Should return a list of CSS file names.
    These names will be appended to global css_list and included in a rendered page.
  """
  return []
Widget.get_css_list = Widget_get_css_list

517 518
def Widget_get_javascript_list(self, field, REQUEST):
  """
Bartek Górny's avatar
Bartek Górny committed
519 520 521
    Return JS needed by the widget - to be overwritten in field classes.
    Should return a list of javascript file names.
    These names will be appended to global js_list and included in a rendered page.
522 523 524 525
  """
  return []
Widget.get_javascript_list = Widget_get_javascript_list

526 527 528 529

from Products.Formulator import Widget as WidgetModule

for widget_name in ('MultiItemsWidget', 'LabelWidget',
530
                    'FileWidget', 'PasswordWidget',):
531 532
  widget = getattr(WidgetModule, widget_name)
  widget._old_render_view = widget.render_view
533
  widget.render_view = lambda self, field, value, REQUEST=None, render_prefix=None: \
534
    self._old_render_view(field, value)
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
  widget._old_render = widget.render
  widget.render = lambda self, field, key, value, REQUEST=None, render_prefix=None: \
    self._old_render(field, key, value, REQUEST)

from Products.Formulator.ListTextAreaField import ListTextAreaWidget
original_ListTextAreaWidget_render = ListTextAreaWidget.render
def ListTextAreaWidget_render(self, field, key, value, REQUEST, render_prefix=None):
  return original_ListTextAreaWidget_render(self, field, key, value, REQUEST)
ListTextAreaWidget.render = ListTextAreaWidget_render

from Products.Formulator.MethodField import MethodWidget
original_MethodWidget_render = MethodWidget.render
def MethodWidget_render(self, field, key, value, REQUEST, render_prefix=None):
  return original_MethodWidget_render(self, field, key, value, REQUEST)
MethodWidget.render = MethodWidget_render
550

Sebastien Robin's avatar
Sebastien Robin committed
551 552 553 554 555
from Products.Formulator.Validator import LinesValidator

def LinesValidator_validate(self, field, key, REQUEST):
    value = StringBaseValidator.validate(self, field, key, REQUEST)
    # Added as a patch for hidden values
556
    if isinstance(value, (list, tuple)):
Sebastien Robin's avatar
Sebastien Robin committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
      value = string.join(value, "\n")
    # we need to add this check again
    if value == "" and not field.get_value('required'):
        return []
    if field.get_value('unicode'):
        value = unicode(value, field.get_form_encoding())
    # check whether the entire input is too long
    max_length = field.get_value('max_length') or 0
    if max_length and len(value) > max_length:
        self.raise_error('too_long', field)
    # split input into separate lines
    lines = string.split(value, "\n")

    # check whether we have too many lines
    max_lines = field.get_value('max_lines') or 0
    if max_lines and len(lines) > max_lines:
        self.raise_error('too_many_lines', field)

    # strip extraneous data from lines and check whether each line is
    # short enough
    max_linelength = field.get_value('max_linelength') or 0
    result = []
    whitespace_preserve = field.get_value('whitespace_preserve')
    for line in lines:
        if not whitespace_preserve:
            line = string.strip(line)
        if max_linelength and len(line) > max_linelength:
            self.raise_error('line_too_long', field)
        result.append(line)

    return result

LinesValidator.validate = LinesValidator_validate

from Products.Formulator.Validator import FloatValidator
def FloatValidator_validate(self, field, key, REQUEST):
    value = StringBaseValidator.validate(self, field, key, REQUEST)
    if value == "" and not field.get_value('required'):
        return value
596 597 598 599 600 601
    value = value.replace(' ','')
    input_style = field.get_value('input_style')
    if value.find(',') >= 0:
        value = value.replace(',','.')
    if value.find('%')>=0:
        value = value.replace('%','')
Sebastien Robin's avatar
Sebastien Robin committed
602 603
    try:
        value = float(value)
604 605
        if input_style.find('%')>=0:
            value = value/100
Sebastien Robin's avatar
Sebastien Robin committed
606 607 608 609 610
    except ValueError:
        self.raise_error('not_float', field)
    return value

FloatValidator.validate = FloatValidator_validate
611

612 613
from Products.Formulator.Widget import SingleItemsWidget

614
def SingleItemsWidget_render_items(self, field, key, value, REQUEST, render_prefix=None):
615
  # get items
616 617
  cell = getattr(REQUEST, 'cell', None)
  items = field.get_value('items', REQUEST=REQUEST, cell=cell)
618 619 620 621
  if not items:
    # single item widget should have at least one child in order to produce
    # valid XHTML; disable it so user can not select it
    return [self.render_item('', '', '', '', 'disabled="disabled"')]
622 623

  # check if we want to select first item
624 625 626
  if not value and field.get_value('first_item',
                                   REQUEST=REQUEST,
                                   cell=cell) and len(items) > 0:
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
      try:
          text, value = items[0]
      except ValueError:
          value = items[0]

  css_class = field.get_value('css_class')
  extra_item = field.get_value('extra_item')

  # if we run into multiple items with same value, we select the
  # first one only (for now, may be able to fix this better later)
  selected_found = 0
  rendered_items = []
  for item in items:
      try:
          item_text, item_value = item
      except ValueError:
          item_text = item
          item_value = item


      if item_value == value and not selected_found:
648
          rendered_item = self.render_selected_item(escape(ustr(item_text)),
649 650 651 652 653 654
                                                    item_value,
                                                    key,
                                                    css_class,
                                                    extra_item)
          selected_found = 1
      else:
655
          rendered_item = self.render_item(escape(ustr(item_text)),
656 657 658 659 660 661 662 663 664
                                            item_value,
                                            key,
                                            css_class,
                                            extra_item)

      rendered_items.append(rendered_item)

  # XXX We want to make sure that we always have the current value in items. -yo
  if not selected_found and value:
665
      value = escape(ustr(value))
666 667 668 669 670 671 672 673 674 675 676
      rendered_item = self.render_selected_item('??? (%s)' % value,
                                                value,
                                                key,
                                                css_class,
                                                extra_item)
      rendered_items.append(rendered_item)

  return rendered_items

SingleItemsWidget.render_items = SingleItemsWidget_render_items

677
def SingleItemsWidget_render_view(self, field, value, REQUEST=None, render_prefix=None):
678 679 680 681 682 683 684 685 686 687 688 689
  """
  This method is not as efficient as using a StringField in read only.
  Always consider to change the field in your Form.
  """
  if value is None:
      return ''
  title_list = [x[0] for x in field.get_value("items", REQUEST=REQUEST) if x[1]==value]
  if len(title_list) == 0:
    return "??? (%s)" % escape(value)
  else:
    return title_list[0]
  return value
690 691

def RadioWidget_render(self, field, key, value, REQUEST, render_prefix=None):
692 693
  input_hidden = render_element('input', type='hidden',
                                name="default_%s:int" % (key, ), value="")
694
  rendered_items = self.render_items(field, key, value, REQUEST)
695
  rendered_items.append(input_hidden)
696 697 698 699 700 701
  orientation = field.get_value('orientation')
  if orientation == 'horizontal':
      return string.join(rendered_items, "&nbsp;&nbsp;")
  else:
      return string.join(rendered_items, "<br />")

702 703 704
ListWidget.render_view = SingleItemsWidget_render_view
ListWidget.render_pdf = SingleItemsWidget_render_view
RadioWidget.render_view = SingleItemsWidget_render_view
705
RadioWidget.render = RadioWidget_render
706
RadioWidget.render_pdf = SingleItemsWidget_render_view
707

708
def MultiItemsWidget_render_items(self, field, key, value, REQUEST, render_prefix=None):
Romain Courteaud's avatar
Romain Courteaud committed
709
  # list is needed, not a tuple
710
  if isinstance(value, tuple):
Romain Courteaud's avatar
Romain Courteaud committed
711
      value = list(value)
712
  # need to deal with single item selects
713
  if not isinstance(value, list):
714 715
      value = [value]

716
  # XXX -yo
717
  selected_found = {}
718

719
  items = field.get_value('items',REQUEST=REQUEST, cell=getattr(REQUEST,'cell',None)) # Added request
Ivan Tyagov's avatar
Ivan Tyagov committed
720 721 722 723 724 725
  if not items and not isinstance(self, MultiLinkFieldWidget):
    # multi items widget should have at least one child in order to produce
    # valid XHTML; disable it so user can not select it.
    # This cannot be applied to MultiLinkFields, which are just some <a>
    # links
    return [self.render_item('', '', '', '', 'disabled="disabled"')]
726

727 728 729
  css_class = field.get_value('css_class')
  extra_item = field.get_value('extra_item')
  rendered_items = []
730

731 732 733 734 735 736 737 738
  for item in items:
      try:
          item_text, item_value = item
      except ValueError:
          item_text = item
          item_value = item

      if item_value in value:
739
          rendered_item = self.render_selected_item(
740
              escape(ustr(item_text)),
741
              escape(ustr(item_value)),
742 743 744
              key,
              css_class,
              extra_item)
745
          # XXX -yo
746 747
          index = value.index(item_value)
          selected_found[index] = 1
748
      else:
749
          rendered_item = self.render_item(
750
               escape(ustr(item_text)),
751
               escape(ustr(item_value)),
752 753 754
               key,
               css_class,
               extra_item)
755 756
      rendered_items.append(rendered_item)

757
  # XXX We want to make sure that we always have the current value in items. -yo
758 759 760
  for index in range(len(value)):
    v = value[index]
    if index not in selected_found and v:
761
      v = escape(v)
762 763 764 765 766 767
      rendered_item = self.render_selected_item('??? (%s)' % v,
                                                v,
                                                key,
                                                css_class,
                                                extra_item)
      rendered_items.append(rendered_item)
768 769 770
  
  # Moved marked field to Render
  # rendered_items.append(render_element('input', type='hidden', name="default_%s:int" % (key, ), value="0"))
771 772 773 774
  return rendered_items

MultiItemsWidget.render_items = MultiItemsWidget_render_items

775 776
from Products.Formulator.Widget import MultiListWidget

777
def MultiListWidget_render(self, field, key, value, REQUEST, render_prefix=None):
778
  rendered_items = self.render_items(field, key, value, REQUEST)
779 780 781 782 783 784 785 786 787 788 789
  input_hidden = render_element('input', type='hidden', name="default_%s:int" % (key, ), value="0")
  multi_list = render_element(
                'select',
                name=key,
                multiple=None,
                css_class=field.get_value('css_class', REQUEST=REQUEST),
                size=field.get_value('size', REQUEST=REQUEST),
                contents=string.join(rendered_items, "\n"),
                extra=field.get_value('extra', REQUEST=REQUEST))
   
  return "\n".join([multi_list,input_hidden]) 
790 791 792

MultiListWidget.render = MultiListWidget_render

793 794
from Products.Formulator.Widget import MultiCheckBoxWidget

795
def MultiCheckBoxWidget_render(self, field, key, value, REQUEST, render_prefix=None):
796 797 798 799 800 801 802
  rendered_items = self.render_items(field, key, value, REQUEST)
  rendered_items.append(render_element('input', type='hidden', name="default_%s:int" % (key, ), value="0"))
  orientation = field.get_value('orientation')
  if orientation == 'horizontal':
    return string.join(rendered_items, "&nbsp;&nbsp;")
  else:
    return string.join(rendered_items, "<br />")
803

804 805
MultiCheckBoxWidget.render = MultiCheckBoxWidget_render

806
def ListWidget_render(self, field, key, value, REQUEST, render_prefix=None):
807
  rendered_items = self.render_items(field, key, value, REQUEST)
808 809
  input_hidden = render_element('input', type='hidden', 
                                name="default_%s:int" % (key, ), value="0") 
810 811 812 813 814 815 816 817
  list_widget = render_element(
                'select',
                name=key,
                css_class=field.get_value('css_class', REQUEST=REQUEST),
                size=field.get_value('size', REQUEST=REQUEST),
                contents=string.join(rendered_items, "\n"),
                extra=field.get_value('extra', REQUEST=REQUEST))

818
  return "\n".join([list_widget, input_hidden])
819
  
820 821
ListWidget.render = ListWidget_render

822 823
# JPS - Subfield handling with listbox requires extension
from Products.Formulator.StandardFields import DateTimeField
824
from Products.Formulator.Field import ZMIField
825

826
def DateTimeField_get_default(self, key, value, REQUEST):
827 828 829 830 831 832 833 834 835 836 837
    """
    Use the default method
    """
    return ZMIField._get_default(self, key, value, REQUEST)

def DateTimeField_get_user_input_value(self, key, REQUEST):
  """
  Try to get a value of the field from the REQUEST
  """
  if REQUEST.form['subfield_%s_%s' % (key, 'year')]:
    return None
838

839
DateTimeField._get_default = DateTimeField_get_default
840
DateTimeField._get_user_input_value = DateTimeField_get_user_input_value
841

842
from Products.Formulator.Widget import DateTimeWidget
843
old_date_time_widget_property_names = DateTimeWidget.property_names
844
from Products.Formulator.StandardFields import create_datetime_text_sub_form
845 846

class PatchedDateTimeWidget(DateTimeWidget):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
847 848 849
    """
      Added support for key in every call to render_sub_field
    """
850 851 852 853 854 855 856 857 858 859 860 861

    sql_format_year  = '%Y'
    sql_format_month = '%m'
    sql_format_day   = '%d'
    format_to_sql_format_dict = {'dmy': (sql_format_day  , sql_format_month, sql_format_year),
                                 'ymd': (sql_format_year , sql_format_month, sql_format_day ),
                                 'mdy': (sql_format_month, sql_format_day  , sql_format_year),
                                 'my' : (sql_format_month, sql_format_year ),
                                 'ym' : (sql_format_year , sql_format_month)
                                }
    sql_format_default = format_to_sql_format_dict['ymd']

862 863 864 865 866 867 868 869 870 871 872 873 874
    hide_day = fields.CheckBoxField('hide_day',
                                  title="Hide Day",
                                  description=(
        "The day will be hidden on the output. Instead the default"
        "Day will be taken"),
                                  default=0)

    hidden_day_is_last_day = fields.CheckBoxField('hidden_day_is_last_day',
                                  title="Hidden Day is last day of the Month",
                                  description=(
        "Defines wether hidden day means, you want the last day of the month"
        "Else it will be the first day"),
                                  default=0)
875 876 877 878 879 880
                          
    timezone_style = fields.CheckBoxField('timezone_style',
                                     title="Display timezone",
                                     description=("Display timezone"),
                                     default=0)
    
881
    property_names = old_date_time_widget_property_names \
882
        + ['timezone_style', 'hide_day', 'hidden_day_is_last_day']
883 884 885 886 887 888 889 890 891

    def getInputOrder(self, field):
      input_order = field.get_value('input_order')
      if field.get_value('hide_day'):
        if input_order == 'ymd':
          input_order = 'ym'
        elif input_order in ('dmy', 'mdy'):
          input_order = 'my'
      return input_order
892

893
    def render_dict(self, field, value, render_prefix=None):
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
      """
        This is yet another field rendering. It is designed to allow code to
        understand field's value data by providing its type and format when
        applicable.

        It returns a dict with 3 keys:
          type  : Text representation of value's type.
          format: Type-dependant-formated formating information.
                  This only describes the field format settings, not the actual
                  format of provided value.
          query : Passthrough of given value.
      """
      format_dict = self.format_to_sql_format_dict
      input_order = format_dict.get(self.getInputOrder(field),
                                    self.sql_format_default)
909
      if isinstance(value, unicode):
910
        value = value.encode(field.get_form_encoding())
911 912 913 914
      return {'query': value,
              'format': field.get_value('date_separator').join(input_order),
              'type': 'date'}

915
    def render(self, field, key, value, REQUEST, render_prefix=None):
916
        use_ampm = field.get_value('ampm_time_style')
917
        use_timezone = field.get_value('timezone_style')
918 919 920
        # FIXME: backwards compatibility hack:
        if not hasattr(field, 'sub_form'):
            field.sub_form = create_datetime_text_sub_form()
921
            
922 923 924
        # Is it still usefull to test the None value,
        # as DateTimeField should be considerer as the other field
        # and get an empty string as default value?
925 926 927 928 929
        # XXX hasattr(REQUEST, 'form') seems useless, 
        # because REQUEST always has a form property
        if (value in (None, '')) and (field.get_value('default_now')) and \
           ((REQUEST is None) or (not hasattr(REQUEST, 'form')) or \
            (not REQUEST.form.has_key('subfield_%s_%s' % (key, 'year')))):
930
            value = DateTime()
931 932 933 934 935 936
        year   = None
        month  = None
        day    = None
        hour   = None
        minute = None
        ampm   = None
937
        timezone = None
938
        if isinstance(value, DateTime):
939 940 941 942 943 944 945 946 947
            year = "%04d" % value.year()
            month = "%02d" % value.month()
            day = "%02d" % value.day()
            if use_ampm:
                hour = "%02d" % value.h_12()
            else:
                hour = "%02d" % value.hour()
            minute = "%02d" % value.minute()
            ampm = value.ampm()
948
            timezone = value.timezone()
949
        input_order = self.getInputOrder(field)
950 951 952 953 954 955 956 957 958 959 960 961
        if input_order == 'ymd':
            order = [('year', year),
                     ('month', month),
                     ('day', day)]
        elif input_order == 'dmy':
            order = [('day', day),
                     ('month', month),
                     ('year', year)]
        elif input_order == 'mdy':
            order = [('month', month),
                     ('day', day),
                     ('year', year)]
962 963 964 965 966 967
        elif input_order == 'my':
            order = [('month', month),
                     ('year', year)]
        elif input_order == 'ym':
            order = [('year', year),
                     ('month', month)]
968 969 970 971
        else:
            order = [('year', year),
                     ('month', month),
                     ('day', day)]
972 973 974 975 976 977 978 979 980
        result = []
        for sub_field_name, sub_field_value in order:
            result.append(field.render_sub_field(sub_field_name,
                                                 sub_field_value, REQUEST, key=key))
        date_result = string.join(result, field.get_value('date_separator'))
        if not field.get_value('date_only'):
            time_result = (field.render_sub_field('hour', hour, REQUEST, key=key) +
                           field.get_value('time_separator') +
                           field.render_sub_field('minute', minute, REQUEST, key=key))
981

982
            if use_ampm:
983
                time_result += '&nbsp;' + field.render_sub_field('ampm',
984
                                                            ampm, REQUEST, key=key)
985 986 987
            if use_timezone:
                time_result += '&nbsp;' + field.render_sub_field('timezone',
                                                            timezone, REQUEST, key=key)
988 989 990
            return date_result + '&nbsp;&nbsp;&nbsp;' + time_result
        else:
            return date_result
991 992
    
    def format_value(self, field, value, mode='html'):
993 994 995 996
        # Is it still usefull to test the None value,
        # as DateTimeField should be considerer as the other field
        # and get an empty string as default value?
        if value in (None, ''):
997 998 999
            return ''

        use_ampm = field.get_value('ampm_time_style')
1000
        use_timezone = field.get_value('timezone_style')
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

        year = "%04d" % value.year()
        month = "%02d" % value.month()
        day = "%02d" % value.day()
        if use_ampm:
            hour = "%02d" % value.h_12()
        else:
            hour = "%02d" % value.hour()
        minute = "%02d" % value.minute()
        ampm = value.ampm()
1011
        timezone = value.timezone()
1012

1013
        order = self.getInputOrder(field)
1014 1015 1016 1017 1018 1019
        if order == 'ymd':
            output = [year, month, day]
        elif order == 'dmy':
            output = [day, month, year]
        elif order == 'mdy':
            output = [month, day, year]
1020 1021 1022 1023
        elif order == 'my':
            output = [month, year]
        elif order == 'ym':
            output = [year, month]
1024 1025 1026
        else:
            output = [year, month, day]
        date_result = string.join(output, field.get_value('date_separator'))
1027 1028 1029 1030 1031
        
        if mode in ('html', ):
            space = '&nbsp;'
        else:
            space = ' '
1032 1033 1034 1035

        if not field.get_value('date_only'):
            time_result = hour + field.get_value('time_separator') + minute
            if use_ampm:
1036
                time_result += space + ampm
1037 1038
            if use_timezone:
                time_result += space + timezone
1039
            return date_result + (space * 3) + time_result
1040 1041
        else:
            return date_result
1042
    
1043
    def render_view(self, field, value, REQUEST=None, render_prefix=None):
1044 1045
        return self.format_value(field, value, mode='html')
    
1046
    def render_pdf(self, field, value, render_prefix=None):
1047
        return self.format_value(field, value, mode='pdf')
1048

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1049 1050
DateTimeField.widget = PatchedDateTimeWidget()

Yoshinori Okuji's avatar
Yoshinori Okuji committed
1051
from Products.Formulator.Validator import DateTimeValidator, ValidationError, DateTime
1052
from DateTime.DateTime import DateError, TimeError
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
from Products.Formulator.StandardFields import ListField, StringField, IntegerField, create_items
from Products.Formulator.Form import BasicForm
import Products.Formulator.StandardFields

gmt_timezones =  [('GMT%s' %zone, 'GMT%s' %zone,) for zone in range(-12, 0)]\
                  + [('GMT', 'GMT',),] \
                  + [('GMT+%s' %zone, 'GMT+%s' %zone,) for zone in range(1, 13)]
                  
def Patched_create_datetime_text_sub_form():
    """ Patch Products.Formulator.StandardFields so we can add timezone subfield """
    sub_form = BasicForm()
        
    year = IntegerField('year',
                        title="Year",
                        required=0,
                        display_width=4,
                        display_maxwidth=4,
                        max_length=4)
    
    month = IntegerField('month',
                         title="Month",
                         required=0,
                         display_width=2,
                         display_maxwidth=2,
                         max_length=2)
    
    day = IntegerField('day',
                       title="Day",
                       required=0,
                       display_width=2,
                       display_maxwidth=2,
                       max_length=2)
    sub_form.add_group("date")
    sub_form.add_fields([year, month, day], "date")
    
    hour = IntegerField('hour',
                        title="Hour",
                        required=0,
                        display_width=2,
                        display_maxwidth=2,
                        max_length=2)
    
    minute = IntegerField('minute',
                          title="Minute",
                          required=0,
                          display_width=2,
                          display_maxwidth=2,
                          max_length=2)

    ampm = StringField('ampm',
                       title="am/pm",
                       required=0,
                       display_width=2,
                       display_maxwidth=2,
                       max_length=2)
Ivan Tyagov's avatar
Ivan Tyagov committed
1108 1109 1110 1111 1112 1113 1114
    timezone = ListField('timezone',
                          title = "Timezone",
                          required = 0,
                          default = 'GMT',
                          items = gmt_timezones,
                          size = 1)                       
    sub_form.add_fields([hour, minute, ampm, timezone], "time")
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    return sub_form
    
def Patched_create_datetime_list_sub_form():
    """ Patch Products.Formulator.StandardFields so we can add timezone subfield """
    sub_form = BasicForm()

    year = ListField('year',
                     title="Year",
                     required=0,
                     default="",
                     items=create_items(2000, 2010, digits=4),
                     size=1)
    
    month = ListField('month',
                      title="Month",
                      required=0,
                      default="",
                      items=create_items(1, 13, digits=2),
                      size=1)
    
    day = ListField('day',
                    title="Day",
                    required=0,
                    default="",
                    items=create_items(1, 32, digits=2),
                    size=1)

    sub_form.add_group("date")
    sub_form.add_fields([year, month, day], "date")
    
    hour = IntegerField('hour',
                        title="Hour",
                        required=0,
                        display_width=2,
                        display_maxwidth=2,
                        max_length=2)
    
    minute = IntegerField('minute',
                          title="Minute",
                          required=0,
                          display_width=2,
                          display_maxwidth=2,
                          max_length=2)

    ampm = ListField('ampm',
                     title="am/pm",
                     required=0,
                     default="am",
                     items=[("am","am"),
                            ("pm","pm")],
                     size=1)
    timezone = ListField('timezone',
                          title = "Timezone",
                          required = 0,
                          default = 'GMT',
                          items = gmt_timezones,
                          size = 1)                                            
    sub_form.add_group("time")

    sub_form.add_fields([hour, minute, ampm, timezone], "time")
    return sub_form

Products.Formulator.StandardFields.create_datetime_text_sub_form = Patched_create_datetime_text_sub_form
Products.Formulator.StandardFields.create_datetime_list_sub_form = Patched_create_datetime_list_sub_form
    
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1180 1181 1182 1183 1184
class PatchedDateTimeValidator(DateTimeValidator):
    """
      Added support for key in every call to validate_sub_field
    """

1185
    def validate(self, field, key, REQUEST):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1186 1187 1188
        try:
            year = field.validate_sub_field('year', REQUEST, key=key)
            month = field.validate_sub_field('month', REQUEST, key=key)
1189 1190 1191 1192
            if field.get_value('hide_day'):
              day = 1
            else:
              day = field.validate_sub_field('day', REQUEST, key=key)
1193

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
            if field.get_value('date_only'):
                hour = 0
                minute = 0
            elif field.get_value('allow_empty_time'):
                hour = field.validate_sub_field('hour', REQUEST, key=key)
                minute = field.validate_sub_field('minute', REQUEST, key=key)
                if hour == '' and minute == '':
                    hour = 0
                    minute = 0
                elif hour == '' or minute == '':
                    raise ValidationError('not_datetime', field)
            else:
                hour = field.validate_sub_field('hour', REQUEST, key=key)
                minute = field.validate_sub_field('minute', REQUEST, key=key)
        except ValidationError:
            self.raise_error('not_datetime', field)

        # handling of completely empty sub fields
1212 1213
        if ((year == '' and month == '') and
            (field.get_value('hide_day') or day == '') and
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1214
            (field.get_value('date_only') or (hour == '' and minute == '')
1215
            or (hour == 0 and minute == 0))):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1216 1217 1218 1219 1220 1221
            if field.get_value('required'):
                self.raise_error('required_not_found', field)
            else:
                # field is not required, return None for no entry
                return None
        # handling of partially empty sub fields; invalid datetime
1222 1223
        if ((year == '' or month == '') or
            (not field.get_value('hide_day') and day == '') or
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
            (not field.get_value('date_only') and
             (hour == '' or minute == ''))):
            self.raise_error('not_datetime', field)

        if field.get_value('ampm_time_style'):
            ampm = field.validate_sub_field('ampm', REQUEST, key=key)
            if field.get_value('allow_empty_time'):
                if ampm == '':
                    ampm = 'am'
            hour = int(hour)
            # handling not am or pm
            # handling hour > 12
            if ((ampm != 'am') and (ampm != 'pm')) or (hour > 12):
1237 1238 1239
                self.raise_error('not_datetime', field)
            if (ampm == 'pm') and (hour == 0):
                self.raise_error('not_datetime', field)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1240 1241
            elif ampm == 'pm' and hour < 12:
                hour += 12
1242 1243 1244 1245 1246 1247
                
        # handle possible timezone input
        timezone = ''
        if field.get_value('timezone_style'):
          timezone =  field.validate_sub_field('timezone', REQUEST, key=key)
          
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1248
        try:
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
            # handling of hidden day, which can be first or last day of the month:
            if field.get_value('hidden_day_is_last_day'):
              if int(month) == 12:
                tmp_year = int(year) + 1
                tmp_month = 1
              else:
                tmp_year = int(year)
                tmp_month = int(month) + 1
              tmp_day = DateTime(tmp_year, tmp_month, 1, hour, minute)
              result = tmp_day - 1
            else:
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
              result = DateTime(int(year),
                                int(month),
                                int(day),
                                hour,
                                minute)
              year = result.year()
              result = DateTime('%s/%s/%s %s:%s %s' % (year,
                                  int(month),
                                  int(day),
                                  hour,
                                  minute, timezone))
1271
         # ugh, a host of string based exceptions (not since Zope 2.7)
1272 1273
        except ('DateTimeError', 'Invalid Date Components', 'TimeError',
                DateError, TimeError) :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1274 1275 1276 1277
            self.raise_error('not_datetime', field)

        # check if things are within range
        start_datetime = field.get_value('start_datetime')
1278
        if (start_datetime not in (None, '') and
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1279 1280 1281
            result < start_datetime):
            self.raise_error('datetime_out_of_range', field)
        end_datetime = field.get_value('end_datetime')
1282
        if (end_datetime not in (None, '') and
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1283 1284 1285 1286 1287 1288
            result >= end_datetime):
            self.raise_error('datetime_out_of_range', field)

        return result

DateTimeField.validator = PatchedDateTimeValidator()
1289 1290 1291

class FloatWidget(TextWidget):

1292
    property_names = TextWidget.property_names +\
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
                     ['input_style','precision']

    input_style = fields.ListField('input_style',
                                   title="Input style",
                                   description=(
        "The type of float we should enter. "),
                                   default="-1234.5",
                                   items=[("-1234.5",  "-1234.5"),
                                          ("-1 234.5", "-1 234.5"),
                                          ("-12.3%", "-12.3%"),],
                                   required=1,
                                   size=1)

    precision = fields.IntegerField('precision',
                                        title='Precision',
                                        description=(
        "Number of digits after the decimal point"),
                                        default=None,
                                        required=0)

1313 1314
    def format_value(self, field, value):
        """Formats the value as requested"""
1315
        if value not in (None,''):
1316
          precision = field.get_value('precision')
1317 1318
          input_style = field.get_value('input_style')
          percent = 0
1319
          original_value = value
1320 1321
          if input_style.find('%')>=0:
            percent=1
1322 1323 1324 1325
            try:
              value = float(value) * 100
            except ValueError:
              return value
1326
          try :
1327 1328 1329 1330
            float_value = float(value)
            if precision:
              float_value = round(float_value, precision)
            value = str(float_value)
1331 1332
          except ValueError:
            return value
1333
          else:
1334 1335
            if 'e' in value:
              # %f will not use exponential format
1336
              value = '%f' % float(original_value)
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
          value_list = value.split('.')
          integer = value_list[0]
          if input_style.find(' ')>=0:
            integer = value_list[0]
            i = len(integer)%3
            value = integer[:i]
            while i != len(integer):
              value += ' ' + integer[i:i+3]
              i += 3
          else:
            value = value_list[0]
1348 1349
          if precision != 0:
            value += '.'
1350 1351 1352
          if precision not in (None,''):
            for i in range(0,precision):
              if i < len(value_list[1]):
1353
                value += value_list[1][i]
1354 1355 1356 1357 1358 1359
              else:
                value += '0'
          else:
            value += value_list[1]
          if percent:
            value += '%'
1360 1361
          return value.strip()
        return ''
1362

1363
    def render(self, field, key, value, REQUEST, render_prefix=None):
1364 1365 1366
        """Render Float input field
        """
        value = self.format_value(field, value)
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
        display_maxwidth = field.get_value('display_maxwidth') or 0
        extra_keys = {}
        if display_maxwidth > 0:
          extra_keys['maxlength'] = display_maxwidth
        return render_element( "input",
                                type="text",
                                name=key,
                                css_class=field.get_value('css_class'),
                                value=value,
                                size=field.get_value('display_width'),
                                extra=field.get_value('extra'),
                                **extra_keys)

1380

1381
    def render_view(self, field, value, REQUEST=None, render_prefix=None):
Kevin Deldycke's avatar
Kevin Deldycke committed
1382 1383 1384 1385 1386
        """
          Render Float display field.
          This patch add:
            * replacement of spaces by unbreakable spaces if the content is float-like
            * support of extra CSS class when render as pure text
1387 1388
        """
        value = self.format_value(field, value)
Kevin Deldycke's avatar
Kevin Deldycke committed
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401

        float_value = None
        try:
          float_value = float(value.replace(' ', ''))
        except:
          pass
        if float_value != None:
          value = value.replace(' ', '&nbsp;')

        extra = field.get_value('extra')
        if extra not in (None, ''):
          value = "<div %s>%s</div>" % (extra, value)

1402 1403 1404 1405
        css_class = field.get_value('css_class')
        if css_class not in ('', None):
          return "<span class='%s'>%s</span>" % (css_class, value)
        return value
1406

1407
    def render_pdf(self, field, value, render_prefix=None):
1408 1409
        """Render the field as PDF."""
        return self.format_value(field, value)
Kevin Deldycke's avatar
Kevin Deldycke committed
1410

1411

1412
    def render_dict(self, field, value, render_prefix=None):
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
      """
        This is yet another field rendering. It is designed to allow code to
        understand field's value data by providing its type and format when
        applicable.

        It returns a dict with 3 keys:
          type  : Text representation of value's type.
          format: Type-dependant-formated formating information.
                  This only describes the field format settings, not the actual
                  format of provided value.
          query : Passthrough of given value.
      """
      input_style = field.get_value('input_style')
      precision = field.get_value('precision')      
1427
      if precision not in (None, '') and precision != 0:
1428 1429 1430 1431
        for x in xrange(1, precision):
          input_style += '5'
      else:
        input_style = input_style.split('.')[0]
1432
      if isinstance(value, unicode):
1433
        value = value.encode(field.get_form_encoding())
1434 1435
      return {'query': value,
              'format': input_style,
Aurel's avatar
Aurel committed
1436
              'type': 'float'}
1437 1438


1439 1440 1441
FloatWidgetInstance = FloatWidget()
from Products.Formulator.StandardFields import FloatField
FloatField.widget = FloatWidgetInstance
1442 1443 1444

###################################################################
# New formulator API
1445
#
1446 1447
# render method on Field must change, and have a new parameter:
#   render_format
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1448
# which is used to call others methods ('html' call render_html)
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
###################################################################
# XXX Patching all Fields is not easy, as ERP5 defines his own fields.
# def Widget_render(self, field, key, value, REQUEST, render_format='html')
#   # Test if method defined on class
#   method_id = 'render_%' % render_format
#   if hasattr(aq_self(self), method_id):
#     # Try to return built-in renderer
#     return getattr(self, method_id )(self, field, key, value, REQUEST)
#   raise KeyError, "Rendering not defined"

# Monkey Patch
1460
#
1461
# Lookup all registered widgets and create render_html
1462
# XXX This method is not a good way of patching,
1463
# because it breaks inheritance
1464
# XXX It's difficult to get all possible widgets, as ERP5 defines
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
# also his owns.
# for f in Formulator.widgets():
#   if not hasattr(f, '__erp5_patched'):
#     f.render_html = f.render
def Widget_render_html(self, *args, **kw):
  return self.render(*args, **kw)
Widget.render_html = Widget_render_html

def Field_render_html(self, *args, **kw):
  """
  render_html is used to as definition of render method in Formulator.
  """
  return self.render(*args, **kw)
Field.render_html = Field_render_html

1480
def Field_render_htmlgrid(self, value=None, REQUEST=None, key=None, render_prefix=None):
1481 1482 1483 1484
  """
  render_htmlgrid returns a list of tuple (title, html render)
  """
  # What about CSS ? What about description ? What about error ?
1485
  widget_key = self.generate_field_key(key=key)
1486
  value = self._get_default(widget_key, value, REQUEST)
1487
  __traceback_info__ = ('key=%s value=%r' % (key, value))
1488 1489 1490 1491 1492 1493
  # XXX: API transition try..except..log..raise. Remove after a while.
  try:
    return self.widget.render_htmlgrid(self, widget_key, value, REQUEST, render_prefix=render_prefix)
  except TypeError:
    LOG('FormulatorPatch', 0, 'To update: %r (%r)' % (self.widget.render_htmlgrid, getattr(self.widget.render_htmlgrid, 'func_code', None)))
    raise
1494

1495 1496
Field.render_htmlgrid = Field_render_htmlgrid

1497
def Widget_render_htmlgrid(self, field, key, value, REQUEST, render_prefix=None):
1498 1499 1500 1501
  """
  render_htmlgrid returns a list of tuple (title, html render)
  """
  # XXX Calling _render_helper on the field is not optimized
1502 1503 1504 1505 1506 1507 1508
  # XXX: API transition try..except..log..raise. Remove after a while.
  try:
    return ((field.get_value('title'), 
             field._render_helper(key, value, REQUEST, render_prefix=render_prefix)),)
  except TypeError:
    LOG('FormulatorPatch', 0, 'To update: %r (%r)' % (field._render_helper, getattr(field._render_helper, 'func_code', None)))
    raise
1509 1510
Widget.render_htmlgrid = Widget_render_htmlgrid

1511
# Generic possible renderers
1512
#   def render_ext(self, field, key, value, REQUEST, render_prefix=None):
1513
#     return getattr(self, '%s_render' % self.__class__.__name__)
1514
#
1515
#   def render_pt(self, field, key, value, REQUEST, render_prefix=None):
1516 1517 1518 1519
#     """
#     Call a page template which contains 1 macro per field
#     """
#     return self.field_master(self.__class__.__name__)
1520
#
1521
#   def render_grid(self, field, key, value, REQUEST, render_prefix=None):
1522 1523 1524 1525 1526
#     return ((self.get_value('title'), self.get_value('value'),)
#    # What about CSS ? What about description ? What about error ?
#    # What about rendering a listbox ?
#    # Grid is only valid if stucture of grid has some meaning and is
#    # implemeted by listbox (ex. spreadsheet = grid)
1527
#
1528 1529 1530 1531 1532 1533 1534 1535

def Field_render_pdf(self, value=None, REQUEST=None, key=None, **kw):
  """
  render_pdf renders the field for reportlab
  """
  return self.widget.render_pdf(self, value)
Field.render_pdf = Field_render_pdf

1536 1537
def Field_render_css(self, REQUEST=None):
  """
1538
  Generate css content which will be added inline.
1539 1540 1541 1542 1543 1544

  XXX key parameter may be needed.
  """
  return self.widget.render_css(self, REQUEST)
Field.render_css = Field_render_css

1545 1546 1547 1548 1549 1550 1551 1552 1553
def Field_get_css_list(self, REQUEST=None):
  """
    Returns list of css sheets needed by the field
    to be included in global css imports
  """
  return self.widget.get_css_list(self, REQUEST)
Field.get_css_list = Field_get_css_list


1554 1555
def Field_get_javascript_list(self, REQUEST=None):
  """
1556 1557
    Returns list of javascript needed by the field
    to be included in global js imports
1558
  """
1559
  return self.widget.get_javascript_list(self, REQUEST)
1560 1561
Field.get_javascript_list = Field_get_javascript_list

1562 1563

from Products.Formulator.TALESField import TALESWidget
1564
def TALESWidget_render_view(self, field, value, REQUEST=None, render_prefix=None):
1565 1566 1567 1568
  """
  Render TALES as read only
  """
  if value == None:
1569
    text = field.get_value('default', REQUEST=REQUEST)
1570 1571 1572 1573 1574 1575 1576 1577
  else:
    if value != "":
      text = value._text
    else:
      text = ""
  return text

TALESWidget.render_view = TALESWidget_render_view
1578

1579 1580 1581 1582 1583
original_TALESWidget_render = TALESWidget.render
def TALESWidget_render(self, field, key, value, REQUEST, render_prefix=None):
  return original_TALESWidget_render(self, field, key, value, REQUEST)
TALESWidget.render = TALESWidget_render

1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
def Widget_render_dict(self, field, value):
  """
  This is yet another field rendering. It is designed to allow code to
  understand field's value data by providing its type and format when
  applicable.
  """
  return None
Widget.render_dict = Widget_render_dict

def Field_render_dict(self, value=None, REQUEST=None, key=None, **kw):
  """
  This is yet another field rendering. It is designed to allow code to
  understand field's value data by providing its type and format when
  applicable.
  """
  return self.widget.render_dict(self, value)
Field.render_dict = Field_render_dict
1601 1602 1603


# Find support in ZMI. This is useful for development.
1604 1605 1606 1607 1608 1609 1610
def getSearchSource(obj):
  obj_type = type(obj)
  if obj_type is MethodField.Method:
    return obj.method_name
  elif obj_type is TALESField.TALESMethod:
    return obj._text
  return str(obj)
1611
def Field_PrincipiaSearchSource(self):
1612 1613 1614
  return ''.join(
    map(getSearchSource,
        (self.values.values()+self.tales.values()+self.overrides.values())))
1615
Field.PrincipiaSearchSource = Field_PrincipiaSearchSource
1616 1617 1618 1619 1620 1621 1622 1623

# If type definition is missing for LinesField, the input text will be
# splitted into list like ['f', 'o', 'o'] with original Formulator's
# implementation. So explicit conversion to list is required before
# passing to LinesTextAreaWidget's render and render_view methods.
from Products.Formulator.Widget import LinesTextAreaWidget

original_LinesTextAreaWidget_render = LinesTextAreaWidget.render
1624
def LinesTextAreaWidget_render(self, field, key, value, REQUEST, render_prefix=None):
1625 1626 1627 1628 1629 1630
  if isinstance(value, (str, unicode)):
    value = [value]
  return original_LinesTextAreaWidget_render(self, field, key, value, REQUEST)
LinesTextAreaWidget.render = LinesTextAreaWidget_render

original_LinesTextAreaWidget_render_view = LinesTextAreaWidget.render_view
1631
def LinesTextAreaWidget_render_view(self, field, value, REQUEST=None, render_prefix=None):
1632 1633
  if isinstance(value, (str, unicode)):
    value = [value]
1634
  return original_LinesTextAreaWidget_render_view(self, field, value)
1635
LinesTextAreaWidget.render_view = LinesTextAreaWidget_render_view
1636

1637 1638 1639 1640 1641 1642 1643 1644
from Products.Formulator.Validator import EmailValidator
import re
# This regexp is based on the default Formulator regexp, and add the
# possibility to allow ' in the email address
# see: http://www.regular-expressions.info/email.html
EmailValidator.pattern = \
  re.compile('^[0-9a-zA-Z_\'&.%+-]+@([0-9a-zA-Z]([0-9a-zA-Z-]*[0-9a-zA-Z])?\.)+[a-zA-Z]{2,6}$')