Form.py 40 KB
Newer Older
1
from __future__ import absolute_import
2
import six
3
import AccessControl
4
import OFS
5
from AccessControl.class_init import InitializeClass
6
from Acquisition import aq_base
7 8
from App.special_dtml import DTMLFile
from Persistence import Persistent
9
from AccessControl import ClassSecurityInfo
10
from OFS.role import RoleManager
11 12 13 14
from OFS.ObjectManager import ObjectManager
from OFS.PropertyManager import PropertyManager
from OFS.SimpleItem import Item
import Acquisition
15
from six.moves.urllib.parse import quote
16
import os
17
from six import StringIO
18

19 20 21 22 23 24
from .Errors import ValidationError, FormValidationError, FieldDisabledError
from .FieldRegistry import FieldRegistry
from .Widget import render_tag
from .DummyField import fields
from .FormToXML import formToXML
from .XMLToForm import XMLToForm
25 26 27 28 29 30

from ComputedAttribute import ComputedAttribute

# FIXME: manage_renameObject hack needs these imports
from Acquisition import aq_base
from App.Dialogs import MessageDialog
31
from OFS.CopySupport import CopyError
32 33 34 35 36 37 38 39 40 41
import sys

class Form:
    """Form base class.
    """
    security = ClassSecurityInfo()

    # need to make settings form upgrade
    encoding = 'UTF-8'
    stored_encoding = 'ISO-8859-1'
Nicolas Dumazet's avatar
Nicolas Dumazet committed
42
    unicode_mode = False
43 44

    # CONSTRUCTORS
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    def __init__(self, action, method, enctype, name,
                 encoding, stored_encoding, unicode_mode):
        """Initialize form.
        """
        # make groups dict with entry for default group
        self.groups = {"Default": []}
        # the display order of the groups
        self.group_list = ["Default"]
        # form submit info
        self.name = name     # for use by javascript
        self.action = action
        self.method = method
        self.enctype = enctype
        self.encoding = encoding
        self.stored_encoding = stored_encoding
        self.unicode_mode = unicode_mode
61

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    # MANIPULATORS
    security.declareProtected('Change Formulator Forms', 'field_added')
    def field_added(self, field_id, group=None):
        """A field was added to the form.
        """
        # get indicated group or the first group if none was indicated
        group = group or self.group_list[0]
        # add it to the indicated group (create group if nonexistent)
        groups = self.groups
        field_list = groups.get(group, [])
        field_list.append(field_id)
        groups[group] = field_list
        if group not in self.group_list:
            self.group_list.append(group)
            self.group_list = self.group_list
        self.groups = groups
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    security.declareProtected('Change Formulator Forms', 'field_removed')
    def field_removed(self, field_id):
        """A field was removed from the form.
        """
        for field_list in self.groups.values():
            if field_id in field_list:
                field_list.remove(field_id)
                break # should be done as soon as we found it once
        self.groups = self.groups

    security.declareProtected('Change Formulator Forms', 'move_field_up')
    def move_field_up(self, field_id, group):
        groups = self.groups
        field_list = groups[group]
        i = field_list.index(field_id)
        if i == 0:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
95
            return False # can't move further up, so we're done
96 97 98
        # swap fields, moving i up
        field_list[i], field_list[i - 1] = field_list[i - 1], field_list[i]
        self.groups = groups
Nicolas Dumazet's avatar
Nicolas Dumazet committed
99
        return True
100

101 102 103 104 105 106
    security.declareProtected('Change Formulator Forms', 'move_field_down')
    def move_field_down(self, field_id, group):
        groups = self.groups
        field_list = groups[group]
        i = field_list.index(field_id)
        if i == len(field_list) - 1:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
107
            return False # can't move further down, so we're done
108 109 110
        # swap fields, moving i down
        field_list[i], field_list[i + 1] = field_list[i + 1], field_list[i]
        self.groups = groups
Nicolas Dumazet's avatar
Nicolas Dumazet committed
111
        return True
112 113 114 115 116

    security.declareProtected('Change Formulator Forms', 'move_field_group')
    def move_field_group(self, field_ids, from_group, to_group):
        """Moves a fields from one group to the other.
        """
Nicolas Dumazet's avatar
Nicolas Dumazet committed
117 118
        if len(field_ids) == 0 or from_group == to_group:
            return False
119 120 121 122 123 124 125 126
        groups = self.groups
        from_list = groups[from_group]
        to_list = groups[to_group]
        for field in self.get_fields_in_group(from_group, include_disabled=1)[:]:
            if field.id in field_ids:
                from_list.remove(field.id)
                to_list.append(field.id)
        self.groups = groups
Nicolas Dumazet's avatar
Nicolas Dumazet committed
127
        return True
128

129 130 131 132 133
    security.declareProtected('Change Formulator Forms', 'add_group')
    def add_group(self, group):
        """Add a new group.
        """
        groups = self.groups
134
        if group in groups:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
135
            return False # group already exists (NOTE: should we raise instead?)
