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