paul@0 | 1 | # -*- coding: iso-8859-1 -*- |
paul@0 | 2 | """ |
paul@0 | 3 | MoinMoin - MoinForms library |
paul@0 | 4 | |
paul@21 | 5 | @copyright: 2012, 2013 by Paul Boddie <paul@boddie.org.uk> |
paul@0 | 6 | @license: GNU GPL (v2 or later), see COPYING.txt for details. |
paul@0 | 7 | """ |
paul@0 | 8 | |
paul@23 | 9 | from compiler import parse |
paul@23 | 10 | from compiler.ast import Const, Dict, Discard, List, Module, Stmt |
paul@3 | 11 | from MoinMoin.action import do_show |
paul@8 | 12 | from MoinMoin.Page import Page |
paul@24 | 13 | from MoinMoin import security, wikiutil |
paul@0 | 14 | from MoinSupport import * |
paul@0 | 15 | import re |
paul@0 | 16 | |
paul@0 | 17 | __version__ = "0.1" |
paul@0 | 18 | |
paul@4 | 19 | form_field_regexp_str = r"<<Form(Field|Message)\((.*?)\)>>" |
paul@1 | 20 | form_field_regexp = re.compile(form_field_regexp_str, re.DOTALL) |
paul@1 | 21 | |
paul@3 | 22 | # Common action functionality. |
paul@3 | 23 | |
paul@3 | 24 | class MoinFormHandlerAction: |
paul@3 | 25 | |
paul@3 | 26 | "A handler action that can be specialised for individual forms." |
paul@3 | 27 | |
paul@3 | 28 | def __init__(self, pagename, request): |
paul@3 | 29 | self.pagename = pagename |
paul@3 | 30 | self.request = request |
paul@3 | 31 | |
paul@3 | 32 | def processForm(self): |
paul@3 | 33 | |
paul@3 | 34 | """ |
paul@3 | 35 | Interpret the request details and modify them according to the structure |
paul@3 | 36 | of the interpreted information. |
paul@3 | 37 | """ |
paul@3 | 38 | |
paul@13 | 39 | _ = self.request.getText |
paul@13 | 40 | |
paul@3 | 41 | # Get the form fields and obtain the hierarchical field structure. |
paul@3 | 42 | |
paul@3 | 43 | form = get_form(self.request) |
paul@3 | 44 | fields = getFields(form, remove=True) |
paul@3 | 45 | |
paul@8 | 46 | # Modify and validate the form. |
paul@3 | 47 | |
paul@3 | 48 | self.modifyFields(fields) |
paul@8 | 49 | |
paul@13 | 50 | # Get the form definition. |
paul@13 | 51 | |
paul@23 | 52 | self.attributes, structure = self.getFormStructure(fields) |
paul@23 | 53 | |
paul@23 | 54 | # Check the permissions on the form. |
paul@23 | 55 | |
paul@23 | 56 | if not self.checkPermissions("write"): |
paul@23 | 57 | self.request.theme.add_msg(_("You do not appear to have access to this form."), "error") |
paul@23 | 58 | do_show(self.pagename, self.request) |
paul@23 | 59 | return |
paul@13 | 60 | |
paul@13 | 61 | # Without any form definition, the page is probably the wrong one. |
paul@13 | 62 | |
paul@13 | 63 | if not structure: |
paul@13 | 64 | self.request.theme.add_msg(_("This page does not provide a form."), "error") |
paul@13 | 65 | do_show(self.pagename, self.request) |
paul@13 | 66 | return |
paul@13 | 67 | |
paul@13 | 68 | # With a form definition, attempt to validate the fields. |
paul@13 | 69 | |
paul@13 | 70 | if self.validateFields(fields, structure): |
paul@8 | 71 | self.finished(fields, form) |
paul@8 | 72 | else: |
paul@8 | 73 | self.unfinished(fields, form) |
paul@8 | 74 | |
paul@8 | 75 | def finished(self, fields, form): |
paul@8 | 76 | |
paul@8 | 77 | "Handle the finished 'fields' and 'form'." |
paul@8 | 78 | |
paul@23 | 79 | self.storeFields(fields) |
paul@8 | 80 | self.unfinished(fields, form) |
paul@8 | 81 | |
paul@8 | 82 | def unfinished(self, fields, form): |
paul@8 | 83 | |
paul@8 | 84 | "Handle the unfinished 'fields' and 'form'." |
paul@8 | 85 | |
paul@8 | 86 | # Serialise and show the form. |
paul@8 | 87 | |
paul@3 | 88 | self.serialiseFields(fields, form) |
paul@3 | 89 | do_show(self.pagename, self.request) |
paul@3 | 90 | |
paul@17 | 91 | def getFormStructure(self, fields): |
paul@8 | 92 | |
paul@23 | 93 | "Return the attributes and structure of the form being handled." |
paul@8 | 94 | |
paul@22 | 95 | fragment = fields.get("fragment", [None])[0] |
paul@8 | 96 | text = Page(self.request, self.pagename).get_raw_body() |
paul@23 | 97 | attributes, text = getFormForFragment(text, fragment) |
paul@23 | 98 | return attributes, getFormStructure(text, self.request) |
paul@23 | 99 | |
paul@23 | 100 | def checkPermissions(self, action): |
paul@23 | 101 | |
paul@23 | 102 | """ |
paul@23 | 103 | Check the permissions of the user against any restrictions specified in |
paul@23 | 104 | the form's 'attributes'. |
paul@23 | 105 | """ |
paul@23 | 106 | |
paul@23 | 107 | user = self.request.user |
paul@23 | 108 | |
paul@24 | 109 | # Use the access definition if one is given. |
paul@23 | 110 | |
paul@24 | 111 | if self.attributes.has_key("access"): |
paul@24 | 112 | access = self.attributes["access"] |
paul@24 | 113 | acl = security.AccessControlList(self.request.cfg, [access]) |
paul@24 | 114 | policy = lambda request, pagename, username, action: acl.may(request, username, action) |
paul@23 | 115 | |
paul@24 | 116 | # Otherwise, use the page permissions. |
paul@23 | 117 | |
paul@23 | 118 | else: |
paul@24 | 119 | policy = security._check |
paul@24 | 120 | |
paul@24 | 121 | # The "read" action is only satisfied by the "admin" role. |
paul@24 | 122 | |
paul@24 | 123 | return user and ( |
paul@24 | 124 | action != "read" and policy(self.request, self.pagename, user.name, action) or |
paul@24 | 125 | action == "read" and policy(self.request, self.pagename, user.name, "admin") |
paul@24 | 126 | ) |
paul@13 | 127 | |
paul@13 | 128 | def validateFields(self, fields, structure): |
paul@13 | 129 | |
paul@13 | 130 | """ |
paul@13 | 131 | Validate the given 'fields' using the given form 'structure', |
paul@13 | 132 | introducing error fields where the individual fields do not conform to |
paul@13 | 133 | their descriptions. |
paul@13 | 134 | """ |
paul@8 | 135 | |
paul@8 | 136 | return self.validateFieldsUsingStructure(fields, structure) |
paul@8 | 137 | |
paul@8 | 138 | def validateFieldsUsingStructure(self, fields, structure): |
paul@8 | 139 | |
paul@8 | 140 | "Validate the given 'fields' using the given 'structure'." |
paul@8 | 141 | |
paul@8 | 142 | _ = self.request.getText |
paul@8 | 143 | valid = True |
paul@8 | 144 | |
paul@8 | 145 | for key, definition in structure.items(): |
paul@8 | 146 | value = fields.get(key) |
paul@8 | 147 | |
paul@8 | 148 | # Enter form sections and validate them. |
paul@8 | 149 | |
paul@8 | 150 | if isinstance(definition, dict): |
paul@8 | 151 | if value: |
paul@8 | 152 | for element in getSectionElements(value): |
paul@11 | 153 | valid = self.validateFieldsUsingStructure(element, structure[key]) and valid |
paul@8 | 154 | |
paul@8 | 155 | # Validate individual fields. |
paul@8 | 156 | |
paul@8 | 157 | elif structure.has_key(key): |
paul@8 | 158 | path, dictpage, label, section, field_args, allowed_values = definition |
paul@8 | 159 | errors = [] |
paul@8 | 160 | |
paul@8 | 161 | # Test for obligatory values. |
paul@8 | 162 | |
paul@10 | 163 | if not value or not value[0]: |
paul@8 | 164 | if field_args.get("required"): |
paul@11 | 165 | |
paul@11 | 166 | # Detect new parts of the structure and avoid producing |
paul@11 | 167 | # premature error messages. |
paul@11 | 168 | |
paul@11 | 169 | if not fields.has_key("_new"): |
paul@11 | 170 | errors.append(_("This field must be filled out.")) |
paul@11 | 171 | else: |
paul@11 | 172 | valid = False |
paul@8 | 173 | else: |
paul@8 | 174 | # Test for unacceptable values. |
paul@8 | 175 | |
paul@8 | 176 | if allowed_values and set(value).difference(allowed_values): |
paul@8 | 177 | errors.append(_("At least one of the choices is not acceptable.")) |
paul@8 | 178 | |
paul@8 | 179 | # Test the number of values. |
paul@8 | 180 | |
paul@8 | 181 | if field_args.get("type") == "select": |
paul@8 | 182 | if field_args.has_key("maxselected"): |
paul@8 | 183 | if len(value) > int(field_args["maxselected"]): |
paul@8 | 184 | errors.append(_("Incorrect number of choices given: need %s.") % field_args["maxselected"]) |
paul@8 | 185 | |
paul@8 | 186 | if errors: |
paul@8 | 187 | fields["%s-error" % key] = errors |
paul@8 | 188 | valid = False |
paul@8 | 189 | |
paul@8 | 190 | return valid |
paul@4 | 191 | |
paul@3 | 192 | def serialiseFields(self, fields, form, path=None): |
paul@3 | 193 | |
paul@3 | 194 | """ |
paul@3 | 195 | Serialise the given 'fields' to the given 'form', using the given 'path' |
paul@3 | 196 | to name the entries. |
paul@3 | 197 | """ |
paul@3 | 198 | |
paul@3 | 199 | for key, value in fields.items(): |
paul@3 | 200 | |
paul@3 | 201 | # Serialise sections. |
paul@3 | 202 | |
paul@3 | 203 | if isinstance(value, dict): |
paul@3 | 204 | for index, element in enumerate(getSectionElements(value)): |
paul@3 | 205 | element_ref = "%s$%s" % (key, index) |
paul@3 | 206 | |
paul@3 | 207 | self.serialiseFields(element, form, |
paul@3 | 208 | path and ("%s/%s" % (path, element_ref)) or element_ref |
paul@3 | 209 | ) |
paul@3 | 210 | |
paul@3 | 211 | # Serialise fields. |
paul@3 | 212 | |
paul@3 | 213 | else: |
paul@3 | 214 | form[path and ("%s/%s" % (path, key)) or key] = value |
paul@3 | 215 | |
paul@3 | 216 | def modifyFields(self, fields): |
paul@3 | 217 | |
paul@3 | 218 | "Modify the given 'fields', removing and adding items." |
paul@3 | 219 | |
paul@3 | 220 | # First, remove fields. |
paul@3 | 221 | |
paul@3 | 222 | for key in fields.keys(): |
paul@3 | 223 | if key.startswith("_remove="): |
paul@3 | 224 | self.removeField(key[8:], fields) |
paul@3 | 225 | |
paul@3 | 226 | # Then, add fields. |
paul@3 | 227 | |
paul@3 | 228 | for key in fields.keys(): |
paul@3 | 229 | if key.startswith("_add="): |
paul@3 | 230 | self.addField(key[5:], fields) |
paul@3 | 231 | |
paul@3 | 232 | def removeField(self, path, fields): |
paul@3 | 233 | |
paul@3 | 234 | """ |
paul@3 | 235 | Remove the section element indicated by the given 'path' from the |
paul@3 | 236 | 'fields'. |
paul@3 | 237 | """ |
paul@3 | 238 | |
paul@3 | 239 | section, (name, index) = getSectionForPath(path, fields) |
paul@17 | 240 | try: |
paul@17 | 241 | del section[name][index] |
paul@17 | 242 | except KeyError: |
paul@17 | 243 | pass |
paul@3 | 244 | |
paul@3 | 245 | def addField(self, path, fields): |
paul@3 | 246 | |
paul@3 | 247 | """ |
paul@3 | 248 | Add a section element indicated by the given 'path' to the 'fields'. |
paul@3 | 249 | """ |
paul@3 | 250 | |
paul@3 | 251 | section, (name, index) = getSectionForPath(path, fields) |
paul@3 | 252 | placeholder = {"_new" : ""} |
paul@3 | 253 | |
paul@3 | 254 | if section.has_key(name): |
paul@3 | 255 | indexes = section[name].keys() |
paul@3 | 256 | max_index = max(map(int, indexes)) |
paul@3 | 257 | section[name][max_index + 1] = placeholder |
paul@3 | 258 | else: |
paul@3 | 259 | max_index = -1 |
paul@3 | 260 | section[name] = {0 : placeholder} |
paul@3 | 261 | |
paul@23 | 262 | # Storage of form submissions. |
paul@23 | 263 | |
paul@23 | 264 | def storeFields(self, fields): |
paul@23 | 265 | |
paul@23 | 266 | """ |
paul@23 | 267 | Store the given 'fields' as a Python object representation, subject to |
paul@23 | 268 | the given 'attributes'. |
paul@23 | 269 | """ |
paul@23 | 270 | |
paul@23 | 271 | store = FormStore(self) |
paul@23 | 272 | store.append(repr(fields)) |
paul@23 | 273 | |
paul@23 | 274 | def loadFields(self, number): |
paul@23 | 275 | |
paul@23 | 276 | "Load the fields associated with the given submission 'number'." |
paul@23 | 277 | |
paul@23 | 278 | try: |
paul@23 | 279 | module = parse(store[number]) |
paul@23 | 280 | if checkStoredFormData(module): |
paul@23 | 281 | return eval(module) |
paul@23 | 282 | |
paul@23 | 283 | # NOTE: Should indicate any errors in retrieving form data. |
paul@23 | 284 | |
paul@23 | 285 | except: |
paul@23 | 286 | pass |
paul@23 | 287 | |
paul@23 | 288 | return {} |
paul@23 | 289 | |
paul@23 | 290 | def checkStoredFormData(node): |
paul@23 | 291 | |
paul@23 | 292 | """ |
paul@23 | 293 | Check the syntax 'node' and its descendants for suitability as parts of |
paul@23 | 294 | a field definition. |
paul@23 | 295 | """ |
paul@23 | 296 | |
paul@23 | 297 | for child in node.getChildNodes(): |
paul@23 | 298 | if isinstance(child, Const): |
paul@23 | 299 | pass |
paul@23 | 300 | elif not isinstance(child, (Dict, Discard, List, Module, Stmt)) or not checkStoredFormData(child): |
paul@23 | 301 | return False |
paul@23 | 302 | |
paul@23 | 303 | return True |
paul@23 | 304 | |
paul@23 | 305 | class FormStore(ItemStore): |
paul@23 | 306 | |
paul@23 | 307 | "A form-specific storage mechanism." |
paul@23 | 308 | |
paul@23 | 309 | def __init__(self, handler): |
paul@23 | 310 | |
paul@23 | 311 | "Initialise the store with the form 'handler'." |
paul@23 | 312 | |
paul@23 | 313 | self.handler = handler |
paul@23 | 314 | page = Page(handler.request, handler.pagename) |
paul@23 | 315 | ItemStore.__init__(self, page, "forms", "form-locks") |
paul@23 | 316 | |
paul@23 | 317 | def can_write(self): |
paul@23 | 318 | |
paul@23 | 319 | """ |
paul@23 | 320 | Permit writing of form data using the form attributes or page |
paul@23 | 321 | permissions. |
paul@23 | 322 | """ |
paul@23 | 323 | |
paul@23 | 324 | return self.handler.checkPermissions("write") |
paul@23 | 325 | |
paul@24 | 326 | def can_read(self): |
paul@24 | 327 | |
paul@24 | 328 | """ |
paul@24 | 329 | Permit reading of form data using the form attributes or page |
paul@24 | 330 | permissions. |
paul@24 | 331 | """ |
paul@24 | 332 | |
paul@24 | 333 | return self.handler.checkPermissions("read") |
paul@24 | 334 | |
paul@5 | 335 | # Form and field information. |
paul@5 | 336 | |
paul@8 | 337 | def getFormStructure(text, request, path=None, structure=None): |
paul@8 | 338 | |
paul@8 | 339 | """ |
paul@8 | 340 | For the given form 'text' and using the 'request', return details of the |
paul@8 | 341 | form for the section at the given 'path' (or the entire form if 'path' is |
paul@8 | 342 | omitted), populating the given 'structure' (or populating a new structure if |
paul@8 | 343 | 'structure' is omitted). |
paul@8 | 344 | """ |
paul@8 | 345 | |
paul@8 | 346 | if structure is None: |
paul@8 | 347 | structure = {} |
paul@8 | 348 | |
paul@8 | 349 | for format, attributes, body in getFragments(text, True): |
paul@8 | 350 | |
paul@8 | 351 | # Get field details at the current level. |
paul@8 | 352 | |
paul@8 | 353 | if format is None: |
paul@8 | 354 | structure.update(getFormFields(body, path, request)) |
paul@8 | 355 | |
paul@8 | 356 | # Where a section is found, get details from within the section. |
paul@8 | 357 | |
paul@11 | 358 | elif format == "form": |
paul@11 | 359 | if attributes.has_key("section"): |
paul@11 | 360 | section_name = attributes["section"] |
paul@11 | 361 | section = structure[section_name] = {} |
paul@11 | 362 | getFormStructure(body, request, path and ("%s/%s" % (path, section_name)) or section_name, section) |
paul@11 | 363 | elif attributes.has_key("message"): |
paul@11 | 364 | getFormStructure(body, request, path, structure) |
paul@12 | 365 | elif attributes.has_key("not-message"): |
paul@12 | 366 | getFormStructure(body, request, path, structure) |
paul@8 | 367 | |
paul@8 | 368 | # Get field details from other kinds of region. |
paul@8 | 369 | |
paul@8 | 370 | elif format != "form": |
paul@8 | 371 | getFormStructure(body, request, path, structure) |
paul@8 | 372 | |
paul@8 | 373 | return structure |
paul@8 | 374 | |
paul@8 | 375 | def getFormForFragment(text, fragment=None): |
paul@8 | 376 | |
paul@8 | 377 | """ |
paul@8 | 378 | Return the form region from the given 'text' for the specified 'fragment'. |
paul@23 | 379 | If no fragment is specified, the first form region is returned. The form |
paul@23 | 380 | region is described using a tuple containing the attributes for the form |
paul@23 | 381 | and the body text of the form. |
paul@8 | 382 | """ |
paul@8 | 383 | |
paul@8 | 384 | for format, attributes, body in getFragments(text): |
paul@23 | 385 | if format == "form" and (not fragment or attributes.get("fragment") == fragment): |
paul@23 | 386 | return attributes, body |
paul@8 | 387 | |
paul@23 | 388 | return {}, None |
paul@8 | 389 | |
paul@5 | 390 | def getFieldArguments(field_definition): |
paul@5 | 391 | |
paul@5 | 392 | "Return the parsed arguments from the given 'field_definition' string." |
paul@5 | 393 | |
paul@5 | 394 | field_args = {} |
paul@5 | 395 | |
paul@5 | 396 | for field_arg in field_definition.split(): |
paul@8 | 397 | if field_arg == "required": |
paul@8 | 398 | field_args[field_arg] = True |
paul@8 | 399 | continue |
paul@5 | 400 | |
paul@5 | 401 | # Record the key-value details. |
paul@5 | 402 | |
paul@5 | 403 | try: |
paul@5 | 404 | argname, argvalue = field_arg.split("=", 1) |
paul@5 | 405 | field_args[argname] = argvalue |
paul@5 | 406 | |
paul@5 | 407 | # Single keywords are interpreted as type descriptions. |
paul@5 | 408 | |
paul@5 | 409 | except ValueError: |
paul@5 | 410 | if not field_args.has_key("type"): |
paul@5 | 411 | field_args["type"] = field_arg |
paul@5 | 412 | |
paul@5 | 413 | return field_args |
paul@5 | 414 | |
paul@0 | 415 | # Common formatting functions. |
paul@0 | 416 | |
paul@22 | 417 | def getFormOutput(text, fields, path=None, fragment=None, repeating=None, index=None): |
paul@0 | 418 | |
paul@0 | 419 | """ |
paul@0 | 420 | Combine regions found in the given 'text' and then return them as a single |
paul@0 | 421 | block. The reason for doing this, as opposed to just passing each region to |
paul@0 | 422 | a suitable parser for formatting, is that form sections may break up |
paul@0 | 423 | regions, and such sections may not define separate subregions but instead |
paul@0 | 424 | act as a means of conditional inclusion of text into an outer region. |
paul@0 | 425 | |
paul@0 | 426 | The given 'fields' are used to populate fields provided in forms and to |
paul@0 | 427 | control whether sections are populated or not. |
paul@18 | 428 | |
paul@18 | 429 | The optional 'path' is used to adjust form fields to refer to the correct |
paul@18 | 430 | part of the form hierarchy. |
paul@18 | 431 | |
paul@22 | 432 | The optional 'fragment' is used to indicate the form to which the fields |
paul@22 | 433 | belong. |
paul@22 | 434 | |
paul@18 | 435 | The optional 'repeating' and 'index' is used to refer to individual values |
paul@18 | 436 | of a designated field. |
paul@0 | 437 | """ |
paul@0 | 438 | |
paul@0 | 439 | output = [] |
paul@0 | 440 | section = fields |
paul@0 | 441 | |
paul@0 | 442 | for region in getRegions(text, True): |
paul@0 | 443 | format, attributes, body, header, close = getFragmentFromRegion(region) |
paul@0 | 444 | |
paul@6 | 445 | # Adjust any FormField macros to use hierarchical names. |
paul@0 | 446 | |
paul@0 | 447 | if format is None: |
paul@22 | 448 | output.append((path or fragment or repeating) and |
paul@22 | 449 | adjustFormFields(body, path, fragment, repeating, index) or body) |
paul@0 | 450 | |
paul@0 | 451 | # Include form sections only if fields exist for those sections. |
paul@0 | 452 | |
paul@0 | 453 | elif format == "form": |
paul@0 | 454 | section_name = attributes.get("section") |
paul@10 | 455 | message_name = attributes.get("message") |
paul@12 | 456 | absent_message_name = attributes.get("not-message") |
paul@10 | 457 | |
paul@10 | 458 | # Sections are groups of fields in their own namespace. |
paul@10 | 459 | |
paul@0 | 460 | if section_name and section.has_key(section_name): |
paul@1 | 461 | |
paul@1 | 462 | # Iterate over the section contents ignoring the given indexes. |
paul@1 | 463 | |
paul@1 | 464 | for index, element in enumerate(getSectionElements(section[section_name])): |
paul@6 | 465 | element_ref = "%s$%s" % (section_name, index) |
paul@1 | 466 | |
paul@6 | 467 | # Get the output for the section. |
paul@6 | 468 | |
paul@6 | 469 | output.append(getFormOutput(body, element, |
paul@22 | 470 | path and ("%s/%s" % (path, element_ref)) or element_ref, fragment)) |
paul@0 | 471 | |
paul@10 | 472 | # Message regions are conditional on a particular field and |
paul@10 | 473 | # reference the current namespace. |
paul@10 | 474 | |
paul@10 | 475 | elif message_name and section.has_key(message_name): |
paul@18 | 476 | |
paul@18 | 477 | if attributes.get("repeating"): |
paul@18 | 478 | for index in range(0, len(section[message_name])): |
paul@22 | 479 | output.append(getFormOutput(body, section, path, fragment, message_name, index)) |
paul@18 | 480 | else: |
paul@22 | 481 | output.append(getFormOutput(body, section, path, fragment)) |
paul@10 | 482 | |
paul@12 | 483 | # Not-message regions are conditional on a particular field being |
paul@12 | 484 | # absent. They reference the current namespace. |
paul@12 | 485 | |
paul@12 | 486 | elif absent_message_name and not section.has_key(absent_message_name): |
paul@22 | 487 | output.append(getFormOutput(body, section, path, fragment)) |
paul@12 | 488 | |
paul@0 | 489 | # Inspect and include other regions. |
paul@0 | 490 | |
paul@0 | 491 | else: |
paul@0 | 492 | output.append(header) |
paul@22 | 493 | output.append(getFormOutput(body, section, path, fragment, repeating, index)) |
paul@0 | 494 | output.append(close) |
paul@0 | 495 | |
paul@0 | 496 | return "".join(output) |
paul@0 | 497 | |
paul@8 | 498 | def getFormFields(body, path, request): |
paul@8 | 499 | |
paul@8 | 500 | "Return a dictionary of fields from the given 'body' at the given 'path'." |
paul@8 | 501 | |
paul@8 | 502 | fields = {} |
paul@8 | 503 | cache = {} |
paul@8 | 504 | type = None |
paul@8 | 505 | |
paul@8 | 506 | for i, match in enumerate(form_field_regexp.split(body)): |
paul@8 | 507 | state = i % 3 |
paul@8 | 508 | |
paul@8 | 509 | if state == 1: |
paul@8 | 510 | type = match |
paul@8 | 511 | elif state == 2 and type == "Field": |
paul@8 | 512 | args = {} |
paul@8 | 513 | |
paul@8 | 514 | # Obtain the macro arguments, adjusted to consider the path. |
paul@8 | 515 | |
paul@22 | 516 | name, path, dictpage, label, section, fragment = \ |
paul@8 | 517 | getMacroArguments(adjustMacroArguments(parseMacroArguments(match), path)) |
paul@8 | 518 | |
paul@8 | 519 | # Obtain field information from the cache, if possible. |
paul@8 | 520 | |
paul@8 | 521 | cache_key = (name, dictpage) |
paul@8 | 522 | |
paul@8 | 523 | if cache.has_key(cache_key): |
paul@8 | 524 | field_args, allowed_values = cache[cache_key] |
paul@8 | 525 | |
paul@8 | 526 | # Otherwise, obtain field information from any WikiDict. |
paul@8 | 527 | |
paul@8 | 528 | else: |
paul@8 | 529 | field_args = {} |
paul@8 | 530 | allowed_values = None |
paul@8 | 531 | |
paul@8 | 532 | if dictpage: |
paul@8 | 533 | wikidict = getWikiDict(dictpage, request) |
paul@8 | 534 | if wikidict: |
paul@8 | 535 | field_definition = wikidict.get(name) |
paul@8 | 536 | if field_definition: |
paul@8 | 537 | field_args = getFieldArguments(field_definition) |
paul@8 | 538 | if field_args.has_key("source"): |
paul@8 | 539 | sourcedict = getWikiDict(field_args["source"], request) |
paul@8 | 540 | if sourcedict: |
paul@8 | 541 | allowed_values = sourcedict.keys() |
paul@8 | 542 | |
paul@8 | 543 | cache[cache_key] = field_args, allowed_values |
paul@8 | 544 | |
paul@8 | 545 | # Store the field information. |
paul@8 | 546 | |
paul@8 | 547 | fields[name] = path, dictpage, label, section, field_args, allowed_values |
paul@8 | 548 | |
paul@8 | 549 | return fields |
paul@8 | 550 | |
paul@22 | 551 | def adjustFormFields(body, path, fragment, repeating=None, index=None): |
paul@1 | 552 | |
paul@1 | 553 | """ |
paul@1 | 554 | Return a version of the 'body' with the names in FormField macros updated to |
paul@22 | 555 | incorporate the given 'path' and 'fragment'. If 'repeating' is specified, |
paul@22 | 556 | any field with such a name will be adjusted to reference the value with the |
paul@22 | 557 | given 'index'. |
paul@1 | 558 | """ |
paul@1 | 559 | |
paul@1 | 560 | result = [] |
paul@4 | 561 | type = None |
paul@1 | 562 | |
paul@7 | 563 | for i, match in enumerate(form_field_regexp.split(body)): |
paul@7 | 564 | state = i % 3 |
paul@4 | 565 | |
paul@4 | 566 | # Reproduce normal text as is. |
paul@4 | 567 | |
paul@7 | 568 | if state == 0: |
paul@1 | 569 | result.append(match) |
paul@4 | 570 | |
paul@4 | 571 | # Capture the macro type. |
paul@4 | 572 | |
paul@7 | 573 | elif state == 1: |
paul@4 | 574 | type = match |
paul@4 | 575 | |
paul@4 | 576 | # Substitute the macro and modified arguments. |
paul@4 | 577 | |
paul@1 | 578 | else: |
paul@4 | 579 | result.append("<<Form%s(%s)>>" % (type, ",".join( |
paul@22 | 580 | adjustMacroArguments(parseMacroArguments(match), path, fragment, repeating, index) |
paul@4 | 581 | ))) |
paul@1 | 582 | |
paul@1 | 583 | return "".join(result) |
paul@1 | 584 | |
paul@22 | 585 | def adjustMacroArguments(args, path, fragment=None, repeating=None, index=None): |
paul@0 | 586 | |
paul@0 | 587 | """ |
paul@1 | 588 | Adjust the given 'args' so that the path incorporates the given |
paul@22 | 589 | 'path' and 'fragment', returning a new list containing the revised path, |
paul@22 | 590 | fragment and remaining arguments. If 'repeating' is specified, any field |
paul@22 | 591 | with such a name will be adjusted to reference the value with the given |
paul@22 | 592 | 'index'. |
paul@1 | 593 | """ |
paul@1 | 594 | |
paul@22 | 595 | if not path and not fragment and not repeating: |
paul@8 | 596 | return args |
paul@8 | 597 | |
paul@1 | 598 | result = [] |
paul@6 | 599 | old_path = None |
paul@18 | 600 | found_name = None |
paul@1 | 601 | |
paul@1 | 602 | for arg in args: |
paul@1 | 603 | if arg.startswith("path="): |
paul@6 | 604 | old_path = arg[5:] |
paul@22 | 605 | elif arg.startswith("fragment=") and fragment: |
paul@22 | 606 | pass |
paul@1 | 607 | else: |
paul@1 | 608 | result.append(arg) |
paul@18 | 609 | if arg.startswith("name="): |
paul@18 | 610 | found_name = arg[5:] |
paul@18 | 611 | elif found_name is None: |
paul@18 | 612 | found_name = arg |
paul@1 | 613 | |
paul@18 | 614 | if path: |
paul@18 | 615 | qualified = old_path and ("%s/%s" % (old_path, path)) or path |
paul@18 | 616 | result.append("path=%s" % qualified) |
paul@18 | 617 | |
paul@22 | 618 | if fragment: |
paul@22 | 619 | result.append("fragment=%s" % fragment) |
paul@22 | 620 | |
paul@18 | 621 | if repeating and repeating == found_name: |
paul@18 | 622 | result.append("index=%s" % index) |
paul@1 | 623 | |
paul@1 | 624 | return result |
paul@1 | 625 | |
paul@1 | 626 | def parseMacroArguments(args): |
paul@1 | 627 | |
paul@1 | 628 | """ |
paul@21 | 629 | Interpret the arguments. To support commas in labels, the label argument |
paul@21 | 630 | should be quoted. For example: |
paul@21 | 631 | |
paul@21 | 632 | "label=No, thanks!" |
paul@1 | 633 | """ |
paul@1 | 634 | |
paul@1 | 635 | try: |
paul@1 | 636 | parsed_args = args and wikiutil.parse_quoted_separated(args, name_value=False) or [] |
paul@1 | 637 | except AttributeError: |
paul@1 | 638 | parsed_args = args.split(",") |
paul@1 | 639 | |
paul@1 | 640 | return [arg for arg in parsed_args if arg] |
paul@1 | 641 | |
paul@8 | 642 | def getMacroArguments(parsed_args): |
paul@8 | 643 | |
paul@8 | 644 | "Return the macro arguments decoded from 'parsed_args'." |
paul@8 | 645 | |
paul@8 | 646 | name = None |
paul@8 | 647 | path = None |
paul@8 | 648 | dictpage = None |
paul@8 | 649 | label = None |
paul@8 | 650 | section = None |
paul@22 | 651 | fragment = None |
paul@8 | 652 | |
paul@8 | 653 | for arg in parsed_args: |
paul@8 | 654 | if arg.startswith("name="): |
paul@8 | 655 | name = arg[5:] |
paul@8 | 656 | |
paul@8 | 657 | elif arg.startswith("path="): |
paul@8 | 658 | path = arg[5:] |
paul@8 | 659 | |
paul@8 | 660 | elif arg.startswith("dict="): |
paul@8 | 661 | dictpage = arg[5:] |
paul@8 | 662 | |
paul@8 | 663 | elif arg.startswith("label="): |
paul@8 | 664 | label = arg[6:] |
paul@8 | 665 | |
paul@8 | 666 | elif arg.startswith("section="): |
paul@8 | 667 | section = arg[8:] |
paul@8 | 668 | |
paul@22 | 669 | elif arg.startswith("fragment="): |
paul@22 | 670 | fragment = arg[9:] |
paul@22 | 671 | |
paul@8 | 672 | elif name is None: |
paul@8 | 673 | name = arg |
paul@8 | 674 | |
paul@8 | 675 | elif dictpage is None: |
paul@8 | 676 | dictpage = arg |
paul@8 | 677 | |
paul@22 | 678 | return name, path, dictpage, label, section, fragment |
paul@8 | 679 | |
paul@1 | 680 | def getFields(d, remove=False): |
paul@1 | 681 | |
paul@1 | 682 | """ |
paul@1 | 683 | Return the form fields hierarchy for the given dictionary 'd'. If the |
paul@1 | 684 | optional 'remove' parameter is set to a true value, remove the entries for |
paul@1 | 685 | the fields from 'd'. |
paul@0 | 686 | """ |
paul@0 | 687 | |
paul@0 | 688 | fields = {} |
paul@0 | 689 | |
paul@0 | 690 | for key, value in d.items(): |
paul@0 | 691 | |
paul@1 | 692 | # Detect modifying fields. |
paul@1 | 693 | |
paul@1 | 694 | if key.find("=") != -1: |
paul@1 | 695 | fields[key] = value |
paul@1 | 696 | if remove: |
paul@1 | 697 | del d[key] |
paul@1 | 698 | continue |
paul@1 | 699 | |
paul@0 | 700 | # Reproduce the original hierarchy of the fields. |
paul@0 | 701 | |
paul@0 | 702 | section = fields |
paul@1 | 703 | parts = getPathDetails(key) |
paul@0 | 704 | |
paul@1 | 705 | for name, index in parts[:-1]: |
paul@1 | 706 | |
paul@1 | 707 | # Add an entry for instances of the section. |
paul@0 | 708 | |
paul@0 | 709 | if not section.has_key(name): |
paul@0 | 710 | section[name] = {} |
paul@0 | 711 | |
paul@1 | 712 | # Add an entry for the specific instance of the section. |
paul@1 | 713 | |
paul@0 | 714 | if not section[name].has_key(index): |
paul@0 | 715 | section[name][index] = {} |
paul@0 | 716 | |
paul@0 | 717 | section = section[name][index] |
paul@0 | 718 | |
paul@1 | 719 | section[parts[-1][0]] = value |
paul@1 | 720 | |
paul@1 | 721 | if remove: |
paul@1 | 722 | del d[key] |
paul@0 | 723 | |
paul@0 | 724 | return fields |
paul@0 | 725 | |
paul@1 | 726 | def getPathDetails(path): |
paul@4 | 727 | |
paul@4 | 728 | """ |
paul@4 | 729 | Return the given 'path' as a list of (name, index) tuples providing details |
paul@4 | 730 | of section instances, with any specific field appearing as the last element |
paul@4 | 731 | and having the form (name, None). |
paul@4 | 732 | """ |
paul@4 | 733 | |
paul@1 | 734 | parts = [] |
paul@1 | 735 | |
paul@1 | 736 | for part in path.split("/"): |
paul@1 | 737 | try: |
paul@1 | 738 | name, index = part.split("$", 1) |
paul@1 | 739 | index = int(index) |
paul@1 | 740 | except ValueError: |
paul@1 | 741 | name, index = part, None |
paul@1 | 742 | |
paul@1 | 743 | parts.append((name, index)) |
paul@1 | 744 | |
paul@1 | 745 | return parts |
paul@1 | 746 | |
paul@1 | 747 | def getSectionForPath(path, fields): |
paul@1 | 748 | |
paul@1 | 749 | """ |
paul@1 | 750 | Obtain the section indicated by the given 'path' from the 'fields', |
paul@1 | 751 | returning a tuple of the form (parent section, (name, index)), where the |
paul@1 | 752 | parent section contains the referenced section, where name is the name of |
paul@1 | 753 | the referenced section, and where index, if not None, is the index of a |
paul@1 | 754 | specific section instance within the named section. |
paul@1 | 755 | """ |
paul@1 | 756 | |
paul@1 | 757 | parts = getPathDetails(path) |
paul@1 | 758 | section = fields |
paul@1 | 759 | |
paul@1 | 760 | for name, index in parts[:-1]: |
paul@1 | 761 | section = fields[name][index] |
paul@1 | 762 | |
paul@1 | 763 | return section, parts[-1] |
paul@1 | 764 | |
paul@1 | 765 | def getSectionElements(section_elements): |
paul@1 | 766 | |
paul@1 | 767 | "Return the given 'section_elements' as an ordered collection." |
paul@1 | 768 | |
paul@1 | 769 | keys = map(int, section_elements.keys()) |
paul@1 | 770 | keys.sort() |
paul@1 | 771 | |
paul@1 | 772 | elements = [] |
paul@1 | 773 | |
paul@1 | 774 | for key in keys: |
paul@1 | 775 | elements.append(section_elements[key]) |
paul@1 | 776 | |
paul@1 | 777 | return elements |
paul@1 | 778 | |
paul@9 | 779 | # Parser-related formatting functions. |
paul@9 | 780 | |
paul@9 | 781 | def formatForm(text, request, fmt, attrs=None, write=None): |
paul@9 | 782 | |
paul@9 | 783 | """ |
paul@9 | 784 | Format the given 'text' using the specified 'request' and formatter 'fmt'. |
paul@9 | 785 | The optional 'attrs' can be used to control the presentation of the form. |
paul@9 | 786 | |
paul@9 | 787 | If the 'write' parameter is specified, use it to write output; otherwise, |
paul@9 | 788 | write output using the request. |
paul@9 | 789 | """ |
paul@9 | 790 | |
paul@9 | 791 | write = write or request.write |
paul@9 | 792 | page = request.page |
paul@9 | 793 | |
paul@9 | 794 | fields = getFields(get_form(request)) |
paul@9 | 795 | |
paul@9 | 796 | queryparams = [] |
paul@9 | 797 | |
paul@16 | 798 | for argname, default in [("fragment", None), ("action", "MoinFormHandler")]: |
paul@9 | 799 | if attrs and attrs.has_key(argname): |
paul@9 | 800 | queryparams.append("%s=%s" % (argname, attrs[argname])) |
paul@14 | 801 | elif default: |
paul@14 | 802 | queryparams.append("%s=%s" % (argname, default)) |
paul@9 | 803 | |
paul@9 | 804 | querystr = "&".join(queryparams) |
paul@17 | 805 | fragment = attrs.get("fragment") |
paul@9 | 806 | |
paul@17 | 807 | write(fmt.rawHTML('<form method="post" action="%s%s"%s>' % ( |
paul@14 | 808 | escattr(page.url(request, querystr)), |
paul@17 | 809 | fragment and ("#%s" % escattr(fragment)) or "", |
paul@17 | 810 | fragment and (' id="%s"' % escattr(fragment)) or "" |
paul@14 | 811 | ))) |
paul@9 | 812 | |
paul@9 | 813 | # Obtain page text for the form, incorporating subregions and applicable |
paul@9 | 814 | # sections. |
paul@9 | 815 | |
paul@22 | 816 | output = getFormOutput(text, fields, fragment=fragment) |
paul@9 | 817 | write(formatText(output, request, fmt, inhibit_p=False)) |
paul@9 | 818 | |
paul@9 | 819 | write(fmt.rawHTML('</form>')) |
paul@9 | 820 | |
paul@0 | 821 | def formatFormForOutputType(text, request, mimetype, attrs=None, write=None): |
paul@0 | 822 | |
paul@0 | 823 | """ |
paul@0 | 824 | Format the given 'text' using the specified 'request' for the given output |
paul@0 | 825 | 'mimetype'. |
paul@0 | 826 | |
paul@0 | 827 | The optional 'attrs' can be used to control the presentation of the form. |
paul@0 | 828 | |
paul@0 | 829 | If the 'write' parameter is specified, use it to write output; otherwise, |
paul@0 | 830 | write output using the request. |
paul@0 | 831 | """ |
paul@0 | 832 | |
paul@0 | 833 | write = write or request.write |
paul@0 | 834 | |
paul@0 | 835 | if mimetype == "text/html": |
paul@0 | 836 | write('<html>') |
paul@0 | 837 | write('<body>') |
paul@0 | 838 | fmt = request.html_formatter |
paul@0 | 839 | fmt.setPage(request.page) |
paul@0 | 840 | formatForm(text, request, fmt, attrs, write) |
paul@0 | 841 | write('</body>') |
paul@0 | 842 | write('</html>') |
paul@0 | 843 | |
paul@0 | 844 | # vim: tabstop=4 expandtab shiftwidth=4 |