136 137 138
        groups[group] = []
        # add the group to the bottom of the list of groups
        self.group_list.append(group)
139

140 141
        self.group_list = self.group_list
        self.groups = groups
Nicolas Dumazet's avatar
Nicolas Dumazet committed
142
        return True
143

144 145 146 147 148 149
    security.declareProtected('Change Formulator Forms', 'remove_group')
    def remove_group(self, group):
        """Remove a group.
        """
        groups = self.groups
        if group == self.group_list[0]:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
150
            return False # can't remove first group
151
        if group not in groups:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
152
            return False # group does not exist (NOTE: should we raise instead?)
153 154 155 156 157 158
        # move whatever is in the group now to the end of the first group
        groups[self.group_list[0]].extend(groups[group])
        # now remove the key
        del groups[group]
        # remove it from the group order list as well
        self.group_list.remove(group)
159

160 161
        self.group_list = self.group_list
        self.groups = groups
Nicolas Dumazet's avatar
Nicolas Dumazet committed
162
        return True
163

164 165 166 167 168 169
    security.declareProtected('Change Formulator Forms', 'rename_group')
    def rename_group(self, group, name):
        """Rename a group.
        """
        group_list = self.group_list
        groups = self.groups
170
        if group not in groups:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
171
            return False # can't rename unexisting group
172
        if name in groups:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
173
            return False # can't rename into existing name
174 175 176 177 178 179
        i = group_list.index(group)
        group_list[i] = name
        groups[name] = groups[group]
        del groups[group]
        self.group_list = group_list
        self.groups = groups
Nicolas Dumazet's avatar
Nicolas Dumazet committed
180
        return True
181 182 183 184 185 186 187

    security.declareProtected('Change Formulator Forms', 'move_group_up')
    def move_group_up(self, group):
        """Move a group up in the group list.
        """
        group_list = self.group_list
        i = group_list.index(group)
188
        if i == 0:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
189
            return False # can't move further up, so we're done
190 191 192
        # swap groups, moving i up
        group_list[i], group_list[i - 1] = group_list[i - 1], group_list[i]
        self.group_list = group_list
Nicolas Dumazet's avatar
Nicolas Dumazet committed
193
        return True
194 195

    security.declareProtected('Change Formulator Forms', 'move_group_down')
196 197 198 199 200 201
    def move_group_down(self, group):
        """Move a group down in the group list.
        """
        group_list = self.group_list
        i = group_list.index(group)
        if i  == len(group_list) - 1:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
202
            return False # can't move further up, so we're done
203 204 205
        # swap groups, moving i down
        group_list[i], group_list[i + 1] = group_list[i + 1], group_list[i]
        self.group_list = group_list
Nicolas Dumazet's avatar
Nicolas Dumazet committed
206
        return True
207

208 209
    # ACCESSORS
    security.declareProtected('View', 'get_fields')
Nicolas Dumazet's avatar
Nicolas Dumazet committed
210
    def get_fields(self, include_disabled=False):
211 212 213
        """Get all fields for all groups (in the display order).
        """
        result = []
Nicolas Dumazet's avatar
Nicolas Dumazet committed
214
        for group in self.get_groups(include_empty=True):
215 216 217 218
            result.extend(self.get_fields_in_group(group, include_disabled))
        return result

    security.declareProtected('View', 'get_field_ids')
Nicolas Dumazet's avatar
Nicolas Dumazet committed
219
    def get_field_ids(self, include_disabled=False):
220 221 222 223 224 225
        """Get all the ids of the fields in the form.
        """
        result = []
        for field in self.get_fields(include_disabled):
            result.append(field.id)
        return result
226

227
    security.declareProtected('View', 'get_fields_in_group')
Nicolas Dumazet's avatar
Nicolas Dumazet committed
228
    def get_fields_in_group(self, group, include_disabled=False):
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        """Get all fields in a group (in the display order).
        """
        result = []
        for field_id in self.groups.get(group, []):
            try:
                field = self.get_field(field_id, include_disabled)
            except FieldDisabledError:
                pass
            else:
                result.append(field)
        return result

    security.declareProtected('View', 'has_field')
    def has_field(self, id, include_disabled):
        """Check whether the form has a field of a certain id.
        """
        # define in subclass
        pass
247

248 249 250 251 252 253
    security.declareProtected('View', 'get_field')
    def get_field(self, id):
        """Get a field of a certain id.
        """
        # define in subclass
        pass
254

255
    security.declareProtected('View', 'get_groups')
Nicolas Dumazet's avatar
Nicolas Dumazet committed
256
    def get_groups(self, include_empty=False):
257 258 259 260 261 262 263 264 265
        """Get a list of all groups, in display order.

        If include_empty is false, suppress groups that do not have
        enabled fields.
        """
        if include_empty:
            return self.group_list
        return [group for group in self.group_list
                if self.get_fields_in_group(group)]
266

