pieform.php 50.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
/**
 * This program is part of Pieforms
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 * @package    pieform
 * @subpackage core
 * @author     Nigel McNie <nigel@catalyst.net.nz>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006 Catalyst IT Ltd http://catalyst.net.nz
 *
 */

27
28
$GLOBALS['_PIEFORM_REGISTRY'] = array();

Nigel McNie's avatar
Nigel McNie committed
29
30
31
32
33
34
35
/** The form was processed successfully */
define('PIEFORM_OK', 0);
/** The form failed processing/validating */
define('PIEFORM_ERR', -1);
/** A cancel button was pressed */
define('PIEFORM_CANCEL', -2);

36
37
38
39
40
41
42
43
44
45
46
/**
 * Builds, validates and processes a form.
 *
 * Given a form definition, and as long as one or two functions are implemented
 * by the caller, this function will handle everything else.
 *
 * USAGE:
 *
 * <pre>
 * $form = array(
 *     'name' => 'myform',
Nigel McNie's avatar
Nigel McNie committed
47
 *     'action' => 'myscript.php',
48
49
50
51
52
53
 *     'method' => 'post',
 *     'elements' => array(
 *         // definition of elements in the form
 *     )
 * );
 *
Nigel McNie's avatar
Nigel McNie committed
54
 * $smarty->assign('myform', pieform($form));
55
 *
Nigel McNie's avatar
Nigel McNie committed
56
 * function myform_validate(Pieform $form, $values) {
57
58
59
60
61
 *     // perform validation agains form elements here
 *     // some types of validation are conveniently available already as
 *     // as part of the form definition hash
 * }
 *
Nigel McNie's avatar
Nigel McNie committed
62
 * function myform_submit(Pieform $form, $values) {
63
64
65
66
67
68
69
70
71
72
73
74
75
 *     // perform action knowing that the values are valid, e.g. DB insert.
 * }
 * </pre>
 *
 * Please see https://eduforge.org/wiki/wiki/mahara/wiki?pagename=FormAPI for
 * more information on creating and using forms.
 *
 */
function pieform($data) {
    return Pieform::process($data);
    //
    // @todo stuff to do for forms:
    // 
Nigel McNie's avatar
Nigel McNie committed
76
    //  - more form element types (inc. types like autocomplete and wyswiyg)
77
78
79
80
81
82
83
84
85
86
87
88
    //  - support processing of data before validation occurs (e.g. trim(), strtoupper())
    //  - Basic validation is possible as there's a callback function for checking,
    //    but some helper functions could be written to make people's job validating
    //    stuff much easier (form_validate_email, form_validate_date etc).
    //  - Collapsible js for fieldsets
    //  - Grippie for textareas
    //  - handle multipage forms?
    //  - handle a tabbed interface type of form?
    //  
}

if (!function_exists('json_encode')) {
Nigel McNie's avatar
Nigel McNie committed
89
    require_once 'JSON/JSON.php';
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    function json_encode($data) {
        $json = new Services_JSON();
        return $json->encode($data);
    }
}

/**
 * Pieform throws PieformExceptions, so you can catch them specifically
 */
class PieformException extends Exception {}

/**
 * Represents an HTML form. Forms created using this class have a lot of the
 * legwork for forms abstracted away.
 *
Nigel McNie's avatar
Nigel McNie committed
105
 * Pieforms makes it really easy to build complex HTML forms, simply by
106
107
108
 * building a hash describing your form, and defining one or two callback
 * functions.
 *
Nigel McNie's avatar
Nigel McNie committed
109
 * For more information on how Pieforms works, please see the documentation
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
 * at https://eduforge.org/wiki/wiki/mahara/wiki?pagename=FormAPI
 */
class Pieform {

    /**
     * Maintains a tab index across all created forms, to make it easy for
     * people to forget about it and have it just work for all of their forms.
     *
     * @var int
     */
    public static $formtabindex = 1;

    /**
     * The form name. This is required.
     *
     * @var string
     */
    private $name = '';

    /**
Nigel McNie's avatar
Nigel McNie committed
130
     * Data for the form
131
132
133
     *
     * @var array
     */
Nigel McNie's avatar
Nigel McNie committed
134
    private $data = array();
135
136
137
138

    /**
     * Whether this form includes a file element. If so, the enctype attribute
     * for the form will be specified as "multipart/mixed" as required. This
Nigel McNie's avatar
Nigel McNie committed
139
     * is auto-detected by the Pieform class.
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
     *
     * @var bool
     */
    private $fileupload = false;

    /**
     * Whether the form has been submitted. Available through the
     * {@link is_submitted} method.
     *
     * @var bool
     */
    private $submitted = false;

    /**
     * Processes the form. Called by the {@link pieform} function. It simply
     * builds the form (processing it if it has been submitted), and returns
     * the HTML to display the form
     *
     * @param array $data The form description hash
     * @return string     The HTML representing the form
     */
    public static function process($data) {
        $form = new Pieform($data);
        return $form->build();
    }

