forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickForm.php
1992 lines (1822 loc) · 74.3 KB
/
QuickForm.php
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
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
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4.0 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | [email protected] so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Adam Daniel <[email protected]> |
// | Bertrand Mansion <[email protected]> |
// +----------------------------------------------------------------------+
//
// $Id$
require_once('PEAR.php');
require_once('HTML/Common.php');
$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] =
array(
'group' =>array('HTML/QuickForm/group.php','HTML_QuickForm_group'),
'hidden' =>array('HTML/QuickForm/hidden.php','HTML_QuickForm_hidden'),
'reset' =>array('HTML/QuickForm/reset.php','HTML_QuickForm_reset'),
'checkbox' =>array('HTML/QuickForm/checkbox.php','HTML_QuickForm_checkbox'),
'file' =>array('HTML/QuickForm/file.php','HTML_QuickForm_file'),
'image' =>array('HTML/QuickForm/image.php','HTML_QuickForm_image'),
'password' =>array('HTML/QuickForm/password.php','HTML_QuickForm_password'),
'radio' =>array('HTML/QuickForm/radio.php','HTML_QuickForm_radio'),
'button' =>array('HTML/QuickForm/button.php','HTML_QuickForm_button'),
'submit' =>array('HTML/QuickForm/submit.php','HTML_QuickForm_submit'),
'select' =>array('HTML/QuickForm/select.php','HTML_QuickForm_select'),
'hiddenselect' =>array('HTML/QuickForm/hiddenselect.php','HTML_QuickForm_hiddenselect'),
'text' =>array('HTML/QuickForm/text.php','HTML_QuickForm_text'),
'textarea' =>array('HTML/QuickForm/textarea.php','HTML_QuickForm_textarea'),
'link' =>array('HTML/QuickForm/link.php','HTML_QuickForm_link'),
'advcheckbox' =>array('HTML/QuickForm/advcheckbox.php','HTML_QuickForm_advcheckbox'),
'date' =>array('HTML/QuickForm/date.php','HTML_QuickForm_date'),
'static' =>array('HTML/QuickForm/static.php','HTML_QuickForm_static'),
'header' =>array('HTML/QuickForm/header.php', 'HTML_QuickForm_header'),
'html' =>array('HTML/QuickForm/html.php', 'HTML_QuickForm_html'),
'hierselect' =>array('HTML/QuickForm/hierselect.php', 'HTML_QuickForm_hierselect'),
'autocomplete' =>array('HTML/QuickForm/autocomplete.php', 'HTML_QuickForm_autocomplete'),
'xbutton' =>array('HTML/QuickForm/xbutton.php','HTML_QuickForm_xbutton')
);
$GLOBALS['_HTML_QuickForm_registered_rules'] = array(
'required' => array('html_quickform_rule_required', 'HTML/QuickForm/Rule/Required.php'),
'maxlength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
'minlength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
'rangelength' => array('html_quickform_rule_range', 'HTML/QuickForm/Rule/Range.php'),
'email' => array('html_quickform_rule_email', 'HTML/QuickForm/Rule/Email.php'),
'regex' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
'lettersonly' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
'alphanumeric' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
'numeric' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
'nopunctuation' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
'nonzero' => array('html_quickform_rule_regex', 'HTML/QuickForm/Rule/Regex.php'),
'callback' => array('html_quickform_rule_callback', 'HTML/QuickForm/Rule/Callback.php'),
'compare' => array('html_quickform_rule_compare', 'HTML/QuickForm/Rule/Compare.php')
);
// {{{ error codes
/*
* Error codes for the QuickForm interface, which will be mapped to textual messages
* in the QuickForm::errorMessage() function. If you are to add a new error code, be
* sure to add the textual messages to the QuickForm::errorMessage() function as well
*/
define('QUICKFORM_OK', 1);
define('QUICKFORM_ERROR', -1);
define('QUICKFORM_INVALID_RULE', -2);
define('QUICKFORM_NONEXIST_ELEMENT', -3);
define('QUICKFORM_INVALID_FILTER', -4);
define('QUICKFORM_UNREGISTERED_ELEMENT', -5);
define('QUICKFORM_INVALID_ELEMENT_NAME', -6);
define('QUICKFORM_INVALID_PROCESS', -7);
define('QUICKFORM_DEPRECATED', -8);
define('QUICKFORM_INVALID_DATASOURCE', -9);
// }}}
/**
* Create, validate and process HTML forms
*
* @author Adam Daniel <[email protected]>
* @author Bertrand Mansion <[email protected]>
* @version 2.0
* @since PHP 4.0.3pl1
*/
class HTML_QuickForm extends HTML_Common {
// {{{ properties
/**
* Array containing the form fields
* @since 1.0
* @var array
* @access private
*/
var $_elements = array();
/**
* Array containing element name to index map
* @since 1.1
* @var array
* @access private
*/
var $_elementIndex = array();
/**
* Array containing indexes of duplicate elements
* @since 2.10
* @var array
* @access private
*/
var $_duplicateIndex = array();
/**
* Array containing required field IDs
* @since 1.0
* @var array
* @access private
*/
var $_required = array();
/**
* Prefix message in javascript alert if error
* @since 1.0
* @var string
* @access public
*/
var $_jsPrefix = 'Invalid information entered.';
/**
* Postfix message in javascript alert if error
* @since 1.0
* @var string
* @access public
*/
var $_jsPostfix = 'Please correct these fields.';
/**
* Datasource object implementing the informal
* datasource protocol
* @since 3.3
* @var object
* @access private
*/
var $_datasource;
/**
* Array of default form values
* @since 2.0
* @var array
* @access private
*/
var $_defaultValues = array();
/**
* Array of constant form values
* @since 2.0
* @var array
* @access private
*/
var $_constantValues = array();
/**
* Array of submitted form values
* @since 1.0
* @var array
* @access private
*/
var $_submitValues = array();
/**
* Array of submitted form files
* @since 1.0
* @var integer
* @access public
*/
var $_submitFiles = array();
/**
* Value for maxfilesize hidden element if form contains file input
* @since 1.0
* @var integer
* @access public
*/
var $_maxFileSize = 1048576; // 1 Mb = 1048576
/**
* Flag to know if all fields are frozen
* @since 1.0
* @var boolean
* @access private
*/
var $_freezeAll = false;
/**
* Array containing the form rules
* @since 1.0
* @var array
* @access private
*/
var $_rules = array();
/**
* Form rules, global variety
* @var array
* @access private
*/
var $_formRules = array();
/**
* Array containing the validation errors
* @since 1.0
* @var array
* @access private
*/
var $_errors = array();
/**
* Note for required fields in the form
* @var string
* @since 1.0
* @access private
*/
var $_requiredNote = '<span style="font-size:80%; color:#ff0000;">*</span><span style="font-size:80%;"> denotes required field</span>';
/**
* Whether the form was submitted
* @var boolean
* @access private
*/
var $_flagSubmitted = false;
// }}}
// {{{ constructor
/**
* Class constructor
* @param string $formName Form's name.
* @param string $method (optional)Form's method defaults to 'POST'
* @param string $action (optional)Form's action
* @param string $target (optional)Form's target defaults to '_self'
* @param mixed $attributes (optional)Extra attributes for <form> tag
* @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
* @access public
*/
function HTML_QuickForm($formName='', $method='post', $action='', $target='', $attributes=null, $trackSubmit = false)
{
HTML_Common::HTML_Common($attributes);
$method = (strtoupper($method) == 'GET') ? 'get' : 'post';
$action = ($action == '') ? $_SERVER['PHP_SELF'] : $action;
$target = empty($target) ? array() : array('target' => $target);
$attributes = array('action'=>$action, 'method'=>$method, 'name'=>$formName, 'id'=>$formName) + $target;
$this->updateAttributes($attributes);
if (!$trackSubmit || isset($_REQUEST['_qf__' . $formName])) {
if (1 == get_magic_quotes_gpc()) {
$this->_submitValues = ('get' == $method? $_GET: $_POST); // we already eliminated magic quotes in moodle setup.php
foreach ($_FILES as $keyFirst => $valFirst) {
foreach ($valFirst as $keySecond => $valSecond) {
if ('name' == $keySecond) {
$this->_submitFiles[$keyFirst][$keySecond] = $valSecond; // we already eliminated magic quotes in moodle setup.php
} else {
$this->_submitFiles[$keyFirst][$keySecond] = $valSecond;
}
}
}
} else {
$this->_submitValues = 'get' == $method? $_GET: $_POST;
$this->_submitFiles = $_FILES;
}
$this->_flagSubmitted = count($this->_submitValues) > 0 || count($this->_submitFiles) > 0;
}
if ($trackSubmit) {
unset($this->_submitValues['_qf__' . $formName]);
$this->addElement('hidden', '_qf__' . $formName, null);
}
if (preg_match('/^([0-9]+)([a-zA-Z]*)$/', ini_get('upload_max_filesize'), $matches)) {
// see http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
switch (strtoupper($matches['2'])) {
case 'G':
$this->_maxFileSize = $matches['1'] * 1073741824;
break;
case 'M':
$this->_maxFileSize = $matches['1'] * 1048576;
break;
case 'K':
$this->_maxFileSize = $matches['1'] * 1024;
break;
default:
$this->_maxFileSize = $matches['1'];
}
}
} // end constructor
// }}}
// {{{ apiVersion()
/**
* Returns the current API version
*
* @since 1.0
* @access public
* @return float
*/
function apiVersion()
{
return 3.2;
} // end func apiVersion
// }}}
// {{{ registerElementType()
/**
* Registers a new element type
*
* @param string $typeName Name of element type
* @param string $include Include path for element type
* @param string $className Element class name
* @since 1.0
* @access public
* @return void
*/
function registerElementType($typeName, $include, $className)
{
$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][strtolower($typeName)] = array($include, $className);
} // end func registerElementType
// }}}
// {{{ registerRule()
/**
* Registers a new validation rule
*
* @param string $ruleName Name of validation rule
* @param string $type Either: 'regex', 'function' or 'rule' for an HTML_QuickForm_Rule object
* @param string $data1 Name of function, regular expression or HTML_QuickForm_Rule classname
* @param string $data2 Object parent of above function or HTML_QuickForm_Rule file path
* @since 1.0
* @access public
* @return void
*/
function registerRule($ruleName, $type, $data1, $data2 = null)
{
include_once('HTML/QuickForm/RuleRegistry.php');
$registry =& HTML_QuickForm_RuleRegistry::singleton();
$registry->registerRule($ruleName, $type, $data1, $data2);
} // end func registerRule
// }}}
// {{{ elementExists()
/**
* Returns true if element is in the form
*
* @param string $element form name of element to check
* @since 1.0
* @access public
* @return boolean
*/
function elementExists($element=null)
{
return isset($this->_elementIndex[$element]);
} // end func elementExists
// }}}
// {{{ setDatasource()
/**
* Sets a datasource object for this form object
*
* Datasource default and constant values will feed the QuickForm object if
* the datasource implements defaultValues() and constantValues() methods.
*
* @param object $datasource datasource object implementing the informal datasource protocol
* @param mixed $defaultsFilter string or array of filter(s) to apply to default values
* @param mixed $constantsFilter string or array of filter(s) to apply to constants values
* @since 3.3
* @access public
* @return void
*/
function setDatasource(&$datasource, $defaultsFilter = null, $constantsFilter = null)
{
if (is_object($datasource)) {
$this->_datasource =& $datasource;
if (is_callable(array($datasource, 'defaultValues'))) {
$this->setDefaults($datasource->defaultValues($this), $defaultsFilter);
}
if (is_callable(array($datasource, 'constantValues'))) {
$this->setConstants($datasource->constantValues($this), $constantsFilter);
}
} else {
return PEAR::raiseError(null, QUICKFORM_INVALID_DATASOURCE, null, E_USER_WARNING, "Datasource is not an object in QuickForm::setDatasource()", 'HTML_QuickForm_Error', true);
}
} // end func setDatasource
// }}}
// {{{ setDefaults()
/**
* Initializes default form values
*
* @param array $defaultValues values used to fill the form
* @param mixed $filter (optional) filter(s) to apply to all default values
* @since 1.0
* @access public
* @return void
*/
function setDefaults($defaultValues = null, $filter = null)
{
if (is_array($defaultValues)) {
if (isset($filter)) {
if (is_array($filter) && (2 != count($filter) || !is_callable($filter))) {
foreach ($filter as $val) {
if (!is_callable($val)) {
return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setDefaults()", 'HTML_QuickForm_Error', true);
} else {
$defaultValues = $this->_recursiveFilter($val, $defaultValues);
}
}
} elseif (!is_callable($filter)) {
return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setDefaults()", 'HTML_QuickForm_Error', true);
} else {
$defaultValues = $this->_recursiveFilter($filter, $defaultValues);
}
}
$this->_defaultValues = HTML_QuickForm::arrayMerge($this->_defaultValues, $defaultValues);
foreach (array_keys($this->_elements) as $key) {
$this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
}
}
} // end func setDefaults
// }}}
// {{{ setConstants()
/**
* Initializes constant form values.
* These values won't get overridden by POST or GET vars
*
* @param array $constantValues values used to fill the form
* @param mixed $filter (optional) filter(s) to apply to all default values
*
* @since 2.0
* @access public
* @return void
*/
function setConstants($constantValues = null, $filter = null)
{
if (is_array($constantValues)) {
if (isset($filter)) {
if (is_array($filter) && (2 != count($filter) || !is_callable($filter))) {
foreach ($filter as $val) {
if (!is_callable($val)) {
return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setConstants()", 'HTML_QuickForm_Error', true);
} else {
$constantValues = $this->_recursiveFilter($val, $constantValues);
}
}
} elseif (!is_callable($filter)) {
return PEAR::raiseError(null, QUICKFORM_INVALID_FILTER, null, E_USER_WARNING, "Callback function does not exist in QuickForm::setConstants()", 'HTML_QuickForm_Error', true);
} else {
$constantValues = $this->_recursiveFilter($filter, $constantValues);
}
}
$this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, $constantValues);
foreach (array_keys($this->_elements) as $key) {
$this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
}
}
} // end func setConstants
// }}}
// {{{ setMaxFileSize()
/**
* Sets the value of MAX_FILE_SIZE hidden element
*
* @param int $bytes Size in bytes
* @since 3.0
* @access public
* @return void
*/
function setMaxFileSize($bytes = 0)
{
if ($bytes > 0) {
$this->_maxFileSize = $bytes;
}
if (!$this->elementExists('MAX_FILE_SIZE')) {
$this->addElement('hidden', 'MAX_FILE_SIZE', $this->_maxFileSize);
} else {
$el =& $this->getElement('MAX_FILE_SIZE');
$el->updateAttributes(array('value' => $this->_maxFileSize));
}
} // end func setMaxFileSize
// }}}
// {{{ getMaxFileSize()
/**
* Returns the value of MAX_FILE_SIZE hidden element
*
* @since 3.0
* @access public
* @return int max file size in bytes
*/
function getMaxFileSize()
{
return $this->_maxFileSize;
} // end func getMaxFileSize
// }}}
// {{{ &createElement()
/**
* Creates a new form element of the given type.
*
* This method accepts variable number of parameters, their
* meaning and count depending on $elementType
*
* @param string $elementType type of element to add (text, textarea, file...)
* @since 1.0
* @access public
* @return object extended class of HTML_element
* @throws HTML_QuickForm_Error
*/
function &createElement($elementType)
{
$args = func_get_args();
$element =& HTML_QuickForm::_loadElement('createElement', $elementType, array_slice($args, 1));
return $element;
} // end func createElement
// }}}
// {{{ _loadElement()
/**
* Returns a form element of the given type
*
* @param string $event event to send to newly created element ('createElement' or 'addElement')
* @param string $type element type
* @param array $args arguments for event
* @since 2.0
* @access private
* @return object a new element
* @throws HTML_QuickForm_Error
*/
function &_loadElement($event, $type, $args)
{
$type = strtolower($type);
if (!HTML_QuickForm::isTypeRegistered($type)) {
$error = PEAR::raiseError(null, QUICKFORM_UNREGISTERED_ELEMENT, null, E_USER_WARNING, "Element '$type' does not exist in HTML_QuickForm::_loadElement()", 'HTML_QuickForm_Error', true);
return $error;
}
$className = $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type][1];
$includeFile = $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type][0];
include_once($includeFile);
$elementObject = new $className(); //Moodle: PHP 5.3 compatibility
for ($i = 0; $i < 5; $i++) {
if (!isset($args[$i])) {
$args[$i] = null;
}
}
$err = $elementObject->onQuickFormEvent($event, $args, $this);
if ($err !== true) {
return $err;
}
return $elementObject;
} // end func _loadElement
// }}}
// {{{ addElement()
/**
* Adds an element into the form
*
* If $element is a string representing element type, then this
* method accepts variable number of parameters, their meaning
* and count depending on $element
*
* @param mixed $element element object or type of element to add (text, textarea, file...)
* @since 1.0
* @return object reference to element
* @access public
* @throws HTML_QuickForm_Error
*/
function &addElement($element)
{
if (is_object($element) && is_subclass_of($element, 'html_quickform_element')) {
$elementObject = &$element;
$elementObject->onQuickFormEvent('updateValue', null, $this);
} else {
$args = func_get_args();
$elementObject =& $this->_loadElement('addElement', $element, array_slice($args, 1));
if (PEAR::isError($elementObject)) {
return $elementObject;
}
}
$elementName = $elementObject->getName();
// Add the element if it is not an incompatible duplicate
if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
if ($this->_elements[$this->_elementIndex[$elementName]]->getType() ==
$elementObject->getType()) {
$this->_elements[] =& $elementObject;
$elKeys = array_keys($this->_elements);
$this->_duplicateIndex[$elementName][] = end($elKeys);
} else {
$error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::addElement()", 'HTML_QuickForm_Error', true);
return $error;
}
} else {
$this->_elements[] =& $elementObject;
$elKeys = array_keys($this->_elements);
$this->_elementIndex[$elementName] = end($elKeys);
}
if ($this->_freezeAll) {
$elementObject->freeze();
}
return $elementObject;
} // end func addElement
// }}}
// {{{ insertElementBefore()
/**
* Inserts a new element right before the other element
*
* Warning: it is not possible to check whether the $element is already
* added to the form, therefore if you want to move the existing form
* element to a new position, you'll have to use removeElement():
* $form->insertElementBefore($form->removeElement('foo', false), 'bar');
*
* @access public
* @since 3.2.4
* @param object HTML_QuickForm_element Element to insert
* @param string Name of the element before which the new one is inserted
* @return object HTML_QuickForm_element reference to inserted element
* @throws HTML_QuickForm_Error
*/
function &insertElementBefore(&$element, $nameAfter)
{
if (!empty($this->_duplicateIndex[$nameAfter])) {
$error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, 'Several elements named "' . $nameAfter . '" exist in HTML_QuickForm::insertElementBefore().', 'HTML_QuickForm_Error', true);
return $error;
} elseif (!$this->elementExists($nameAfter)) {
$error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$nameAfter' does not exist in HTML_QuickForm::insertElementBefore()", 'HTML_QuickForm_Error', true);
return $error;
}
$elementName = $element->getName();
$targetIdx = $this->_elementIndex[$nameAfter];
$duplicate = false;
// Like in addElement(), check that it's not an incompatible duplicate
if (!empty($elementName) && isset($this->_elementIndex[$elementName])) {
if ($this->_elements[$this->_elementIndex[$elementName]]->getType() != $element->getType()) {
$error = PEAR::raiseError(null, QUICKFORM_INVALID_ELEMENT_NAME, null, E_USER_WARNING, "Element '$elementName' already exists in HTML_QuickForm::insertElementBefore()", 'HTML_QuickForm_Error', true);
return $error;
}
$duplicate = true;
}
// Move all the elements after added back one place, reindex _elementIndex and/or _duplicateIndex
$elKeys = array_keys($this->_elements);
for ($i = end($elKeys); $i >= $targetIdx; $i--) {
if (isset($this->_elements[$i])) {
$currentName = $this->_elements[$i]->getName();
$this->_elements[$i + 1] =& $this->_elements[$i];
if ($this->_elementIndex[$currentName] == $i) {
$this->_elementIndex[$currentName] = $i + 1;
} else {
$dupIdx = array_search($i, $this->_duplicateIndex[$currentName]);
$this->_duplicateIndex[$currentName][$dupIdx] = $i + 1;
}
unset($this->_elements[$i]);
}
}
// Put the element in place finally
$this->_elements[$targetIdx] =& $element;
if (!$duplicate) {
$this->_elementIndex[$elementName] = $targetIdx;
} else {
$this->_duplicateIndex[$elementName][] = $targetIdx;
}
$element->onQuickFormEvent('updateValue', null, $this);
if ($this->_freezeAll) {
$element->freeze();
}
// If not done, the elements will appear in reverse order
ksort($this->_elements);
return $element;
}
// }}}
// {{{ addGroup()
/**
* Adds an element group
* @param array $elements array of elements composing the group
* @param string $name (optional)group name
* @param string $groupLabel (optional)group label
* @param string $separator (optional)string to separate elements
* @param string $appendName (optional)specify whether the group name should be
* used in the form element name ex: group[element]
* @return object reference to added group of elements
* @since 2.8
* @access public
* @throws PEAR_Error
*/
function &addGroup($elements, $name=null, $groupLabel='', $separator=null, $appendName = true)
{
static $anonGroups = 1;
if (0 == strlen($name)) {
$name = 'qf_group_' . $anonGroups++;
$appendName = false;
}
$group =& $this->addElement('group', $name, $groupLabel, $elements, $separator, $appendName);
return $group;
} // end func addGroup
// }}}
// {{{ &getElement()
/**
* Returns a reference to the element
*
* @param string $element Element name
* @since 2.0
* @access public
* @return object reference to element
* @throws HTML_QuickForm_Error
*/
function &getElement($element)
{
if (isset($this->_elementIndex[$element])) {
return $this->_elements[$this->_elementIndex[$element]];
} else {
$error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElement()", 'HTML_QuickForm_Error', true);
return $error;
}
} // end func getElement
// }}}
// {{{ &getElementValue()
/**
* Returns the element's raw value
*
* This returns the value as submitted by the form (not filtered)
* or set via setDefaults() or setConstants()
*
* @param string $element Element name
* @since 2.0
* @access public
* @return mixed element value
* @throws HTML_QuickForm_Error
*/
function &getElementValue($element)
{
if (!isset($this->_elementIndex[$element])) {
$error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$element' does not exist in HTML_QuickForm::getElementValue()", 'HTML_QuickForm_Error', true);
return $error;
}
$value = $this->_elements[$this->_elementIndex[$element]]->getValue();
if (isset($this->_duplicateIndex[$element])) {
foreach ($this->_duplicateIndex[$element] as $index) {
if (null !== ($v = $this->_elements[$index]->getValue())) {
if (is_array($value)) {
$value[] = $v;
} else {
$value = (null === $value)? $v: array($value, $v);
}
}
}
}
return $value;
} // end func getElementValue
// }}}
// {{{ getSubmitValue()
/**
* Returns the elements value after submit and filter
*
* @param string Element name
* @since 2.0
* @access public
* @return mixed submitted element value or null if not set
*/
function getSubmitValue($elementName)
{
$value = null;
if (isset($this->_submitValues[$elementName]) || isset($this->_submitFiles[$elementName])) {
$value = isset($this->_submitValues[$elementName])? $this->_submitValues[$elementName]: array();
if (is_array($value) && isset($this->_submitFiles[$elementName])) {
foreach ($this->_submitFiles[$elementName] as $k => $v) {
$value = HTML_QuickForm::arrayMerge($value, $this->_reindexFiles($this->_submitFiles[$elementName][$k], $k));
}
}
} elseif ('file' == $this->getElementType($elementName)) {
return $this->getElementValue($elementName);
} elseif (false !== ($pos = strpos($elementName, '['))) {
$base = substr($elementName, 0, $pos);
$idx = "['" . str_replace(array(']', '['), array('', "']['"), substr($elementName, $pos + 1, -1)) . "']";
if (isset($this->_submitValues[$base])) {
$value = eval("return (isset(\$this->_submitValues['{$base}']{$idx})) ? \$this->_submitValues['{$base}']{$idx} : null;");
}
if ((is_array($value) || null === $value) && isset($this->_submitFiles[$base])) {
$props = array('name', 'type', 'size', 'tmp_name', 'error');
$code = "if (!isset(\$this->_submitFiles['{$base}']['name']{$idx})) {\n" .
" return null;\n" .
"} else {\n" .
" \$v = array();\n";
foreach ($props as $prop) {
$code .= " \$v = HTML_QuickForm::arrayMerge(\$v, \$this->_reindexFiles(\$this->_submitFiles['{$base}']['{$prop}']{$idx}, '{$prop}'));\n";
}
$fileValue = eval($code . " return \$v;\n}\n");
if (null !== $fileValue) {
$value = null === $value? $fileValue: HTML_QuickForm::arrayMerge($value, $fileValue);
}
}
}
// This is only supposed to work for groups with appendName = false
if (null === $value && 'group' == $this->getElementType($elementName)) {
$group =& $this->getElement($elementName);
$elements =& $group->getElements();
foreach (array_keys($elements) as $key) {
$name = $group->getElementName($key);
// prevent endless recursion in case of radios and such
if ($name != $elementName) {
if (null !== ($v = $this->getSubmitValue($name))) {
$value[$name] = $v;
}
}
}
}
return $value;
} // end func getSubmitValue
// }}}
// {{{ _reindexFiles()
/**
* A helper function to change the indexes in $_FILES array
*
* @param mixed Some value from the $_FILES array
* @param string The key from the $_FILES array that should be appended
* @return array
*/
function _reindexFiles($value, $key)
{
if (!is_array($value)) {
return array($key => $value);
} else {
$ret = array();
foreach ($value as $k => $v) {
$ret[$k] = $this->_reindexFiles($v, $key);
}
return $ret;
}
}
// }}}
// {{{ getElementError()
/**
* Returns error corresponding to validated element
*
* @param string $element Name of form element to check
* @since 1.0
* @access public
* @return string error message corresponding to checked element
*/
function getElementError($element)
{
if (isset($this->_errors[$element])) {
return $this->_errors[$element];
}
} // end func getElementError
// }}}
// {{{ setElementError()
/**
* Set error message for a form element
*
* @param string $element Name of form element to set error for
* @param string $message Error message, if empty then removes the current error message
* @since 1.0
* @access public
* @return void
*/
function setElementError($element, $message = null)
{
if (!empty($message)) {
$this->_errors[$element] = $message;
} else {
unset($this->_errors[$element]);
}
} // end func setElementError
// }}}
// {{{ getElementType()
/**
* Returns the type of the given element
*
* @param string $element Name of form element
* @since 1.1
* @access public
* @return string Type of the element, false if the element is not found
*/
function getElementType($element)
{
if (isset($this->_elementIndex[$element])) {
return $this->_elements[$this->_elementIndex[$element]]->getType();
}
return false;
} // end func getElementType
// }}}
// {{{ updateElementAttr()
/**
* Updates Attributes for one or more elements
*
* @param mixed $elements Array of element names/objects or string of elements to be updated
* @param mixed $attrs Array or sting of html attributes
* @since 2.10
* @access public
* @return void
*/
function updateElementAttr($elements, $attrs)
{
if (is_string($elements)) {
$elements = preg_split('/[ ]?,[ ]?/', $elements);
}
foreach (array_keys($elements) as $key) {
if (is_object($elements[$key]) && is_a($elements[$key], 'HTML_QuickForm_element')) {
$elements[$key]->updateAttributes($attrs);
} elseif (isset($this->_elementIndex[$elements[$key]])) {
$this->_elements[$this->_elementIndex[$elements[$key]]]->updateAttributes($attrs);
if (isset($this->_duplicateIndex[$elements[$key]])) {
foreach ($this->_duplicateIndex[$elements[$key]] as $index) {
$this->_elements[$index]->updateAttributes($attrs);
}
}
}
}
} // end func updateElementAttr
// }}}
// {{{ removeElement()
/**
* Removes an element
*
* The method "unlinks" an element from the form, returning the reference
* to the element object. If several elements named $elementName exist,
* it removes the first one, leaving the others intact.
*
* @param string $elementName The element name
* @param boolean $removeRules True if rules for this element are to be removed too
* @access public
* @since 2.0
* @return object HTML_QuickForm_element a reference to the removed element
* @throws HTML_QuickForm_Error
*/
function &removeElement($elementName, $removeRules = true)
{
if (!isset($this->_elementIndex[$elementName])) {
$error = PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Element '$elementName' does not exist in HTML_QuickForm::removeElement()", 'HTML_QuickForm_Error', true);
return $error;
}
$el =& $this->_elements[$this->_elementIndex[$elementName]];
unset($this->_elements[$this->_elementIndex[$elementName]]);
if (empty($this->_duplicateIndex[$elementName])) {
unset($this->_elementIndex[$elementName]);
} else {
$this->_elementIndex[$elementName] = array_shift($this->_duplicateIndex[$elementName]);
}
if ($removeRules) {
unset($this->_rules[$elementName], $this->_errors[$elementName]);
}
return $el;
} // end func removeElement
// }}}