acb5db31ae8256aab7e77e318dfc24520c43fa89
[moodle.git] / lib / formslib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
19  *
20  * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
21  * and you want to name your class something like {modulename}_{purpose}_form. Your class will
22  * extend moodleform overriding abstract classes definition and optionally defintion_after_data
23  * and validation.
24  *
25  * See examples of use of this library in course/edit.php and course/edit_form.php
26  *
27  * A few notes :
28  *      form definition is used for both printing of form and processing and should be the same
29  *              for both or you may lose some submitted data which won't be let through.
30  *      you should be using setType for every form element except select, radio or checkbox
31  *              elements, these elements clean themselves.
32  *
33  * @package   core_form
34  * @copyright 2006 Jamie Pratt <me@jamiep.org>
35  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
38 defined('MOODLE_INTERNAL') || die();
40 /** setup.php includes our hacked pear libs first */
41 require_once 'HTML/QuickForm.php';
42 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43 require_once 'HTML/QuickForm/Renderer/Tableless.php';
44 require_once 'HTML/QuickForm/Rule.php';
46 require_once $CFG->libdir.'/filelib.php';
48 /**
49  * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
50  */
51 define('EDITOR_UNLIMITED_FILES', -1);
53 /**
54  * Callback called when PEAR throws an error
55  *
56  * @param PEAR_Error $error
57  */
58 function pear_handle_error($error){
59     echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
60     echo '<br /> <strong>Backtrace </strong>:';
61     print_object($error->backtrace);
62 }
64 if ($CFG->debugdeveloper) {
65     //TODO: this is a wrong place to init PEAR!
66     $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
67     $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
68 }
70 /**
71  * Initalize javascript for date type form element
72  *
73  * @staticvar bool $done make sure it gets initalize once.
74  * @global moodle_page $PAGE
75  */
76 function form_init_date_js() {
77     global $PAGE;
78     static $done = false;
79     if (!$done) {
80         $module   = 'moodle-form-dateselector';
81         $function = 'M.form.dateselector.init_date_selectors';
82         $config = array(array(
83             'firstdayofweek'    => get_string('firstdayofweek', 'langconfig'),
84             'mon'               => date_format_string(strtotime("Monday"), '%a', 99),
85             'tue'               => date_format_string(strtotime("Tuesday"), '%a', 99),
86             'wed'               => date_format_string(strtotime("Wednesday"), '%a', 99),
87             'thu'               => date_format_string(strtotime("Thursday"), '%a', 99),
88             'fri'               => date_format_string(strtotime("Friday"), '%a', 99),
89             'sat'               => date_format_string(strtotime("Saturday"), '%a', 99),
90             'sun'               => date_format_string(strtotime("Sunday"), '%a', 99),
91             'january'           => date_format_string(strtotime("January 1"), '%B', 99),
92             'february'          => date_format_string(strtotime("February 1"), '%B', 99),
93             'march'             => date_format_string(strtotime("March 1"), '%B', 99),
94             'april'             => date_format_string(strtotime("April 1"), '%B', 99),
95             'may'               => date_format_string(strtotime("May 1"), '%B', 99),
96             'june'              => date_format_string(strtotime("June 1"), '%B', 99),
97             'july'              => date_format_string(strtotime("July 1"), '%B', 99),
98             'august'            => date_format_string(strtotime("August 1"), '%B', 99),
99             'september'         => date_format_string(strtotime("September 1"), '%B', 99),
100             'october'           => date_format_string(strtotime("October 1"), '%B', 99),
101             'november'          => date_format_string(strtotime("November 1"), '%B', 99),
102             'december'          => date_format_string(strtotime("December 1"), '%B', 99)
103         ));
104         $PAGE->requires->yui_module($module, $function, $config);
105         $done = true;
106     }
109 /**
110  * Wrapper that separates quickforms syntax from moodle code
111  *
112  * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
113  * use this class you should write a class definition which extends this class or a more specific
114  * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
115  *
116  * You will write your own definition() method which performs the form set up.
117  *
118  * @package   core_form
119  * @copyright 2006 Jamie Pratt <me@jamiep.org>
120  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
121  * @todo      MDL-19380 rethink the file scanning
122  */
123 abstract class moodleform {
124     /** @var string name of the form */
125     protected $_formname;       // form name
127     /** @var MoodleQuickForm quickform object definition */
128     protected $_form;
130     /** @var array globals workaround */
131     protected $_customdata;
133     /** @var object definition_after_data executed flag */
134     protected $_definition_finalized = false;
136     /**
137      * The constructor function calls the abstract function definition() and it will then
138      * process and clean and attempt to validate incoming data.
139      *
140      * It will call your custom validate method to validate data and will also check any rules
141      * you have specified in definition using addRule
142      *
143      * The name of the form (id attribute of the form) is automatically generated depending on
144      * the name you gave the class extending moodleform. You should call your class something
145      * like
146      *
147      * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
148      *              current url. If a moodle_url object then outputs params as hidden variables.
149      * @param mixed $customdata if your form defintion method needs access to data such as $course
150      *              $cm, etc. to construct the form definition then pass it in this array. You can
151      *              use globals for somethings.
152      * @param string $method if you set this to anything other than 'post' then _GET and _POST will
153      *               be merged and used as incoming data to the form.
154      * @param string $target target frame for form submission. You will rarely use this. Don't use
155      *               it if you don't need to as the target attribute is deprecated in xhtml strict.
156      * @param mixed $attributes you can pass a string of html attributes here or an array.
157      * @param bool $editable
158      */
159     function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
160         global $CFG, $FULLME;
161         // no standard mform in moodle should allow autocomplete with the exception of user signup
162         if (empty($attributes)) {
163             $attributes = array('autocomplete'=>'off');
164         } else if (is_array($attributes)) {
165             $attributes['autocomplete'] = 'off';
166         } else {
167             if (strpos($attributes, 'autocomplete') === false) {
168                 $attributes .= ' autocomplete="off" ';
169             }
170         }
172         if (empty($action)){
173             // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
174             $action = strip_querystring($FULLME);
175             if (!empty($CFG->sslproxy)) {
176                 // return only https links when using SSL proxy
177                 $action = preg_replace('/^http:/', 'https:', $action, 1);
178             }
179             //TODO: use following instead of FULLME - see MDL-33015
180             //$action = strip_querystring(qualified_me());
181         }
182         // Assign custom data first, so that get_form_identifier can use it.
183         $this->_customdata = $customdata;
184         $this->_formname = $this->get_form_identifier();
186         $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
187         if (!$editable){
188             $this->_form->hardFreeze();
189         }
191         $this->definition();
193         $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
194         $this->_form->setType('sesskey', PARAM_RAW);
195         $this->_form->setDefault('sesskey', sesskey());
196         $this->_form->addElement('hidden', '_qf__'.$this->_formname, null);   // form submission marker
197         $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
198         $this->_form->setDefault('_qf__'.$this->_formname, 1);
199         $this->_form->_setDefaultRuleMessages();
201         // we have to know all input types before processing submission ;-)
202         $this->_process_submission($method);
203     }
205     /**
206      * It should returns unique identifier for the form.
207      * Currently it will return class name, but in case two same forms have to be
208      * rendered on same page then override function to get unique form identifier.
209      * e.g This is used on multiple self enrollments page.
210      *
211      * @return string form identifier.
212      */
213     protected function get_form_identifier() {
214         return get_class($this);
215     }
217     /**
218      * To autofocus on first form element or first element with error.
219      *
220      * @param string $name if this is set then the focus is forced to a field with this name
221      * @return string javascript to select form element with first error or
222      *                first element if no errors. Use this as a parameter
223      *                when calling print_header
224      */
225     function focus($name=NULL) {
226         $form =& $this->_form;
227         $elkeys = array_keys($form->_elementIndex);
228         $error = false;
229         if (isset($form->_errors) &&  0 != count($form->_errors)){
230             $errorkeys = array_keys($form->_errors);
231             $elkeys = array_intersect($elkeys, $errorkeys);
232             $error = true;
233         }
235         if ($error or empty($name)) {
236             $names = array();
237             while (empty($names) and !empty($elkeys)) {
238                 $el = array_shift($elkeys);
239                 $names = $form->_getElNamesRecursive($el);
240             }
241             if (!empty($names)) {
242                 $name = array_shift($names);
243             }
244         }
246         $focus = '';
247         if (!empty($name)) {
248             $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
249         }
251         return $focus;
252      }
254     /**
255      * Internal method. Alters submitted data to be suitable for quickforms processing.
256      * Must be called when the form is fully set up.
257      *
258      * @param string $method name of the method which alters submitted data
259      */
260     function _process_submission($method) {
261         $submission = array();
262         if ($method == 'post') {
263             if (!empty($_POST)) {
264                 $submission = $_POST;
265             }
266         } else {
267             $submission = $_GET;
268             merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
269         }
271         // following trick is needed to enable proper sesskey checks when using GET forms
272         // the _qf__.$this->_formname serves as a marker that form was actually submitted
273         if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
274             if (!confirm_sesskey()) {
275                 print_error('invalidsesskey');
276             }
277             $files = $_FILES;
278         } else {
279             $submission = array();
280             $files = array();
281         }
282         $this->detectMissingSetType();
284         $this->_form->updateSubmission($submission, $files);
285     }
287     /**
288      * Internal method - should not be used anywhere.
289      * @deprecated since 2.6
290      * @return array $_POST.
291      */
292     protected function _get_post_params() {
293         return $_POST;
294     }
296     /**
297      * Internal method. Validates all old-style deprecated uploaded files.
298      * The new way is to upload files via repository api.
299      *
300      * @param array $files list of files to be validated
301      * @return bool|array Success or an array of errors
302      */
303     function _validate_files(&$files) {
304         global $CFG, $COURSE;
306         $files = array();
308         if (empty($_FILES)) {
309             // we do not need to do any checks because no files were submitted
310             // note: server side rules do not work for files - use custom verification in validate() instead
311             return true;
312         }
314         $errors = array();
315         $filenames = array();
317         // now check that we really want each file
318         foreach ($_FILES as $elname=>$file) {
319             $required = $this->_form->isElementRequired($elname);
321             if ($file['error'] == 4 and $file['size'] == 0) {
322                 if ($required) {
323                     $errors[$elname] = get_string('required');
324                 }
325                 unset($_FILES[$elname]);
326                 continue;
327             }
329             if (!empty($file['error'])) {
330                 $errors[$elname] = file_get_upload_error($file['error']);
331                 unset($_FILES[$elname]);
332                 continue;
333             }
335             if (!is_uploaded_file($file['tmp_name'])) {
336                 // TODO: improve error message
337                 $errors[$elname] = get_string('error');
338                 unset($_FILES[$elname]);
339                 continue;
340             }
342             if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
343                 // hmm, this file was not requested
344                 unset($_FILES[$elname]);
345                 continue;
346             }
348             // NOTE: the viruses are scanned in file picker, no need to deal with them here.
350             $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
351             if ($filename === '') {
352                 // TODO: improve error message - wrong chars
353                 $errors[$elname] = get_string('error');
354                 unset($_FILES[$elname]);
355                 continue;
356             }
357             if (in_array($filename, $filenames)) {
358                 // TODO: improve error message - duplicate name
359                 $errors[$elname] = get_string('error');
360                 unset($_FILES[$elname]);
361                 continue;
362             }
363             $filenames[] = $filename;
364             $_FILES[$elname]['name'] = $filename;
366             $files[$elname] = $_FILES[$elname]['tmp_name'];
367         }
369         // return errors if found
370         if (count($errors) == 0){
371             return true;
373         } else {
374             $files = array();
375             return $errors;
376         }
377     }
379     /**
380      * Internal method. Validates filepicker and filemanager files if they are
381      * set as required fields. Also, sets the error message if encountered one.
382      *
383      * @return bool|array with errors
384      */
385     protected function validate_draft_files() {
386         global $USER;
387         $mform =& $this->_form;
389         $errors = array();
390         //Go through all the required elements and make sure you hit filepicker or
391         //filemanager element.
392         foreach ($mform->_rules as $elementname => $rules) {
393             $elementtype = $mform->getElementType($elementname);
394             //If element is of type filepicker then do validation
395             if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
396                 //Check if rule defined is required rule
397                 foreach ($rules as $rule) {
398                     if ($rule['type'] == 'required') {
399                         $draftid = (int)$mform->getSubmitValue($elementname);
400                         $fs = get_file_storage();
401                         $context = context_user::instance($USER->id);
402                         if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
403                             $errors[$elementname] = $rule['message'];
404                         }
405                     }
406                 }
407             }
408         }
409         // Check all the filemanager elements to make sure they do not have too many
410         // files in them.
411         foreach ($mform->_elements as $element) {
412             if ($element->_type == 'filemanager') {
413                 $maxfiles = $element->getMaxfiles();
414                 if ($maxfiles > 0) {
415                     $draftid = (int)$element->getValue();
416                     $fs = get_file_storage();
417                     $context = context_user::instance($USER->id);
418                     $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
419                     if (count($files) > $maxfiles) {
420                         $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
421                     }
422                 }
423             }
424         }
425         if (empty($errors)) {
426             return true;
427         } else {
428             return $errors;
429         }
430     }
432     /**
433      * Load in existing data as form defaults. Usually new entry defaults are stored directly in
434      * form definition (new entry form); this function is used to load in data where values
435      * already exist and data is being edited (edit entry form).
436      *
437      * note: $slashed param removed
438      *
439      * @param stdClass|array $default_values object or array of default values
440      */
441     function set_data($default_values) {
442         if (is_object($default_values)) {
443             $default_values = (array)$default_values;
444         }
445         $this->_form->setDefaults($default_values);
446     }
448     /**
449      * Check that form was submitted. Does not check validity of submitted data.
450      *
451      * @return bool true if form properly submitted
452      */
453     function is_submitted() {
454         return $this->_form->isSubmitted();
455     }
457     /**
458      * Checks if button pressed is not for submitting the form
459      *
460      * @staticvar bool $nosubmit keeps track of no submit button
461      * @return bool
462      */
463     function no_submit_button_pressed(){
464         static $nosubmit = null; // one check is enough
465         if (!is_null($nosubmit)){
466             return $nosubmit;
467         }
468         $mform =& $this->_form;
469         $nosubmit = false;
470         if (!$this->is_submitted()){
471             return false;
472         }
473         foreach ($mform->_noSubmitButtons as $nosubmitbutton){
474             if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
475                 $nosubmit = true;
476                 break;
477             }
478         }
479         return $nosubmit;
480     }
483     /**
484      * Check that form data is valid.
485      * You should almost always use this, rather than {@link validate_defined_fields}
486      *
487      * @return bool true if form data valid
488      */
489     function is_validated() {
490         //finalize the form definition before any processing
491         if (!$this->_definition_finalized) {
492             $this->_definition_finalized = true;
493             $this->definition_after_data();
494         }
496         return $this->validate_defined_fields();
497     }
499     /**
500      * Validate the form.
501      *
502      * You almost always want to call {@link is_validated} instead of this
503      * because it calls {@link definition_after_data} first, before validating the form,
504      * which is what you want in 99% of cases.
505      *
506      * This is provided as a separate function for those special cases where
507      * you want the form validated before definition_after_data is called
508      * for example, to selectively add new elements depending on a no_submit_button press,
509      * but only when the form is valid when the no_submit_button is pressed,
510      *
511      * @param bool $validateonnosubmit optional, defaults to false.  The default behaviour
512      *             is NOT to validate the form when a no submit button has been pressed.
513      *             pass true here to override this behaviour
514      *
515      * @return bool true if form data valid
516      */
517     function validate_defined_fields($validateonnosubmit=false) {
518         static $validated = null; // one validation is enough
519         $mform =& $this->_form;
520         if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
521             return false;
522         } elseif ($validated === null) {
523             $internal_val = $mform->validate();
525             $files = array();
526             $file_val = $this->_validate_files($files);
527             //check draft files for validation and flag them if required files
528             //are not in draft area.
529             $draftfilevalue = $this->validate_draft_files();
531             if ($file_val !== true && $draftfilevalue !== true) {
532                 $file_val = array_merge($file_val, $draftfilevalue);
533             } else if ($draftfilevalue !== true) {
534                 $file_val = $draftfilevalue;
535             } //default is file_val, so no need to assign.
537             if ($file_val !== true) {
538                 if (!empty($file_val)) {
539                     foreach ($file_val as $element=>$msg) {
540                         $mform->setElementError($element, $msg);
541                     }
542                 }
543                 $file_val = false;
544             }
546             $data = $mform->exportValues();
547             $moodle_val = $this->validation($data, $files);
548             if ((is_array($moodle_val) && count($moodle_val)!==0)) {
549                 // non-empty array means errors
550                 foreach ($moodle_val as $element=>$msg) {
551                     $mform->setElementError($element, $msg);
552                 }
553                 $moodle_val = false;
555             } else {
556                 // anything else means validation ok
557                 $moodle_val = true;
558             }
560             $validated = ($internal_val and $moodle_val and $file_val);
561         }
562         return $validated;
563     }
565     /**
566      * Return true if a cancel button has been pressed resulting in the form being submitted.
567      *
568      * @return bool true if a cancel button has been pressed
569      */
570     function is_cancelled(){
571         $mform =& $this->_form;
572         if ($mform->isSubmitted()){
573             foreach ($mform->_cancelButtons as $cancelbutton){
574                 if (optional_param($cancelbutton, 0, PARAM_RAW)){
575                     return true;
576                 }
577             }
578         }
579         return false;
580     }
582     /**
583      * Return submitted data if properly submitted or returns NULL if validation fails or
584      * if there is no submitted data.
585      *
586      * note: $slashed param removed
587      *
588      * @return object submitted data; NULL if not valid or not submitted or cancelled
589      */
590     function get_data() {
591         $mform =& $this->_form;
593         if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
594             $data = $mform->exportValues();
595             unset($data['sesskey']); // we do not need to return sesskey
596             unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
597             if (empty($data)) {
598                 return NULL;
599             } else {
600                 return (object)$data;
601             }
602         } else {
603             return NULL;
604         }
605     }
607     /**
608      * Return submitted data without validation or NULL if there is no submitted data.
609      * note: $slashed param removed
610      *
611      * @return object submitted data; NULL if not submitted
612      */
613     function get_submitted_data() {
614         $mform =& $this->_form;
616         if ($this->is_submitted()) {
617             $data = $mform->exportValues();
618             unset($data['sesskey']); // we do not need to return sesskey
619             unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
620             if (empty($data)) {
621                 return NULL;
622             } else {
623                 return (object)$data;
624             }
625         } else {
626             return NULL;
627         }
628     }
630     /**
631      * Save verified uploaded files into directory. Upload process can be customised from definition()
632      *
633      * @deprecated since Moodle 2.0
634      * @todo MDL-31294 remove this api
635      * @see moodleform::save_stored_file()
636      * @see moodleform::save_file()
637      * @param string $destination path where file should be stored
638      * @return bool Always false
639      */
640     function save_files($destination) {
641         debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
642         return false;
643     }
645     /**
646      * Returns name of uploaded file.
647      *
648      * @param string $elname first element if null
649      * @return string|bool false in case of failure, string if ok
650      */
651     function get_new_filename($elname=null) {
652         global $USER;
654         if (!$this->is_submitted() or !$this->is_validated()) {
655             return false;
656         }
658         if (is_null($elname)) {
659             if (empty($_FILES)) {
660                 return false;
661             }
662             reset($_FILES);
663             $elname = key($_FILES);
664         }
666         if (empty($elname)) {
667             return false;
668         }
670         $element = $this->_form->getElement($elname);
672         if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
673             $values = $this->_form->exportValues($elname);
674             if (empty($values[$elname])) {
675                 return false;
676             }
677             $draftid = $values[$elname];
678             $fs = get_file_storage();
679             $context = context_user::instance($USER->id);
680             if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
681                 return false;
682             }
683             $file = reset($files);
684             return $file->get_filename();
685         }
687         if (!isset($_FILES[$elname])) {
688             return false;
689         }
691         return $_FILES[$elname]['name'];
692     }
694     /**
695      * Save file to standard filesystem
696      *
697      * @param string $elname name of element
698      * @param string $pathname full path name of file
699      * @param bool $override override file if exists
700      * @return bool success
701      */
702     function save_file($elname, $pathname, $override=false) {
703         global $USER;
705         if (!$this->is_submitted() or !$this->is_validated()) {
706             return false;
707         }
708         if (file_exists($pathname)) {
709             if ($override) {
710                 if (!@unlink($pathname)) {
711                     return false;
712                 }
713             } else {
714                 return false;
715             }
716         }
718         $element = $this->_form->getElement($elname);
720         if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
721             $values = $this->_form->exportValues($elname);
722             if (empty($values[$elname])) {
723                 return false;
724             }
725             $draftid = $values[$elname];
726             $fs = get_file_storage();
727             $context = context_user::instance($USER->id);
728             if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
729                 return false;
730             }
731             $file = reset($files);
733             return $file->copy_content_to($pathname);
735         } else if (isset($_FILES[$elname])) {
736             return copy($_FILES[$elname]['tmp_name'], $pathname);
737         }
739         return false;
740     }
742     /**
743      * Returns a temporary file, do not forget to delete after not needed any more.
744      *
745      * @param string $elname name of the elmenet
746      * @return string|bool either string or false
747      */
748     function save_temp_file($elname) {
749         if (!$this->get_new_filename($elname)) {
750             return false;
751         }
752         if (!$dir = make_temp_directory('forms')) {
753             return false;
754         }
755         if (!$tempfile = tempnam($dir, 'tempup_')) {
756             return false;
757         }
758         if (!$this->save_file($elname, $tempfile, true)) {
759             // something went wrong
760             @unlink($tempfile);
761             return false;
762         }
764         return $tempfile;
765     }
767     /**
768      * Get draft files of a form element
769      * This is a protected method which will be used only inside moodleforms
770      *
771      * @param string $elname name of element
772      * @return array|bool|null
773      */
774     protected function get_draft_files($elname) {
775         global $USER;
777         if (!$this->is_submitted()) {
778             return false;
779         }
781         $element = $this->_form->getElement($elname);
783         if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
784             $values = $this->_form->exportValues($elname);
785             if (empty($values[$elname])) {
786                 return false;
787             }
788             $draftid = $values[$elname];
789             $fs = get_file_storage();
790             $context = context_user::instance($USER->id);
791             if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
792                 return null;
793             }
794             return $files;
795         }
796         return null;
797     }
799     /**
800      * Save file to local filesystem pool
801      *
802      * @param string $elname name of element
803      * @param int $newcontextid id of context
804      * @param string $newcomponent name of the component
805      * @param string $newfilearea name of file area
806      * @param int $newitemid item id
807      * @param string $newfilepath path of file where it get stored
808      * @param string $newfilename use specified filename, if not specified name of uploaded file used
809      * @param bool $overwrite overwrite file if exists
810      * @param int $newuserid new userid if required
811      * @return mixed stored_file object or false if error; may throw exception if duplicate found
812      */
813     function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
814                               $newfilename=null, $overwrite=false, $newuserid=null) {
815         global $USER;
817         if (!$this->is_submitted() or !$this->is_validated()) {
818             return false;
819         }
821         if (empty($newuserid)) {
822             $newuserid = $USER->id;
823         }
825         $element = $this->_form->getElement($elname);
826         $fs = get_file_storage();
828         if ($element instanceof MoodleQuickForm_filepicker) {
829             $values = $this->_form->exportValues($elname);
830             if (empty($values[$elname])) {
831                 return false;
832             }
833             $draftid = $values[$elname];
834             $context = context_user::instance($USER->id);
835             if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
836                 return false;
837             }
838             $file = reset($files);
839             if (is_null($newfilename)) {
840                 $newfilename = $file->get_filename();
841             }
843             if ($overwrite) {
844                 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
845                     if (!$oldfile->delete()) {
846                         return false;
847                     }
848                 }
849             }
851             $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
852                                  'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
853             return $fs->create_file_from_storedfile($file_record, $file);
855         } else if (isset($_FILES[$elname])) {
856             $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
858             if ($overwrite) {
859                 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
860                     if (!$oldfile->delete()) {
861                         return false;
862                     }
863                 }
864             }
866             $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
867                                  'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
868             return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
869         }
871         return false;
872     }
874     /**
875      * Get content of uploaded file.
876      *
877      * @param string $elname name of file upload element
878      * @return string|bool false in case of failure, string if ok
879      */
880     function get_file_content($elname) {
881         global $USER;
883         if (!$this->is_submitted() or !$this->is_validated()) {
884             return false;
885         }
887         $element = $this->_form->getElement($elname);
889         if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
890             $values = $this->_form->exportValues($elname);
891             if (empty($values[$elname])) {
892                 return false;
893             }
894             $draftid = $values[$elname];
895             $fs = get_file_storage();
896             $context = context_user::instance($USER->id);
897             if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
898                 return false;
899             }
900             $file = reset($files);
902             return $file->get_content();
904         } else if (isset($_FILES[$elname])) {
905             return file_get_contents($_FILES[$elname]['tmp_name']);
906         }
908         return false;
909     }
911     /**
912      * Print html form.
913      */
914     function display() {
915         //finalize the form definition if not yet done
916         if (!$this->_definition_finalized) {
917             $this->_definition_finalized = true;
918             $this->definition_after_data();
919         }
921         $this->_form->display();
922     }
924     /**
925      * Renders the html form (same as display, but returns the result).
926      *
927      * Note that you can only output this rendered result once per page, as
928      * it contains IDs which must be unique.
929      *
930      * @return string HTML code for the form
931      */
932     public function render() {
933         ob_start();
934         $this->display();
935         $out = ob_get_contents();
936         ob_end_clean();
937         return $out;
938     }
940     /**
941      * Form definition. Abstract method - always override!
942      */
943     protected abstract function definition();
945     /**
946      * Dummy stub method - override if you need to setup the form depending on current
947      * values. This method is called after definition(), data submission and set_data().
948      * All form setup that is dependent on form values should go in here.
949      */
950     function definition_after_data(){
951     }
953     /**
954      * Dummy stub method - override if you needed to perform some extra validation.
955      * If there are errors return array of errors ("fieldname"=>"error message"),
956      * otherwise true if ok.
957      *
958      * Server side rules do not work for uploaded files, implement serverside rules here if needed.
959      *
960      * @param array $data array of ("fieldname"=>value) of submitted data
961      * @param array $files array of uploaded files "element_name"=>tmp_file_path
962      * @return array of "element_name"=>"error_description" if there are errors,
963      *         or an empty array if everything is OK (true allowed for backwards compatibility too).
964      */
965     function validation($data, $files) {
966         return array();
967     }
969     /**
970      * Helper used by {@link repeat_elements()}.
971      *
972      * @param int $i the index of this element.
973      * @param HTML_QuickForm_element $elementclone
974      * @param array $namecloned array of names
975      */
976     function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
977         $name = $elementclone->getName();
978         $namecloned[] = $name;
980         if (!empty($name)) {
981             $elementclone->setName($name."[$i]");
982         }
984         if (is_a($elementclone, 'HTML_QuickForm_header')) {
985             $value = $elementclone->_text;
986             $elementclone->setValue(str_replace('{no}', ($i+1), $value));
988         } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
989             $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
991         } else {
992             $value=$elementclone->getLabel();
993             $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
994         }
995     }
997     /**
998      * Method to add a repeating group of elements to a form.
999      *
1000      * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1001      * @param int $repeats no of times to repeat elements initially
1002      * @param array $options a nested array. The first array key is the element name.
1003      *    the second array key is the type of option to set, and depend on that option,
1004      *    the value takes different forms.
1005      *         'default'    - default value to set. Can include '{no}' which is replaced by the repeat number.
1006      *         'type'       - PARAM_* type.
1007      *         'helpbutton' - array containing the helpbutton params.
1008      *         'disabledif' - array containing the disabledIf() arguments after the element name.
1009      *         'rule'       - array containing the addRule arguments after the element name.
1010      *         'expanded'   - whether this section of the form should be expanded by default. (Name be a header element.)
1011      *         'advanced'   - whether this element is hidden by 'Show more ...'.
1012      * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1013      * @param string $addfieldsname name for button to add more fields
1014      * @param int $addfieldsno how many fields to add at a time
1015      * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1016      * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1017      * @return int no of repeats of element in this page
1018      */
1019     function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1020             $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1021         if ($addstring===null){
1022             $addstring = get_string('addfields', 'form', $addfieldsno);
1023         } else {
1024             $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1025         }
1026         $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1027         $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1028         if (!empty($addfields)){
1029             $repeats += $addfieldsno;
1030         }
1031         $mform =& $this->_form;
1032         $mform->registerNoSubmitButton($addfieldsname);
1033         $mform->addElement('hidden', $repeathiddenname, $repeats);
1034         $mform->setType($repeathiddenname, PARAM_INT);
1035         //value not to be overridden by submitted value
1036         $mform->setConstants(array($repeathiddenname=>$repeats));
1037         $namecloned = array();
1038         for ($i = 0; $i < $repeats; $i++) {
1039             foreach ($elementobjs as $elementobj){
1040                 $elementclone = fullclone($elementobj);
1041                 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1043                 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1044                     foreach ($elementclone->getElements() as $el) {
1045                         $this->repeat_elements_fix_clone($i, $el, $namecloned);
1046                     }
1047                     $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1048                 }
1050                 $mform->addElement($elementclone);
1051             }
1052         }
1053         for ($i=0; $i<$repeats; $i++) {
1054             foreach ($options as $elementname => $elementoptions){
1055                 $pos=strpos($elementname, '[');
1056                 if ($pos!==FALSE){
1057                     $realelementname = substr($elementname, 0, $pos)."[$i]";
1058                     $realelementname .= substr($elementname, $pos);
1059                 }else {
1060                     $realelementname = $elementname."[$i]";
1061                 }
1062                 foreach ($elementoptions as  $option => $params){
1064                     switch ($option){
1065                         case 'default' :
1066                             $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1067                             break;
1068                         case 'helpbutton' :
1069                             $params = array_merge(array($realelementname), $params);
1070                             call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1071                             break;
1072                         case 'disabledif' :
1073                             foreach ($namecloned as $num => $name){
1074                                 if ($params[0] == $name){
1075                                     $params[0] = $params[0]."[$i]";
1076                                     break;
1077                                 }
1078                             }
1079                             $params = array_merge(array($realelementname), $params);
1080                             call_user_func_array(array(&$mform, 'disabledIf'), $params);
1081                             break;
1082                         case 'rule' :
1083                             if (is_string($params)){
1084                                 $params = array(null, $params, null, 'client');
1085                             }
1086                             $params = array_merge(array($realelementname), $params);
1087                             call_user_func_array(array(&$mform, 'addRule'), $params);
1088                             break;
1090                         case 'type':
1091                             $mform->setType($realelementname, $params);
1092                             break;
1094                         case 'expanded':
1095                             $mform->setExpanded($realelementname, $params);
1096                             break;
1098                         case 'advanced' :
1099                             $mform->setAdvanced($realelementname, $params);
1100                             break;
1101                     }
1102                 }
1103             }
1104         }
1105         $mform->addElement('submit', $addfieldsname, $addstring);
1107         if (!$addbuttoninside) {
1108             $mform->closeHeaderBefore($addfieldsname);
1109         }
1111         return $repeats;
1112     }
1114     /**
1115      * Adds a link/button that controls the checked state of a group of checkboxes.
1116      *
1117      * @param int $groupid The id of the group of advcheckboxes this element controls
1118      * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1119      * @param array $attributes associative array of HTML attributes
1120      * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1121      */
1122     function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1123         global $CFG, $PAGE;
1125         // Name of the controller button
1126         $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1127         $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1128         $checkboxgroupclass = 'checkboxgroup'.$groupid;
1130         // Set the default text if none was specified
1131         if (empty($text)) {
1132             $text = get_string('selectallornone', 'form');
1133         }
1135         $mform = $this->_form;
1136         $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1137         $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1139         $newselectvalue = $selectvalue;
1140         if (is_null($selectvalue)) {
1141             $newselectvalue = $originalValue;
1142         } else if (!is_null($contollerbutton)) {
1143             $newselectvalue = (int) !$selectvalue;
1144         }
1145         // set checkbox state depending on orignal/submitted value by controoler button
1146         if (!is_null($contollerbutton) || is_null($selectvalue)) {
1147             foreach ($mform->_elements as $element) {
1148                 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1149                         $element->getAttribute('class') == $checkboxgroupclass &&
1150                         !$element->isFrozen()) {
1151                     $mform->setConstants(array($element->getName() => $newselectvalue));
1152                 }
1153             }
1154         }
1156         $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1157         $mform->setType($checkboxcontrollerparam, PARAM_INT);
1158         $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1160         $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1161                 array(
1162                     array('groupid' => $groupid,
1163                         'checkboxclass' => $checkboxgroupclass,
1164                         'checkboxcontroller' => $checkboxcontrollerparam,
1165                         'controllerbutton' => $checkboxcontrollername)
1166                     )
1167                 );
1169         require_once("$CFG->libdir/form/submit.php");
1170         $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1171         $mform->addElement($submitlink);
1172         $mform->registerNoSubmitButton($checkboxcontrollername);
1173         $mform->setDefault($checkboxcontrollername, $text);
1174     }
1176     /**
1177      * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1178      * if you don't want a cancel button in your form. If you have a cancel button make sure you
1179      * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1180      * get data with get_data().
1181      *
1182      * @param bool $cancel whether to show cancel button, default true
1183      * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1184      */
1185     function add_action_buttons($cancel = true, $submitlabel=null){
1186         if (is_null($submitlabel)){
1187             $submitlabel = get_string('savechanges');
1188         }
1189         $mform =& $this->_form;
1190         if ($cancel){
1191             //when two elements we need a group
1192             $buttonarray=array();
1193             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1194             $buttonarray[] = &$mform->createElement('cancel');
1195             $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1196             $mform->closeHeaderBefore('buttonar');
1197         } else {
1198             //no group needed
1199             $mform->addElement('submit', 'submitbutton', $submitlabel);
1200             $mform->closeHeaderBefore('submitbutton');
1201         }
1202     }
1204     /**
1205      * Adds an initialisation call for a standard JavaScript enhancement.
1206      *
1207      * This function is designed to add an initialisation call for a JavaScript
1208      * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1209      *
1210      * Current options:
1211      *  - Selectboxes
1212      *      - smartselect:  Turns a nbsp indented select box into a custom drop down
1213      *                      control that supports multilevel and category selection.
1214      *                      $enhancement = 'smartselect';
1215      *                      $options = array('selectablecategories' => true|false)
1216      *
1217      * @since Moodle 2.0
1218      * @param string|element $element form element for which Javascript needs to be initalized
1219      * @param string $enhancement which init function should be called
1220      * @param array $options options passed to javascript
1221      * @param array $strings strings for javascript
1222      */
1223     function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1224         global $PAGE;
1225         if (is_string($element)) {
1226             $element = $this->_form->getElement($element);
1227         }
1228         if (is_object($element)) {
1229             $element->_generateId();
1230             $elementid = $element->getAttribute('id');
1231             $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1232             if (is_array($strings)) {
1233                 foreach ($strings as $string) {
1234                     if (is_array($string)) {
1235                         call_user_method_array('string_for_js', $PAGE->requires, $string);
1236                     } else {
1237                         $PAGE->requires->string_for_js($string, 'moodle');
1238                     }
1239                 }
1240             }
1241         }
1242     }
1244     /**
1245      * Returns a JS module definition for the mforms JS
1246      *
1247      * @return array
1248      */
1249     public static function get_js_module() {
1250         global $CFG;
1251         return array(
1252             'name' => 'mform',
1253             'fullpath' => '/lib/form/form.js',
1254             'requires' => array('base', 'node')
1255         );
1256     }
1258     /**
1259      * Detects elements with missing setType() declerations.
1260      *
1261      * Finds elements in the form which should a PARAM_ type set and throws a
1262      * developer debug warning for any elements without it. This is to reduce the
1263      * risk of potential security issues by developers mistakenly forgetting to set
1264      * the type.
1265      *
1266      * @return void
1267      */
1268     private function detectMissingSetType() {
1269         global $CFG;
1271         if (!$CFG->debugdeveloper) {
1272             // Only for devs.
1273             return;
1274         }
1276         $mform = $this->_form;
1277         foreach ($mform->_elements as $element) {
1278             $group = false;
1279             $elements = array($element);
1281             if ($element->getType() == 'group') {
1282                 $group = $element;
1283                 $elements = $element->getElements();
1284             }
1286             foreach ($elements as $index => $element) {
1287                 switch ($element->getType()) {
1288                     case 'hidden':
1289                     case 'text':
1290                     case 'url':
1291                         if ($group) {
1292                             $name = $group->getElementName($index);
1293                         } else {
1294                             $name = $element->getName();
1295                         }
1296                         $key = $name;
1297                         $found = array_key_exists($key, $mform->_types);
1298                         // For repeated elements we need to look for
1299                         // the "main" type, not for the one present
1300                         // on each repetition. All the stuff in formslib
1301                         // (repeat_elements(), updateSubmission()... seems
1302                         // to work that way.
1303                         while (!$found && strrpos($key, '[') !== false) {
1304                             $pos = strrpos($key, '[');
1305                             $key = substr($key, 0, $pos);
1306                             $found = array_key_exists($key, $mform->_types);
1307                         }
1308                         if (!$found) {
1309                             debugging("Did you remember to call setType() for '$name'? ".
1310                                 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1311                         }
1312                         break;
1313                 }
1314             }
1315         }
1316     }
1318     /**
1319      * Used by tests to simulate submitted form data submission from the user.
1320      *
1321      * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1322      * get_data.
1323      *
1324      * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1325      * global arrays after each test.
1326      *
1327      * @param array  $simulatedsubmitteddata       An associative array of form values (same format as $_POST).
1328      * @param array  $simulatedsubmittedfiles      An associative array of files uploaded (same format as $_FILES). Can be omitted.
1329      * @param string $method                       'post' or 'get', defaults to 'post'.
1330      * @param null   $formidentifier               the default is to use the class name for this class but you may need to provide
1331      *                                              a different value here for some forms that are used more than once on the
1332      *                                              same page.
1333      */
1334     public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1335                                        $formidentifier = null) {
1336         $_FILES = $simulatedsubmittedfiles;
1337         if ($formidentifier === null) {
1338             $formidentifier = get_called_class();
1339         }
1340         $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1341         $simulatedsubmitteddata['sesskey'] = sesskey();
1342         if (strtolower($method) === 'get') {
1343             $_GET = $simulatedsubmitteddata;
1344         } else {
1345             $_POST = $simulatedsubmitteddata;
1346         }
1347     }
1350 /**
1351  * MoodleQuickForm implementation
1352  *
1353  * You never extend this class directly. The class methods of this class are available from
1354  * the private $this->_form property on moodleform and its children. You generally only
1355  * call methods on this class from within abstract methods that you override on moodleform such
1356  * as definition and definition_after_data
1357  *
1358  * @package   core_form
1359  * @category  form
1360  * @copyright 2006 Jamie Pratt <me@jamiep.org>
1361  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1362  */
1363 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1364     /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1365     var $_types = array();
1367     /** @var array dependent state for the element/'s */
1368     var $_dependencies = array();
1370     /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1371     var $_noSubmitButtons=array();
1373     /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1374     var $_cancelButtons=array();
1376     /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1377     var $_advancedElements = array();
1379     /**
1380      * Array whose keys are element names and values are the desired collapsible state.
1381      * True for collapsed, False for expanded. If not present, set to default in
1382      * {@link self::accept()}.
1383      *
1384      * @var array
1385      */
1386     var $_collapsibleElements = array();
1388     /**
1389      * Whether to enable shortforms for this form
1390      *
1391      * @var boolean
1392      */
1393     var $_disableShortforms = false;
1395     /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1396     protected $_use_form_change_checker = true;
1398     /**
1399      * The form name is derived from the class name of the wrapper minus the trailing form
1400      * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1401      * @var string
1402      */
1403     var $_formName = '';
1405     /**
1406      * String with the html for hidden params passed in as part of a moodle_url
1407      * object for the action. Output in the form.
1408      * @var string
1409      */
1410     var $_pageparams = '';
1412     /**
1413      * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1414      *
1415      * @staticvar int $formcounter counts number of forms
1416      * @param string $formName Form's name.
1417      * @param string $method Form's method defaults to 'POST'
1418      * @param string|moodle_url $action Form's action
1419      * @param string $target (optional)Form's target defaults to none
1420      * @param mixed $attributes (optional)Extra attributes for <form> tag
1421      */
1422     function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1423         global $CFG, $OUTPUT;
1425         static $formcounter = 1;
1427         HTML_Common::HTML_Common($attributes);
1428         $target = empty($target) ? array() : array('target' => $target);
1429         $this->_formName = $formName;
1430         if (is_a($action, 'moodle_url')){
1431             $this->_pageparams = html_writer::input_hidden_params($action);
1432             $action = $action->out_omit_querystring();
1433         } else {
1434             $this->_pageparams = '';
1435         }
1436         // No 'name' atttribute for form in xhtml strict :
1437         $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1438         if (is_null($this->getAttribute('id'))) {
1439             $attributes['id'] = 'mform' . $formcounter;
1440         }
1441         $formcounter++;
1442         $this->updateAttributes($attributes);
1444         // This is custom stuff for Moodle :
1445         $oldclass=   $this->getAttribute('class');
1446         if (!empty($oldclass)){
1447             $this->updateAttributes(array('class'=>$oldclass.' mform'));
1448         }else {
1449             $this->updateAttributes(array('class'=>'mform'));
1450         }
1451         $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1452         $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1453         $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1454     }
1456     /**
1457      * Use this method to indicate an element in a form is an advanced field. If items in a form
1458      * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1459      * form so the user can decide whether to display advanced form controls.
1460      *
1461      * If you set a header element to advanced then all elements it contains will also be set as advanced.
1462      *
1463      * @param string $elementName group or element name (not the element name of something inside a group).
1464      * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1465      */
1466     function setAdvanced($elementName, $advanced = true) {
1467         if ($advanced){
1468             $this->_advancedElements[$elementName]='';
1469         } elseif (isset($this->_advancedElements[$elementName])) {
1470             unset($this->_advancedElements[$elementName]);
1471         }
1472     }
1474     /**
1475      * Use this method to indicate that the fieldset should be shown as expanded.
1476      * The method is applicable to header elements only.
1477      *
1478      * @param string $headername header element name
1479      * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1480      * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1481      *                                 the form was submitted.
1482      * @return void
1483      */
1484     function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1485         if (empty($headername)) {
1486             return;
1487         }
1488         $element = $this->getElement($headername);
1489         if ($element->getType() != 'header') {
1490             debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1491             return;
1492         }
1493         if (!$headerid = $element->getAttribute('id')) {
1494             $element->_generateId();
1495             $headerid = $element->getAttribute('id');
1496         }
1497         if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1498             // See if the form has been submitted already.
1499             $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1500             if (!$ignoreuserstate && $formexpanded != -1) {
1501                 // Override expanded state with the form variable.
1502                 $expanded = $formexpanded;
1503             }
1504             // Create the form element for storing expanded state.
1505             $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1506             $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1507             $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1508         }
1509         $this->_collapsibleElements[$headername] = !$expanded;
1510     }
1512     /**
1513      * Use this method to add show more/less status element required for passing
1514      * over the advanced elements visibility status on the form submission.
1515      *
1516      * @param string $headerName header element name.
1517      * @param boolean $showmore default false sets the advanced elements to be hidden.
1518      */
1519     function addAdvancedStatusElement($headerid, $showmore=false){
1520         // Add extra hidden element to store advanced items state for each section.
1521         if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1522             // See if we the form has been submitted already.
1523             $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1524             if (!$showmore && $formshowmore != -1) {
1525                 // Override showmore state with the form variable.
1526                 $showmore = $formshowmore;
1527             }
1528             // Create the form element for storing advanced items state.
1529             $this->addElement('hidden', 'mform_showmore_' . $headerid);
1530             $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1531             $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1532         }
1533     }
1535     /**
1536      * This function has been deprecated. Show advanced has been replaced by
1537      * "Show more.../Show less..." in the shortforms javascript module.
1538      *
1539      * @deprecated since Moodle 2.5
1540      * @param bool $showadvancedNow if true will show advanced elements.
1541       */
1542     function setShowAdvanced($showadvancedNow = null){
1543         debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1544     }
1546     /**
1547      * This function has been deprecated. Show advanced has been replaced by
1548      * "Show more.../Show less..." in the shortforms javascript module.
1549      *
1550      * @deprecated since Moodle 2.5
1551      * @return bool (Always false)
1552       */
1553     function getShowAdvanced(){
1554         debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1555         return false;
1556     }
1558     /**
1559      * Use this method to indicate that the form will not be using shortforms.
1560      *
1561      * @param boolean $disable default true, controls if the shortforms are disabled.
1562      */
1563     function setDisableShortforms ($disable = true) {
1564         $this->_disableShortforms = $disable;
1565     }
1567     /**
1568      * Call this method if you don't want the formchangechecker JavaScript to be
1569      * automatically initialised for this form.
1570      */
1571     public function disable_form_change_checker() {
1572         $this->_use_form_change_checker = false;
1573     }
1575     /**
1576      * If you have called {@link disable_form_change_checker()} then you can use
1577      * this method to re-enable it. It is enabled by default, so normally you don't
1578      * need to call this.
1579      */
1580     public function enable_form_change_checker() {
1581         $this->_use_form_change_checker = true;
1582     }
1584     /**
1585      * @return bool whether this form should automatically initialise
1586      *      formchangechecker for itself.
1587      */
1588     public function is_form_change_checker_enabled() {
1589         return $this->_use_form_change_checker;
1590     }
1592     /**
1593     * Accepts a renderer
1594     *
1595     * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1596     */
1597     function accept(&$renderer) {
1598         if (method_exists($renderer, 'setAdvancedElements')){
1599             //Check for visible fieldsets where all elements are advanced
1600             //and mark these headers as advanced as well.
1601             //Also mark all elements in a advanced header as advanced.
1602             $stopFields = $renderer->getStopFieldSetElements();
1603             $lastHeader = null;
1604             $lastHeaderAdvanced = false;
1605             $anyAdvanced = false;
1606             $anyError = false;
1607             foreach (array_keys($this->_elements) as $elementIndex){
1608                 $element =& $this->_elements[$elementIndex];
1610                 // if closing header and any contained element was advanced then mark it as advanced
1611                 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1612                     if ($anyAdvanced && !is_null($lastHeader)) {
1613                         $lastHeader->_generateId();
1614                         $this->setAdvanced($lastHeader->getName());
1615                         $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1616                     }
1617                     $lastHeaderAdvanced = false;
1618                     unset($lastHeader);
1619                     $lastHeader = null;
1620                 } elseif ($lastHeaderAdvanced) {
1621                     $this->setAdvanced($element->getName());
1622                 }
1624                 if ($element->getType()=='header'){
1625                     $lastHeader =& $element;
1626                     $anyAdvanced = false;
1627                     $anyError = false;
1628                     $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1629                 } elseif (isset($this->_advancedElements[$element->getName()])){
1630                     $anyAdvanced = true;
1631                     if (isset($this->_errors[$element->getName()])) {
1632                         $anyError = true;
1633                     }
1634                 }
1635             }
1636             // the last header may not be closed yet...
1637             if ($anyAdvanced && !is_null($lastHeader)){
1638                 $this->setAdvanced($lastHeader->getName());
1639                 $lastHeader->_generateId();
1640                 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1641             }
1642             $renderer->setAdvancedElements($this->_advancedElements);
1643         }
1644         if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1646             // Count the number of sections.
1647             $headerscount = 0;
1648             foreach (array_keys($this->_elements) as $elementIndex){
1649                 $element =& $this->_elements[$elementIndex];
1650                 if ($element->getType() == 'header') {
1651                     $headerscount++;
1652                 }
1653             }
1655             $anyrequiredorerror = false;
1656             $headercounter = 0;
1657             $headername = null;
1658             foreach (array_keys($this->_elements) as $elementIndex){
1659                 $element =& $this->_elements[$elementIndex];
1661                 if ($element->getType() == 'header') {
1662                     $headercounter++;
1663                     $element->_generateId();
1664                     $headername = $element->getName();
1665                     $anyrequiredorerror = false;
1666                 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1667                     $anyrequiredorerror = true;
1668                 } else {
1669                     // Do not reset $anyrequiredorerror to false because we do not want any other element
1670                     // in this header (fieldset) to possibly revert the state given.
1671                 }
1673                 if ($element->getType() == 'header') {
1674                     if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1675                         // By default the first section is always expanded, except if a state has already been set.
1676                         $this->setExpanded($headername, true);
1677                     } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1678                         // The second section is always expanded if the form only contains 2 sections),
1679                         // except if a state has already been set.
1680                         $this->setExpanded($headername, true);
1681                     }
1682                 } else if ($anyrequiredorerror) {
1683                     // If any error or required field are present within the header, we need to expand it.
1684                     $this->setExpanded($headername, true, true);
1685                 } else if (!isset($this->_collapsibleElements[$headername])) {
1686                     // Define element as collapsed by default.
1687                     $this->setExpanded($headername, false);
1688                 }
1689             }
1691             // Pass the array to renderer object.
1692             $renderer->setCollapsibleElements($this->_collapsibleElements);
1693         }
1694         parent::accept($renderer);
1695     }
1697     /**
1698      * Adds one or more element names that indicate the end of a fieldset
1699      *
1700      * @param string $elementName name of the element
1701      */
1702     function closeHeaderBefore($elementName){
1703         $renderer =& $this->defaultRenderer();
1704         $renderer->addStopFieldsetElements($elementName);
1705     }
1707     /**
1708      * Should be used for all elements of a form except for select, radio and checkboxes which
1709      * clean their own data.
1710      *
1711      * @param string $elementname
1712      * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1713      *        {@link lib/moodlelib.php} for defined parameter types
1714      */
1715     function setType($elementname, $paramtype) {
1716         $this->_types[$elementname] = $paramtype;
1717     }
1719     /**
1720      * This can be used to set several types at once.
1721      *
1722      * @param array $paramtypes types of parameters.
1723      * @see MoodleQuickForm::setType
1724      */
1725     function setTypes($paramtypes) {
1726         $this->_types = $paramtypes + $this->_types;
1727     }
1729     /**
1730      * Return the type(s) to use to clean an element.
1731      *
1732      * In the case where the element has an array as a value, we will try to obtain a
1733      * type defined for that specific key, and recursively until done.
1734      *
1735      * This method does not work reverse, you cannot pass a nested element and hoping to
1736      * fallback on the clean type of a parent. This method intends to be used with the
1737      * main element, which will generate child types if needed, not the other way around.
1738      *
1739      * Example scenario:
1740      *
1741      * You have defined a new repeated element containing a text field called 'foo'.
1742      * By default there will always be 2 occurence of 'foo' in the form. Even though
1743      * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1744      * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1745      * $mform->setType('foo[0]', PARAM_FLOAT).
1746      *
1747      * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1748      * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1749      * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1750      * get the default clean type returned (param $default).
1751      *
1752      * @param string $elementname name of the element.
1753      * @param mixed $value value that should be cleaned.
1754      * @param int $default default constant value to be returned (PARAM_...)
1755      * @return string|array constant value or array of constant values (PARAM_...)
1756      */
1757     public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1758         $type = $default;
1759         if (array_key_exists($elementname, $this->_types)) {
1760             $type = $this->_types[$elementname];
1761         }
1762         if (is_array($value)) {
1763             $default = $type;
1764             $type = array();
1765             foreach ($value as $subkey => $subvalue) {
1766                 $typekey = "$elementname" . "[$subkey]";
1767                 if (array_key_exists($typekey, $this->_types)) {
1768                     $subtype = $this->_types[$typekey];
1769                 } else {
1770                     $subtype = $default;
1771                 }
1772                 if (is_array($subvalue)) {
1773                     $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1774                 } else {
1775                     $type[$subkey] = $subtype;
1776                 }
1777             }
1778         }
1779         return $type;
1780     }
1782     /**
1783      * Return the cleaned value using the passed type(s).
1784      *
1785      * @param mixed $value value that has to be cleaned.
1786      * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1787      * @return mixed cleaned up value.
1788      */
1789     public function getCleanedValue($value, $type) {
1790         if (is_array($type) && is_array($value)) {
1791             foreach ($type as $key => $param) {
1792                 $value[$key] = $this->getCleanedValue($value[$key], $param);
1793             }
1794         } else if (!is_array($type) && !is_array($value)) {
1795             $value = clean_param($value, $type);
1796         } else if (!is_array($type) && is_array($value)) {
1797             $value = clean_param_array($value, $type, true);
1798         } else {
1799             throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1800         }
1801         return $value;
1802     }
1804     /**
1805      * Updates submitted values
1806      *
1807      * @param array $submission submitted values
1808      * @param array $files list of files
1809      */
1810     function updateSubmission($submission, $files) {
1811         $this->_flagSubmitted = false;
1813         if (empty($submission)) {
1814             $this->_submitValues = array();
1815         } else {
1816             foreach ($submission as $key => $s) {
1817                 $type = $this->getCleanType($key, $s);
1818                 $submission[$key] = $this->getCleanedValue($s, $type);
1819             }
1820             $this->_submitValues = $submission;
1821             $this->_flagSubmitted = true;
1822         }
1824         if (empty($files)) {
1825             $this->_submitFiles = array();
1826         } else {
1827             $this->_submitFiles = $files;
1828             $this->_flagSubmitted = true;
1829         }
1831         // need to tell all elements that they need to update their value attribute.
1832          foreach (array_keys($this->_elements) as $key) {
1833              $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1834          }
1835     }
1837     /**
1838      * Returns HTML for required elements
1839      *
1840      * @return string
1841      */
1842     function getReqHTML(){
1843         return $this->_reqHTML;
1844     }
1846     /**
1847      * Returns HTML for advanced elements
1848      *
1849      * @return string
1850      */
1851     function getAdvancedHTML(){
1852         return $this->_advancedHTML;
1853     }
1855     /**
1856      * Initializes a default form value. Used to specify the default for a new entry where
1857      * no data is loaded in using moodleform::set_data()
1858      *
1859      * note: $slashed param removed
1860      *
1861      * @param string $elementName element name
1862      * @param mixed $defaultValue values for that element name
1863      */
1864     function setDefault($elementName, $defaultValue){
1865         $this->setDefaults(array($elementName=>$defaultValue));
1866     }
1868     /**
1869      * Add a help button to element, only one button per element is allowed.
1870      *
1871      * This is new, simplified and preferable method of setting a help icon on form elements.
1872      * It uses the new $OUTPUT->help_icon().
1873      *
1874      * Typically, you will provide the same identifier and the component as you have used for the
1875      * label of the element. The string identifier with the _help suffix added is then used
1876      * as the help string.
1877      *
1878      * There has to be two strings defined:
1879      *   1/ get_string($identifier, $component) - the title of the help page
1880      *   2/ get_string($identifier.'_help', $component) - the actual help page text
1881      *
1882      * @since Moodle 2.0
1883      * @param string $elementname name of the element to add the item to
1884      * @param string $identifier help string identifier without _help suffix
1885      * @param string $component component name to look the help string in
1886      * @param string $linktext optional text to display next to the icon
1887      * @param bool $suppresscheck set to true if the element may not exist
1888      */
1889     function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1890         global $OUTPUT;
1891         if (array_key_exists($elementname, $this->_elementIndex)) {
1892             $element = $this->_elements[$this->_elementIndex[$elementname]];
1893             $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1894         } else if (!$suppresscheck) {
1895             debugging(get_string('nonexistentformelements', 'form', $elementname));
1896         }
1897     }
1899     /**
1900      * Set constant value not overridden by _POST or _GET
1901      * note: this does not work for complex names with [] :-(
1902      *
1903      * @param string $elname name of element
1904      * @param mixed $value
1905      */
1906     function setConstant($elname, $value) {
1907         $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1908         $element =& $this->getElement($elname);
1909         $element->onQuickFormEvent('updateValue', null, $this);
1910     }
1912     /**
1913      * export submitted values
1914      *
1915      * @param string $elementList list of elements in form
1916      * @return array
1917      */
1918     function exportValues($elementList = null){
1919         $unfiltered = array();
1920         if (null === $elementList) {
1921             // iterate over all elements, calling their exportValue() methods
1922             foreach (array_keys($this->_elements) as $key) {
1923                 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1924                     $varname = $this->_elements[$key]->_attributes['name'];
1925                     $value = '';
1926                     // If we have a default value then export it.
1927                     if (isset($this->_defaultValues[$varname])) {
1928                         $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
1929                     }
1930                 } else {
1931                     $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1932                 }
1934                 if (is_array($value)) {
1935                     // This shit throws a bogus warning in PHP 4.3.x
1936                     $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1937                 }
1938             }
1939         } else {
1940             if (!is_array($elementList)) {
1941                 $elementList = array_map('trim', explode(',', $elementList));
1942             }
1943             foreach ($elementList as $elementName) {
1944                 $value = $this->exportValue($elementName);
1945                 if (@PEAR::isError($value)) {
1946                     return $value;
1947                 }
1948                 //oh, stock QuickFOrm was returning array of arrays!
1949                 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1950             }
1951         }
1953         if (is_array($this->_constantValues)) {
1954             $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1955         }
1956         return $unfiltered;
1957     }
1959     /**
1960      * This is a bit of a hack, and it duplicates the code in
1961      * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
1962      * reliably calling that code. (Think about date selectors, for example.)
1963      * @param string $name the element name.
1964      * @param mixed $value the fixed value to set.
1965      * @return mixed the appropriate array to add to the $unfiltered array.
1966      */
1967     protected function prepare_fixed_value($name, $value) {
1968         if (null === $value) {
1969             return null;
1970         } else {
1971             if (!strpos($name, '[')) {
1972                 return array($name => $value);
1973             } else {
1974                 $valueAry = array();
1975                 $myIndex  = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
1976                 eval("\$valueAry$myIndex = \$value;");
1977                 return $valueAry;
1978             }
1979         }
1980     }
1982     /**
1983      * Adds a validation rule for the given field
1984      *
1985      * If the element is in fact a group, it will be considered as a whole.
1986      * To validate grouped elements as separated entities,
1987      * use addGroupRule instead of addRule.
1988      *
1989      * @param string $element Form element name
1990      * @param string $message Message to display for invalid data
1991      * @param string $type Rule type, use getRegisteredRules() to get types
1992      * @param string $format (optional)Required for extra rule data
1993      * @param string $validation (optional)Where to perform validation: "server", "client"
1994      * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1995      * @param bool $force Force the rule to be applied, even if the target form element does not exist
1996      */
1997     function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1998     {
1999         parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2000         if ($validation == 'client') {
2001             $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2002         }
2004     }
2006     /**
2007      * Adds a validation rule for the given group of elements
2008      *
2009      * Only groups with a name can be assigned a validation rule
2010      * Use addGroupRule when you need to validate elements inside the group.
2011      * Use addRule if you need to validate the group as a whole. In this case,
2012      * the same rule will be applied to all elements in the group.
2013      * Use addRule if you need to validate the group against a function.
2014      *
2015      * @param string $group Form group name
2016      * @param array|string $arg1 Array for multiple elements or error message string for one element
2017      * @param string $type (optional)Rule type use getRegisteredRules() to get types
2018      * @param string $format (optional)Required for extra rule data
2019      * @param int $howmany (optional)How many valid elements should be in the group
2020      * @param string $validation (optional)Where to perform validation: "server", "client"
2021      * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2022      */
2023     function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2024     {
2025         parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2026         if (is_array($arg1)) {
2027              foreach ($arg1 as $rules) {
2028                 foreach ($rules as $rule) {
2029                     $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2031                     if ('client' == $validation) {
2032                         $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2033                     }
2034                 }
2035             }
2036         } elseif (is_string($arg1)) {
2038             if ($validation == 'client') {
2039                 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2040             }
2041         }
2042     }
2044     /**
2045      * Returns the client side validation script
2046      *
2047      * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from  HTML_QuickForm
2048      * and slightly modified to run rules per-element
2049      * Needed to override this because of an error with client side validation of grouped elements.
2050      *
2051      * @return string Javascript to perform validation, empty string if no 'client' rules were added
2052      */
2053     function getValidationScript()
2054     {
2055         if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
2056             return '';
2057         }
2059         include_once('HTML/QuickForm/RuleRegistry.php');
2060         $registry =& HTML_QuickForm_RuleRegistry::singleton();
2061         $test = array();
2062         $js_escape = array(
2063             "\r"    => '\r',
2064             "\n"    => '\n',
2065             "\t"    => '\t',
2066             "'"     => "\\'",
2067             '"'     => '\"',
2068             '\\'    => '\\\\'
2069         );
2071         foreach ($this->_rules as $elementName => $rules) {
2072             foreach ($rules as $rule) {
2073                 if ('client' == $rule['validation']) {
2074                     unset($element); //TODO: find out how to properly initialize it
2076                     $dependent  = isset($rule['dependent']) && is_array($rule['dependent']);
2077                     $rule['message'] = strtr($rule['message'], $js_escape);
2079                     if (isset($rule['group'])) {
2080                         $group    =& $this->getElement($rule['group']);
2081                         // No JavaScript validation for frozen elements
2082                         if ($group->isFrozen()) {
2083                             continue 2;
2084                         }
2085                         $elements =& $group->getElements();
2086                         foreach (array_keys($elements) as $key) {
2087                             if ($elementName == $group->getElementName($key)) {
2088                                 $element =& $elements[$key];
2089                                 break;
2090                             }
2091                         }
2092                     } elseif ($dependent) {
2093                         $element   =  array();
2094                         $element[] =& $this->getElement($elementName);
2095                         foreach ($rule['dependent'] as $elName) {
2096                             $element[] =& $this->getElement($elName);
2097                         }
2098                     } else {
2099                         $element =& $this->getElement($elementName);
2100                     }
2101                     // No JavaScript validation for frozen elements
2102                     if (is_object($element) && $element->isFrozen()) {
2103                         continue 2;
2104                     } elseif (is_array($element)) {
2105                         foreach (array_keys($element) as $key) {
2106                             if ($element[$key]->isFrozen()) {
2107                                 continue 3;
2108                             }
2109                         }
2110                     }
2111                     //for editor element, [text] is appended to the name.
2112                     $fullelementname = $elementName;
2113                     if ($element->getType() == 'editor') {
2114                         $fullelementname .= '[text]';
2115                         //Add format to rule as moodleform check which format is supported by browser
2116                         //it is not set anywhere... So small hack to make sure we pass it down to quickform
2117                         if (is_null($rule['format'])) {
2118                             $rule['format'] = $element->getFormat();
2119                         }
2120                     }
2121                     // Fix for bug displaying errors for elements in a group
2122                     $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2123                     $test[$fullelementname][1]=$element;
2124                     //end of fix
2125                 }
2126             }
2127         }
2129         // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2130         // the form, and then that form field gets corrupted by the code that follows.
2131         unset($element);
2133         $js = '
2134 <script type="text/javascript">
2135 //<![CDATA[
2137 var skipClientValidation = false;
2139 function qf_errorHandler(element, _qfMsg) {
2140   div = element.parentNode;
2142   if ((div == undefined) || (element.name == undefined)) {
2143     //no checking can be done for undefined elements so let server handle it.
2144     return true;
2145   }
2147   if (_qfMsg != \'\') {
2148     var errorSpan = document.getElementById(\'id_error_\'+element.name);
2149     if (!errorSpan) {
2150       errorSpan = document.createElement("span");
2151       errorSpan.id = \'id_error_\'+element.name;
2152       errorSpan.className = "error";
2153       element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2154       document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2155       document.getElementById(errorSpan.id).focus();
2156     }
2158     while (errorSpan.firstChild) {
2159       errorSpan.removeChild(errorSpan.firstChild);
2160     }
2162     errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2164     if (div.className.substr(div.className.length - 6, 6) != " error"
2165       && div.className != "error") {
2166         div.className += " error";
2167         linebreak = document.createElement("br");
2168         linebreak.className = "error";
2169         linebreak.id = \'id_error_break_\'+element.name;
2170         errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2171     }
2173     return false;
2174   } else {
2175     var errorSpan = document.getElementById(\'id_error_\'+element.name);
2176     if (errorSpan) {
2177       errorSpan.parentNode.removeChild(errorSpan);
2178     }
2179     var linebreak = document.getElementById(\'id_error_break_\'+element.name);
2180     if (linebreak) {
2181       linebreak.parentNode.removeChild(linebreak);
2182     }
2184     if (div.className.substr(div.className.length - 6, 6) == " error") {
2185       div.className = div.className.substr(0, div.className.length - 6);
2186     } else if (div.className == "error") {
2187       div.className = "";
2188     }
2190     return true;
2191   }
2192 }';
2193         $validateJS = '';
2194         foreach ($test as $elementName => $jsandelement) {
2195             // Fix for bug displaying errors for elements in a group
2196             //unset($element);
2197             list($jsArr,$element)=$jsandelement;
2198             //end of fix
2199             $escapedElementName = preg_replace_callback(
2200                 '/[_\[\]-]/',
2201                 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2202                 $elementName);
2203             $js .= '
2204 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
2205   if (undefined == element) {
2206      //required element was not found, then let form be submitted without client side validation
2207      return true;
2208   }
2209   var value = \'\';
2210   var errFlag = new Array();
2211   var _qfGroups = {};
2212   var _qfMsg = \'\';
2213   var frm = element.parentNode;
2214   if ((undefined != element.name) && (frm != undefined)) {
2215       while (frm && frm.nodeName.toUpperCase() != "FORM") {
2216         frm = frm.parentNode;
2217       }
2218     ' . join("\n", $jsArr) . '
2219       return qf_errorHandler(element, _qfMsg);
2220   } else {
2221     //element name should be defined else error msg will not be displayed.
2222     return true;
2223   }
2225 ';
2226             $validateJS .= '
2227   ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
2228   if (!ret && !first_focus) {
2229     first_focus = true;
2230     document.getElementById(\'id_error_'.$elementName.'\').focus();
2231   }
2232 ';
2234             // Fix for bug displaying errors for elements in a group
2235             //unset($element);
2236             //$element =& $this->getElement($elementName);
2237             //end of fix
2238             $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
2239             $onBlur = $element->getAttribute('onBlur');
2240             $onChange = $element->getAttribute('onChange');
2241             $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2242                                              'onChange' => $onChange . $valFunc));
2243         }
2244 //  do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2245         $js .= '
2246 function validate_' . $this->_formName . '(frm) {
2247   if (skipClientValidation) {
2248      return true;
2249   }
2250   var ret = true;
2252   var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2253   var first_focus = false;
2254 ' . $validateJS . ';
2255   return ret;
2257 //]]>
2258 </script>';
2259         return $js;
2260     } // end func getValidationScript
2262     /**
2263      * Sets default error message
2264      */
2265     function _setDefaultRuleMessages(){
2266         foreach ($this->_rules as $field => $rulesarr){
2267             foreach ($rulesarr as $key => $rule){
2268                 if ($rule['message']===null){
2269                     $a=new stdClass();
2270                     $a->format=$rule['format'];
2271                     $str=get_string('err_'.$rule['type'], 'form', $a);
2272                     if (strpos($str, '[[')!==0){
2273                         $this->_rules[$field][$key]['message']=$str;
2274                     }
2275                 }
2276             }
2277         }
2278     }
2280     /**
2281      * Get list of attributes which have dependencies
2282      *
2283      * @return array
2284      */
2285     function getLockOptionObject(){
2286         $result = array();
2287         foreach ($this->_dependencies as $dependentOn => $conditions){
2288             $result[$dependentOn] = array();
2289             foreach ($conditions as $condition=>$values) {
2290                 $result[$dependentOn][$condition] = array();
2291                 foreach ($values as $value=>$dependents) {
2292                     $result[$dependentOn][$condition][$value] = array();
2293                     $i = 0;
2294                     foreach ($dependents as $dependent) {
2295                         $elements = $this->_getElNamesRecursive($dependent);
2296                         if (empty($elements)) {
2297                             // probably element inside of some group
2298                             $elements = array($dependent);
2299                         }
2300                         foreach($elements as $element) {
2301                             if ($element == $dependentOn) {
2302                                 continue;
2303                             }
2304                             $result[$dependentOn][$condition][$value][] = $element;
2305                         }
2306                     }
2307                 }
2308             }
2309         }
2310         return array($this->getAttribute('id'), $result);
2311     }
2313     /**
2314      * Get names of element or elements in a group.
2315      *
2316      * @param HTML_QuickForm_group|element $element element group or element object
2317      * @return array
2318      */
2319     function _getElNamesRecursive($element) {
2320         if (is_string($element)) {
2321             if (!$this->elementExists($element)) {
2322                 return array();
2323             }
2324             $element = $this->getElement($element);
2325         }
2327         if (is_a($element, 'HTML_QuickForm_group')) {
2328             $elsInGroup = $element->getElements();
2329             $elNames = array();
2330             foreach ($elsInGroup as $elInGroup){
2331                 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2332                     // not sure if this would work - groups nested in groups
2333                     $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2334                 } else {
2335                     $elNames[] = $element->getElementName($elInGroup->getName());
2336                 }
2337             }
2339         } else if (is_a($element, 'HTML_QuickForm_header')) {
2340             return array();
2342         } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2343             return array();
2345         } else if (method_exists($element, 'getPrivateName') &&
2346                 !($element instanceof HTML_QuickForm_advcheckbox)) {
2347             // The advcheckbox element implements a method called getPrivateName,
2348             // but in a way that is not compatible with the generic API, so we
2349             // have to explicitly exclude it.
2350             return array($element->getPrivateName());
2352         } else {
2353             $elNames = array($element->getName());
2354         }
2356         return $elNames;
2357     }
2359     /**
2360      * Adds a dependency for $elementName which will be disabled if $condition is met.
2361      * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2362      * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2363      * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2364      * of the $dependentOn element is $condition (such as equal) to $value.
2365      *
2366      * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2367      * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2368      * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2369      *
2370      * @param string $elementName the name of the element which will be disabled
2371      * @param string $dependentOn the name of the element whose state will be checked for condition
2372      * @param string $condition the condition to check
2373      * @param mixed $value used in conjunction with condition.
2374      */
2375     function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2376         // Multiple selects allow for a multiple selection, we transform the array to string here as
2377         // an array cannot be used as a key in an associative array.
2378         if (is_array($value)) {
2379             $value = implode('|', $value);
2380         }
2381         if (!array_key_exists($dependentOn, $this->_dependencies)) {
2382             $this->_dependencies[$dependentOn] = array();
2383         }
2384         if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2385             $this->_dependencies[$dependentOn][$condition] = array();
2386         }
2387         if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2388             $this->_dependencies[$dependentOn][$condition][$value] = array();
2389         }
2390         $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2391     }
2393     /**
2394      * Registers button as no submit button
2395      *
2396      * @param string $buttonname name of the button
2397      */
2398     function registerNoSubmitButton($buttonname){
2399         $this->_noSubmitButtons[]=$buttonname;
2400     }
2402     /**
2403      * Checks if button is a no submit button, i.e it doesn't submit form
2404      *
2405      * @param string $buttonname name of the button to check
2406      * @return bool
2407      */
2408     function isNoSubmitButton($buttonname){
2409         return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2410     }
2412     /**
2413      * Registers a button as cancel button
2414      *
2415      * @param string $addfieldsname name of the button
2416      */
2417     function _registerCancelButton($addfieldsname){
2418         $this->_cancelButtons[]=$addfieldsname;
2419     }
2421     /**
2422      * Displays elements without HTML input tags.
2423      * This method is different to freeze() in that it makes sure no hidden
2424      * elements are included in the form.
2425      * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2426      *
2427      * This function also removes all previously defined rules.
2428      *
2429      * @param string|array $elementList array or string of element(s) to be frozen
2430      * @return object|bool if element list is not empty then return error object, else true
2431      */
2432     function hardFreeze($elementList=null)
2433     {
2434         if (!isset($elementList)) {
2435             $this->_freezeAll = true;
2436             $elementList = array();
2437         } else {
2438             if (!is_array($elementList)) {
2439                 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2440             }
2441             $elementList = array_flip($elementList);
2442         }
2444         foreach (array_keys($this->_elements) as $key) {
2445             $name = $this->_elements[$key]->getName();
2446             if ($this->_freezeAll || isset($elementList[$name])) {
2447                 $this->_elements[$key]->freeze();
2448                 $this->_elements[$key]->setPersistantFreeze(false);
2449                 unset($elementList[$name]);
2451                 // remove all rules
2452                 $this->_rules[$name] = array();
2453                 // if field is required, remove the rule
2454                 $unset = array_search($name, $this->_required);
2455                 if ($unset !== false) {
2456                     unset($this->_required[$unset]);
2457                 }
2458             }
2459         }
2461         if (!empty($elementList)) {
2462             return self::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
2463         }
2464         return true;
2465     }
2467     /**
2468      * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2469      *
2470      * This function also removes all previously defined rules of elements it freezes.
2471      *
2472      * @throws HTML_QuickForm_Error
2473      * @param array $elementList array or string of element(s) not to be frozen
2474      * @return bool returns true
2475      */
2476     function hardFreezeAllVisibleExcept($elementList)
2477     {
2478         $elementList = array_flip($elementList);
2479         foreach (array_keys($this->_elements) as $key) {
2480             $name = $this->_elements[$key]->getName();
2481             $type = $this->_elements[$key]->getType();
2483             if ($type == 'hidden'){
2484                 // leave hidden types as they are
2485             } elseif (!isset($elementList[$name])) {
2486                 $this->_elements[$key]->freeze();
2487                 $this->_elements[$key]->setPersistantFreeze(false);
2489                 // remove all rules
2490                 $this->_rules[$name] = array();
2491                 // if field is required, remove the rule
2492                 $unset = array_search($name, $this->_required);
2493                 if ($unset !== false) {
2494                     unset($this->_required[$unset]);
2495                 }
2496             }
2497         }
2498         return true;
2499     }
2501    /**
2502     * Tells whether the form was already submitted
2503     *
2504     * This is useful since the _submitFiles and _submitValues arrays
2505     * may be completely empty after the trackSubmit value is removed.
2506     *
2507     * @return bool
2508     */
2509     function isSubmitted()
2510     {
2511         return parent::isSubmitted() && (!$this->isFrozen());
2512     }
2515 /**
2516  * MoodleQuickForm renderer
2517  *
2518  * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2519  * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2520  *
2521  * Stylesheet is part of standard theme and should be automatically included.
2522  *
2523  * @package   core_form
2524  * @copyright 2007 Jamie Pratt <me@jamiep.org>
2525  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2526  */
2527 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2529     /** @var array Element template array */
2530     var $_elementTemplates;
2532     /**
2533      * Template used when opening a hidden fieldset
2534      * (i.e. a fieldset that is opened when there is no header element)
2535      * @var string
2536      */
2537     var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2539     /** @var string Header Template string */
2540     var $_headerTemplate =
2541        "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2543     /** @var string Template used when opening a fieldset */
2544     var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2546     /** @var string Template used when closing a fieldset */
2547     var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2549     /** @var string Required Note template string */
2550     var $_requiredNoteTemplate =
2551         "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2553     /**
2554      * Collapsible buttons string template.
2555      *
2556      * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2557      * until the Javascript has been fully loaded.
2558      *
2559      * @var string
2560      */
2561     var $_collapseButtonsTemplate =
2562         "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2564     /**
2565      * Array whose keys are element names. If the key exists this is a advanced element
2566      *
2567      * @var array
2568      */
2569     var $_advancedElements = array();
2571     /**
2572      * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2573      *
2574      * @var array
2575      */
2576     var $_collapsibleElements = array();
2578     /**
2579      * @var string Contains the collapsible buttons to add to the form.
2580      */
2581     var $_collapseButtons = '';
2583     /**
2584      * Constructor
2585      */
2586     function MoodleQuickForm_Renderer(){
2587         // switch next two lines for ol li containers for form items.
2588         //        $this->_elementTemplates=array('default'=>"\n\t\t".'<li class="fitem"><label>{label}{help}<!-- BEGIN required -->{req}<!-- END required --></label><div class="qfelement<!-- BEGIN error --> error<!-- END error --> {type}"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></li>');
2589         $this->_elementTemplates = array(
2590         'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}" {aria-live}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
2592         'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2594         'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2596         'static'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
2598         'warning'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}">{element}</div>',
2600         'nodisplay'=>'');
2602         parent::HTML_QuickForm_Renderer_Tableless();
2603     }
2605     /**
2606      * Set element's as adavance element
2607      *
2608      * @param array $elements form elements which needs to be grouped as advance elements.
2609      */
2610     function setAdvancedElements($elements){
2611         $this->_advancedElements = $elements;
2612     }
2614     /**
2615      * Setting collapsible elements
2616      *
2617      * @param array $elements
2618      */
2619     function setCollapsibleElements($elements) {
2620         $this->_collapsibleElements = $elements;
2621     }
2623     /**
2624      * What to do when starting the form
2625      *
2626      * @param MoodleQuickForm $form reference of the form
2627      */
2628     function startForm(&$form){
2629         global $PAGE;
2630         $this->_reqHTML = $form->getReqHTML();
2631         $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2632         $this->_advancedHTML = $form->getAdvancedHTML();
2633         $this->_collapseButtons = '';
2634         $formid = $form->getAttribute('id');
2635         parent::startForm($form);
2636         if ($form->isFrozen()){
2637             $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2638         } else {
2639             $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2640             $this->_hiddenHtml .= $form->_pageparams;
2641         }
2643         if ($form->is_form_change_checker_enabled()) {
2644             $PAGE->requires->yui_module('moodle-core-formchangechecker',
2645                     'M.core_formchangechecker.init',
2646                     array(array(
2647                         'formid' => $formid
2648                     ))
2649             );
2650             $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2651         }
2652         if (!empty($this->_collapsibleElements)) {
2653             if (count($this->_collapsibleElements) > 1) {
2654                 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2655                 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2656                 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2657             }
2658             $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2659         }
2660         if (!empty($this->_advancedElements)){
2661             $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2662             $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2663         }
2664     }
2666     /**
2667      * Create advance group of elements
2668      *
2669      * @param object $group Passed by reference
2670      * @param bool $required if input is required field
2671      * @param string $error error message to display
2672      */
2673     function startGroup(&$group, $required, $error){
2674         // Make sure the element has an id.
2675         $group->_generateId();
2677         if (method_exists($group, 'getElementTemplateType')){
2678             $html = $this->_elementTemplates[$group->getElementTemplateType()];
2679         }else{
2680             $html = $this->_elementTemplates['default'];
2682         }
2684         if (isset($this->_advancedElements[$group->getName()])){
2685             $html =str_replace(' {advanced}', ' advanced', $html);
2686             $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2687         } else {
2688             $html =str_replace(' {advanced}', '', $html);
2689             $html =str_replace('{advancedimg}', '', $html);
2690         }
2691         if (method_exists($group, 'getHelpButton')){
2692             $html =str_replace('{help}', $group->getHelpButton(), $html);
2693         }else{
2694             $html =str_replace('{help}', '', $html);
2695         }
2696         $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2697         $html =str_replace('{name}', $group->getName(), $html);
2698         $html =str_replace('{type}', 'fgroup', $html);
2699         $emptylabel = '';
2700         if ($group->getLabel() == '') {
2701             $emptylabel = 'femptylabel';
2702         }
2703         $html = str_replace('{emptylabel}', $emptylabel, $html);
2705         $this->_templates[$group->getName()]=$html;
2706         // Fix for bug in tableless quickforms that didn't allow you to stop a
2707         // fieldset before a group of elements.
2708         // if the element name indicates the end of a fieldset, close the fieldset
2709         if (   in_array($group->getName(), $this->_stopFieldsetElements)
2710             && $this->_fieldsetsOpen > 0
2711            ) {
2712             $this->_html .= $this->_closeFieldsetTemplate;
2713             $this->_fieldsetsOpen--;
2714         }
2715         parent::startGroup($group, $required, $error);
2716     }
2718     /**
2719      * Renders element
2720      *
2721      * @param HTML_QuickForm_element $element element
2722      * @param bool $required if input is required field
2723      * @param string $error error message to display
2724      */
2725     function renderElement(&$element, $required, $error){
2726         // Make sure the element has an id.
2727         $element->_generateId();
2729         //adding stuff to place holders in template
2730         //check if this is a group element first
2731         if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2732             // so it gets substitutions for *each* element
2733             $html = $this->_groupElementTemplate;
2734         }
2735         elseif (method_exists($element, 'getElementTemplateType')){
2736             $html = $this->_elementTemplates[$element->getElementTemplateType()];
2737         }else{
2738             $html = $this->_elementTemplates['default'];
2739         }
2740         if (isset($this->_advancedElements[$element->getName()])){
2741             $html = str_replace(' {advanced}', ' advanced', $html);
2742             $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2743         } else {
2744             $html = str_replace(' {advanced}', '', $html);
2745             $html = str_replace(' {aria-live}', '', $html);
2746         }
2747         if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2748             $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2749         } else {
2750             $html =str_replace('{advancedimg}', '', $html);
2751         }
2752         $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2753         $html =str_replace('{type}', 'f'.$element->getType(), $html);
2754         $html =str_replace('{name}', $element->getName(), $html);
2755         $emptylabel = '';
2756         if ($element->getLabel() == '') {
2757             $emptylabel = 'femptylabel';
2758         }
2759         $html = str_replace('{emptylabel}', $emptylabel, $html);
2760         if (method_exists($element, 'getHelpButton')){
2761             $html = str_replace('{help}', $element->getHelpButton(), $html);
2762         }else{
2763             $html = str_replace('{help}', '', $html);
2765         }
2766         if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2767             $this->_groupElementTemplate = $html;
2768         }
2769         elseif (!isset($this->_templates[$element->getName()])) {
2770             $this->_templates[$element->getName()] = $html;
2771         }
2773         parent::renderElement($element, $required, $error);
2774     }
2776     /**
2777      * Called when visiting a form, after processing all form elements
2778      * Adds required note, form attributes, validation javascript and form content.
2779      *
2780      * @global moodle_page $PAGE
2781      * @param moodleform $form Passed by reference
2782      */
2783     function finishForm(&$form){
2784         global $PAGE;
2785         if ($form->isFrozen()){
2786             $this->_hiddenHtml = '';
2787         }
2788         parent::finishForm($form);
2789         $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2790         if (!$form->isFrozen()) {
2791             $args = $form->getLockOptionObject();
2792             if (count($args[1]) > 0) {
2793                 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2794             }
2795         }
2796     }
2797    /**
2798     * Called when visiting a header element
2799     *
2800     * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2801     * @global moodle_page $PAGE
2802     */
2803     function renderHeader(&$header) {
2804         global $PAGE;
2806         $header->_generateId();
2807         $name = $header->getName();
2809         $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2810         if (is_null($header->_text)) {
2811             $header_html = '';
2812         } elseif (!empty($name) && isset($this->_templates[$name])) {
2813             $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2814         } else {
2815             $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2816         }
2818         if ($this->_fieldsetsOpen > 0) {
2819             $this->_html .= $this->_closeFieldsetTemplate;
2820             $this->_fieldsetsOpen--;
2821         }
2823         // Define collapsible classes for fieldsets.
2824         $arialive = '';
2825         $fieldsetclasses = array('clearfix');
2826         if (isset($this->_collapsibleElements[$header->getName()])) {
2827             $fieldsetclasses[] = 'collapsible';
2828             if ($this->_collapsibleElements[$header->getName()]) {
2829                 $fieldsetclasses[] = 'collapsed';
2830             }
2831         }
2833         if (isset($this->_advancedElements[$name])){
2834             $fieldsetclasses[] = 'containsadvancedelements';
2835         }
2837         $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2838         $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
2840         $this->_html .= $openFieldsetTemplate . $header_html;
2841         $this->_fieldsetsOpen++;
2842     }
2844     /**
2845      * Return Array of element names that indicate the end of a fieldset
2846      *
2847      * @return array
2848      */
2849     function getStopFieldsetElements(){
2850         return $this->_stopFieldsetElements;
2851     }
2854 /**
2855  * Required elements validation
2856  *
2857  * This class overrides QuickForm validation since it allowed space or empty tag as a value
2858  *
2859  * @package   core_form
2860  * @category  form
2861  * @copyright 2006 Jamie Pratt <me@jamiep.org>
2862  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2863  */
2864 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2865     /**
2866      * Checks if an element is not empty.
2867      * This is a server-side validation, it works for both text fields and editor fields
2868      *
2869      * @param string $value Value to check
2870      * @param int|string|array $options Not used yet
2871      * @return bool true if value is not empty
2872      */
2873     function validate($value, $options = null) {
2874         global $CFG;
2875         if (is_array($value) && array_key_exists('text', $value)) {
2876             $value = $value['text'];
2877         }
2878         if (is_array($value)) {
2879             // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2880             $value = implode('', $value);
2881         }
2882         $stripvalues = array(
2883             '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2884             '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
2885         );
2886         if (!empty($CFG->strictformsrequired)) {
2887             $value = preg_replace($stripvalues, '', (string)$value);
2888         }
2889         if ((string)$value == '') {
2890             return false;
2891         }
2892         return true;
2893     }
2895     /**
2896      * This function returns Javascript code used to build client-side validation.
2897      * It checks if an element is not empty.
2898      *
2899      * @param int $format format of data which needs to be validated.
2900      * @return array
2901      */
2902     function getValidationScript($format = null) {
2903         global $CFG;
2904         if (!empty($CFG->strictformsrequired)) {
2905             if (!empty($format) && $format == FORMAT_HTML) {
2906                 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2907             } else {
2908                 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2909             }
2910         } else {
2911             return array('', "{jsVar} == ''");
2912         }
2913     }
2916 /**
2917  * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2918  * @name $_HTML_QuickForm_default_renderer
2919  */
2920 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2922 /** Please keep this list in alphabetical order. */
2923 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2924 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2925 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2926 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2927 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2928 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2929 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2930 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2931 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2932 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2933 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2934 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2935 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2936 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2937 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2938 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2939 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
2940 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2941 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2942 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2943 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2944 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2945 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2946 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2947 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2948 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2949 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2950 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2951 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2952 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2953 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2954 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2955 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2956 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2957 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2958 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2960 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");