267 268 269 270 271 272 273
    security.declareProtected('View', 'get_form_encoding')
    def get_form_encoding(self):
        """Get the encoding the form is in. Should be the same as the
        encoding of the page, if specified, for unicode to work. Default
        is 'UTF-8'.
        """
        return getattr(self, 'encoding', 'UTF-8')
274

275 276 277 278 279
    security.declareProtected('View', 'get_stored_encoding')
    def get_stored_encoding(self):
        """Get the encoding of the stored field properties.
        """
        return getattr(self, 'stored_encoding', 'ISO-8859-1')
280

281 282 283 284
    security.declareProtected('View', 'get_unicode_mode')
    def get_unicode_mode(self):
        """Get unicode mode information.
        """
Nicolas Dumazet's avatar
Nicolas Dumazet committed
285
        return getattr(self, 'unicode_mode', False)
286

287 288 289 290 291 292 293 294 295 296 297 298
    security.declareProtected('View', 'render')
    def render(self, dict=None, REQUEST=None):
        """Render form in a default way.
        """
        dict = dict or {}
        result = StringIO()
        w = result.write
        w(self.header())
        for group in self.get_groups():
            w('<h2>%s</h2>\n' % group)
            w('<table border="0" cellspacing="0" cellpadding="2">\n')
            for field in self.get_fields_in_group(group):
299
                if field.id in dict:
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
                    value = dict[field.id]
                else:
                    value = None
                w('<tr>\n')
                if not field.get_value('hidden'):
                    w('<td>%s</td>\n' % field.get_value('title'))
                else:
                    w('<td></td>')
                w('<td>%s</td>\n' % field.render(value, REQUEST))
                w('</tr>\n')
            w('</table>\n')
        w('<input type="submit" value=" OK ">\n')
        w(self.footer())
        return result.getvalue()

    security.declareProtected('View', 'render_view')
    def render_view(self, dict=None):
        """Render contents (default simplistic way).
        """
        dict = dict or {}
        result = StringIO()
        w = result.write
        for group in self.get_groups():
            w('<h2>%s</h2>\n' % group)
            w('<table border="0" cellspacing="0" cellpadding="2">\n')
            for field in self.get_fields_in_group(group):
326
                if field.id in dict:
327 328 329 330 331 332 333 334 335
                    value = dict[field.id]
                else:
                    value = None
                w('<tr>\n')
                w('<td>%s</td>\n' % field.get_value('title'))
                w('<td>%s</td>\n' % field.render_view(value))
                w('</tr>\n')
            w('</table>\n')
        return result.getvalue()
336

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    security.declareProtected('View', 'validate')
    def validate(self, REQUEST):
        """Validate all enabled fields in this form. Stop validating and
        pass up ValidationError if any occurs.
        """
        result = {}
        for field in self.get_fields():
            # skip any fields we don't need to validate
            if not field.need_validate(REQUEST):
                continue
            value = field.validate(REQUEST)
            # store under id
            result[field.id] = value
            # store as alternate name as well if necessary
            alternate_name = field.get_value('alternate_name')
            if alternate_name:
353
                result[alternate_name] = value
354 355 356 357 358 359 360 361 362 363
        return result

    security.declareProtected('View', 'validate_to_request')
    def validate_to_request(self, REQUEST):
        """Validation, stop validating as soon as error.
        """
        result = self.validate(REQUEST)
        for key, value in result.items():
            REQUEST.set(key, value)
        return result
364

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    security.declareProtected('View', 'validate_all')
    def validate_all(self, REQUEST):
        """Validate all enabled fields in this form, catch any ValidationErrors
        if they occur and raise a FormValidationError in the end if any
        Validation Errors occured.
        """
        result = {}
        errors = []
        for field in self.get_fields():
            # skip any field we don't need to validate
            if not field.need_validate(REQUEST):
                continue
            try:
                value = field.validate(REQUEST)
                # store under id
                result[field.id] = value
                # store as alternate name as well if necessary
                alternate_name = field.get_value('alternate_name')
                if alternate_name:
                    result[alternate_name] = value
385
            except ValidationError as err:
386 387
                errors.append(err)
        if len(errors) > 0:
388
            raise FormValidationError(errors, result)
389 390 391
        return result

    security.declareProtected('View', 'validate_all_to_request')
392
    def validate_all_to_request(self, REQUEST, key_prefix=None):
393 394 395 396
        """Validation, continue validating all fields, catch errors.
        Everything that could be validated will be added to REQUEST.
        """
        try:
397
            result = self.validate_all(REQUEST, key_prefix=key_prefix)
