Merge branch 'MDL-30839-master' of git://github.com/phalacee/moodle
[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 = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
268         }
270         // following trick is needed to enable proper sesskey checks when using GET forms
271         // the _qf__.$this->_formname serves as a marker that form was actually submitted
272         if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
273             if (!confirm_sesskey()) {
274                 print_error('invalidsesskey');
275             }
276             $files = $_FILES;
277         } else {
278             $submission = array();
279             $files = array();
280         }
281         $this->detectMissingSetType();
283         $this->_form->updateSubmission($submission, $files);
284     }
286     /**
287      * Internal method. Validates all old-style deprecated uploaded files.
288      * The new way is to upload files via repository api.
289      *
290      * @param array $files list of files to be validated
291      * @return bool|array Success or an array of errors
292      */
293     function _validate_files(&$files) {
294         global $CFG, $COURSE;
296         $files = array();
298         if (empty($_FILES)) {
299             // we do not need to do any checks because no files were submitted
300             // note: server side rules do not work for files - use custom verification in validate() instead
301             return true;
302         }
304         $errors = array();
305         $filenames = array();
307         // now check that we really want each file
308         foreach ($_FILES as $elname=>$file) {
309             $required = $this->_form->isElementRequired($elname);
311             if ($file['error'] == 4 and $file['size'] == 0) {
312                 if ($required) {
313                     $errors[$elname] = get_string('required');
314                 }
315                 unset($_FILES[$elname]);
316                 continue;
317             }
319             if (!empty($file['error'])) {
320                 $errors[$elname] = file_get_upload_error($file['error']);
321                 unset($_FILES[$elname]);
322                 continue;
323             }
325             if (!is_uploaded_file($file['tmp_name'])) {
326                 // TODO: improve error message
327                 $errors[$elname] = get_string('error');
328                 unset($_FILES[$elname]);
329                 continue;
330             }
332             if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
333                 // hmm, this file was not requested
334                 unset($_FILES[$elname]);
335                 continue;
336             }
338 /*
339   // TODO: rethink the file scanning MDL-19380
340             if ($CFG->runclamonupload) {
341                 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
342                     $errors[$elname] = $_FILES[$elname]['uploadlog'];
343                     unset($_FILES[$elname]);
344                     continue;
345                 }
346             }
347 */
348             $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
349             if ($filename === '') {
350                 // TODO: improve error message - wrong chars
351                 $errors[$elname] = get_string('error');
352                 unset($_FILES[$elname]);
353                 continue;
354             }
355             if (in_array($filename, $filenames)) {
356                 // TODO: improve error message - duplicate name
357                 $errors[$elname] = get_string('error');
358                 unset($_FILES[$elname]);
359                 continue;
360             }
361             $filenames[] = $filename;
362             $_FILES[$elname]['name'] = $filename;
364             $files[$elname] = $_FILES[$elname]['tmp_name'];
365         }
367         // return errors if found
368         if (count($errors) == 0){
369             return true;
371         } else {
372             $files = array();
373             return $errors;
374         }
375     }
377     /**
378      * Internal method. Validates filepicker and filemanager files if they are
379      * set as required fields. Also, sets the error message if encountered one.
380      *
381      * @return bool|array with errors
382      */
383     protected function validate_draft_files() {
384         global $USER;
385         $mform =& $this->_form;
387         $errors = array();
388         //Go through all the required elements and make sure you hit filepicker or
389         //filemanager element.
390         foreach ($mform->_rules as $elementname => $rules) {
391             $elementtype = $mform->getElementType($elementname);
392             //If element is of type filepicker then do validation
393             if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
394                 //Check if rule defined is required rule
395                 foreach ($rules as $rule) {
396                     if ($rule['type'] == 'required') {
397                         $draftid = (int)$mform->getSubmitValue($elementname);
398                         $fs = get_file_storage();
399                         $context = context_user::instance($USER->id);
400                         if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
401                             $errors[$elementname] = $rule['message'];
402                         }
403                     }
404                 }
405             }
406         }
407         // Check all the filemanager elements to make sure they do not have too many
408         // files in them.
409         foreach ($mform->_elements as $element) {
410             if ($element->_type == 'filemanager') {
411                 $maxfiles = $element->getMaxfiles();
412                 if ($maxfiles > 0) {
413                     $draftid = (int)$element->getValue();
414                     $fs = get_file_storage();
415                     $context = context_user::instance($USER->id);
416                     $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
417                     if (count($files) > $maxfiles) {
418                         $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
419                     }
420                 }
421             }
422         }
423         if (empty($errors)) {
424             return true;
425         } else {
426             return $errors;
427         }
428     }
430     /**
431      * Load in existing data as form defaults. Usually new entry defaults are stored directly in
432      * form definition (new entry form); this function is used to load in data where values
433      * already exist and data is being edited (edit entry form).
434      *
435      * note: $slashed param removed
436      *
437      * @param stdClass|array $default_values object or array of default values
438      */
439     function set_data($default_values) {
440         if (is_object($default_values)) {
441             $default_values = (array)$default_values;
442         }
443         $this->_form->setDefaults($default_values);
444     }
446     /**
447      * Check that form was submitted. Does not check validity of submitted data.
448      *
449      * @return bool true if form properly submitted
450      */
451     function is_submitted() {
452         return $this->_form->isSubmitted();
453     }
455     /**
456      * Checks if button pressed is not for submitting the form
457      *
458      * @staticvar bool $nosubmit keeps track of no submit button
459      * @return bool
460      */
461     function no_submit_button_pressed(){
462         static $nosubmit = null; // one check is enough
463         if (!is_null($nosubmit)){
464             return $nosubmit;
465         }
466         $mform =& $this->_form;
467         $nosubmit = false;
468         if (!$this->is_submitted()){
469             return false;
470         }
471         foreach ($mform->_noSubmitButtons as $nosubmitbutton){
472             if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
473                 $nosubmit = true;
474                 break;
475             }
476         }
477         return $nosubmit;
478     }
481     /**
482      * Check that form data is valid.
483      * You should almost always use this, rather than {@link validate_defined_fields}
484      *
485      * @return bool true if form data valid
486      */
487     function is_validated() {
488         //finalize the form definition before any processing
489         if (!$this->_definition_finalized) {
490             $this->_definition_finalized = true;
491             $this->definition_after_data();
492         }
494         return $this->validate_defined_fields();
495     }
497     /**
498      * Validate the form.
499      *
500      * You almost always want to call {@link is_validated} instead of this
501      * because it calls {@link definition_after_data} first, before validating the form,
502      * which is what you want in 99% of cases.
503      *
504      * This is provided as a separate function for those special cases where
505      * you want the form validated before definition_after_data is called
506      * for example, to selectively add new elements depending on a no_submit_button press,
507      * but only when the form is valid when the no_submit_button is pressed,
508      *
509      * @param bool $validateonnosubmit optional, defaults to false.  The default behaviour
510      *             is NOT to validate the form when a no submit button has been pressed.
511      *             pass true here to override this behaviour
512      *
513      * @return bool true if form data valid
514      */
515     function validate_defined_fields($validateonnosubmit=false) {
516         static $validated = null; // one validation is enough
517         $mform =& $this->_form;
518         if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
519             return false;
520         } elseif ($validated === null) {
521             $internal_val = $mform->validate();
523             $files = array();
524             $file_val = $this->_validate_files($files);
525             //check draft files for validation and flag them if required files
526             //are not in draft area.
527             $draftfilevalue = $this->validate_draft_files();
529             if ($file_val !== true && $draftfilevalue !== true) {
530                 $file_val = array_merge($file_val, $draftfilevalue);
531             } else if ($draftfilevalue !== true) {
532                 $file_val = $draftfilevalue;
533             } //default is file_val, so no need to assign.
535             if ($file_val !== true) {
536                 if (!empty($file_val)) {
537                     foreach ($file_val as $element=>$msg) {
538                         $mform->setElementError($element, $msg);
539                     }
540                 }
541                 $file_val = false;
542             }
544             $data = $mform->exportValues();
545             $moodle_val = $this->validation($data, $files);
546             if ((is_array($moodle_val) && count($moodle_val)!==0)) {
547                 // non-empty array means errors
548                 foreach ($moodle_val as $element=>$msg) {
549                     $mform->setElementError($element, $msg);
550                 }
551                 $moodle_val = false;
553             } else {
554                 // anything else means validation ok
555                 $moodle_val = true;
556             }
558             $validated = ($internal_val and $moodle_val and $file_val);
559         }
560         return $validated;
561     }
563     /**
564      * Return true if a cancel button has been pressed resulting in the form being submitted.
565      *
566      * @return bool true if a cancel button has been pressed
567      */
568     function is_cancelled(){
569         $mform =& $this->_form;
570         if ($mform->isSubmitted()){
571             foreach ($mform->_cancelButtons as $cancelbutton){
572                 if (optional_param($cancelbutton, 0, PARAM_RAW)){
573                     return true;
574                 }
575             }
576         }
577         return false;
578     }
580     /**
581      * Return submitted data if properly submitted or returns NULL if validation fails or
582      * if there is no submitted data.
583      *
584      * note: $slashed param removed
585      *
586      * @return object submitted data; NULL if not valid or not submitted or cancelled
587      */
588     function get_data() {
589         $mform =& $this->_form;
591         if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
592             $data = $mform->exportValues();
593             unset($data['sesskey']); // we do not need to return sesskey
594             unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
595             if (empty($data)) {
596                 return NULL;
597             } else {
598                 return (object)$data;
599             }
600         } else {
601             return NULL;
602         }
603     }
605     /**
606      * Return submitted data without validation or NULL if there is no submitted data.
607      * note: $slashed param removed
608      *
609      * @return object submitted data; NULL if not submitted
610      */
611     function get_submitted_data() {
612         $mform =& $this->_form;
614         if ($this->is_submitted()) {
615             $data = $mform->exportValues();
616             unset($data['sesskey']); // we do not need to return sesskey
617             unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
618             if (empty($data)) {
619                 return NULL;
620             } else {
621                 return (object)$data;
622             }
623         } else {
624             return NULL;
625         }
626     }
628     /**
629      * Save verified uploaded files into directory. Upload process can be customised from definition()
630      *
631      * @deprecated since Moodle 2.0
632      * @todo MDL-31294 remove this api
633      * @see moodleform::save_stored_file()
634      * @see moodleform::save_file()
635      * @param string $destination path where file should be stored
636      * @return bool Always false
637      */
638     function save_files($destination) {
639         debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
640         return false;
641     }
643     /**
644      * Returns name of uploaded file.
645      *
646      * @param string $elname first element if null
647      * @return string|bool false in case of failure, string if ok
648      */
649     function get_new_filename($elname=null) {
650         global $USER;
652         if (!$this->is_submitted() or !$this->is_validated()) {
653             return false;
654         }
656         if (is_null($elname)) {
657             if (empty($_FILES)) {
658                 return false;
659             }
660             reset($_FILES);
661             $elname = key($_FILES);
662         }
664         if (empty($elname)) {
665             return false;
666         }
668         $element = $this->_form->getElement($elname);
670         if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
671             $values = $this->_form->exportValues($elname);
672             if (empty($values[$elname])) {
673                 return false;
674             }
675             $draftid = $values[$elname];
676             $fs = get_file_storage();
677             $context = context_user::instance($USER->id);
678             if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
679                 return false;
680             }
681             $file = reset($files);
682             return $file->get_filename();
683         }
685         if (!isset($_FILES[$elname])) {
686             return false;
687         }
689         return $_FILES[$elname]['name'];
690     }
692     /**
693      * Save file to standard filesystem
694      *
695      * @param string $elname name of element
696      * @param string $pathname full path name of file
697      * @param bool $override override file if exists
698      * @return bool success
699      */
700     function save_file($elname, $pathname, $override=false) {
701         global $USER;
703         if (!$this->is_submitted() or !$this->is_validated()) {
704             return false;
705         }
706         if (file_exists($pathname)) {
707             if ($override) {
708                 if (!@unlink($pathname)) {
709                     return false;
710                 }
711             } else {
712                 return false;
713             }
714         }
716         $element = $this->_form->getElement($elname);
718         if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
719             $values = $this->_form->exportValues($elname);
720             if (empty($values[$elname])) {
721                 return false;
722             }
723             $draftid = $values[$elname];
724             $fs = get_file_storage();
725             $context = context_user::instance($USER->id);
726             if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
727                 return false;
728             }
729             $file = reset($files);
731             return $file->copy_content_to($pathname);
733         } else if (isset($_FILES[$elname])) {
734             return copy($_FILES[$elname]['tmp_name'], $pathname);
735         }
737         return false;
738     }
740     /**
741      * Returns a temporary file, do not forget to delete after not needed any more.
742      *
743      * @param string $elname name of the elmenet
744      * @return string|bool either string or false
745      */
746     function save_temp_file($elname) {
747         if (!$this->get_new_filename($elname)) {
748             return false;
749         }
750         if (!$dir = make_temp_directory('forms')) {
751             return false;
752         }
753         if (!$tempfile = tempnam($dir, 'tempup_')) {
754             return false;
755         }
756         if (!$this->save_file($elname, $tempfile, true)) {
757             // something went wrong
758             @unlink($tempfile);
759             return false;
760         }
762         return $tempfile;
763     }
765     /**
766      * Get draft files of a form element
767      * This is a protected method which will be used only inside moodleforms
768      *
769      * @param string $elname name of element
770      * @return array|bool|null
771      */
772     protected function get_draft_files($elname) {
773         global $USER;
775         if (!$this->is_submitted()) {
776             return false;
777         }
779         $element = $this->_form->getElement($elname);
781         if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
782             $values = $this->_form->exportValues($elname);
783             if (empty($values[$elname])) {
784                 return false;
785             }
786             $draftid = $values[$elname];
787             $fs = get_file_storage();
788             $context = context_user::instance($USER->id);
789             if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
790                 return null;
791             }
792             return $files;
793         }
794         return null;
795     }
797     /**
798      * Save file to local filesystem pool
799      *
800      * @param string $elname name of element
801      * @param int $newcontextid id of context
802      * @param string $newcomponent name of the component
803      * @param string $newfilearea name of file area
804      * @param int $newitemid item id
805      * @param string $newfilepath path of file where it get stored
806      * @param string $newfilename use specified filename, if not specified name of uploaded file used
807      * @param bool $overwrite overwrite file if exists
808      * @param int $newuserid new userid if required
809      * @return mixed stored_file object or false if error; may throw exception if duplicate found
810      */
811     function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
812                               $newfilename=null, $overwrite=false, $newuserid=null) {
813         global $USER;
815         if (!$this->is_submitted() or !$this->is_validated()) {
816             return false;
817         }
819         if (empty($newuserid)) {
820             $newuserid = $USER->id;
821         }
823         $element = $this->_form->getElement($elname);
824         $fs = get_file_storage();
826         if ($element instanceof MoodleQuickForm_filepicker) {
827             $values = $this->_form->exportValues($elname);
828             if (empty($values[$elname])) {
829                 return false;
830             }
831             $draftid = $values[$elname];
832             $context = context_user::instance($USER->id);
833             if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
834                 return false;
835             }
836             $file = reset($files);
837             if (is_null($newfilename)) {
838                 $newfilename = $file->get_filename();
839             }
841             if ($overwrite) {
842                 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
843                     if (!$oldfile->delete()) {
844                         return false;
845                     }
846                 }
847             }
849             $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
850                                  'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
851             return $fs->create_file_from_storedfile($file_record, $file);
853         } else if (isset($_FILES[$elname])) {
854             $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
856             if ($overwrite) {
857                 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
858                     if (!$oldfile->delete()) {
859                         return false;
860                     }
861                 }
862             }
864             $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
865                                  'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
866             return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
867         }
869         return false;
870     }
872     /**
873      * Get content of uploaded file.
874      *
875      * @param string $elname name of file upload element
876      * @return string|bool false in case of failure, string if ok
877      */
878     function get_file_content($elname) {
879         global $USER;
881         if (!$this->is_submitted() or !$this->is_validated()) {
882             return false;
883         }
885         $element = $this->_form->getElement($elname);
887         if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
888             $values = $this->_form->exportValues($elname);
889             if (empty($values[$elname])) {
890                 return false;
891             }
892             $draftid = $values[$elname];
893             $fs = get_file_storage();
894             $context = context_user::instance($USER->id);
895             if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
896                 return false;
897             }
898             $file = reset($files);
900             return $file->get_content();
902         } else if (isset($_FILES[$elname])) {
903             return file_get_contents($_FILES[$elname]['tmp_name']);
904         }
906         return false;
907     }
909     /**
910      * Print html form.
911      */
912     function display() {
913         //finalize the form definition if not yet done
914         if (!$this->_definition_finalized) {
915             $this->_definition_finalized = true;
916             $this->definition_after_data();
917         }
919         $this->_form->display();
920     }
922     /**
923      * Renders the html form (same as display, but returns the result).
924      *
925      * Note that you can only output this rendered result once per page, as
926      * it contains IDs which must be unique.
927      *
928      * @return string HTML code for the form
929      */
930     public function render() {
931         ob_start();
932         $this->display();
933         $out = ob_get_contents();
934         ob_end_clean();
935         return $out;
936     }
938     /**
939      * Form definition. Abstract method - always override!
940      */
941     protected abstract function definition();
943     /**
944      * Dummy stub method - override if you need to setup the form depending on current
945      * values. This method is called after definition(), data submission and set_data().
946      * All form setup that is dependent on form values should go in here.
947      */
948     function definition_after_data(){
949     }
951     /**
952      * Dummy stub method - override if you needed to perform some extra validation.
953      * If there are errors return array of errors ("fieldname"=>"error message"),
954      * otherwise true if ok.
955      *
956      * Server side rules do not work for uploaded files, implement serverside rules here if needed.
957      *
958      * @param array $data array of ("fieldname"=>value) of submitted data
959      * @param array $files array of uploaded files "element_name"=>tmp_file_path
960      * @return array of "element_name"=>"error_description" if there are errors,
961      *         or an empty array if everything is OK (true allowed for backwards compatibility too).
962      */
963     function validation($data, $files) {
964         return array();
965     }
967     /**
968      * Helper used by {@link repeat_elements()}.
969      *
970      * @param int $i the index of this element.
971      * @param HTML_QuickForm_element $elementclone
972      * @param array $namecloned array of names
973      */
974     function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
975         $name = $elementclone->getName();
976         $namecloned[] = $name;
978         if (!empty($name)) {
979             $elementclone->setName($name."[$i]");
980         }
982         if (is_a($elementclone, 'HTML_QuickForm_header')) {
983             $value = $elementclone->_text;
984             $elementclone->setValue(str_replace('{no}', ($i+1), $value));
986         } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
987             $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
989         } else {
990             $value=$elementclone->getLabel();
991             $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
992         }
993     }
995     /**
996      * Method to add a repeating group of elements to a form.
997      *
998      * @param array $elementobjs Array of elements or groups of elements that are to be repeated
999      * @param int $repeats no of times to repeat elements initially
1000      * @param array $options Array of options to apply to elements. Array keys are element names.
1001      *     This is an array of arrays. The second sets of keys are the option types for the elements :
1002      *         'default' - default value is value
1003      *         'type' - PARAM_* constant is value
1004      *         'helpbutton' - helpbutton params array is value
1005      *         'disabledif' - last three moodleform::disabledIf()
1006      *         params are value as an array
1007      * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1008      * @param string $addfieldsname name for button to add more fields
1009      * @param int $addfieldsno how many fields to add at a time
1010      * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1011      * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1012      * @return int no of repeats of element in this page
1013      */
1014     function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1015             $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1016         if ($addstring===null){
1017             $addstring = get_string('addfields', 'form', $addfieldsno);
1018         } else {
1019             $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1020         }
1021         $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1022         $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1023         if (!empty($addfields)){
1024             $repeats += $addfieldsno;
1025         }
1026         $mform =& $this->_form;
1027         $mform->registerNoSubmitButton($addfieldsname);
1028         $mform->addElement('hidden', $repeathiddenname, $repeats);
1029         $mform->setType($repeathiddenname, PARAM_INT);
1030         //value not to be overridden by submitted value
1031         $mform->setConstants(array($repeathiddenname=>$repeats));
1032         $namecloned = array();
1033         for ($i = 0; $i < $repeats; $i++) {
1034             foreach ($elementobjs as $elementobj){
1035                 $elementclone = fullclone($elementobj);
1036                 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1038                 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1039                     foreach ($elementclone->getElements() as $el) {
1040                         $this->repeat_elements_fix_clone($i, $el, $namecloned);
1041                     }
1042                     $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1043                 }
1045                 $mform->addElement($elementclone);
1046             }
1047         }
1048         for ($i=0; $i<$repeats; $i++) {
1049             foreach ($options as $elementname => $elementoptions){
1050                 $pos=strpos($elementname, '[');
1051                 if ($pos!==FALSE){
1052                     $realelementname = substr($elementname, 0, $pos)."[$i]";
1053                     $realelementname .= substr($elementname, $pos);
1054                 }else {
1055                     $realelementname = $elementname."[$i]";
1056                 }
1057                 foreach ($elementoptions as  $option => $params){
1059                     switch ($option){
1060                         case 'default' :
1061                             $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1062                             break;
1063                         case 'helpbutton' :
1064                             $params = array_merge(array($realelementname), $params);
1065                             call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1066                             break;
1067                         case 'disabledif' :
1068                             foreach ($namecloned as $num => $name){
1069                                 if ($params[0] == $name){
1070                                     $params[0] = $params[0]."[$i]";
1071                                     break;
1072                                 }
1073                             }
1074                             $params = array_merge(array($realelementname), $params);
1075                             call_user_func_array(array(&$mform, 'disabledIf'), $params);
1076                             break;
1077                         case 'rule' :
1078                             if (is_string($params)){
1079                                 $params = array(null, $params, null, 'client');
1080                             }
1081                             $params = array_merge(array($realelementname), $params);
1082                             call_user_func_array(array(&$mform, 'addRule'), $params);
1083                             break;
1085                         case 'type':
1086                             $mform->setType($realelementname, $params);
1087                             break;
1089                         case 'expanded':
1090                             $mform->setExpanded($realelementname, $params);
1091                             break;
1093                         case 'advanced' :
1094                             $mform->setAdvanced($realelementname, $params);
1095                             break;
1096                     }
1097                 }
1098             }
1099         }
1100         $mform->addElement('submit', $addfieldsname, $addstring);
1102         if (!$addbuttoninside) {
1103             $mform->closeHeaderBefore($addfieldsname);
1104         }
1106         return $repeats;
1107     }
1109     /**
1110      * Adds a link/button that controls the checked state of a group of checkboxes.
1111      *
1112      * @param int $groupid The id of the group of advcheckboxes this element controls
1113      * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1114      * @param array $attributes associative array of HTML attributes
1115      * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1116      */
1117     function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1118         global $CFG, $PAGE;
1120         // Name of the controller button
1121         $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1122         $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1123         $checkboxgroupclass = 'checkboxgroup'.$groupid;
1125         // Set the default text if none was specified
1126         if (empty($text)) {
1127             $text = get_string('selectallornone', 'form');
1128         }
1130         $mform = $this->_form;
1131         $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1132         $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1134         $newselectvalue = $selectvalue;
1135         if (is_null($selectvalue)) {
1136             $newselectvalue = $originalValue;
1137         } else if (!is_null($contollerbutton)) {
1138             $newselectvalue = (int) !$selectvalue;
1139         }
1140         // set checkbox state depending on orignal/submitted value by controoler button
1141         if (!is_null($contollerbutton) || is_null($selectvalue)) {
1142             foreach ($mform->_elements as $element) {
1143                 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1144                         $element->getAttribute('class') == $checkboxgroupclass &&
1145                         !$element->isFrozen()) {
1146                     $mform->setConstants(array($element->getName() => $newselectvalue));
1147                 }
1148             }
1149         }
1151         $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1152         $mform->setType($checkboxcontrollerparam, PARAM_INT);
1153         $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1155         $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1156                 array(
1157                     array('groupid' => $groupid,
1158                         'checkboxclass' => $checkboxgroupclass,
1159                         'checkboxcontroller' => $checkboxcontrollerparam,
1160                         'controllerbutton' => $checkboxcontrollername)
1161                     )
1162                 );
1164         require_once("$CFG->libdir/form/submit.php");
1165         $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1166         $mform->addElement($submitlink);
1167         $mform->registerNoSubmitButton($checkboxcontrollername);
1168         $mform->setDefault($checkboxcontrollername, $text);
1169     }
1171     /**
1172      * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1173      * if you don't want a cancel button in your form. If you have a cancel button make sure you
1174      * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1175      * get data with get_data().
1176      *
1177      * @param bool $cancel whether to show cancel button, default true
1178      * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1179      */
1180     function add_action_buttons($cancel = true, $submitlabel=null){
1181         if (is_null($submitlabel)){
1182             $submitlabel = get_string('savechanges');
1183         }
1184         $mform =& $this->_form;
1185         if ($cancel){
1186             //when two elements we need a group
1187             $buttonarray=array();
1188             $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1189             $buttonarray[] = &$mform->createElement('cancel');
1190             $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1191             $mform->closeHeaderBefore('buttonar');
1192         } else {
1193             //no group needed
1194             $mform->addElement('submit', 'submitbutton', $submitlabel);
1195             $mform->closeHeaderBefore('submitbutton');
1196         }
1197     }
1199     /**
1200      * Adds an initialisation call for a standard JavaScript enhancement.
1201      *
1202      * This function is designed to add an initialisation call for a JavaScript
1203      * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1204      *
1205      * Current options:
1206      *  - Selectboxes
1207      *      - smartselect:  Turns a nbsp indented select box into a custom drop down
1208      *                      control that supports multilevel and category selection.
1209      *                      $enhancement = 'smartselect';
1210      *                      $options = array('selectablecategories' => true|false)
1211      *
1212      * @since Moodle 2.0
1213      * @param string|element $element form element for which Javascript needs to be initalized
1214      * @param string $enhancement which init function should be called
1215      * @param array $options options passed to javascript
1216      * @param array $strings strings for javascript
1217      */
1218     function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1219         global $PAGE;
1220         if (is_string($element)) {
1221             $element = $this->_form->getElement($element);
1222         }
1223         if (is_object($element)) {
1224             $element->_generateId();
1225             $elementid = $element->getAttribute('id');
1226             $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1227             if (is_array($strings)) {
1228                 foreach ($strings as $string) {
1229                     if (is_array($string)) {
1230                         call_user_method_array('string_for_js', $PAGE->requires, $string);
1231                     } else {
1232                         $PAGE->requires->string_for_js($string, 'moodle');
1233                     }
1234                 }
1235             }
1236         }
1237     }
1239     /**
1240      * Returns a JS module definition for the mforms JS
1241      *
1242      * @return array
1243      */
1244     public static function get_js_module() {
1245         global $CFG;
1246         return array(
1247             'name' => 'mform',
1248             'fullpath' => '/lib/form/form.js',
1249             'requires' => array('base', 'node')
1250         );
1251     }
1253     /**
1254      * Detects elements with missing setType() declerations.
1255      *
1256      * Finds elements in the form which should a PARAM_ type set and throws a
1257      * developer debug warning for any elements without it. This is to reduce the
1258      * risk of potential security issues by developers mistakenly forgetting to set
1259      * the type.
1260      *
1261      * @return void
1262      */
1263     private function detectMissingSetType() {
1264         global $CFG;
1266         if (!$CFG->debugdeveloper) {
1267             // Only for devs.
1268             return;
1269         }
1271         $mform = $this->_form;
1272         foreach ($mform->_elements as $element) {
1273             $group = false;
1274             $elements = array($element);
1276             if ($element->getType() == 'group') {
1277                 $group = $element;
1278                 $elements = $element->getElements();
1279             }
1281             foreach ($elements as $index => $element) {
1282                 switch ($element->getType()) {
1283                     case 'hidden':
1284                     case 'text':
1285                     case 'url':
1286                         if ($group) {
1287                             $name = $group->getElementName($index);
1288                         } else {
1289                             $name = $element->getName();
1290                         }
1291                         $key = $name;
1292                         $found = array_key_exists($key, $mform->_types);
1293                         // For repeated elements we need to look for
1294                         // the "main" type, not for the one present
1295                         // on each repetition. All the stuff in formslib
1296                         // (repeat_elements(), updateSubmission()... seems
1297                         // to work that way.
1298                         while (!$found && strrpos($key, '[') !== false) {
1299                             $pos = strrpos($key, '[');
1300                             $key = substr($key, 0, $pos);
1301                             $found = array_key_exists($key, $mform->_types);
1302                         }
1303                         if (!$found) {
1304                             debugging("Did you remember to call setType() for '$name'? ".
1305                                 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1306                         }
1307                         break;
1308                 }
1309             }
1310         }
1311     }
1313     /**
1314      * Used by tests to simulate submitted form data submission from the user.
1315      *
1316      * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1317      * get_data.
1318      *
1319      * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1320      * global arrays after each test.
1321      *
1322      * @param array  $simulatedsubmitteddata       An associative array of form values (same format as $_POST).
1323      * @param array  $simulatedsubmittedfiles      An associative array of files uploaded (same format as $_FILES). Can be omitted.
1324      * @param string $method                       'post' or 'get', defaults to 'post'.
1325      * @param null   $formidentifier               the default is to use the class name for this class but you may need to provide
1326      *                                              a different value here for some forms that are used more than once on the
1327      *                                              same page.
1328      */
1329     public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1330                                        $formidentifier = null) {
1331         $_FILES = $simulatedsubmittedfiles;
1332         if ($formidentifier === null) {
1333             $formidentifier = get_called_class();
1334         }
1335         $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1336         $simulatedsubmitteddata['sesskey'] = sesskey();
1337         if (strtolower($method) === 'get') {
1338             $_GET = $simulatedsubmitteddata;
1339         } else {
1340             $_POST = $simulatedsubmitteddata;
1341         }
1342     }
1345 /**
1346  * MoodleQuickForm implementation
1347  *
1348  * You never extend this class directly. The class methods of this class are available from
1349  * the private $this->_form property on moodleform and its children. You generally only
1350  * call methods on this class from within abstract methods that you override on moodleform such
1351  * as definition and definition_after_data
1352  *
1353  * @package   core_form
1354  * @category  form
1355  * @copyright 2006 Jamie Pratt <me@jamiep.org>
1356  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1357  */
1358 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1359     /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1360     var $_types = array();
1362     /** @var array dependent state for the element/'s */
1363     var $_dependencies = array();
1365     /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1366     var $_noSubmitButtons=array();
1368     /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1369     var $_cancelButtons=array();
1371     /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1372     var $_advancedElements = array();
1374     /**
1375      * Array whose keys are element names and values are the desired collapsible state.
1376      * True for collapsed, False for expanded. If not present, set to default in
1377      * {@link self::accept()}.
1378      *
1379      * @var array
1380      */
1381     var $_collapsibleElements = array();
1383     /**
1384      * Whether to enable shortforms for this form
1385      *
1386      * @var boolean
1387      */
1388     var $_disableShortforms = false;
1390     /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1391     protected $_use_form_change_checker = true;
1393     /**
1394      * The form name is derived from the class name of the wrapper minus the trailing form
1395      * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1396      * @var string
1397      */
1398     var $_formName = '';
1400     /**
1401      * String with the html for hidden params passed in as part of a moodle_url
1402      * object for the action. Output in the form.
1403      * @var string
1404      */
1405     var $_pageparams = '';
1407     /**
1408      * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1409      *
1410      * @staticvar int $formcounter counts number of forms
1411      * @param string $formName Form's name.
1412      * @param string $method Form's method defaults to 'POST'
1413      * @param string|moodle_url $action Form's action
1414      * @param string $target (optional)Form's target defaults to none
1415      * @param mixed $attributes (optional)Extra attributes for <form> tag
1416      */
1417     function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1418         global $CFG, $OUTPUT;
1420         static $formcounter = 1;
1422         HTML_Common::HTML_Common($attributes);
1423         $target = empty($target) ? array() : array('target' => $target);
1424         $this->_formName = $formName;
1425         if (is_a($action, 'moodle_url')){
1426             $this->_pageparams = html_writer::input_hidden_params($action);
1427             $action = $action->out_omit_querystring();
1428         } else {
1429             $this->_pageparams = '';
1430         }
1431         // No 'name' atttribute for form in xhtml strict :
1432         $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1433         if (is_null($this->getAttribute('id'))) {
1434             $attributes['id'] = 'mform' . $formcounter;
1435         }
1436         $formcounter++;
1437         $this->updateAttributes($attributes);
1439         // This is custom stuff for Moodle :
1440         $oldclass=   $this->getAttribute('class');
1441         if (!empty($oldclass)){
1442             $this->updateAttributes(array('class'=>$oldclass.' mform'));
1443         }else {
1444             $this->updateAttributes(array('class'=>'mform'));
1445         }
1446         $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1447         $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1448         $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1449     }
1451     /**
1452      * Use this method to indicate an element in a form is an advanced field. If items in a form
1453      * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1454      * form so the user can decide whether to display advanced form controls.
1455      *
1456      * If you set a header element to advanced then all elements it contains will also be set as advanced.
1457      *
1458      * @param string $elementName group or element name (not the element name of something inside a group).
1459      * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1460      */
1461     function setAdvanced($elementName, $advanced = true) {
1462         if ($advanced){
1463             $this->_advancedElements[$elementName]='';
1464         } elseif (isset($this->_advancedElements[$elementName])) {
1465             unset($this->_advancedElements[$elementName]);
1466         }
1467     }
1469     /**
1470      * Use this method to indicate that the fieldset should be shown as expanded.
1471      * The method is applicable to header elements only.
1472      *
1473      * @param string $headername header element name
1474      * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1475      * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1476      *                                 the form was submitted.
1477      * @return void
1478      */
1479     function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1480         if (empty($headername)) {
1481             return;
1482         }
1483         $element = $this->getElement($headername);
1484         if ($element->getType() != 'header') {
1485             debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1486             return;
1487         }
1488         if (!$headerid = $element->getAttribute('id')) {
1489             $element->_generateId();
1490             $headerid = $element->getAttribute('id');
1491         }
1492         if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1493             // See if the form has been submitted already.
1494             $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1495             if (!$ignoreuserstate && $formexpanded != -1) {
1496                 // Override expanded state with the form variable.
1497                 $expanded = $formexpanded;
1498             }
1499             // Create the form element for storing expanded state.
1500             $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1501             $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1502             $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1503         }
1504         $this->_collapsibleElements[$headername] = !$expanded;
1505     }
1507     /**
1508      * Use this method to add show more/less status element required for passing
1509      * over the advanced elements visibility status on the form submission.
1510      *
1511      * @param string $headerName header element name.
1512      * @param boolean $showmore default false sets the advanced elements to be hidden.
1513      */
1514     function addAdvancedStatusElement($headerid, $showmore=false){
1515         // Add extra hidden element to store advanced items state for each section.
1516         if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1517             // See if we the form has been submitted already.
1518             $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1519             if (!$showmore && $formshowmore != -1) {
1520                 // Override showmore state with the form variable.
1521                 $showmore = $formshowmore;
1522             }
1523             // Create the form element for storing advanced items state.
1524             $this->addElement('hidden', 'mform_showmore_' . $headerid);
1525             $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1526             $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1527         }
1528     }
1530     /**
1531      * This function has been deprecated. Show advanced has been replaced by
1532      * "Show more.../Show less..." in the shortforms javascript module.
1533      *
1534      * @deprecated since Moodle 2.5
1535      * @param bool $showadvancedNow if true will show advanced elements.
1536       */
1537     function setShowAdvanced($showadvancedNow = null){
1538         debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1539     }
1541     /**
1542      * This function has been deprecated. Show advanced has been replaced by
1543      * "Show more.../Show less..." in the shortforms javascript module.
1544      *
1545      * @deprecated since Moodle 2.5
1546      * @return bool (Always false)
1547       */
1548     function getShowAdvanced(){
1549         debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1550         return false;
1551     }
1553     /**
1554      * Use this method to indicate that the form will not be using shortforms.
1555      *
1556      * @param boolean $disable default true, controls if the shortforms are disabled.
1557      */
1558     function setDisableShortforms ($disable = true) {
1559         $this->_disableShortforms = $disable;
1560     }
1562     /**
1563      * Call this method if you don't want the formchangechecker JavaScript to be
1564      * automatically initialised for this form.
1565      */
1566     public function disable_form_change_checker() {
1567         $this->_use_form_change_checker = false;
1568     }
1570     /**
1571      * If you have called {@link disable_form_change_checker()} then you can use
1572      * this method to re-enable it. It is enabled by default, so normally you don't
1573      * need to call this.
1574      */
1575     public function enable_form_change_checker() {
1576         $this->_use_form_change_checker = true;
1577     }
1579     /**
1580      * @return bool whether this form should automatically initialise
1581      *      formchangechecker for itself.
1582      */
1583     public function is_form_change_checker_enabled() {
1584         return $this->_use_form_change_checker;
1585     }
1587     /**
1588     * Accepts a renderer
1589     *
1590     * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1591     */
1592     function accept(&$renderer) {
1593         if (method_exists($renderer, 'setAdvancedElements')){
1594             //Check for visible fieldsets where all elements are advanced
1595             //and mark these headers as advanced as well.
1596             //Also mark all elements in a advanced header as advanced.
1597             $stopFields = $renderer->getStopFieldSetElements();
1598             $lastHeader = null;
1599             $lastHeaderAdvanced = false;
1600             $anyAdvanced = false;
1601             $anyError = false;
1602             foreach (array_keys($this->_elements) as $elementIndex){
1603                 $element =& $this->_elements[$elementIndex];
1605                 // if closing header and any contained element was advanced then mark it as advanced
1606                 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1607                     if ($anyAdvanced && !is_null($lastHeader)) {
1608                         $lastHeader->_generateId();
1609                         $this->setAdvanced($lastHeader->getName());
1610                         $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1611                     }
1612                     $lastHeaderAdvanced = false;
1613                     unset($lastHeader);
1614                     $lastHeader = null;
1615                 } elseif ($lastHeaderAdvanced) {
1616                     $this->setAdvanced($element->getName());
1617                 }
1619                 if ($element->getType()=='header'){
1620                     $lastHeader =& $element;
1621                     $anyAdvanced = false;
1622                     $anyError = false;
1623                     $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1624                 } elseif (isset($this->_advancedElements[$element->getName()])){
1625                     $anyAdvanced = true;
1626                     if (isset($this->_errors[$element->getName()])) {
1627                         $anyError = true;
1628                     }
1629                 }
1630             }
1631             // the last header may not be closed yet...
1632             if ($anyAdvanced && !is_null($lastHeader)){
1633                 $this->setAdvanced($lastHeader->getName());
1634                 $lastHeader->_generateId();
1635                 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1636             }
1637             $renderer->setAdvancedElements($this->_advancedElements);
1638         }
1639         if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1641             // Count the number of sections.
1642             $headerscount = 0;
1643             foreach (array_keys($this->_elements) as $elementIndex){
1644                 $element =& $this->_elements[$elementIndex];
1645                 if ($element->getType() == 'header') {
1646                     $headerscount++;
1647                 }
1648             }
1650             $anyrequiredorerror = false;
1651             $headercounter = 0;
1652             $headername = null;
1653             foreach (array_keys($this->_elements) as $elementIndex){
1654                 $element =& $this->_elements[$elementIndex];
1656                 if ($element->getType() == 'header') {
1657                     $headercounter++;
1658                     $element->_generateId();
1659                     $headername = $element->getName();
1660                     $anyrequiredorerror = false;
1661                 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1662                     $anyrequiredorerror = true;
1663                 } else {
1664                     // Do not reset $anyrequiredorerror to false because we do not want any other element
1665                     // in this header (fieldset) to possibly revert the state given.
1666                 }
1668                 if ($element->getType() == 'header') {
1669                     if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1670                         // By default the first section is always expanded, except if a state has already been set.
1671                         $this->setExpanded($headername, true);
1672                     } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1673                         // The second section is always expanded if the form only contains 2 sections),
1674                         // except if a state has already been set.
1675                         $this->setExpanded($headername, true);
1676                     }
1677                 } else if ($anyrequiredorerror) {
1678                     // If any error or required field are present within the header, we need to expand it.
1679                     $this->setExpanded($headername, true, true);
1680                 } else if (!isset($this->_collapsibleElements[$headername])) {
1681                     // Define element as collapsed by default.
1682                     $this->setExpanded($headername, false);
1683                 }
1684             }
1686             // Pass the array to renderer object.
1687             $renderer->setCollapsibleElements($this->_collapsibleElements);
1688         }
1689         parent::accept($renderer);
1690     }
1692     /**
1693      * Adds one or more element names that indicate the end of a fieldset
1694      *
1695      * @param string $elementName name of the element
1696      */
1697     function closeHeaderBefore($elementName){
1698         $renderer =& $this->defaultRenderer();
1699         $renderer->addStopFieldsetElements($elementName);
1700     }
1702     /**
1703      * Should be used for all elements of a form except for select, radio and checkboxes which
1704      * clean their own data.
1705      *
1706      * @param string $elementname
1707      * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1708      *        {@link lib/moodlelib.php} for defined parameter types
1709      */
1710     function setType($elementname, $paramtype) {
1711         $this->_types[$elementname] = $paramtype;
1712     }
1714     /**
1715      * This can be used to set several types at once.
1716      *
1717      * @param array $paramtypes types of parameters.
1718      * @see MoodleQuickForm::setType
1719      */
1720     function setTypes($paramtypes) {
1721         $this->_types = $paramtypes + $this->_types;
1722     }
1724     /**
1725      * Return the type(s) to use to clean an element.
1726      *
1727      * In the case where the element has an array as a value, we will try to obtain a
1728      * type defined for that specific key, and recursively until done.
1729      *
1730      * This method does not work reverse, you cannot pass a nested element and hoping to
1731      * fallback on the clean type of a parent. This method intends to be used with the
1732      * main element, which will generate child types if needed, not the other way around.
1733      *
1734      * Example scenario:
1735      *
1736      * You have defined a new repeated element containing a text field called 'foo'.
1737      * By default there will always be 2 occurence of 'foo' in the form. Even though
1738      * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1739      * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1740      * $mform->setType('foo[0]', PARAM_FLOAT).
1741      *
1742      * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1743      * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1744      * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1745      * get the default clean type returned (param $default).
1746      *
1747      * @param string $elementname name of the element.
1748      * @param mixed $value value that should be cleaned.
1749      * @param int $default default constant value to be returned (PARAM_...)
1750      * @return string|array constant value or array of constant values (PARAM_...)
1751      */
1752     public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1753         $type = $default;
1754         if (array_key_exists($elementname, $this->_types)) {
1755             $type = $this->_types[$elementname];
1756         }
1757         if (is_array($value)) {
1758             $default = $type;
1759             $type = array();
1760             foreach ($value as $subkey => $subvalue) {
1761                 $typekey = "$elementname" . "[$subkey]";
1762                 if (array_key_exists($typekey, $this->_types)) {
1763                     $subtype = $this->_types[$typekey];
1764                 } else {
1765                     $subtype = $default;
1766                 }
1767                 if (is_array($subvalue)) {
1768                     $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1769                 } else {
1770                     $type[$subkey] = $subtype;
1771                 }
1772             }
1773         }
1774         return $type;
1775     }
1777     /**
1778      * Return the cleaned value using the passed type(s).
1779      *
1780      * @param mixed $value value that has to be cleaned.
1781      * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1782      * @return mixed cleaned up value.
1783      */
1784     public function getCleanedValue($value, $type) {
1785         if (is_array($type) && is_array($value)) {
1786             foreach ($type as $key => $param) {
1787                 $value[$key] = $this->getCleanedValue($value[$key], $param);
1788             }
1789         } else if (!is_array($type) && !is_array($value)) {
1790             $value = clean_param($value, $type);
1791         } else if (!is_array($type) && is_array($value)) {
1792             $value = clean_param_array($value, $type, true);
1793         } else {
1794             throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1795         }
1796         return $value;
1797     }
1799     /**
1800      * Updates submitted values
1801      *
1802      * @param array $submission submitted values
1803      * @param array $files list of files
1804      */
1805     function updateSubmission($submission, $files) {
1806         $this->_flagSubmitted = false;
1808         if (empty($submission)) {
1809             $this->_submitValues = array();
1810         } else {
1811             foreach ($submission as $key => $s) {
1812                 $type = $this->getCleanType($key, $s);
1813                 $submission[$key] = $this->getCleanedValue($s, $type);
1814             }
1815             $this->_submitValues = $submission;
1816             $this->_flagSubmitted = true;
1817         }
1819         if (empty($files)) {
1820             $this->_submitFiles = array();
1821         } else {
1822             $this->_submitFiles = $files;
1823             $this->_flagSubmitted = true;
1824         }
1826         // need to tell all elements that they need to update their value attribute.
1827          foreach (array_keys($this->_elements) as $key) {
1828              $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1829          }
1830     }
1832     /**
1833      * Returns HTML for required elements
1834      *
1835      * @return string
1836      */
1837     function getReqHTML(){
1838         return $this->_reqHTML;
1839     }
1841     /**
1842      * Returns HTML for advanced elements
1843      *
1844      * @return string
1845      */
1846     function getAdvancedHTML(){
1847         return $this->_advancedHTML;
1848     }
1850     /**
1851      * Initializes a default form value. Used to specify the default for a new entry where
1852      * no data is loaded in using moodleform::set_data()
1853      *
1854      * note: $slashed param removed
1855      *
1856      * @param string $elementName element name
1857      * @param mixed $defaultValue values for that element name
1858      */
1859     function setDefault($elementName, $defaultValue){
1860         $this->setDefaults(array($elementName=>$defaultValue));
1861     }
1863     /**
1864      * Add a help button to element, only one button per element is allowed.
1865      *
1866      * This is new, simplified and preferable method of setting a help icon on form elements.
1867      * It uses the new $OUTPUT->help_icon().
1868      *
1869      * Typically, you will provide the same identifier and the component as you have used for the
1870      * label of the element. The string identifier with the _help suffix added is then used
1871      * as the help string.
1872      *
1873      * There has to be two strings defined:
1874      *   1/ get_string($identifier, $component) - the title of the help page
1875      *   2/ get_string($identifier.'_help', $component) - the actual help page text
1876      *
1877      * @since Moodle 2.0
1878      * @param string $elementname name of the element to add the item to
1879      * @param string $identifier help string identifier without _help suffix
1880      * @param string $component component name to look the help string in
1881      * @param string $linktext optional text to display next to the icon
1882      * @param bool $suppresscheck set to true if the element may not exist
1883      */
1884     function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1885         global $OUTPUT;
1886         if (array_key_exists($elementname, $this->_elementIndex)) {
1887             $element = $this->_elements[$this->_elementIndex[$elementname]];
1888             $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1889         } else if (!$suppresscheck) {
1890             debugging(get_string('nonexistentformelements', 'form', $elementname));
1891         }
1892     }
1894     /**
1895      * Set constant value not overridden by _POST or _GET
1896      * note: this does not work for complex names with [] :-(
1897      *
1898      * @param string $elname name of element
1899      * @param mixed $value
1900      */
1901     function setConstant($elname, $value) {
1902         $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1903         $element =& $this->getElement($elname);
1904         $element->onQuickFormEvent('updateValue', null, $this);
1905     }
1907     /**
1908      * export submitted values
1909      *
1910      * @param string $elementList list of elements in form
1911      * @return array
1912      */
1913     function exportValues($elementList = null){
1914         $unfiltered = array();
1915         if (null === $elementList) {
1916             // iterate over all elements, calling their exportValue() methods
1917             foreach (array_keys($this->_elements) as $key) {
1918                 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1919                     $varname = $this->_elements[$key]->_attributes['name'];
1920                     $value = '';
1921                     // If we have a default value then export it.
1922                     if (isset($this->_defaultValues[$varname])) {
1923                         $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
1924                     }
1925                 } else {
1926                     $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1927                 }
1929                 if (is_array($value)) {
1930                     // This shit throws a bogus warning in PHP 4.3.x
1931                     $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1932                 }
1933             }
1934         } else {
1935             if (!is_array($elementList)) {
1936                 $elementList = array_map('trim', explode(',', $elementList));
1937             }
1938             foreach ($elementList as $elementName) {
1939                 $value = $this->exportValue($elementName);
1940                 if (@PEAR::isError($value)) {
1941                     return $value;
1942                 }
1943                 //oh, stock QuickFOrm was returning array of arrays!
1944                 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1945             }
1946         }
1948         if (is_array($this->_constantValues)) {
1949             $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1950         }
1951         return $unfiltered;
1952     }
1954     /**
1955      * This is a bit of a hack, and it duplicates the code in
1956      * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
1957      * reliably calling that code. (Think about date selectors, for example.)
1958      * @param string $name the element name.
1959      * @param mixed $value the fixed value to set.
1960      * @return mixed the appropriate array to add to the $unfiltered array.
1961      */
1962     protected function prepare_fixed_value($name, $value) {
1963         if (null === $value) {
1964             return null;
1965         } else {
1966             if (!strpos($name, '[')) {
1967                 return array($name => $value);
1968             } else {
1969                 $valueAry = array();
1970                 $myIndex  = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
1971                 eval("\$valueAry$myIndex = \$value;");
1972                 return $valueAry;
1973             }
1974         }
1975     }
1977     /**
1978      * Adds a validation rule for the given field
1979      *
1980      * If the element is in fact a group, it will be considered as a whole.
1981      * To validate grouped elements as separated entities,
1982      * use addGroupRule instead of addRule.
1983      *
1984      * @param string $element Form element name
1985      * @param string $message Message to display for invalid data
1986      * @param string $type Rule type, use getRegisteredRules() to get types
1987      * @param string $format (optional)Required for extra rule data
1988      * @param string $validation (optional)Where to perform validation: "server", "client"
1989      * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1990      * @param bool $force Force the rule to be applied, even if the target form element does not exist
1991      */
1992     function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1993     {
1994         parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1995         if ($validation == 'client') {
1996             $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1997         }
1999     }
2001     /**
2002      * Adds a validation rule for the given group of elements
2003      *
2004      * Only groups with a name can be assigned a validation rule
2005      * Use addGroupRule when you need to validate elements inside the group.
2006      * Use addRule if you need to validate the group as a whole. In this case,
2007      * the same rule will be applied to all elements in the group.
2008      * Use addRule if you need to validate the group against a function.
2009      *
2010      * @param string $group Form group name
2011      * @param array|string $arg1 Array for multiple elements or error message string for one element
2012      * @param string $type (optional)Rule type use getRegisteredRules() to get types
2013      * @param string $format (optional)Required for extra rule data
2014      * @param int $howmany (optional)How many valid elements should be in the group
2015      * @param string $validation (optional)Where to perform validation: "server", "client"
2016      * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2017      */
2018     function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2019     {
2020         parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2021         if (is_array($arg1)) {
2022              foreach ($arg1 as $rules) {
2023                 foreach ($rules as $rule) {
2024                     $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2026                     if ('client' == $validation) {
2027                         $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2028                     }
2029                 }
2030             }
2031         } elseif (is_string($arg1)) {
2033             if ($validation == 'client') {
2034                 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2035             }
2036         }
2037     }
2039     /**
2040      * Returns the client side validation script
2041      *
2042      * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from  HTML_QuickForm
2043      * and slightly modified to run rules per-element
2044      * Needed to override this because of an error with client side validation of grouped elements.
2045      *
2046      * @return string Javascript to perform validation, empty string if no 'client' rules were added
2047      */
2048     function getValidationScript()
2049     {
2050         if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
2051             return '';
2052         }
2054         include_once('HTML/QuickForm/RuleRegistry.php');
2055         $registry =& HTML_QuickForm_RuleRegistry::singleton();
2056         $test = array();
2057         $js_escape = array(
2058             "\r"    => '\r',
2059             "\n"    => '\n',
2060             "\t"    => '\t',
2061             "'"     => "\\'",
2062             '"'     => '\"',
2063             '\\'    => '\\\\'
2064         );
2066         foreach ($this->_rules as $elementName => $rules) {
2067             foreach ($rules as $rule) {
2068                 if ('client' == $rule['validation']) {
2069                     unset($element); //TODO: find out how to properly initialize it
2071                     $dependent  = isset($rule['dependent']) && is_array($rule['dependent']);
2072                     $rule['message'] = strtr($rule['message'], $js_escape);
2074                     if (isset($rule['group'])) {
2075                         $group    =& $this->getElement($rule['group']);
2076                         // No JavaScript validation for frozen elements
2077                         if ($group->isFrozen()) {
2078                             continue 2;
2079                         }
2080                         $elements =& $group->getElements();
2081                         foreach (array_keys($elements) as $key) {
2082                             if ($elementName == $group->getElementName($key)) {
2083                                 $element =& $elements[$key];
2084                                 break;
2085                             }
2086                         }
2087                     } elseif ($dependent) {
2088                         $element   =  array();
2089                         $element[] =& $this->getElement($elementName);
2090                         foreach ($rule['dependent'] as $elName) {
2091                             $element[] =& $this->getElement($elName);
2092                         }
2093                     } else {
2094                         $element =& $this->getElement($elementName);
2095                     }
2096                     // No JavaScript validation for frozen elements
2097                     if (is_object($element) && $element->isFrozen()) {
2098                         continue 2;
2099                     } elseif (is_array($element)) {
2100                         foreach (array_keys($element) as $key) {
2101                             if ($element[$key]->isFrozen()) {
2102                                 continue 3;
2103                             }
2104                         }
2105                     }
2106                     //for editor element, [text] is appended to the name.
2107                     if ($element->getType() == 'editor') {
2108                         $elementName .= '[text]';
2109                         //Add format to rule as moodleform check which format is supported by browser
2110                         //it is not set anywhere... So small hack to make sure we pass it down to quickform
2111                         if (is_null($rule['format'])) {
2112                             $rule['format'] = $element->getFormat();
2113                         }
2114                     }
2115                     // Fix for bug displaying errors for elements in a group
2116                     $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
2117                     $test[$elementName][1]=$element;
2118                     //end of fix
2119                 }
2120             }
2121         }
2123         // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2124         // the form, and then that form field gets corrupted by the code that follows.
2125         unset($element);
2127         $js = '
2128 <script type="text/javascript">
2129 //<![CDATA[
2131 var skipClientValidation = false;
2133 function qf_errorHandler(element, _qfMsg) {
2134   div = element.parentNode;
2136   if ((div == undefined) || (element.name == undefined)) {
2137     //no checking can be done for undefined elements so let server handle it.
2138     return true;
2139   }
2141   if (_qfMsg != \'\') {
2142     var errorSpan = document.getElementById(\'id_error_\'+element.name);
2143     if (!errorSpan) {
2144       errorSpan = document.createElement("span");
2145       errorSpan.id = \'id_error_\'+element.name;
2146       errorSpan.className = "error";
2147       element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2148       document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2149       document.getElementById(errorSpan.id).focus();
2150     }
2152     while (errorSpan.firstChild) {
2153       errorSpan.removeChild(errorSpan.firstChild);
2154     }
2156     errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2158     if (div.className.substr(div.className.length - 6, 6) != " error"
2159       && div.className != "error") {
2160         div.className += " error";
2161         linebreak = document.createElement("br");
2162         linebreak.className = "error";
2163         linebreak.id = \'id_error_break_\'+element.name;
2164         errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2165     }
2167     return false;
2168   } else {
2169     var errorSpan = document.getElementById(\'id_error_\'+element.name);
2170     if (errorSpan) {
2171       errorSpan.parentNode.removeChild(errorSpan);
2172     }
2173     var linebreak = document.getElementById(\'id_error_break_\'+element.name);
2174     if (linebreak) {
2175       linebreak.parentNode.removeChild(linebreak);
2176     }
2178     if (div.className.substr(div.className.length - 6, 6) == " error") {
2179       div.className = div.className.substr(0, div.className.length - 6);
2180     } else if (div.className == "error") {
2181       div.className = "";
2182     }
2184     return true;
2185   }
2186 }';
2187         $validateJS = '';
2188         foreach ($test as $elementName => $jsandelement) {
2189             // Fix for bug displaying errors for elements in a group
2190             //unset($element);
2191             list($jsArr,$element)=$jsandelement;
2192             //end of fix
2193             $escapedElementName = preg_replace_callback(
2194                 '/[_\[\]-]/',
2195                 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2196                 $elementName);
2197             $js .= '
2198 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
2199   if (undefined == element) {
2200      //required element was not found, then let form be submitted without client side validation
2201      return true;
2202   }
2203   var value = \'\';
2204   var errFlag = new Array();
2205   var _qfGroups = {};
2206   var _qfMsg = \'\';
2207   var frm = element.parentNode;
2208   if ((undefined != element.name) && (frm != undefined)) {
2209       while (frm && frm.nodeName.toUpperCase() != "FORM") {
2210         frm = frm.parentNode;
2211       }
2212     ' . join("\n", $jsArr) . '
2213       return qf_errorHandler(element, _qfMsg);
2214   } else {
2215     //element name should be defined else error msg will not be displayed.
2216     return true;
2217   }
2219 ';
2220             $validateJS .= '
2221   ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
2222   if (!ret && !first_focus) {
2223     first_focus = true;
2224     frm.elements[\''.$elementName.'\'].focus();
2225   }
2226 ';
2228             // Fix for bug displaying errors for elements in a group
2229             //unset($element);
2230             //$element =& $this->getElement($elementName);
2231             //end of fix
2232             $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
2233             $onBlur = $element->getAttribute('onBlur');
2234             $onChange = $element->getAttribute('onChange');
2235             $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2236                                              'onChange' => $onChange . $valFunc));
2237         }
2238 //  do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2239         $js .= '
2240 function validate_' . $this->_formName . '(frm) {
2241   if (skipClientValidation) {
2242      return true;
2243   }
2244   var ret = true;
2246   var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2247   var first_focus = false;
2248 ' . $validateJS . ';
2249   return ret;
2251 //]]>
2252 </script>';
2253         return $js;
2254     } // end func getValidationScript
2256     /**
2257      * Sets default error message
2258      */
2259     function _setDefaultRuleMessages(){
2260         foreach ($this->_rules as $field => $rulesarr){
2261             foreach ($rulesarr as $key => $rule){
2262                 if ($rule['message']===null){
2263                     $a=new stdClass();
2264                     $a->format=$rule['format'];
2265                     $str=get_string('err_'.$rule['type'], 'form', $a);
2266                     if (strpos($str, '[[')!==0){
2267                         $this->_rules[$field][$key]['message']=$str;
2268                     }
2269                 }
2270             }
2271         }
2272     }
2274     /**
2275      * Get list of attributes which have dependencies
2276      *
2277      * @return array
2278      */
2279     function getLockOptionObject(){
2280         $result = array();
2281         foreach ($this->_dependencies as $dependentOn => $conditions){
2282             $result[$dependentOn] = array();
2283             foreach ($conditions as $condition=>$values) {
2284                 $result[$dependentOn][$condition] = array();
2285                 foreach ($values as $value=>$dependents) {
2286                     $result[$dependentOn][$condition][$value] = array();
2287                     $i = 0;
2288                     foreach ($dependents as $dependent) {
2289                         $elements = $this->_getElNamesRecursive($dependent);
2290                         if (empty($elements)) {
2291                             // probably element inside of some group
2292                             $elements = array($dependent);
2293                         }
2294                         foreach($elements as $element) {
2295                             if ($element == $dependentOn) {
2296                                 continue;
2297                             }
2298                             $result[$dependentOn][$condition][$value][] = $element;
2299                         }
2300                     }
2301                 }
2302             }
2303         }
2304         return array($this->getAttribute('id'), $result);
2305     }
2307     /**
2308      * Get names of element or elements in a group.
2309      *
2310      * @param HTML_QuickForm_group|element $element element group or element object
2311      * @return array
2312      */
2313     function _getElNamesRecursive($element) {
2314         if (is_string($element)) {
2315             if (!$this->elementExists($element)) {
2316                 return array();
2317             }
2318             $element = $this->getElement($element);
2319         }
2321         if (is_a($element, 'HTML_QuickForm_group')) {
2322             $elsInGroup = $element->getElements();
2323             $elNames = array();
2324             foreach ($elsInGroup as $elInGroup){
2325                 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2326                     // not sure if this would work - groups nested in groups
2327                     $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2328                 } else {
2329                     $elNames[] = $element->getElementName($elInGroup->getName());
2330                 }
2331             }
2333         } else if (is_a($element, 'HTML_QuickForm_header')) {
2334             return array();
2336         } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2337             return array();
2339         } else if (method_exists($element, 'getPrivateName') &&
2340                 !($element instanceof HTML_QuickForm_advcheckbox)) {
2341             // The advcheckbox element implements a method called getPrivateName,
2342             // but in a way that is not compatible with the generic API, so we
2343             // have to explicitly exclude it.
2344             return array($element->getPrivateName());
2346         } else {
2347             $elNames = array($element->getName());
2348         }
2350         return $elNames;
2351     }
2353     /**
2354      * Adds a dependency for $elementName which will be disabled if $condition is met.
2355      * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2356      * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2357      * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2358      * of the $dependentOn element is $condition (such as equal) to $value.
2359      *
2360      * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2361      * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2362      * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2363      *
2364      * @param string $elementName the name of the element which will be disabled
2365      * @param string $dependentOn the name of the element whose state will be checked for condition
2366      * @param string $condition the condition to check
2367      * @param mixed $value used in conjunction with condition.
2368      */
2369     function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2370         // Multiple selects allow for a multiple selection, we transform the array to string here as
2371         // an array cannot be used as a key in an associative array.
2372         if (is_array($value)) {
2373             $value = implode('|', $value);
2374         }
2375         if (!array_key_exists($dependentOn, $this->_dependencies)) {
2376             $this->_dependencies[$dependentOn] = array();
2377         }
2378         if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2379             $this->_dependencies[$dependentOn][$condition] = array();
2380         }
2381         if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2382             $this->_dependencies[$dependentOn][$condition][$value] = array();
2383         }
2384         $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2385     }
2387     /**
2388      * Registers button as no submit button
2389      *
2390      * @param string $buttonname name of the button
2391      */
2392     function registerNoSubmitButton($buttonname){
2393         $this->_noSubmitButtons[]=$buttonname;
2394     }
2396     /**
2397      * Checks if button is a no submit button, i.e it doesn't submit form
2398      *
2399      * @param string $buttonname name of the button to check
2400      * @return bool
2401      */
2402     function isNoSubmitButton($buttonname){
2403         return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2404     }
2406     /**
2407      * Registers a button as cancel button
2408      *
2409      * @param string $addfieldsname name of the button
2410      */
2411     function _registerCancelButton($addfieldsname){
2412         $this->_cancelButtons[]=$addfieldsname;
2413     }
2415     /**
2416      * Displays elements without HTML input tags.
2417      * This method is different to freeze() in that it makes sure no hidden
2418      * elements are included in the form.
2419      * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2420      *
2421      * This function also removes all previously defined rules.
2422      *
2423      * @param string|array $elementList array or string of element(s) to be frozen
2424      * @return object|bool if element list is not empty then return error object, else true
2425      */
2426     function hardFreeze($elementList=null)
2427     {
2428         if (!isset($elementList)) {
2429             $this->_freezeAll = true;
2430             $elementList = array();
2431         } else {
2432             if (!is_array($elementList)) {
2433                 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2434             }
2435             $elementList = array_flip($elementList);
2436         }
2438         foreach (array_keys($this->_elements) as $key) {
2439             $name = $this->_elements[$key]->getName();
2440             if ($this->_freezeAll || isset($elementList[$name])) {
2441                 $this->_elements[$key]->freeze();
2442                 $this->_elements[$key]->setPersistantFreeze(false);
2443                 unset($elementList[$name]);
2445                 // remove all rules
2446                 $this->_rules[$name] = array();
2447                 // if field is required, remove the rule
2448                 $unset = array_search($name, $this->_required);
2449                 if ($unset !== false) {
2450                     unset($this->_required[$unset]);
2451                 }
2452             }
2453         }
2455         if (!empty($elementList)) {
2456             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);
2457         }
2458         return true;
2459     }
2461     /**
2462      * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2463      *
2464      * This function also removes all previously defined rules of elements it freezes.
2465      *
2466      * @throws HTML_QuickForm_Error
2467      * @param array $elementList array or string of element(s) not to be frozen
2468      * @return bool returns true
2469      */
2470     function hardFreezeAllVisibleExcept($elementList)
2471     {
2472         $elementList = array_flip($elementList);
2473         foreach (array_keys($this->_elements) as $key) {
2474             $name = $this->_elements[$key]->getName();
2475             $type = $this->_elements[$key]->getType();
2477             if ($type == 'hidden'){
2478                 // leave hidden types as they are
2479             } elseif (!isset($elementList[$name])) {
2480                 $this->_elements[$key]->freeze();
2481                 $this->_elements[$key]->setPersistantFreeze(false);
2483                 // remove all rules
2484                 $this->_rules[$name] = array();
2485                 // if field is required, remove the rule
2486                 $unset = array_search($name, $this->_required);
2487                 if ($unset !== false) {
2488                     unset($this->_required[$unset]);
2489                 }
2490             }
2491         }
2492         return true;
2493     }
2495    /**
2496     * Tells whether the form was already submitted
2497     *
2498     * This is useful since the _submitFiles and _submitValues arrays
2499     * may be completely empty after the trackSubmit value is removed.
2500     *
2501     * @return bool
2502     */
2503     function isSubmitted()
2504     {
2505         return parent::isSubmitted() && (!$this->isFrozen());
2506     }
2509 /**
2510  * MoodleQuickForm renderer
2511  *
2512  * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2513  * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2514  *
2515  * Stylesheet is part of standard theme and should be automatically included.
2516  *
2517  * @package   core_form
2518  * @copyright 2007 Jamie Pratt <me@jamiep.org>
2519  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2520  */
2521 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2523     /** @var array Element template array */
2524     var $_elementTemplates;
2526     /**
2527      * Template used when opening a hidden fieldset
2528      * (i.e. a fieldset that is opened when there is no header element)
2529      * @var string
2530      */
2531     var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2533     /** @var string Header Template string */
2534     var $_headerTemplate =
2535        "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2537     /** @var string Template used when opening a fieldset */
2538     var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id} {aria-live}>";
2540     /** @var string Template used when closing a fieldset */
2541     var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2543     /** @var string Required Note template string */
2544     var $_requiredNoteTemplate =
2545         "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2547     /**
2548      * Collapsible buttons string template.
2549      *
2550      * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2551      * until the Javascript has been fully loaded.
2552      *
2553      * @var string
2554      */
2555     var $_collapseButtonsTemplate =
2556         "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2558     /**
2559      * Array whose keys are element names. If the key exists this is a advanced element
2560      *
2561      * @var array
2562      */
2563     var $_advancedElements = array();
2565     /**
2566      * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2567      *
2568      * @var array
2569      */
2570     var $_collapsibleElements = array();
2572     /**
2573      * @var string Contains the collapsible buttons to add to the form.
2574      */
2575     var $_collapseButtons = '';
2577     /**
2578      * Constructor
2579      */
2580     function MoodleQuickForm_Renderer(){
2581         // switch next two lines for ol li containers for form items.
2582         //        $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>');
2583         $this->_elementTemplates = array(
2584         'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}" {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>',
2586         'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2588         'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}"><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>',
2590         'static'=>"\n\t\t".'<div class="fitem {advanced}"><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}&nbsp;</div></div>',
2592         'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2594         'nodisplay'=>'');
2596         parent::HTML_QuickForm_Renderer_Tableless();
2597     }
2599     /**
2600      * Set element's as adavance element
2601      *
2602      * @param array $elements form elements which needs to be grouped as advance elements.
2603      */
2604     function setAdvancedElements($elements){
2605         $this->_advancedElements = $elements;
2606     }
2608     /**
2609      * Setting collapsible elements
2610      *
2611      * @param array $elements
2612      */
2613     function setCollapsibleElements($elements) {
2614         $this->_collapsibleElements = $elements;
2615     }
2617     /**
2618      * What to do when starting the form
2619      *
2620      * @param MoodleQuickForm $form reference of the form
2621      */
2622     function startForm(&$form){
2623         global $PAGE;
2624         $this->_reqHTML = $form->getReqHTML();
2625         $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2626         $this->_advancedHTML = $form->getAdvancedHTML();
2627         $this->_collapseButtons = '';
2628         $formid = $form->getAttribute('id');
2629         parent::startForm($form);
2630         if ($form->isFrozen()){
2631             $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2632         } else {
2633             $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2634             $this->_hiddenHtml .= $form->_pageparams;
2635         }
2637         if ($form->is_form_change_checker_enabled()) {
2638             $PAGE->requires->yui_module('moodle-core-formchangechecker',
2639                     'M.core_formchangechecker.init',
2640                     array(array(
2641                         'formid' => $formid
2642                     ))
2643             );
2644             $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2645         }
2646         if (!empty($this->_collapsibleElements)) {
2647             if (count($this->_collapsibleElements) > 1) {
2648                 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2649                 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2650                 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2651             }
2652             $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2653         }
2654         if (!empty($this->_advancedElements)){
2655             $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2656             $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2657         }
2658     }
2660     /**
2661      * Create advance group of elements
2662      *
2663      * @param object $group Passed by reference
2664      * @param bool $required if input is required field
2665      * @param string $error error message to display
2666      */
2667     function startGroup(&$group, $required, $error){
2668         // Make sure the element has an id.
2669         $group->_generateId();
2671         if (method_exists($group, 'getElementTemplateType')){
2672             $html = $this->_elementTemplates[$group->getElementTemplateType()];
2673         }else{
2674             $html = $this->_elementTemplates['default'];
2676         }
2678         if (isset($this->_advancedElements[$group->getName()])){
2679             $html =str_replace(' {advanced}', ' advanced', $html);
2680             $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2681         } else {
2682             $html =str_replace(' {advanced}', '', $html);
2683             $html =str_replace('{advancedimg}', '', $html);
2684         }
2685         if (method_exists($group, 'getHelpButton')){
2686             $html =str_replace('{help}', $group->getHelpButton(), $html);
2687         }else{
2688             $html =str_replace('{help}', '', $html);
2689         }
2690         $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2691         $html =str_replace('{name}', $group->getName(), $html);
2692         $html =str_replace('{type}', 'fgroup', $html);
2694         $this->_templates[$group->getName()]=$html;
2695         // Fix for bug in tableless quickforms that didn't allow you to stop a
2696         // fieldset before a group of elements.
2697         // if the element name indicates the end of a fieldset, close the fieldset
2698         if (   in_array($group->getName(), $this->_stopFieldsetElements)
2699             && $this->_fieldsetsOpen > 0
2700            ) {
2701             $this->_html .= $this->_closeFieldsetTemplate;
2702             $this->_fieldsetsOpen--;
2703         }
2704         parent::startGroup($group, $required, $error);
2705     }
2707     /**
2708      * Renders element
2709      *
2710      * @param HTML_QuickForm_element $element element
2711      * @param bool $required if input is required field
2712      * @param string $error error message to display
2713      */
2714     function renderElement(&$element, $required, $error){
2715         // Make sure the element has an id.
2716         $element->_generateId();
2718         //adding stuff to place holders in template
2719         //check if this is a group element first
2720         if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2721             // so it gets substitutions for *each* element
2722             $html = $this->_groupElementTemplate;
2723         }
2724         elseif (method_exists($element, 'getElementTemplateType')){
2725             $html = $this->_elementTemplates[$element->getElementTemplateType()];
2726         }else{
2727             $html = $this->_elementTemplates['default'];
2728         }
2729         if (isset($this->_advancedElements[$element->getName()])){
2730             $html = str_replace(' {advanced}', ' advanced', $html);
2731             $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2732         } else {
2733             $html = str_replace(' {advanced}', '', $html);
2734             $html = str_replace(' {aria-live}', '', $html);
2735         }
2736         if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2737             $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2738         } else {
2739             $html =str_replace('{advancedimg}', '', $html);
2740         }
2741         $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2742         $html =str_replace('{type}', 'f'.$element->getType(), $html);
2743         $html =str_replace('{name}', $element->getName(), $html);
2744         if (method_exists($element, 'getHelpButton')){
2745             $html = str_replace('{help}', $element->getHelpButton(), $html);
2746         }else{
2747             $html = str_replace('{help}', '', $html);
2749         }
2750         if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2751             $this->_groupElementTemplate = $html;
2752         }
2753         elseif (!isset($this->_templates[$element->getName()])) {
2754             $this->_templates[$element->getName()] = $html;
2755         }
2757         parent::renderElement($element, $required, $error);
2758     }
2760     /**
2761      * Called when visiting a form, after processing all form elements
2762      * Adds required note, form attributes, validation javascript and form content.
2763      *
2764      * @global moodle_page $PAGE
2765      * @param moodleform $form Passed by reference
2766      */
2767     function finishForm(&$form){
2768         global $PAGE;
2769         if ($form->isFrozen()){
2770             $this->_hiddenHtml = '';
2771         }
2772         parent::finishForm($form);
2773         $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2774         if (!$form->isFrozen()) {
2775             $args = $form->getLockOptionObject();
2776             if (count($args[1]) > 0) {
2777                 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2778             }
2779         }
2780     }
2781    /**
2782     * Called when visiting a header element
2783     *
2784     * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2785     * @global moodle_page $PAGE
2786     */
2787     function renderHeader(&$header) {
2788         global $PAGE;
2790         $header->_generateId();
2791         $name = $header->getName();
2793         $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2794         if (is_null($header->_text)) {
2795             $header_html = '';
2796         } elseif (!empty($name) && isset($this->_templates[$name])) {
2797             $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2798         } else {
2799             $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2800         }
2802         if ($this->_fieldsetsOpen > 0) {
2803             $this->_html .= $this->_closeFieldsetTemplate;
2804             $this->_fieldsetsOpen--;
2805         }
2807         // Define collapsible classes for fieldsets.
2808         $arialive = '';
2809         $fieldsetclasses = array('clearfix');
2810         if (isset($this->_collapsibleElements[$header->getName()])) {
2811             $fieldsetclasses[] = 'collapsible';
2812             $arialive = 'aria-live="polite"';
2813             if ($this->_collapsibleElements[$header->getName()]) {
2814                 $fieldsetclasses[] = 'collapsed';
2815             }
2816         }
2818         if (isset($this->_advancedElements[$name])){
2819             $fieldsetclasses[] = 'containsadvancedelements';
2820         }
2822         $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2823         $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
2824         $openFieldsetTemplate = str_replace('{aria-live}', $arialive, $openFieldsetTemplate);
2826         $this->_html .= $openFieldsetTemplate . $header_html;
2827         $this->_fieldsetsOpen++;
2828     }
2830     /**
2831      * Return Array of element names that indicate the end of a fieldset
2832      *
2833      * @return array
2834      */
2835     function getStopFieldsetElements(){
2836         return $this->_stopFieldsetElements;
2837     }
2840 /**
2841  * Required elements validation
2842  *
2843  * This class overrides QuickForm validation since it allowed space or empty tag as a value
2844  *
2845  * @package   core_form
2846  * @category  form
2847  * @copyright 2006 Jamie Pratt <me@jamiep.org>
2848  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2849  */
2850 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2851     /**
2852      * Checks if an element is not empty.
2853      * This is a server-side validation, it works for both text fields and editor fields
2854      *
2855      * @param string $value Value to check
2856      * @param int|string|array $options Not used yet
2857      * @return bool true if value is not empty
2858      */
2859     function validate($value, $options = null) {
2860         global $CFG;
2861         if (is_array($value) && array_key_exists('text', $value)) {
2862             $value = $value['text'];
2863         }
2864         if (is_array($value)) {
2865             // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2866             $value = implode('', $value);
2867         }
2868         $stripvalues = array(
2869             '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2870             '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
2871         );
2872         if (!empty($CFG->strictformsrequired)) {
2873             $value = preg_replace($stripvalues, '', (string)$value);
2874         }
2875         if ((string)$value == '') {
2876             return false;
2877         }
2878         return true;
2879     }
2881     /**
2882      * This function returns Javascript code used to build client-side validation.
2883      * It checks if an element is not empty.
2884      *
2885      * @param int $format format of data which needs to be validated.
2886      * @return array
2887      */
2888     function getValidationScript($format = null) {
2889         global $CFG;
2890         if (!empty($CFG->strictformsrequired)) {
2891             if (!empty($format) && $format == FORMAT_HTML) {
2892                 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2893             } else {
2894                 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2895             }
2896         } else {
2897             return array('', "{jsVar} == ''");
2898         }
2899     }
2902 /**
2903  * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2904  * @name $_HTML_QuickForm_default_renderer
2905  */
2906 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2908 /** Please keep this list in alphabetical order. */
2909 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2910 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2911 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2912 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2913 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2914 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2915 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2916 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2917 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2918 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2919 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2920 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2921 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2922 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2923 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2924 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2925 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
2926 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2927 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2928 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2929 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2930 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2931 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2932 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2933 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2934 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2935 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2936 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2937 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2938 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2939 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2940 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2941 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2942 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2943 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2944 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2946 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");