    /**
     * Sets the attributes of the form according to the passed data, performing
     * validation on the way. If the form is submitted, this checks and processes
     * the form.
     *
     * @param array $data The form description hash
     */
    public function __construct($data) {
174
175
        $GLOBALS['_PIEFORM_REGISTRY'][] = $this;

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
        if (!isset($data['name']) || !preg_match('/^[a-z_][a-z0-9_]*$/', $data['name'])) {
            throw new PieformException('Forms must have a name, and that name must be valid (validity test: could you give a PHP function the name?)');
        }
        $this->name = $data['name'];

        // If the form has global configuration, get it now
        if (function_exists('pieform_configure')) {
            $formconfig = pieform_configure();
            $defaultelements = (isset($formconfig['elements'])) ? $formconfig['elements'] : array();
            foreach ($defaultelements as $name => $element) {
                if (!isset($data['elements'][$name])) {
                    $data['elements'][$name] = $element;
                }
            }
        }
        else {
            $formconfig = array();
        }

        // Assign defaults for the form
        $formdefaults = array(
Nigel McNie's avatar
Nigel McNie committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
            // The method used to submit the form, should always be 'get' or 'post'
            'method' => 'get',

            // The form target. The vast majority of the time this should be blank,
            // as the functions that handle the submit should be in the same script
            // as the form definition
            'action' => '',

            // The form elements
            'elements' => array(),

            // The form renderer (see the pieform/renderers directory)
            'renderer' => 'table',

            // Whether to validate the form. Non validated forms have none of the
            // validate, success or error callbacks called on them
            'validate' => true,

            // Whether to process the submission of this form. The form will still
            // be validated. Handy if the code handling the submission is elsewhere
            'submit' => true,

            // The PHP callback called to validate the form. Optional
            'validatecallback' => '',

            // The PHP callback called to process the submission of the form.
            // Required, unless a success function is provided for each submit
            // button in the form
            'successcallback' => '',

            // The PHP callback called if there is any validation error. Optional
            'errorcallback' => '',

            // Whether this form should submit to a hidden iframe and use DOM
            // manipulation to insert error messages (faster than a normal submit,
            // supported in less browsers. Most modern browsers should be fine)
            'jsform' => false,

            // The javascript function called before submission of a form
            // (regardless of whether the form is a jsform)
            'presubmitcallback' => '',

            // The javascript function called after submission of a form. As non-js
            // forms will trigger a page load on submit, this has no effect for them. 
            'postsubmitcallback' => '',

            // The javascript function called if the form submission was successful
            'jssuccesscallback' => '',

            // The javascript function called if the form submission was unsuccessful
            'jserrorcallback' => '',

            // The javascript function called if the form submission returned an
            // unknown error code
            'globaljserrorcallback' => '',

            // The message to pass back as a reason for the form submission failing
            // if the form is a jsform. This can be used by your application however
            // you choose.
            'jserrormessage' => '',

            // Whether this form can be cancelled, regardless of the presence of
            // 'cancel' buttons or form inputs mischeviously named as to behave
            // like cancel buttons
            'iscancellable' => true,

            // Whether Pieforms should die after calling a submit function. Generally
            // this is a good idea, as it forces the user to reply to the form
            // submission. However, there are occasions where you might want to let
            // it continue, so this behaviour can be turned off
            'dieaftersubmit' => true,

            // Whether to auto-focus either the first field (if the value is true,
            // or the named field (if the value is a string) when the form is
            // displayed. If this has any value other than false and the form has
            // been submitted with an error, the first field with an error will
            // be focussed.
274
            'autofocus'  => false,
Nigel McNie's avatar
Nigel McNie committed
275
276
277
278
279
280
281

            // The directories to search for additional elements, renderers and
            // rules
            'configdirs' => array(),

            // The language to use for any form strings, such as those found in
            // rules.
282
            'language'   => 'en.utf8',
Nigel McNie's avatar
Nigel McNie committed
283
284
285
286
287
288

            // Any overriding language strings for rules
            'rulei18n'   => array(),

            // The tabindex for the form (managed automatically by Pieforms)
            'tabindex'   => false
289
290
291
292
293
        );
        $data = array_merge($formdefaults, $formconfig, $data);
        $this->data = $data;

        // Set the method - only get/post allowed
Nigel McNie's avatar
Nigel McNie committed
294
295
296
        $this->data['method'] = strtolower($data['method']);
        if ($this->data['method'] != 'post') {
            $this->data['method'] = 'get';
297
298
        }

Nigel McNie's avatar
Nigel McNie committed
299
300
301
        // Make sure that the javascript callbacks are valid
        if ($this->data['jsform']) {
            $this->validate_js_callbacks();
302
303
        }

Nigel McNie's avatar
Nigel McNie committed
304
305
        if (!$this->data['validatecallback']) {
            $this->data['validatecallback'] = $this->name . '_validate';
306
307
        }

Nigel McNie's avatar
Nigel McNie committed
308
309
        if (!$this->data['successcallback']) {
            $this->data['successcallback'] = $this->name . '_submit';
310
311
        }

Nigel McNie's avatar
Nigel McNie committed
312
313
314
        $this->data['configdirs'] = array_map(
            create_function('$a', 'return substr($a, -1) == "/" ? substr($a, 0, -1) : $a;'),
            (array) $this->data['configdirs']);
315
316


Nigel McNie's avatar
Nigel McNie committed
317
318
319
320
321
        if (empty($this->data['tabindex'])) {
            $this->data['tabindex'] = self::$formtabindex++;
        }

        if (!is_array($this->data['elements']) || count($this->data['elements']) == 0) {
322
323
            throw new PieformException('Forms must have a list of elements');
        }
324
325

        // Remove elements to ignore
Nigel McNie's avatar
Nigel McNie committed
326
        foreach ($this->data['elements'] as $name => $element) {
327
328
329
            if (isset($element['type']) && $element['type'] == 'fieldset') {
                foreach ($element['elements'] as $subname => $subelement) {
                    if (!empty($subelement['ignore'])) {
Nigel McNie's avatar
Nigel McNie committed
330
                        unset ($this->data['elements'][$name]['elements'][$subname]);
331
332
333
334
335
                    }
                }
            }
            else {
                if (!empty($element['ignore'])) {
Nigel McNie's avatar
Nigel McNie committed
336
                    unset($this->data['elements'][$name]);
337
338
339
340
                }
            }
        }

341
342
        // Set some attributes for all elements
        $autofocusadded = false;
Nigel McNie's avatar
Nigel McNie committed
343
344
        foreach ($this->data['elements'] as $name => &$element) {
            // @todo re-check ordering of this section
Nigel McNie's avatar
Nigel McNie committed
345
346
347
348
            // The name can be in the element itself. This is compatibility for the perl version
            if (isset($element['name'])) {
                $name = $element['name'];
            }
349
            if (count($element) == 0) {
Nigel McNie's avatar
Nigel McNie committed
350
                throw new PieformException('An element in form "' . $this->name . '" has no data (' . $name . ')');
351
352
353
354
355
356
357
358
359
360
361
362
363
            }
            if (!isset($element['type'])) {
                $element['type'] = 'markup';
                if (!isset($element['value'])) {
                    throw new PieformException('The markup element "'
                        . $name . '" has no value');
                }
            }
            if (!isset($element['title'])) {
                $element['title'] = '';
            }
            if ($element['type'] == 'file') {
                $this->fileupload = true;
Nigel McNie's avatar
Nigel McNie committed
364
365
                if ($this->data['method'] == 'get') {
                    $this->data['method'] = 'post';
366
367
368
369
                    self::info("Your form '$this->name' had the method 'get' and also a file element - it has been converted to 'post'");
                }
            }
            if ($element['type'] == 'fieldset') {
Nigel McNie's avatar
Nigel McNie committed
370
                $this->include_plugin('element', 'fieldset');
371
                foreach ($element['elements'] as $subname => &$subelement) {
Nigel McNie's avatar
Nigel McNie committed
372
373
374
375
376
377
378
                    // The name can be in the element itself. This is compatibility for the perl version
                    if (isset($subelement['name'])) {
                        $subname = $subelement['name'];
                    }
                    if (count($subelement) == 0) {
                        throw new PieformException('An element in form "' . $this->name . '" has no data (' . $subname . ')');
                    }
379
380
381
382
383
384
385
386
                    if (!isset($subelement['type'])) {
                        $subelement['type'] = 'markup';
                        if (!isset($subelement['value'])) {
                            throw new PieformException('The markup element "'
                                . $name . '" has no value');
                        }
                    }

Nigel McNie's avatar
Nigel McNie committed
387
                    // Configure some basics for real elements
388
                    if ($subelement['type'] != 'markup') {
389
390
                        // This function can be defined by the application using Pieforms,
                        // and applies to all elements of this type
Nigel McNie's avatar
Nigel McNie committed
391
                        $function = 'pieform_element_' . $subelement['type'] . '_configure';
392
393
394
395
396
397
398
                        if (function_exists($function)) {
                            $subelement = $function($subelement);
                        }

                        // This function is defined by the plugin itself, to set fields on
                        // the element that need to be set but should not be set by the
                        // application
Nigel McNie's avatar
Nigel McNie committed
399
                        $function = 'pieform_element_' . $subelement['type'] . '_set_attributes';
400
                        $this->include_plugin('element',  $subelement['type']);
401
402
403
                        if (function_exists($function)) {
                            $subelement = $function($subelement);
                        }
Nigel McNie's avatar
Nigel McNie committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430

                        // Add the autofocus flag to the element if required
                        if (!$autofocusadded && $this->data['autofocus'] === true && empty($element['nofocus'])) {
                            $subelement['autofocus'] = true;
                            $autofocusadded = true;
                        }
                        else if (!empty($this->data['autofocus']) && $this->data['autofocus'] !== true
                            && $subname == $this->data['autofocus']) {
                            $subelement['autofocus'] = true;
                        }

                        // All elements should have some kind of title
                        if (!isset($subelement['title'])) {
                            $subelement['title'] = '';
                        }

                        // Force the form method to post if there is a file to upload.
                        if ($subelement['type'] == 'file') {
                            $this->fileupload = true;
                            if ($this->data['method'] == 'get') {
                                $this->data['method'] = 'post';
                                self::info("Your form '$this->name' had the method 'get' and also a file element - it has been converted to 'post'");
                            }
                        }

                        // All elements inherit the form tabindex
                        $subelement['tabindex'] = $this->data['tabindex'];
431
                    }
Nigel McNie's avatar
Nigel McNie committed
432
433
                    $subelement['name'] = $subname;

434
435
436
                }
            }
            else {
Nigel McNie's avatar
Nigel McNie committed
437
438
439
440
441
442
                // Let each element set and override attributes if necessary
                if ($element['type'] != 'markup') {
                    $function = 'pieform_element_' . $element['type'] . '_configure';
                    if (function_exists($function)) {
                        $element = $function($element);
                    }
443

Nigel McNie's avatar
Nigel McNie committed
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
                    $function = 'pieform_element_' . $element['type'] . '_set_attributes';
                    $this->include_plugin('element',  $element['type']);
                    if (function_exists($function)) {
                        $element = $function($element);
                    }

                    // Add the autofocus flag to the element if required
                    if (!$autofocusadded && $this->data['autofocus'] === true && empty($element['nofocus'])) {
                        $element['autofocus'] = true;
                        $autofocusadded = true;
                    }
                    elseif (!empty($this->data['autofocus']) && $this->data['autofocus'] !== true
                        && $name == $this->data['autofocus']) {
                        $element['autofocus'] = true;
                    }
459

Nigel McNie's avatar
Nigel McNie committed
460
                    $element['tabindex'] = $this->data['tabindex'];
461
                }
Nigel McNie's avatar
Nigel McNie committed
462
                $element['name'] = $name;
463
            }
Nigel McNie's avatar
Nigel McNie committed
464

465
466
467
        }

        // Check if the form was submitted, and if so, validate and process it
Nigel McNie's avatar
Nigel McNie committed
468
469
470
        $global = ($this->data['method'] == 'get') ? $_GET: $_POST;
        if ($this->data['validate'] && isset($global['pieform_' . $this->name] )) {
            if ($this->data['submit']) {
471
472
                $this->submitted = true;
                // Check if the form has been cancelled
Nigel McNie's avatar
Nigel McNie committed
473
                if ($this->data['iscancellable']) {
474
475
                    foreach ($global as $key => $value) {
                        if (substr($key, 0, 7) == 'cancel_') {
Nigel McNie's avatar
Nigel McNie committed
476
                            // Check for and call the cancel function handler, if defined
477
                            $function = $this->name . '_' . $key;
Nigel McNie's avatar
Nigel McNie committed
478
479
                            if (function_exists($function)) {
                                $function($this);
480
                            }
Nigel McNie's avatar
Nigel McNie committed
481
482

                            // Redirect the user to where they should go, if the cancel handler didn't already
483
484
485
486
                            $element = $this->get_element(substr($key, 7));
                            if (!isset($element['goto'])) {
                                throw new PieformException('Cancel element "' . $element['name'] . '" has no page to go to');
                            }
Nigel McNie's avatar
Nigel McNie committed
487
488
489
490
491
                            if ($this->data['jsform']) {
                                $this->json_reply(PIEFORM_CANCEL, $element['goto']);
                            }
                            header('HTTP/1.1 303 See Other');
                            header('Location:' . $element['goto']); exit;
492
493
494
495
496
497
498
499
500
501
                        }
                    }
                }
            }

            // Get the values that were submitted
            $values = $this->get_submitted_values();
            // Perform general validation first
            $this->validate($values);
            // Then user specific validation if a function is available for that
Nigel McNie's avatar
Nigel McNie committed
502
503
504
            $function = $this->data['validatecallback'];
            if (is_callable($function)) {
                call_user_func_array($function, array($this, $values));
505
506
507
            }

            // Submit the form if things went OK
Nigel McNie's avatar
Nigel McNie committed
508
            if ($this->data['submit'] && !$this->has_errors()) {
509
510
                $submitted = false;
                foreach ($this->get_elements() as $element) {
Nigel McNie's avatar
Nigel McNie committed
511
                    if (!empty($element['submitelement']) && isset($global[$element['name']])) {
512
513
                        $function = "{$this->name}_submit_{$element['name']}";
                        if (function_exists($function)) {
Nigel McNie's avatar
Nigel McNie committed
514
                            $function($this, $values);
515
516
517
518
519
                            $submitted = true;
                            break;
                        }
                    }
                }
Nigel McNie's avatar
Nigel McNie committed
520
521
                $function = $this->data['successcallback'];
                if (!$submitted && is_callable($function)) {
522
523
524
525
                    // Call the user defined function for processing a submit
                    // This function should really redirect/exit after it has
                    // finished processing the form.
                    // @todo maybe it should do just that...
Nigel McNie's avatar
Nigel McNie committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
                    call_user_func_array($function, array($this, $values));
                    if ($this->data['dieaftersubmit']) {
                        // This will only work if I can make the login_submit function stuff work in login_validate
                        if ($this->data['jsform']) {
                            $message = 'Your ' . $this->name . '_submit function should use $form->json_reply to send a response';
                        }
                        else {
                            $message = 'Your ' . $this->name . '_submit function should redirect or exit when it is done';
                        }
                        throw new PieformException($message);
                    }
                    else {
                        // Successful submission, and the user doesn't care about replying, so...
                        return;
                    }
541
                }
542
                else if (!$submitted) {
543
544
545
546
547
                    throw new PieformException('No function registered to handle form submission for form "' . $this->name . '"');
                }
            }

            // Auto focus the first element with an error if required
Nigel McNie's avatar
Nigel McNie committed
548
            if ($this->data['autofocus'] !== false) {
549
550
                $this->auto_focus_first_error();
            }
Nigel McNie's avatar
Nigel McNie committed
551
552
553
554
555
556

            // Call the user-defined PHP error function, if it exists
            $function = $this->data['errorcallback'];
            if (is_callable($function)) {
                call_user_func_array($function, array($this));
            }
557
            
Nigel McNie's avatar
Nigel McNie committed
558
559
            // If the form has been submitted by javascript, return json
            if ($this->data['jsform']) {
560
561
562
563
564
                $errors = $this->get_errors();
                $json = array();
                foreach ($errors as $element) {
                    $json[$element['name']] = $element['error'];
                }
Nigel McNie's avatar
Nigel McNie committed
565
566
                $message = $this->get_property('jserrormessage');
                $this->json_reply(PIEFORM_ERR, array('message' => $message, 'errors' => $json));
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
            }
        }
    }