398
        except FormValidationError as e:
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
            # put whatever result we have in REQUEST
            for key, value in e.result.items():
                REQUEST.set(key, value)
            # reraise exception
            raise
        for key, value in result.items():
            REQUEST.set(key, value)
        return result

    security.declareProtected('View', 'session_store')
    def session_store(self, session, REQUEST):
        """Store form data in REQUEST into session.
        """
        data = session.getSessionData()
        for field in self.get_fields():
            id = field.id
            data.set(id, REQUEST[id])

    security.declareProtected('View', 'session_retrieve')
    def session_retrieve(self, session, REQUEST):
        """Retrieve form data from session into REQUEST.
        """
        data = session.getSessionData()
        for field in self.get_fields():
            id = field.id
            REQUEST.set(id, data.get(id))

    security.declareProtected('View', 'header')
    def header(self):
        """Starting form tag.
        """
        # FIXME: backwards compatibility; name attr may not be present
        if not hasattr(self, "name"):
            self.name = ""
        name = self.name

        if self.enctype is not "":
            if name:
                return render_tag("form",
                                  name=name,
                                  action=self.action,
                                  method=self.method,
                                  enctype=self.enctype) + ">"
            else:
                return render_tag("form",
                                  action=self.action,
                                  method=self.method,
                                  enctype=self.enctype) + ">"
        else:
            if name:
                return render_tag("form",
                                  name=name,
                                  action=self.action,
                                  method=self.method) + ">"
            else:
                return render_tag("form",
                                  action=self.action,
                                  method=self.method) + ">"

    security.declareProtected('View', 'footer')
    def footer(self):
        """Closing form tag.
        """
        return "</form>"

    security.declareProtected('Change Formulator Forms', 'get_xml')
    def get_xml(self):
        """Get this form in XML serialization.
        """
        return formToXML(self)

    security.declareProtected('Change Formulator Forms', 'set_xml')
    def set_xml(self, xml, override_encoding=None):
        """change form according to xml"""
        XMLToForm(xml, self, override_encoding)

    def _management_page_charset(self):
        if not self.unicode_mode:
            return self.stored_encoding
        else:
            return 'UTF-8'

    security.declareProtected('Access contents information',
                              'management_page_charset')
    management_page_charset = ComputedAttribute(_management_page_charset)
484

485 486 487 488 489 490 491 492 493 494 495 496 497 498
    security.declareProtected('View', 'set_encoding_header')
    def set_encoding_header(self):
        """Set the encoding in the RESPONSE object.

        This can be used to make sure a page is in the same encoding the
        textual form contents is in.
        """
        if not self.unicode_mode:
            encoding = self.stored_encoding
        else:
            encoding = 'UTF-8'
        self.REQUEST.RESPONSE.setHeader(
            'Content-Type',
            'text/html;charset=%s' % encoding)
499

500
InitializeClass(Form)
501 502 503 504 505 506

class BasicForm(Persistent, Acquisition.Implicit, Form):
    """A form that manages its own fields, not using ObjectManager.
    Can contain dummy fields defined by DummyField.
    """
    security = ClassSecurityInfo()
507

508 509
    def __init__(self, action="", method="POST", enctype="", name="",
                 encoding="UTF-8", stored_encoding='ISO-8859-1',
Nicolas Dumazet's avatar
Nicolas Dumazet committed
510
                 unicode_mode=False):
511 512 513 514 515 516 517 518
        BasicForm.inheritedAttribute('__init__')(
            self, action, method, enctype,
            name, encoding, stored_encoding, unicode_mode)
        self.title = 'Basic Form' # XXX to please FormToXML..
        self.fields = {}

    security.declareProtected('Change Formulator Forms', 'add_field')
    def add_field(self, field, group=None):
519
        """Add a field to the form to a certain group.
520 521 522 523
        """
        # update group info
        self.field_added(field.id, group)
        # add field to list
524
        self.fields[field.id] = field
525 526 527 528 529 530 531 532
        self.fields = self.fields

    security.declareProtected('Change Formulator Forms', 'add_fields')
    def add_fields(self, fields, group=None):
        """Add a number of fields to the form at once (in a group).
        """
        for field in fields:
            self.add_field(field, group)
533

534 535 536 537 538 539 540 541 542 543 544
    security.declareProtected('Change Formulator Forms', 'remove_field')
    def remove_field(self, field):
        """Remove field from form.
        """
        # update group info
        self.field_removed(field.id)
        # remove field from list
        del self.fields[field.id]
        self.fields = self.fields

    security.declareProtected('View', 'has_field')
Nicolas Dumazet's avatar
Nicolas Dumazet committed
545
    def has_field(self, id, include_disabled=False):
546 547 548 549 550
        """Check whether the form has a field of a certain id.
        If disabled fields are not included, pretend they're not there.
        """
        field = self.fields.get(id, None)
        if field is None:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
551
            return False
552
        return include_disabled or field.get_value('enabled')
553

554
    security.declareProtected('View', 'get_field')
Nicolas Dumazet's avatar
Nicolas Dumazet committed
555
    def get_field(self, id, include_disabled=False):
556 557 558 559 560
        """get a field of a certain id."""
        field = self.fields[id]
        if include_disabled or field.get_value('enabled'):
            return field
        raise FieldDisabledError("Field %s is disabled" % id, field)
561

562 563 564
    def _realize_fields(self):
        """Make the fields in this form actual fields, not just dummy fields.
        """
