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