    /**
     * Returns a generic property. This can be used to retrieve any property
     * set in the form data array, so developers can pass in random stuff and
     * get access to it.
     *
     * @param string The key of the property to return
     * @return mixed
     */
    public function get_property($key) {
        return $this->data[$key];
    }

    /**
     * Returns the form name
     *
     * @return string
     */
    public function get_name() {
        return $this->name;
    }

    /**
Nigel McNie's avatar
Nigel McNie committed
593
     * Returns whether the form has been submitted
594
595
596
     *
     * @return bool
     */
Nigel McNie's avatar
Nigel McNie committed
597
598
    public function is_submitted() {
        return $this->submitted;
599
600
    }

601
602
603
604
605
606
    /**
     * Returns the HTML for the <form...> tag
     *
     * @return string
     */
    public function get_form_tag() {
Nigel McNie's avatar
Nigel McNie committed
607
        $result = '<form class="pieform"';
608
        foreach (array('name', 'method', 'action') as $attribute) {
Nigel McNie's avatar
Nigel McNie committed
609
            $result .= ' ' . $attribute . '="' . $this->data[$attribute] . '"';
610
611
612
613
614
615
616
617
618
        }
        $result .= ' id="' . $this->name . '"';
        if ($this->fileupload) {
            $result .= ' enctype="multipart/form-data"';
        }
        $result .= '>';
        return $result;
    }

619
620
621
622
623
624
625
626
    /**
     * Builds and returns the HTML for the form, respecting the chosen renderer.
     *
     * Note that the "action" attribute for the form tag are NOT HTML escaped
     * for you. This allows you to build your own URLs, should you require. On
     * the other hand, this means you must be careful about escaping the URL,
     * especially if it has data from an external source in it.
     *
627
     * @param boolean Whether to include the <form...></form> tags in the output
628
629
     * @return string The form as HTML
     */
630
631
632
633
    public function build($outputformtags=true) {
        $result = '';
        if ($outputformtags) {
            $result = $this->get_form_tag() . "\n";
634
635
        }

Nigel McNie's avatar
Nigel McNie committed
636
        $this->include_plugin('renderer',  $this->data['renderer']);
637
638
        
        // Form header
Nigel McNie's avatar
Nigel McNie committed
639
        $function = 'pieform_renderer_' . $this->data['renderer'] . '_header';
640
641
642
643
644
        if (function_exists($function)) {
            $result .= $function();
        }

        // Render each element
Nigel McNie's avatar
Nigel McNie committed
645
        foreach ($this->data['elements'] as $name => $elem) {
646
            if ($elem['type'] != 'hidden') {
Nigel McNie's avatar
Nigel McNie committed
647
                $result .= pieform_render_element($this, $elem);
648
649
650
651
            }
        }

        // Form footer
Nigel McNie's avatar
Nigel McNie committed
652
        $function = 'pieform_renderer_' . $this->data['renderer'] . '_footer';
653
654
655
656
657
        if (function_exists($function)) {
            $result .= $function();
        }

        // Hidden elements
658
        $this->include_plugin('element', 'hidden');
659
660
        foreach ($this->get_elements() as $element) {
            if ($element['type'] == 'hidden') {
Nigel McNie's avatar
Nigel McNie committed
661
                $result .= pieform_element_hidden($element, $this);
662
663
664
665
666
667
668
            }
        }
        $element = array(
            'type'  => 'hidden',
            'name'  => 'pieform_' . $this->name,
            'value' => ''
        );
Nigel McNie's avatar
Nigel McNie committed
669
        $result .= pieform_element_hidden($element, $this);
670
671
672
        if ($outputformtags) {
            $result .= "</form>\n";
        }
673

Nigel McNie's avatar
Nigel McNie committed
674
675
676
677
678
        if ($this->data['jsform'] || $this->data['presubmitcallback']) {
            $result .= '<script type="text/javascript">';
            $result .= "\n" . $this->whichbutton_js();
        }
        if ($this->data['jsform']) {
679
            $result .= $this->submit_js();
Nigel McNie's avatar
Nigel McNie committed
680
681
682
683
684
685
686
        }
        else if ($this->data['presubmitcallback']) {
            $result .= 'connect(\'' . $this->name . '\', \'onsubmit\', '
                . 'function() { ' . $this->data['presubmitcallback'] . "('{$this->name}', {$this->name}_btn); });";
        }
        if ($this->data['jsform'] || $this->data['presubmitcallback']) {
            $result .=  "\n</script>\n";
687
688
689
690
691
692
693
694
695
696
697
698
699
        }

        return $result;
    }