Nicolas Dumazet's avatar
Nicolas Dumazet committed
565
        for field in self.get_fields(include_disabled=True):
566 567 568 569 570
            if hasattr(field, 'get_real_field'):
                field = field.get_real_field()
            self.fields[field.id] = field
        self.fields = self.fields

571
InitializeClass(BasicForm)
572 573 574 575 576 577 578 579

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

    title = fields.StringField('title',
                               title="Title",
Nicolas Dumazet's avatar
Nicolas Dumazet committed
580
                               required=False,
581
                               css_class="form-control",
582 583 584
                               default="")
    row_length = fields.IntegerField('row_length',
                                     title='Number of groups in row (in order tab)',
Nicolas Dumazet's avatar
Nicolas Dumazet committed
585
                                     required=True,
586
                                     css_class="form-control",
587 588 589
                                     default=4)
    name = fields.StringField('name',
                              title="Form name",
Nicolas Dumazet's avatar
Nicolas Dumazet committed
590
                              required=False,
591
                              css_class="form-control",
592 593 594
                              default="")
    action = fields.StringField('action',
                                title='Form action',
Nicolas Dumazet's avatar
Nicolas Dumazet committed
595
                                required=False,
596
                                css_class="form-control",
597 598 599 600 601
                                default="")
    method = fields.ListField('method',
                              title='Form method',
                              items=[('POST', 'POST'),
                                     ('GET', 'GET')],
Nicolas Dumazet's avatar
Nicolas Dumazet committed
602
                              required=True,
603
                              size=1,
604
                              css_class="form-control",
605 606 607 608 609 610 611 612
                              default='POST')
    enctype = fields.ListField('enctype',
                               title='Form enctype',
                               items=[('No enctype', ""),
                                      ('application/x-www-form-urlencoded',
                                       'application/x-www-form-urlencoded'),
                                      ('multipart/form-data',
                                       'multipart/form-data')],
Nicolas Dumazet's avatar
Nicolas Dumazet committed
613
                               required=False,
614
                               size=1,
615
                               css_class="form-control",
616
                               default=None)
617 618 619 620

    encoding = fields.StringField('encoding',
                                  title='Encoding of pages the form is in',
                                  default="UTF-8",
621
                                  css_class="form-control",
Nicolas Dumazet's avatar
Nicolas Dumazet committed
622
                                  required=True)
623 624 625 626

    stored_encoding = fields.StringField('stored_encoding',
                                      title='Encoding of form properties',
                                      default='ISO-8859-1',
627
                                      css_class="form-control",
Nicolas Dumazet's avatar
Nicolas Dumazet committed
628
                                      required=True)
629 630
    unicode_mode = fields.CheckBoxField('unicode_mode',
                                        title='Form properties are unicode',
Nicolas Dumazet's avatar
Nicolas Dumazet committed
631
                                        default=False,
632
                                        css_class="form-control",
Nicolas Dumazet's avatar
Nicolas Dumazet committed
633
                                        required=True)
634

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    form.add_fields([title, row_length, name, action, method,
                     enctype, encoding, stored_encoding, unicode_mode])
    return form

class ZMIForm(ObjectManager, PropertyManager, RoleManager, Item, Form):
    """
    A Formulator Form, fields are managed by ObjectManager.
    """
    meta_type = "Formulator Form"

    security = ClassSecurityInfo()

    # should be helpful with ZClasses, but not sure why I
    # had it in here as a comment in the first place..
    security.declareObjectProtected('View')
650

651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
    # the tabs we want to show
    manage_options = (
        (
        {'label':'Contents', 'action':'manage_main',
         'help':('Formulator', 'formContents.txt')},
        {'label':'Test', 'action':'formTest',
         'help':('Formulator', 'formTest.txt')},
        {'label':'Order', 'action':'formOrder',
         'help':('Formulator', 'formOrder.txt')},
        {'label':'Settings', 'action':'formSettings',
         'help':('Formulator', 'formSettings.txt')},
        {'label':'XML', 'action':'formXML',
         'help':('Formulator', 'formXML.txt')},
        ) +
        PropertyManager.manage_options +
        RoleManager.manage_options +
        Item.manage_options
        )

Nicolas Dumazet's avatar
Nicolas Dumazet committed
670
    def __init__(self, id, title, unicode_mode=False):
671 672 673 674 675 676 677 678 679 680
        """Initialize form.
        id    -- id of form
        title -- the title of the form
        """
        ZMIForm.inheritedAttribute('__init__')(self, "", "POST", "", id,
                                               'UTF-8', 'ISO-8859-1',
                                               unicode_mode)
        self.id = id
        self.title = title
        self.row_length = 4
681

682
    security.declarePublic('all_meta_types')
683 684 685 686 687 688 689 690 691 692 693
    def all_meta_types(self):
        """Get all meta types addable to this field. The ZMI uses
        this method (original defined in ObjectManager).
        """
        return self._meta_types

    def manage_renameObject(self, id, new_id, REQUEST=None):
        """Rename a particular sub-object, the *old* way.
        FIXME: hack that could be removed once Zope 2.4.x
        goes back to a useful semantics..."""
        try: self._checkId(new_id)
