forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformslib.php
1615 lines (1471 loc) · 66.1 KB
/
formslib.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 // $Id$
/**
* formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
*
* To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
* and you want to name your class something like {modulename}_{purpose}_form. Your class will
* extend moodleform overriding abstract classes definition and optionally defintion_after_data
* and validation.
*
* See examples of use of this library in course/edit.php and course/edit_form.php
*
* A few notes :
* form defintion is used for both printing of form and processing and should be the same
* for both or you may lose some submitted data which won't be let through.
* you should be using setType for every form element except select, radio or checkbox
* elements, these elements clean themselves.
*
*
* @author Jamie Pratt
* @version $Id$
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
//point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else.
if (FALSE===strstr(ini_get('include_path'), $CFG->libdir.'/pear' )){
ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
}
require_once 'HTML/QuickForm.php';
require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
require_once 'HTML/QuickForm/Renderer/Tableless.php';
require_once $CFG->libdir.'/uploadlib.php';
/**
* Callback called when PEAR throws an error
*
* @param PEAR_Error $error
*/
function pear_handle_error($error){
echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
echo '<br /> <strong>Backtrace </strong>:';
print_object($error->backtrace);
}
if ($CFG->debug >= DEBUG_ALL){
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
}
/**
* Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
* use this class you should write a class defintion which extends this class or a more specific
* subclass such a moodleform_mod for each form you want to display and/or process with formslib.
*
* You will write your own definition() method which performs the form set up.
*/
class moodleform {
var $_formname; // form name
/**
* quickform object definition
*
* @var MoodleQuickForm
*/
var $_form;
/**
* globals workaround
*
* @var array
*/
var $_customdata;
/**
* file upload manager
*
* @var upload_manager
*/
var $_upload_manager; //
/**
* The constructor function calls the abstract function definition() and it will then
* process and clean and attempt to validate incoming data.
*
* It will call your custom validate method to validate data and will also check any rules
* you have specified in definition using addRule
*
* The name of the form (id attribute of the form) is automatically generated depending on
* the name you gave the class extending moodleform. You should call your class something
* like
*
* @param string $action the action attribute for the form. If empty defaults to auto detect the
* current url.
* @param array $customdata if your form defintion method needs access to data such as $course
* $cm, etc. to construct the form definition then pass it in this array. You can
* use globals for somethings.
* @param string $method if you set this to anything other than 'post' then _GET and _POST will
* be merged and used as incoming data to the form.
* @param string $target target frame for form submission. You will rarely use this. Don't use
* it if you don't need to as the target attribute is deprecated in xhtml
* strict.
* @param mixed $attributes you can pass a string of html attributes here or an array.
* @return moodleform
*/
function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null) {
if (empty($action)){
$action = strip_querystring(qualified_me());
}
$this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
$this->_customdata = $customdata;
$this->_form =& new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
$this->set_upload_manager(new upload_manager());
$this->definition();
$this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
$this->_form->setDefault('sesskey', sesskey());
$this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
$this->_form->setDefault('_qf__'.$this->_formname, 1);
$this->_form->_setDefaultRuleMessages();
// we have to know all input types before processing submission ;-)
$this->_process_submission($method);
// update form definition based on final data
$this->definition_after_data();
}
/**
* To autofocus on first form element or first element with error.
*
* @param string $name if this is set then the focus is forced to a field with this name
*
* @return string javascript to select form element with first error or
* first element if no errors. Use this as a parameter
* when calling print_header
*/
function focus($name=NULL){
$form =& $this->_form;
$elkeys=array_keys($form->_elementIndex);
if (isset($form->_errors) && 0 != count($form->_errors)){
$errorkeys = array_keys($form->_errors);
$elkeys = array_intersect($elkeys, $errorkeys);
}
$names=null;
while (!$names){
$el = array_shift($elkeys);
$names = $form->_getElNamesRecursive($el);
}
if (empty($name)) {
$name=array_shift($names);
}
$focus='forms[\''.$this->_form->getAttribute('id').'\'].elements[\''.$name.'\']';
return $focus;
}
/**
* Internal method. Alters submitted data to be suitable for quickforms processing.
* Must be called when the form is fully set up.
*/
function _process_submission($method) {
$submission = array();
if ($method == 'post') {
if (!empty($_POST)) {
$submission = $_POST;
}
} else {
$submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
}
// following trick is needed to enable proper sesskey checks when using GET forms
// the _qf__.$this->_formname serves as a marker that form was actually submitted
if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
if (!confirm_sesskey()) {
error('Incorrect sesskey submitted, form not accepted!');
}
$files = $_FILES;
} else {
$submission = array();
$files = array();
}
$this->_form->updateSubmission($submission, $files);
}
/**
* Internal method. Validates all uploaded files.
*/
function _validate_files() {
if (empty($_FILES)) {
// we do not need to do any checks because no files were submitted
// TODO: find out why server side required rule does not work for uploaded files;
// testing is easily done by always returning true from this function and adding
// $mform->addRule('soubor', get_string('required'), 'required', null, 'server');
// and submitting form without selected file
return true;
}
$errors = array();
$mform =& $this->_form;
// check the files
$status = $this->_upload_manager->preprocess_files();
// now check that we really want each file
foreach ($_FILES as $elname=>$file) {
if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
$required = $mform->isElementRequired($elname);
if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
// file not uploaded and not required - ignore it
continue;
}
$errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
}
} else {
error('Incorrect upload attempt!');
}
}
// return errors if found
if ($status and 0 == count($errors)){
return true;
} else {
return $errors;
}
}
/**
* Load in existing data as form defaults. Usually new entry defaults are stored directly in
* form definition (new entry form); this function is used to load in data where values
* already exist and data is being edited (edit entry form).
*
* @param mixed $default_values object or array of default values
* @param bool $slased true if magic quotes applied to data values
*/
function set_data($default_values, $slashed=false) {
if (is_object($default_values)) {
$default_values = (array)$default_values;
}
$filter = $slashed ? 'stripslashes' : NULL;
$this->_form->setDefaults($default_values, $filter);
//update form definition when data changed
$this->definition_after_data();
}
/**
* Set custom upload manager.
* Must be used BEFORE creating of file element!
*
* @param object $um - custom upload manager
*/
function set_upload_manager($um=false) {
if ($um === false) {
$um = new upload_manager();
}
$this->_upload_manager = $um;
$this->_form->setMaxFileSize($um->config->maxbytes);
}
/**
* Check that form was submitted. Does not check validity of submitted data.
*
* @return bool true if form properly submitted
*/
function is_submitted() {
return $this->_form->isSubmitted();
}
function no_submit_button_pressed(){
static $nosubmit = null; // one check is enough
if (!is_null($nosubmit)){
return $nosubmit;
}
$mform =& $this->_form;
$nosubmit = false;
if (!$this->is_submitted()){
return false;
}
foreach ($mform->_noSubmitButtons as $nosubmitbutton){
if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
$nosubmit = true;
break;
}
}
return $nosubmit;
}
/**
* Check that form data is valid.
*
* @return bool true if form data valid
*/
function is_validated() {
static $validated = null; // one validation is enough
$mform =& $this->_form;
if ($this->no_submit_button_pressed()){
return false;
} elseif ($validated === null) {
$internal_val = $mform->validate();
$moodle_val = $this->validation($mform->exportValues(null, true));
if ($moodle_val !== true) {
if ((is_array($moodle_val) && count($moodle_val)!==0)) {
foreach ($moodle_val as $element=>$msg) {
$mform->setElementError($element, $msg);
}
$moodle_val = false;
} else {
$moodle_val = true;
}
}
$file_val = $this->_validate_files();
if ($file_val !== true) {
if (!empty($file_val)) {
foreach ($file_val as $element=>$msg) {
$mform->setElementError($element, $msg);
}
}
$file_val = false;
}
$validated = ($internal_val and $moodle_val and $file_val);
}
return $validated;
}
/**
* Return true if a cancel button has been pressed resulting in the form being submitted.
*
* @return boolean true if a cancel button has been pressed
*/
function is_cancelled(){
$mform =& $this->_form;
if ($mform->isSubmitted()){
foreach ($mform->_cancelButtons as $cancelbutton){
if (optional_param($cancelbutton, 0, PARAM_RAW)){
return true;
}
}
}
return false;
}
/**
* Return submitted data if properly submitted or returns NULL if validation fails or
* if there is no submitted data.
*
* @param bool $slashed true means return data with addslashes applied
* @return object submitted data; NULL if not valid or not submitted
*/
function get_data($slashed=true) {
$mform =& $this->_form;
if ($this->is_submitted() and $this->is_validated()) {
$data = $mform->exportValues(null, $slashed);
unset($data['sesskey']); // we do not need to return sesskey
unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
if (empty($data)) {
return NULL;
} else {
return (object)$data;
}
} else {
return NULL;
}
}
/**
* Save verified uploaded files into directory. Upload process can be customised from definition()
* method by creating instance of upload manager and storing it in $this->_upload_form
*
* @param string $destination where to store uploaded files
* @return bool success
*/
function save_files($destination) {
if ($this->is_submitted() and $this->is_validated()) {
return $this->_upload_manager->save_files($destination);
}
return false;
}
/**
* If we're only handling one file (if inputname was given in the constructor)
* this will return the (possibly changed) filename of the file.
* @return mixed false in case of failure, string if ok
*/
function get_new_filename() {
return $this->_upload_manager->get_new_filename();
}
/**
* Print html form.
*/
function display() {
$this->_form->display();
}
/**
* Abstract method - always override!
*
* If you need special handling of uploaded files, create instance of $this->_upload_manager here.
*/
function definition() {
error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
}
/**
* Dummy stub method - override if you need to setup the form depending on current
* values. This method is called after definition(), data submission and set_data().
* All form setup that is dependent on form values should go in here.
*/
function definition_after_data(){
}
/**
* Dummy stub method - override if you needed to perform some extra validation.
* If there are errors return array of errors ("fieldname"=>"error message"),
* otherwise true if ok.
*
* @param array $data array of ("fieldname"=>value) of submitted data
* @return bool array of errors or true if ok
*/
function validation($data) {
return true;
}
/**
* Method to add a repeating group of elements to a form.
*
* @param array $elementobjs Array of elements or groups of elements that are to be repeated
* @param integer $repeats no of times to repeat elements initially
* @param array $options Array of options to apply to elements. Array keys are element names.
* This is an array of arrays. The second sets of keys are the option types
* for the elements :
* 'default' - default value is value
* 'type' - PARAM_* constant is value
* 'helpbutton' - helpbutton params array is value
* 'disabledif' - last three moodleform::disabledIf()
* params are value as an array
* @param string $repeathiddenname name for hidden element storing no of repeats in this form
* @param string $addfieldsname name for button to add more fields
* @param int $addfieldsno how many fields to add at a time
* @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
* @return int no of repeats of element in this page
*/
function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname, $addfieldsname, $addfieldsno=5, $addstring=null){
if ($addstring===null){
$addstring = get_string('addfields', 'form', $addfieldsno);
} else {
$addstring = str_ireplace('{no}', $addfieldsno, $addstring);
}
$repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
$addfields = optional_param($addfieldsname, '', PARAM_TEXT);
if (!empty($addfields)){
$repeats += $addfieldsno;
}
$mform =& $this->_form;
$mform->registerNoSubmitButton($addfieldsname);
$mform->addElement('hidden', $repeathiddenname, $repeats);
//value not to be overridden by submitted value
$mform->setConstants(array($repeathiddenname=>$repeats));
for ($i=0; $i<$repeats; $i++) {
foreach ($elementobjs as $elementobj){
$elementclone = clone($elementobj);
$name = $elementclone->getName();
if (!empty($name)){
$elementclone->setName($name."[$i]");
}
if (is_a($elementclone, 'HTML_QuickForm_header')){
$value=$elementclone->_text;
$elementclone->setValue(str_replace('{no}', ($i+1), $value));
} else {
$value=$elementclone->getLabel();
$elementclone->setLabel(str_replace('{no}', ($i+1), $value));
}
$mform->addElement($elementclone);
}
}
for ($i=0; $i<$repeats; $i++) {
foreach ($options as $elementname => $elementoptions){
$pos=strpos($elementname, '[');
if ($pos!==FALSE){
$realelementname = substr($elementname, 0, $pos+1)."[$i]";
$realelementname .= substr($elementname, $pos+1);
}else {
$realelementname = $elementname."[$i]";
}
foreach ($elementoptions as $option => $params){
switch ($option){
case 'default' :
$mform->setDefault($realelementname, $params);
break;
case 'helpbutton' :
$mform->setHelpButton($realelementname, $params);
break;
case 'disabledif' :
$params = array_merge(array($realelementname), $params);
call_user_func_array(array(&$mform, 'disabledIf'), $params);
break;
case 'rule' :
if (is_string($params)){
$params = array(null, $params, null, 'client');
}
$params = array_merge(array($realelementname), $params);
call_user_func_array(array(&$mform, 'addRule'), $params);
break;
}
}
}
}
$mform->addElement('submit', $addfieldsname, $addstring);
$mform->closeHeaderBefore($addfieldsname);
return $repeats;
}
/**
* Use this method to a cancel and submit button to the end of your form. Pass a param of false
* if you don't want a cancel button in your form. If you have a cancel button make sure you
* check for it being pressed using is_cancelled() and redirecting if it is true before trying to
* get data with get_data().
*
* @param boolean $cancel whether to show cancel button, default true
* @param boolean $revert whether to show revert button, default true
* @param string $submitlabel label for submit button, defaults to get_string('savechanges')
*/
function add_action_buttons($cancel = true, $submitlabel=null){
if (is_null($submitlabel)){
$submitlabel = get_string('savechanges');
}
$mform =& $this->_form;
if ($cancel){
//when two elements we need a group
$buttonarray=array();
$buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
$buttonarray[] = &$mform->createElement('cancel');
$mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
$mform->closeHeaderBefore('buttonar');
} else {
//no group needed
$mform->addElement('submit', 'submitbutton', $submitlabel);
$mform->closeHeaderBefore('submitbutton');
}
}
}
/**
* You never extend this class directly. The class methods of this class are available from
* the private $this->_form property on moodleform and it's children. You generally only
* call methods on this class from within abstract methods that you override on moodleform such
* as definition and definition_after_data
*
*/
class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
var $_types = array();
var $_dependencies = array();
/**
* Array of buttons that if pressed do not result in the processing of the form.
*
* @var array
*/
var $_noSubmitButtons=array();
/**
* Array of buttons that if pressed do not result in the processing of the form.
*
* @var array
*/
var $_cancelButtons=array();
/**
* Array whose keys are element names. If the key exists this is a advanced element
*
* @var array
*/
var $_advancedElements = array();
/**
* Whether to display advanced elements (on page load)
*
* @var boolean
*/
var $_showAdvanced = null;
/**
* The form name is derrived from the class name of the wrapper minus the trailing form
* It is a name with words joined by underscores whereas the id attribute is words joined by
* underscores.
*
* @var unknown_type
*/
var $_formName = '';
/**
* Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
* @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 none
* @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 MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
global $CFG;
static $formcounter = 1;
HTML_Common::HTML_Common($attributes);
$target = empty($target) ? array() : array('target' => $target);
$this->_formName = $formName;
//no 'name' atttribute for form in xhtml strict :
$attributes = array('action'=>$action, 'method'=>$method, 'id'=>'mform'.$formcounter) + $target;
$formcounter++;
$this->updateAttributes($attributes);
//this is custom stuff for Moodle :
$oldclass= $this->getAttribute('class');
if (!empty($oldclass)){
$this->updateAttributes(array('class'=>$oldclass.' mform'));
}else {
$this->updateAttributes(array('class'=>'mform'));
}
$this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />';
$this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />';
$this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'));
//(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
}
/**
* Use this method to indicate an element in a form is an advanced field. If items in a form
* are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
* form so the user can decide whether to display advanced form controls.
*
* If you set a header element to advanced then all elements it contains will also be set as advanced.
*
* @param string $elementName group or element name (not the element name of something inside a group).
* @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
*/
function setAdvanced($elementName, $advanced=true){
if ($advanced){
$this->_advancedElements[$elementName]='';
} elseif (isset($this->_advancedElements[$elementName])) {
unset($this->_advancedElements[$elementName]);
}
if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
$this->setShowAdvanced();
$this->registerNoSubmitButton('mform_showadvanced');
$this->addElement('hidden', 'mform_showadvanced_last');
}
}
/**
* Set whether to show advanced elements in the form on first displaying form. Default is not to
* display advanced elements in the form until 'Show Advanced' is pressed.
*
* You can get the last state of the form and possibly save it for this user by using
* value 'mform_showadvanced_last' in submitted data.
*
* @param boolean $showadvancedNow
*/
function setShowAdvanced($showadvancedNow = null){
if ($showadvancedNow === null){
if ($this->_showAdvanced !== null){
return;
} else { //if setShowAdvanced is called without any preference
//make the default to not show advanced elements.
$showadvancedNow = get_user_preferences(
moodle_strtolower($this->_formName.'_showadvanced', 0));
}
}
//value of hidden element
$hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
//value of button
$buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
//toggle if button pressed or else stay the same
if ($hiddenLast == -1) {
$next = $showadvancedNow;
} elseif ($buttonPressed) { //toggle on button press
$next = !$hiddenLast;
} else {
$next = $hiddenLast;
}
$this->_showAdvanced = $next;
if ($showadvancedNow != $next){
set_user_preference($this->_formName.'_showadvanced', $next);
}
$this->setConstants(array('mform_showadvanced_last'=>$next));
}
function getShowAdvanced(){
return $this->_showAdvanced;
}
/**
* Accepts a renderer
*
* @param HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
* @since 3.0
* @access public
* @return void
*/
function accept(&$renderer)
{
if (method_exists($renderer, 'setAdvancedElements')){
//check for visible fieldsets where all elements are advanced
//and mark these headers as advanced as well.
//And mark all elements in a advanced header as advanced
$stopFields = $renderer->getStopFieldSetElements();
$lastHeader = null;
$lastHeaderAdvanced = false;
$anyAdvanced = false;
foreach (array_keys($this->_elements) as $elementIndex){
$element =& $this->_elements[$elementIndex];
if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
if ($anyAdvanced && ($lastHeader!==null)){
$this->setAdvanced($lastHeader->getName());
}
$lastHeaderAdvanced = false;
} elseif ($lastHeaderAdvanced) {
$this->setAdvanced($element->getName());
}
if ($element->getType()=='header'){
$lastHeader =& $element;
$anyAdvanced = false;
$lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
} elseif (isset($this->_advancedElements[$element->getName()])){
$anyAdvanced = true;
}
}
$renderer->setAdvancedElements($this->_advancedElements);
}
parent::accept($renderer);
}
function closeHeaderBefore($elementName){
$renderer =& $this->defaultRenderer();
$renderer->addStopFieldsetElements($elementName);
}
/**
* Should be used for all elements of a form except for select, radio and checkboxes which
* clean their own data.
*
* @param string $elementname
* @param integer $paramtype use the constants PARAM_*.
* * PARAM_CLEAN is deprecated and you should try to use a more specific type.
* * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
* It will strip all html tags. But will still let tags for multilang support
* through.
* * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
* html editor. Data from the editor is later cleaned before display using
* format_text() function. PARAM_RAW can also be used for data that is validated
* by some other way or printed by p() or s().
* * PARAM_INT should be used for integers.
* * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
* form actions.
*/
function setType($elementname, $paramtype) {
$this->_types[$elementname] = $paramtype;
}
/**
* See description of setType above. This can be used to set several types at once.
*
* @param array $paramtypes
*/
function setTypes($paramtypes) {
$this->_types = $paramtypes + $this->_types;
}
function updateSubmission($submission, $files) {
$this->_flagSubmitted = false;
if (empty($submission)) {
$this->_submitValues = array();
} else {
foreach ($submission as $key=>$s) {
if (array_key_exists($key, $this->_types)) {
$submission[$key] = clean_param($s, $this->_types[$key]);
}
}
$this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
$this->_flagSubmitted = true;
}
if (empty($files)) {
$this->_submitFiles = array();
} else {
if (1 == get_magic_quotes_gpc()) {
foreach (array_keys($files) as $elname) {
// dangerous characters in filenames are cleaned later in upload_manager
$files[$elname]['name'] = stripslashes($files[$elname]['name']);
}
}
$this->_submitFiles = $files;
$this->_flagSubmitted = true;
}
// need to tell all elements that they need to update their value attribute.
foreach (array_keys($this->_elements) as $key) {
$this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
}
}
function getReqHTML(){
return $this->_reqHTML;
}
function getAdvancedHTML(){
return $this->_advancedHTML;
}
/**
* Initializes a default form value. Used to specify the default for a new entry where
* no data is loaded in using moodleform::set_data()
*
* @param string $elementname element name
* @param mixed $values values for that element name
* @param bool $slashed the default value is slashed
* @access public
* @return void
*/
function setDefault($elementName, $defaultValue, $slashed=false){
$filter = $slashed ? 'stripslashes' : NULL;
$this->setDefaults(array($elementName=>$defaultValue), $filter);
} // end func setDefault
/**
* Add an array of buttons to the form
* @param array $buttons An associative array representing help button to attach to
* to the form. keys of array correspond to names of elements in form.
*
* @access public
*/
function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
foreach ($buttons as $elementname => $button){
$this->setHelpButton($elementname, $button, $suppresscheck, $function);
}
}
/**
* Add a single button.
*
* @param string $elementname name of the element to add the item to
* @param array $button - arguments to pass to function $function
* @param boolean $suppresscheck - whether to throw an error if the element
* doesn't exist.
* @param string $function - function to generate html from the arguments in $button
*/
function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
if (array_key_exists($elementname, $this->_elementIndex)){
//_elements has a numeric index, this code accesses the elements by name
$element=&$this->_elements[$this->_elementIndex[$elementname]];
if (method_exists($element, 'setHelpButton')){
$element->setHelpButton($button, $function);
}else{
$a=new object();
$a->name=$element->getName();
$a->classname=get_class($element);
print_error('nomethodforaddinghelpbutton', 'form', '', $a);
}
}elseif (!$suppresscheck){
print_error('nonexistentformelements', 'form', '', $elementname);
}
}
function exportValues($elementList= null, $addslashes=true){
$unfiltered = array();
if (null === $elementList) {
// iterate over all elements, calling their exportValue() methods
$emptyarray = array();
foreach (array_keys($this->_elements) as $key) {
if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
$value = $this->_elements[$key]->exportValue($emptyarray, true);
} else {
$value = $this->_elements[$key]->exportValue($this->_submitValues, true);
}
if (is_array($value)) {
// This shit throws a bogus warning in PHP 4.3.x
$unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
}
}
} else {
if (!is_array($elementList)) {
$elementList = array_map('trim', explode(',', $elementList));
}
foreach ($elementList as $elementName) {
$value = $this->exportValue($elementName);
if (PEAR::isError($value)) {
return $value;
}
$unfiltered[$elementName] = $value;
}
}
if ($addslashes){
return $this->_recursiveFilter('addslashes', $unfiltered);
} else {
return $unfiltered;
}
}
/**
* Adds a validation rule for the given field
*
* If the element is in fact a group, it will be considered as a whole.
* To validate grouped elements as separated entities,
* use addGroupRule instead of addRule.
*
* @param string $element Form element name
* @param string $message Message to display for invalid data
* @param string $type Rule type, use getRegisteredRules() to get types
* @param string $format (optional)Required for extra rule data
* @param string $validation (optional)Where to perform validation: "server", "client"
* @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
* @param boolean $force Force the rule to be applied, even if the target form element does not exist
* @since 1.0
* @access public
* @throws HTML_QuickForm_Error
*/
function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
{
parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
if ($validation == 'client') {
$this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
}
} // end func addRule
/**
* Adds a validation rule for the given group of elements
*
* Only groups with a name can be assigned a validation rule
* Use addGroupRule when you need to validate elements inside the group.
* Use addRule if you need to validate the group as a whole. In this case,
* the same rule will be applied to all elements in the group.
* Use addRule if you need to validate the group against a function.
*
* @param string $group Form group name
* @param mixed $arg1 Array for multiple elements or error message string for one element
* @param string $type (optional)Rule type use getRegisteredRules() to get types
* @param string $format (optional)Required for extra rule data
* @param int $howmany (optional)How many valid elements should be in the group
* @param string $validation (optional)Where to perform validation: "server", "client"
* @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
* @since 2.5
* @access public
* @throws HTML_QuickForm_Error
*/
function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
{
parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
if (is_array($arg1)) {
foreach ($arg1 as $rules) {
foreach ($rules as $rule) {
$validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
if ('client' == $validation) {
$this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
}
}
}
} elseif (is_string($arg1)) {
if ($validation == 'client') {
$this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
}
}
} // end func addGroupRule
// }}}
/**
* Returns the client side validation script
*
* The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
* and slightly modified to run rules per-element
* Needed to override this because of an error with client side validation of grouped elements.
*
* @access public
* @return string Javascript to perform validation, empty string if no 'client' rules were added
*/
function getValidationScript()
{
if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
return '';
}
include_once('HTML/QuickForm/RuleRegistry.php');
$registry =& HTML_QuickForm_RuleRegistry::singleton();