    /**
     * Given an element, gets the value for it from this form
     *
     * @param  array $element The element to get the value for
     * @return mixed          The element's value. <kbd>null</kbd> if no value
     *                        is available for the element.
     */
    public function get_value($element) {
Nigel McNie's avatar
Nigel McNie committed
700
        $function = 'pieform_element_' . $element['type'] . '_get_value';
701
        if (function_exists($function)) {
Nigel McNie's avatar
Nigel McNie committed
702
            return $function($this, $element);
703
        }
Nigel McNie's avatar
Nigel McNie committed
704
        $global = ($this->data['method'] == 'get') ? $_GET : $_POST;
705
706
707
        // If the element is a submit element and has its value in the request, return it
        // Otherwise, we don't return the value if the form has been submitted, as they
        // aren't normally returned using a standard form.
Nigel McNie's avatar
Nigel McNie committed
708
        if (isset($element['value'])) {
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
            return $element['value'];
        }
        else if (isset($global[$element['name']]) && $element['type'] != 'submit') {
            return $global[$element['name']];
        }
        else if (isset($element['defaultvalue'])) {
            return $element['defaultvalue'];
        }
        return null;
    }

    /**
     * Retrieves a list of elements in the form.
     *
     * This flattens fieldsets, and ignores the actual fieldset elements
     *
     * @return array The elements of the form
     */ 
    public function get_elements() {
        $elements = array();
Nigel McNie's avatar
Nigel McNie committed
729
        foreach ($this->data['elements'] as $name => $element) {
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
            if ($element['type'] == 'fieldset') {
                foreach ($element['elements'] as $subelement) {
                    $elements[] = $subelement;
                }
            }
            else {
                $elements[] = $element;
            }
        }
        return $elements;
    }
    