694
        except: raise CopyError(MessageDialog(
695 696
                      title='Invalid Id',
                      message=sys.exc_info()[1],
697
                      action ='manage_main'))
698 699
        ob=self._getOb(id)
        if not ob.cb_isMoveable():
700
            raise CopyError('Not Supported')
701 702
        self._verifyObjectPaste(ob)
        try:    ob._notifyOfCopyTo(self, op=1)
703
        except: raise CopyError(MessageDialog(
704 705
                      title='Rename Error',
                      message=sys.exc_info()[1],
706
                      action ='manage_main'))
707 708 709
        self._delObject(id)
        ob = aq_base(ob)
        ob._setId(new_id)
710

711 712
        # Note - because a rename always keeps the same context, we
        # can just leave the ownership info unchanged.
Nicolas Dumazet's avatar
Nicolas Dumazet committed
713
        self._setObject(new_id, ob, set_owner=False)
714 715

        if REQUEST is not None:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
716
            return self.manage_main(self, REQUEST, update_menu=True)
717 718 719 720 721 722 723 724 725 726
        return None

    #security.declareProtected('View', 'get_fields_raw')
    #def get_fields_raw(self):
    #    """Get all fields, in arbitrary order.
    #    """
    #    return filter(lambda obj: hasattr(obj.aq_explicit, 'is_field'),
    #                  self.objectValues())

    security.declareProtected('View', 'has_field')
Nicolas Dumazet's avatar
Nicolas Dumazet committed
727
    def has_field(self, id, include_disabled=False):
728 729 730 731
        """Check whether the form has a field of a certain id.
        """
        field = self._getOb(id, None)
        if field is None or not hasattr(aq_base(field), 'is_field'):
Nicolas Dumazet's avatar
Nicolas Dumazet committed
732
            return False
733
        return include_disabled or field.get_value('enabled')
734

735
    security.declareProtected('View', 'get_field')
Nicolas Dumazet's avatar
Nicolas Dumazet committed
736
    def get_field(self, id, include_disabled=False):
737 738 739 740
        """Get a field of a certain id
        """
        field = self._getOb(id, None)
        if field is None or not hasattr(aq_base(field), 'is_field'):
741
            raise AttributeError("No field %s" % id)
742 743 744 745 746 747 748 749 750 751 752 753 754
        if include_disabled or field.get_value('enabled'):
            return field
        raise FieldDisabledError("Field %s disabled" % id, field)

    security.declareProtected('Change Formulator Forms', 'manage_addField')
    def manage_addField(self, id, title, fieldname, REQUEST=None):
        """Add a new field to the form.
        id        -- the id of the field to add
        title     -- the title of the field to add; this will be used in
                     displays of the field on forms
        fieldname -- the name of the field (meta_type) to add
        Result    -- empty string
        """
755
        title = title.strip()
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
        if not title:
            title = id # title is always required, use id if not provided
        # get the field class we want to add
        field_class = FieldRegistry.get_field_class(fieldname)
        # create field instance
        field = field_class(id, title=title, description="")
        # add the field to the form
        id = self._setObject(id, field)
        # respond to add_and_edit button if necessary
        add_and_edit(self, id, REQUEST)
        return ''

    security.declareProtected('View management screens', 'formTest')
    formTest = DTMLFile('dtml/formTest', globals())

    settings_form = create_settings_form()

    security.declareProtected('View management screens', 'formSettings')
    formSettings = DTMLFile('dtml/formSettings', globals())

    security.declareProtected('View management screens', 'formOrder')
    formOrder = DTMLFile('dtml/formOrder', globals())

    security.declareProtected('View management screens', 'formXML')
    formXML = DTMLFile('dtml/formXML', globals())

    security.declareProtected('Change Formulator Forms', 'manage_editXML')
    def manage_editXML(self, form_data, REQUEST):
        """Change form using XML.
        """
        self.set_xml(form_data)
        return self.formXML(self, REQUEST,
                            manage_tabs_message="Changed form")
789

790 791 792 793 794 795
    security.declareProtected('Change Formulator Forms', 'manage_settings')
    def manage_settings(self, REQUEST):
        """Change settings in settings screen.
        """
        try:
            result = self.settings_form.validate_all(REQUEST)
796
        except FormValidationError as e:
797
            message = "Validation error(s).<br />" + "<br />".join(
798
                ["%s: %s" % (error.field.get_value('title'),
799
                                              error.error_text) for error in e.errors])
800 801 802 803 804 805
            return self.formSettings(self, REQUEST,
                                     manage_tabs_message=message)
        # if we need to switch encoding, get xml representation before setting
        if result['unicode_mode'] != self.unicode_mode:
            xml = self.get_xml()
        # now set the form settings
