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