    /**
     * Returns the element with the given name. Throws a PieformException if the
     * element cannot be found.
     *
     * Fieldset elements are ignored. This might change if a valid case for
     * needing them is found.
     *
     * @param  string $name     The name of the element to find
     * @return array            The element
     * @throws PieformException If the element could not be found
     */
    public function get_element($name) {
        foreach ($this->get_elements() as $element) {
            if ($element['name'] == $name) {
                return $element;
            }
        }
        throw new PieformException('Element "' . $name . '" cannot be found');
    }

    /**
Nigel McNie's avatar
Nigel McNie committed
763
     * Retrieves submitted values from the request for the elements of this form.
764
765
766
767
768
769
770
771
772
773
774
775
     *
     * This takes into account that some elements may not even have been set,
     * for example if they were check boxes that were not checked upon
     * submission.
     *
     * A value is returned for every element (except fieldsets of course). If
     * an element was not set, the value set is <kbd>null</kbd>.
     *
     * @return array The submitted values
     */
    private function get_submitted_values() {
        $result = array();
Nigel McNie's avatar
Nigel McNie committed
776
        $global = ($this->data['method'] == 'get') ? $_GET : $_POST;
777
        foreach ($this->get_elements() as $element) {
Nigel McNie's avatar
Nigel McNie committed
778
            if ($element['type'] != 'markup') {
Nigel McNie's avatar
Nigel McNie committed
779
780
781
782
783
784
785
786
787
                if (
                    (empty($element['submitelement']) && empty($element['cancelelement'])) ||
                    (
                        (!empty($element['submitelement']) || !empty($element['cancelelement']))
                        && isset($global[$element['name']])
                    )
                ) {
                    $result[$element['name']] = $this->get_value($element);
                }
Nigel McNie's avatar
Nigel McNie committed
788
            }
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
        }
        return $result;
    }