806

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        # convert XML to or from unicode mode if necessary
        unicode_message = None
        if result['unicode_mode'] != self.unicode_mode:
            # get XML (using current stored_encoding)
            xml = self.get_xml()

            # now save XML data again using specified encoding
            if result['unicode_mode']:
                encoding = 'unicode'
                unicode_message = "Converted to unicode."
            else:
                encoding = result['stored_encoding']
                unicode_message = ("Converted from unicode to %s encoding" %
                                   encoding)
            self.set_xml(xml, encoding)
822

823 824 825 826 827 828 829 830
        # now set the form settings
        for key, value in result.items():
            setattr(self, key, value)
        message="Settings changed."
        if unicode_message is not None:
            message = message + ' ' + unicode_message
        return self.formSettings(self, REQUEST,
                                 manage_tabs_message=message)
831

832 833 834 835 836
    security.declarePrivate('_get_field_ids')
    def _get_field_ids(self, group, REQUEST):
        """Get the checked field_ids that we're operating on
        """
        field_ids = []
Nicolas Dumazet's avatar
Nicolas Dumazet committed
837
        for field in self.get_fields_in_group(group, include_disabled=True):
838
            if field.id in REQUEST.form:
839 840 841 842 843 844 845 846 847
                field_ids.append(field.id)
        return field_ids

    security.declareProtected('View management screens',
                              'get_group_rows')
    def get_group_rows(self):
        """Get the groups in rows (for the order screen).
        """
        row_length = self.row_length
Nicolas Dumazet's avatar
Nicolas Dumazet committed
848
        groups = self.get_groups(include_empty=True)
849
        # get the amount of rows
850
        rows = len(groups) // row_length
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
        # if we would have extra groups not in a row, add a row
        if len(groups) % self.row_length != 0:
            rows = rows + 1
        # now create a list of group lists and return it
        result = []
        for i in range(rows):
            start = i * row_length
            result.append(groups[start: start + row_length])
        return result

    security.declareProtected('View', 'get_largest_group_length')
    def get_largest_group_length(self):
        """Get the largest group length available; necessary for
        'order' screen user interface.
        """
        max = 0
Nicolas Dumazet's avatar
Nicolas Dumazet committed
867
        for group in self.get_groups(include_empty=True):
868 869 870 871
            fields = self.get_fields_in_group(group)
            if len(fields) > max:
                max = len(fields)
        return max
872

873 874 875 876 877 878 879 880 881
    security.declareProtected('Change Formulator Forms',
                              'manage_move_field_up')
    def manage_move_field_up(self, group, REQUEST):
        """Moves up a field in a group.
        """
        field_ids = self._get_field_ids(group, REQUEST)
        if (len(field_ids) == 1 and
            self.move_field_up(field_ids[0], group)):
            message = "Field %s moved up." % field_ids[0]
882
            manage_tabs_type = "success"
883 884
        else:
            message = "Can't move field up."
885
            manage_tabs_type = "danger"
886
        return self.formOrder(self, REQUEST,
887
                              manage_tabs_type=manage_tabs_type,
888
                              manage_tabs_message=message)
889

890 891 892 893 894 895 896 897 898
    security.declareProtected('Change Formulator Forms',
                              'manage_move_field_down')
    def manage_move_field_down(self, group, REQUEST):
        """Moves down a field in a group.
        """
        field_ids = self._get_field_ids(group, REQUEST)
        if (len(field_ids) == 1 and
            self.move_field_down(field_ids[0], group)):
            message = "Field %s moved down." % field_ids[0]
899
            manage_tabs_type = "success"
900 901
        else:
            message = "Can't move field down."
902
            manage_tabs_type = "danger"
903
        return self.formOrder(self, REQUEST,
904
                              manage_tabs_type=manage_tabs_type,
905 906 907 908 909 910 911 912 913 914
                              manage_tabs_message=message)

    security.declareProtected('Change Formulator Forms',
                              'manage_move_group')
    def manage_move_group(self, group, to_group, REQUEST):
        """Moves fields to a different group.
        """
        field_ids = self._get_field_ids(group, REQUEST)
        if (to_group != 'Move to:' and
            self.move_field_group(field_ids, group, to_group)):
915
            fields = ", ".join(field_ids)
916 917 918
            message = "Fields %s transferred from %s to %s." % (fields,
                                                                group,
                                                                to_group)
919
            manage_tabs_type = "success"
920 921
        else:
            message = "Can't transfer fields."
922 923
            manage_tabs_type = "danger"

924
        return self.formOrder(self, REQUEST,
925
                              manage_tabs_type=manage_tabs_type,
926
                              manage_tabs_message=message)
927

928 929 930 931 932
    security.declareProtected('Change Formulator Forms',
                              'manage_add_group')
    def manage_add_group(self, new_group, REQUEST):
        """Adds a new group.
        """
933
        group = new_group.strip()
934 935 936
        if (group and group != 'Select group' and
            self.add_group(group)):
            message = "Group %s created." % (group)
937
            manage_tabs_type = "success"
