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