    /**
     * Performs simple validation based off the definition array.
     *
     * Rules can be added to <kbd>pieform/rules/</kbd> directory, and then
     * re-used in the 'rules' index of each element in the form definition
     * hash.
     *
     * More complicated validation is possible by defining an optional
     * callback with the name {$form->name}_validate. See the documentation for
     * more information.
     *
     * @param array $values The submitted values from the form
     */
    private function validate($values) {
        foreach ($this->get_elements() as $element) {
            if (isset($element['rules']) && is_array($element['rules'])) {
                foreach ($element['rules'] as $rule => $data) {
                    if (!$this->get_error($element['name'])) {
Nigel McNie's avatar
Nigel McNie committed
811
812
813
                        // See if this element has a function that describes
                        // how this rule should apply to it
                        $function = 'pieform_element_' . $element['name'] . '_rule_' . $rule;
814
                        if (!function_exists($function)) {
Nigel McNie's avatar
Nigel McNie committed
815
816
                            // Try instead the default rule function
                            $function = 'pieform_rule_' . $rule;
817
                            if (!function_exists($function)) {
Nigel McNie's avatar
Nigel McNie committed
818
819
820
821
                                $this->include_plugin('rule', $rule);
                                if (!function_exists($function)) {
                                    throw new PieformException('No such form rule "' . $rule . '"');
                                }
822
823
824
825
826
827
828
829
830
831
832
                            }
                        }
                        if ($error = $function($this, $values[$element['name']], $element, $data)) {
                            $this->set_error($element['name'], $error);
                        }
                    }
                }
            }
        }
    }

Nigel McNie's avatar
Nigel McNie committed
833
834
    private function whichbutton_js() {
        $result = "var {$this->name}_btn = null;\n";
835

Nigel McNie's avatar
Nigel McNie committed
836
        $connecteventadded = false;
837
        foreach ($this->get_elements() as $element) {
Nigel McNie's avatar
Nigel McNie committed
838
839
840
841
842
843
844
845
846
847
848
849
            if (!empty($element['submitelement'])) {
                if (!$connecteventadded) {
                    $result .= "addLoadEvent(function() {\n";
                    $connecteventadded = true;
                }
                if (!empty($element['cancelelement'])) {
                    $cancelstr = 'cancel_';
                }
                else {
                    $cancelstr = '';
                }
                $result .= "    connect($('{$cancelstr}{$this->name}_{$element['name']}'), 'onclick', function() { {$this->name}_btn = '{$cancelstr}{$this->name}_{$element['name']}'; });\n";
850
851
            }
        }
Nigel McNie's avatar
Nigel McNie committed
852
853
854
        if ($connecteventadded) {
            $result .= "});\n";
        }
855

Nigel McNie's avatar
Nigel McNie committed
856
857
        return $result;
    }
858

Nigel McNie's avatar
Nigel McNie committed
859
860
861
862
863
864
    private function submit_js() {
        $strprocessingform = get_string('processingform');

        $result = <<<EOF
connect($('{$this->name}'), 'onsubmit', function(e) {
    if (typeof(tinyMCE) != 'undefined') { tinyMCE.triggerSave(); }
865
866

EOF;
Nigel McNie's avatar
Nigel McNie committed
867
868
        if (!empty($this->data['presubmitcallback'])) {
            $result .= "    {$this->data['presubmitcallback']}('{$this->name}', {$this->name}_btn);\n";
869
870
        }
        $result .= <<<EOF
Nigel McNie's avatar
Nigel McNie committed
871
872
873
874
875
876
877
878
879
880
881
882

    var iframe = $('{$this->name}_iframe');
    $('{$this->name}').target = '{$this->name}_iframe';
    if (!iframe) {
        iframe = createDOM('iframe', {
            'name': '{$this->name}_iframe',
            'id'  : '{$this->name}_iframe'
        });
        hideElement(iframe);
        insertSiblingNodesAfter($('{$this->name}'), iframe);

        window.pieformHandler_{$this->name} = function(data) {
883
884

EOF;
Nigel McNie's avatar
Nigel McNie committed
885
886
        if (isset($this->data['processingstopcallback'])) {
            $result .= "            {$this->data['processingstopcallback']}('{$this->name}', {$this->name}_btn);\n";
887
888
        }

Nigel McNie's avatar
Nigel McNie committed
889
890
891
892
893
        $result .= <<<EOF
            evalJSONRequest(data);
            if (data.returnCode == 0) {
                {$this->name}_remove_all_errors();
                // The request completed successfully
894

Nigel McNie's avatar
Nigel McNie committed
895
896
897
898
EOF;
        if (!empty($this->data['jssuccesscallback'])) {
            $result .= "                {$this->data['jssuccesscallback']}('{$this->name}', data);\n";
        }
899
900
901

        $result .= <<<EOF
            }
Nigel McNie's avatar
Nigel McNie committed
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
            else {
                if (data.returnCode == -2) {
                    window.location = data.message;
                    return;
                }
                    
                {$this->name}_remove_all_errors();
                if (data.message.errors) {
                    for (error in data.message.errors) {
                        {$this->name}_set_error(data.message.errors[error], error);
                    }
                    // @todo only output when fieldsets are present
                    forEach(getElementsByTagAndClassName('fieldset', 'collapsed', '{$this->name}'), function(fieldset) {
                        if (getFirstElementByTagAndClassName(null, 'error', fieldset)) {
                            removeElementClass(fieldset, 'collapsed');
                        }
                    });
                }

                if (data.returnCode == -1) {
922
923

EOF;
Nigel McNie's avatar
Nigel McNie committed
924
925
        if (!empty($this->data['jserrorcallback'])) {
            $result .= "                    {$this->data['jserrorcallback']}('{$this->name}', data);\n";
926
927
        }
        $result .= <<<EOF
Nigel McNie's avatar
Nigel McNie committed
928
929
                }
                else {
930
931

EOF;
Nigel McNie's avatar
Nigel McNie committed
932
933
        if (!empty($this->data['globaljserrorcallback'])) {
            $result .= "                    {$this->data['globaljserrorcallback']}('{$this->name}', data);\n";
934
        }
Nigel McNie's avatar
Nigel McNie committed
935
936
937
        else {
            $result .= "                    alert('Developer: got error code ' + data.returnCode
                    + ', either fix your form to not use this code or define a global js error handler');\n";
938
939
        }
        $result .= <<<EOF
Nigel McNie's avatar
Nigel McNie committed
940
941
                }
            }
942
943

EOF;
Nigel McNie's avatar
Nigel McNie committed
944
945
        if (!empty($this->data['postsubmitcallback'])) {
            $result .= "            {$this->data['postsubmitcallback']}('{$this->name}', {$this->name}_btn);\n";
946
        }
Nigel McNie's avatar
Nigel McNie committed
947

948
        $result .= <<<EOF
Nigel McNie's avatar
Nigel McNie committed
949
950
951
            {$this->name}_btn = null;
        }
    }
952
953

EOF;
Nigel McNie's avatar
Nigel McNie committed
954
955
956
957
        $result .= "});\n\n";
        $function = 'pieform_renderer_' . $this->data['renderer'] . '_get_js';
        if (!function_exists($function)) {
            throw new PieformException('No renderer message function "' . $function . '"');
958
959
        }

Nigel McNie's avatar
Nigel McNie committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
        return $result . $function($this->name);
    }
    
    public function json_reply($returncode, $message=null) {
        $data = array(
            'returnCode' => intval($returncode),
            'message'    => $message
        );
        $result = json_encode($data);

        echo <<<EOF
<html><head><script type="text/javascript">function sendResult() { parent.pieformHandler_{$this->name}($result); }</script></head><body onload="sendResult(); "></body></html>
EOF;
        exit;
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
    }

    /**
     * Returns whether a field has an error marked on it.
     *
     * This method should be used in the custom validation functions, to see if
     * there is an error on an element before checking for any more validation.
     *
     * Example:
     *
     * <code>
     * if (!$form->get_error('name') && /* condition {@*}) {
     *     $form->set_error('name', 'error message');
     * }
     * </code>
     *
     * @param  string $name  The name of the element to check
     * @return bool          Whether the element has an error
     * @throws PieformException If the element could not be found
     */
    public function get_error($name) {
        $element = $this->get_element($name);
        return isset($element['error']);
    }

    /**
     * Marks a field has having an error.
     *
     * This method should be used to set an error on an element in a custom
     * validation function, if one has occured.
     *
     * Note that for the Mahara project, your error messages must be passed
     * through {@link get_string} to internationalise them.
     *
     * @param string $name    The name of the element to set an error on
     * @param string $message The error message
     * @throws PieformException  If the element could not be found
     */
    public function set_error($name, $message) {
Nigel McNie's avatar
Nigel McNie committed
1013
        foreach ($this->data['elements'] as &$element) {
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
            if ($element['type'] == 'fieldset') {
                foreach ($element['elements'] as &$subelement) {
                    if ($subelement['name'] == $name) {
                        $subelement['error'] = $message;
                        return;
                    }
                }
            }
            else {
                if ($element['name'] == $name) {
                    $element['error'] = $message;
                    return;
                }
            }
        }
        throw new PieformException('Element "' . $name . '" could not be found');
    }

    /**
     * Makes an ID for an element.
     *
     * Element IDs are used for <label>s, so use this method to ensure that
     * an element gets an ID.
     *
     * The element's existing 'id' and 'name' attributes are checked first. If
     * they are not specified, a random ID is synthesised
     *
     * @param array $element The element to make an ID for
     * @return string        The ID for the element
     */
    public static function make_id($element) {
        if (isset($element['id'])) {
            return self::hsc($element['id']);
        }
        if (isset($element['name'])) {
            return self::hsc($element['name']);
        }
        return substr(md5(mt_rand()), 0, 4);
    }

    /**
     * Makes a class for an element.
     *
     * Elements can have several classes set on them depending on their state.
     * The classes are useful for (among other things), styling elements
     * differently if they are in these states.
     *
     * Currently, the states an element can be in are 'required' and 'error'.
     *
     * @param array $element The element to make a class for
     * @return string        The class for an element
     */
    public static function make_class($element) {
        $classes = array();
        if (isset($element['class'])) {
            $classes[] = $element['class'];
        }
        if (!empty($element['rules']['required'])) {
            $classes[] = 'required';
        }
        if (!empty($element['error'])) {
            $classes[] = 'error';
        }
        // Please make sure that 'autofocus' is the last class added in this
        // method. Otherwise, improve the logic for removing 'autofocus' from
        // the elemnt class string in pieform_render_element
        if (!empty($element['autofocus'])) {
            $classes[] = 'autofocus';
        }
        return implode(' ', $classes);
    }

    /**
     * Given an element, returns a string representing the basic attribute
     * list for the element.
     *
     * This EXCLUDES the "value" attribute, as various form elements set
     * their value in different ways.
     *
     * This allows each element to have most of the standard HTML attributes
     * that you can normally set on a form element.
     *
     * The attributes generated by this method will include (if set for the
     * element itself), are <kbd>accesskey, class, dir, id, lang, maxlength,
     * name, size, style</kbd> and <kbd>tabindex</kbd>.
     *
     * The <kbd>class</kbd> and <kbd>id</kbd> attributes are typically built
     * beforehand with {@link make_class} and {@link make_id} respectively.
     * The <kbd>maxlength</kbd> attribute is only set if the element has a
     * "maxlength" rule on it.
     *
     * @param array $element The element to make attributes for
     * @param array $exclude Any attributes to explicitly exclude from adding
     * @return string        The attributes for the element
     */
1109
    public function element_attributes($element, $exclude=array()) {
1110
1111
1112
1113
1114
        static $attributes = array('accesskey', 'class', 'dir', 'id', 'lang', 'name', 'onclick', 'size', 'style', 'tabindex');
        $elementattributes = array_diff($attributes, $exclude);
        $result = '';
        foreach ($elementattributes as $attribute) {
            if (isset($element[$attribute]) && $element[$attribute] !== '') {
1115
1116
1117
                if ($attribute == 'id') {
                    $element[$attribute] = $this->name . '_' . $element[$attribute];
                }
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
                $result .= ' ' . $attribute . '="' . self::hsc($element[$attribute]) . '"';
            }
        }

        if (!in_array('maxlength', $exclude) && isset($element['rules']['maxlength'])) {
            $result .= ' maxlength="' . intval($element['rules']['maxlength']) . '"';
        }

        foreach (array_diff(array('disabled', 'readonly'), $exclude) as $attribute) {
            if (!empty($element[$attribute])) {
                $result .= " $attribute=\"$attribute\"";
            }
        }
        
        return $result;
    }

    /**
     * Checks if there are errors on any of the form elements.
     *
     * @return bool Whether there are errors with the form
     */
    public function has_errors() {
        foreach ($this->get_elements() as $element) {
            if (isset($element['error'])) {
                return true;
            }
        }
        return false;
    }

1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
    /**
     * Includes a plugin file, checking any configured plugin directories.
     *
     * @param string $type The type of plugin to include: 'element', 'renderer' or 'rule'
     * @param string $name The name of the plugin to include
     * @throws PieformException If the given type or plugin could not be found
     */
    public function include_plugin($type, $name) {
        if (!in_array($type, array('element', 'renderer', 'rule'))) {
            throw new PieformException("The type \"$type\" is not allowed for an include plugin");
        }

        // Check the configured include paths if they are specified
Nigel McNie's avatar
Nigel McNie committed
1162
        foreach ($this->data['configdirs'] as $directory) {
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
            $file = "$directory/{$type}s/$name.php";
            if (is_readable($file)) {
                include_once($file);
                return;
            }
        }

        // Check the default include path
        $file = dirname(__FILE__) . "/pieform/{$type}s/{$name}.php";
        if (is_readable($file)) {
            include_once($file);
            return;
        }

        throw new PieformException("Could not find $type \"$name\"");
    }

1180
1181
1182
1183
1184
    /**
     * Return an internationalised string based on the passed input key
     *
     * Returns english by default.
     *
Nigel McNie's avatar
Nigel McNie committed
1185
1186
1187
1188
1189
1190
1191
     * @param string $plugin     The type of plugin (element, renderer, rule)
     * @param string $pluginname The name of the plugin to get the language
     *                           strings for
     * @param string $key        The language key to look up
     * @param array  $element    The element to get the string for. Elements
     *                           can specify there own i18n strings for rules
     * @return string            The internationalised string
1192
     */
Nigel McNie's avatar
Nigel McNie committed
1193
1194
1195
    public function i18n($plugin, $pluginname, $key, $element) {
        if (!in_array($plugin, array('element', 'renderer', 'rule'))) {
            throw new PieformException("Invalid plugin name '$plugin'");
1196
        }
Nigel McNie's avatar
Nigel McNie committed
1197
1198
1199
1200

        // Check the element itself for the language string
        if ($plugin == 'rule' && isset($element['rulei18n'][$key])) {
            return $element['rulei18n'][$key];
1201
        }
Nigel McNie's avatar
Nigel McNie committed
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215

        // Check to see if a default was configured for the form
        if ($plugin == 'rule' && isset($this->data['rulei18n'][$key])) {
            return $this->data['rulei18n'][$key];
        }

        // Fall back to the default string
        $function = 'pieform_' . $plugin . '_' . $pluginname . '_i18n';
        if (function_exists($function)) {
            $strings = $function();
            return $strings[$this->data['language']][$key];
        }

        // We don't recognise this string
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
        return '[[' . $key . ']]';
    }

    /**
     * HTML-escapes the given value
     *
     * @param string $text The text to escape
     * @return string      The text, HTML escaped
     */
    public static function hsc($text) {
        return htmlspecialchars($text, ENT_COMPAT, 'UTF-8');
    }

    /**
     * Hook for giving information back to the developer
Nigel McNie's avatar
Nigel McNie committed
1231
1232
     *
     * @param string $message The message to give to the developer
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
     */
    public static function info($message) {
        $function = 'pieform_info';
        if (function_exists($function)) {
            $function($message);
        }
        else {
            trigger_error($message, E_USER_NOTICE);
        }
    }

Nigel McNie's avatar
Nigel McNie committed
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
    /**
     * Makes sure that the javascript callbacks for this form are valid javascript
     * function names.
     */
    private function validate_js_callbacks() {
        foreach (array('presubmitcallback', 'postsubmitcallback', 'jssuccesscallback',
            'jserrorcallback', 'globaljserrorcallback') as $callback) {
            if ($this->data[$callback] != '' && !preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/', $this->data[$callback])) {
                throw new PieformException("'{$this->data[$callback]}' is not a valid javascript callback name for callback '$callback'");
            }
1254
1255
1256
1257
1258
1259
1260
1261
1262
        }
    }

    /**
     * Returns elements with errors on them
     *
     * @return array An array of elements with errors on them, the empty array
     *               in the result of no errors.
     */
Nigel McNie's avatar
Nigel McNie committed
1263
    public function get_errors() {
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
        $result = array();
        foreach ($this->get_elements() as $element) {
            if (isset($element['error'])) {
                $result[] = $element;
            }
        }
        return $result;
    }

    /**
     * Sets the 'autofocus' property on the first element encountered that has
     * an error on it
     */
    private function auto_focus_first_error() {
Nigel McNie's avatar
Nigel McNie committed
1278
        foreach ($this->data['elements'] as &$element) {
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
            if ($element['type'] == 'fieldset') {
                foreach ($element['elements'] as &$subelement) {
                    if (isset($subelement['error'])) {
                        $subelement['autofocus'] = true;
                        return;
                    }
                    unset($subelement['autofocus']);
                }
            }
            else {
                if (isset($element['error'])) {
                    $element['autofocus'] = true;
                    return;
                }
                unset($element['autofocus']);
            }
        }
    }
}


/**
 * Renders an element, and returns the result.
 *
 * This function looks in <kbd>pieform/renderers</kbd> for available overall form
 * renderers, and in <kbd>pieform/elements</kbd> for renderers for each form
 * element.
 *
 * If any of the renderers are not available, this function will throw a
 * PieformException.
 *
 * {@internal This is separate so that child element types can nest other
 * elements inside them (like the fieldset element does for example).}}
 *
 * @param Pieform  $form    The form to render the element for
Nigel McNie's avatar
Nigel McNie committed
1314
 * @param array    $element The element to render
Nigel McNie's avatar
Nigel McNie committed
1315
 * @return string           The rendered element
1316
 */
Nigel McNie's avatar
Nigel McNie committed
1317
function pieform_render_element(Pieform $form, $element) {
1318
1319
1320
1321
1322
1323
    // If the element is pure markup, don't pass it to the renderer
    if ($element['type'] == 'markup') {
        return $element['value'] . "\n";
    }

    // Make sure that the function to render the element type is available
Nigel McNie's avatar
Nigel McNie committed
1324
1325
1326
1327
1328
    $function = 'pieform_element_' . $element['type'];

    $rendererfunction = 'pieform_renderer_' . $form->get_property('renderer');
    if (!function_exists($rendererfunction)) {
        throw new PieformException('No such form renderer function: "' . $rendererfunction . '"');
1329
1330
1331
1332
    }

    $element['id']    = Pieform::make_id($element);
    $element['class'] = Pieform::make_class($element);
Nigel McNie's avatar
Nigel McNie committed
1333
    $builtelement = $function($form, $element);
1334
1335
1336
1337
1338
1339
1340
1341

    // Remove the 'autofocus' class, because we only want it on the form input
    // itself, not the wrapping HTML
    $element['class'] = preg_replace('/\s?autofocus/', '', $element['class']);

    return $rendererfunction($form, $builtelement, $element);
}

1342
1343
1344
1345
function pieform_get_headdata() {
    $htmlelements = array();
    foreach ($GLOBALS['_PIEFORM_REGISTRY'] as $form) {
        foreach ($form->get_elements() as $element) {
Nigel McNie's avatar
Nigel McNie committed
1346
            $function = 'pieform_element_' . $element['type'] . '_get_headdata';
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
            if (function_exists($function)) {
                $elems = $function($element);
                $htmlelements = array_merge($htmlelements, $elems);
            }
        }
    }

    return array_unique($htmlelements);
}

1357
?>