938 939
        else:
            message = "Can't create group."
940
            manage_tabs_type = "danger"
941
        return self.formOrder(self, REQUEST,
942
                              manage_tabs_type=manage_tabs_type,
943 944 945 946 947 948 949 950 951
                              manage_tabs_message=message)

    security.declareProtected('Change Formulator Forms',
                              'manage_remove_group')
    def manage_remove_group(self, group, REQUEST):
        """Removes group.
        """
        if self.remove_group(group):
            message = "Group %s removed." % (group)
952
            manage_tabs_type = "success"
953 954
        else:
            message = "Can't remove group."
955
            manage_tabs_type = "danger"
956
        return self.formOrder(self, REQUEST,
957
                              manage_tabs_type=manage_tabs_type,
958 959 960 961 962 963 964
                              manage_tabs_message=message)

    security.declareProtected('Change Formulator Forms',
                              'manage_rename_group')
    def manage_rename_group(self, group, REQUEST):
        """Renames group.
        """
965
        if 'new_name' in REQUEST:
966
            new_name = REQUEST['new_name'].strip()
967 968
            if self.rename_group(group, new_name):
                message = "Group %s renamed to %s." % (group, new_name)
969
                manage_tabs_type = "success"
970 971
            else:
                message = "Can't rename group."
972
                manage_tabs_type = "danger"
973 974
        else:
            message = "No new name supplied."
975
            manage_tabs_type = "danger"
976 977

        return self.formOrder(self, REQUEST,
978
                              manage_tabs_type=manage_tabs_type,
979
                              manage_tabs_message=message)
980

981 982 983 984 985 986 987
    security.declareProtected('Change Formulator Forms',
                              'manage_move_group_up')
    def manage_move_group_up(self, group, REQUEST):
        """Move a group up.
        """
        if self.move_group_up(group):
            message = "Group %s moved up." % group
988
            manage_tabs_type = "success"
989 990
        else:
            message = "Can't move group %s up" % group
991
            manage_tabs_type = "danger"
992
        return self.formOrder(self, REQUEST,
993
                              manage_tabs_type=manage_tabs_type,
994
                              manage_tabs_message=message)
995

996 997 998 999 1000 1001 1002
    security.declareProtected('Change Formulator Forms',
                              'manage_move_group_down')
    def manage_move_group_down(self, group, REQUEST):
        """Move a group down.
        """
        if self.move_group_down(group):
            message = "Group %s moved down." % group
1003
            manage_tabs_type = "success"
1004 1005
        else:
            message = "Can't move group %s down" % group
1006
            manage_tabs_type = "danger"
1007
        return self.formOrder(self, REQUEST,
1008
                              manage_tabs_type=manage_tabs_type,
1009 1010 1011
                              manage_tabs_message=message)

PythonForm = ZMIForm # NOTE: backwards compatibility
1012
InitializeClass(ZMIForm)
1013

1014 1015
manage_addForm = DTMLFile("dtml/formAdd", globals())

Nicolas Dumazet's avatar
Nicolas Dumazet committed
1016
def manage_add(self, id, title="", unicode_mode=False, REQUEST=None):
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    """Add form to folder.
    id     -- the id of the new form to add
    title  -- the title of the form to add
    Result -- empty string
    """
    # add actual object
    id = self._setObject(id, ZMIForm(id, title, unicode_mode))
    # respond to the add_and_edit button if necessary
    add_and_edit(self, id, REQUEST)
    return ''

def add_and_edit(self, id, REQUEST):
    """Helper method to point to the object's management screen if
    'Add and Edit' button is pressed.
    id -- id of the object we just added
    """
    if REQUEST is None:
        return
    try:
        u = self.DestinationURL()
    except:
        u = REQUEST['URL1']
    if hasattr(REQUEST, 'submit_add_and_edit'):
        u = "%s/%s" % (u, quote(id))
    REQUEST.RESPONSE.redirect(u+'/manage_main')

def initializeForm(field_registry):
    """Sets up ZMIForm with fields from field_registry.
    """
    form_class = ZMIForm
1047

1048 1049 1050 1051 1052
    meta_types = []
    for meta_type, field in field_registry.get_field_classes().items():
        # don't set up in form if this is a field for internal use only
        if field.internal_field:
            continue
1053

1054 1055
        # set up individual add dictionaries for meta_types
        dict = { 'name': field.meta_type,
1056
                 'zmi_show_add_dialog': 'modal',
1057 1058 1059 1060 1061 1062 1063
                 'action':
                 'manage_addProduct/Formulator/manage_add%sForm' % meta_type }
        meta_types.append(dict)
        # set up add method
        setattr(form_class,
                'manage_add%sForm' % meta_type,
                DTMLFile('dtml/fieldAdd', globals(), fieldname=meta_type))
1064

1065 1066 1067 1068 1069 1070 1071 1072
    # set up meta_types that can be added to form
    form_class._meta_types = tuple(meta_types)

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



1073

1074 1075 1076