2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
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
25 * See examples of use of this library in course/edit.php and course/edit_form.php
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.
34 * @copyright 2006 Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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';
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
54 * Callback called when PEAR throws an error
56 * @param PEAR_Error $error
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);
64 if (!empty($CFG->debug) and ($CFG->debug >= DEBUG_ALL or $CFG->debug == -1)){
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';
71 * Initalize javascript for date type form element
73 * @staticvar bool $done make sure it gets initalize once.
74 * @global moodle_page $PAGE
76 function form_init_date_js() {
80 $module = 'moodle-form-dateselector';
81 $function = 'M.form.dateselector.init_date_selectors';
82 $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
83 $PAGE->requires->yui_module($module, $function, $config);
89 * Wrapper that separates quickforms syntax from moodle code
91 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
92 * use this class you should write a class definition which extends this class or a more specific
93 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
95 * You will write your own definition() method which performs the form set up.
98 * @copyright 2006 Jamie Pratt <me@jamiep.org>
99 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
100 * @todo MDL-19380 rethink the file scanning
102 abstract class moodleform {
103 /** @var string name of the form */
104 protected $_formname; // form name
106 /** @var MoodleQuickForm quickform object definition */
109 /** @var array globals workaround */
110 protected $_customdata;
112 /** @var object definition_after_data executed flag */
113 protected $_definition_finalized = false;
116 * The constructor function calls the abstract function definition() and it will then
117 * process and clean and attempt to validate incoming data.
119 * It will call your custom validate method to validate data and will also check any rules
120 * you have specified in definition using addRule
122 * The name of the form (id attribute of the form) is automatically generated depending on
123 * the name you gave the class extending moodleform. You should call your class something
126 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
127 * current url. If a moodle_url object then outputs params as hidden variables.
128 * @param mixed $customdata if your form defintion method needs access to data such as $course
129 * $cm, etc. to construct the form definition then pass it in this array. You can
130 * use globals for somethings.
131 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
132 * be merged and used as incoming data to the form.
133 * @param string $target target frame for form submission. You will rarely use this. Don't use
134 * it if you don't need to as the target attribute is deprecated in xhtml strict.
135 * @param mixed $attributes you can pass a string of html attributes here or an array.
136 * @param bool $editable
138 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
139 global $CFG, $FULLME;
140 if (empty($CFG->xmlstrictheaders)) {
141 // no standard mform in moodle should allow autocomplete with the exception of user signup
142 // this is valid attribute in html5, sorry, we have to ignore validation errors in legacy xhtml 1.0
143 if (empty($attributes)) {
144 $attributes = array('autocomplete'=>'off');
145 } else if (is_array($attributes)) {
146 $attributes['autocomplete'] = 'off';
148 if (strpos($attributes, 'autocomplete') === false) {
149 $attributes .= ' autocomplete="off" ';
155 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
156 $action = strip_querystring($FULLME);
157 if (!empty($CFG->sslproxy)) {
158 // return only https links when using SSL proxy
159 $action = preg_replace('/^http:/', 'https:', $action, 1);
161 //TODO: use following instead of FULLME - see MDL-33015
162 //$action = strip_querystring(qualified_me());
164 // Assign custom data first, so that get_form_identifier can use it.
165 $this->_customdata = $customdata;
166 $this->_formname = $this->get_form_identifier();
168 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
170 $this->_form->hardFreeze();
175 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
176 $this->_form->setType('sesskey', PARAM_RAW);
177 $this->_form->setDefault('sesskey', sesskey());
178 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
179 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
180 $this->_form->setDefault('_qf__'.$this->_formname, 1);
181 $this->_form->_setDefaultRuleMessages();
183 // we have to know all input types before processing submission ;-)
184 $this->_process_submission($method);
188 * It should returns unique identifier for the form.
189 * Currently it will return class name, but in case two same forms have to be
190 * rendered on same page then override function to get unique form identifier.
191 * e.g This is used on multiple self enrollments page.
193 * @return string form identifier.
195 protected function get_form_identifier() {
196 return get_class($this);
200 * To autofocus on first form element or first element with error.
202 * @param string $name if this is set then the focus is forced to a field with this name
203 * @return string javascript to select form element with first error or
204 * first element if no errors. Use this as a parameter
205 * when calling print_header
207 function focus($name=NULL) {
208 $form =& $this->_form;
209 $elkeys = array_keys($form->_elementIndex);
211 if (isset($form->_errors) && 0 != count($form->_errors)){
212 $errorkeys = array_keys($form->_errors);
213 $elkeys = array_intersect($elkeys, $errorkeys);
217 if ($error or empty($name)) {
219 while (empty($names) and !empty($elkeys)) {
220 $el = array_shift($elkeys);
221 $names = $form->_getElNamesRecursive($el);
223 if (!empty($names)) {
224 $name = array_shift($names);
230 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
237 * Internal method. Alters submitted data to be suitable for quickforms processing.
238 * Must be called when the form is fully set up.
240 * @param string $method name of the method which alters submitted data
242 function _process_submission($method) {
243 $submission = array();
244 if ($method == 'post') {
245 if (!empty($_POST)) {
246 $submission = $_POST;
249 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
252 // following trick is needed to enable proper sesskey checks when using GET forms
253 // the _qf__.$this->_formname serves as a marker that form was actually submitted
254 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
255 if (!confirm_sesskey()) {
256 print_error('invalidsesskey');
260 $submission = array();
264 $this->_form->updateSubmission($submission, $files);
268 * Internal method. Validates all old-style deprecated uploaded files.
269 * The new way is to upload files via repository api.
271 * @param array $files list of files to be validated
272 * @return bool|array Success or an array of errors
274 function _validate_files(&$files) {
275 global $CFG, $COURSE;
279 if (empty($_FILES)) {
280 // we do not need to do any checks because no files were submitted
281 // note: server side rules do not work for files - use custom verification in validate() instead
286 $filenames = array();
288 // now check that we really want each file
289 foreach ($_FILES as $elname=>$file) {
290 $required = $this->_form->isElementRequired($elname);
292 if ($file['error'] == 4 and $file['size'] == 0) {
294 $errors[$elname] = get_string('required');
296 unset($_FILES[$elname]);
300 if (!empty($file['error'])) {
301 $errors[$elname] = file_get_upload_error($file['error']);
302 unset($_FILES[$elname]);
306 if (!is_uploaded_file($file['tmp_name'])) {
307 // TODO: improve error message
308 $errors[$elname] = get_string('error');
309 unset($_FILES[$elname]);
313 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
314 // hmm, this file was not requested
315 unset($_FILES[$elname]);
320 // TODO: rethink the file scanning MDL-19380
321 if ($CFG->runclamonupload) {
322 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
323 $errors[$elname] = $_FILES[$elname]['uploadlog'];
324 unset($_FILES[$elname]);
329 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
330 if ($filename === '') {
331 // TODO: improve error message - wrong chars
332 $errors[$elname] = get_string('error');
333 unset($_FILES[$elname]);
336 if (in_array($filename, $filenames)) {
337 // TODO: improve error message - duplicate name
338 $errors[$elname] = get_string('error');
339 unset($_FILES[$elname]);
342 $filenames[] = $filename;
343 $_FILES[$elname]['name'] = $filename;
345 $files[$elname] = $_FILES[$elname]['tmp_name'];
348 // return errors if found
349 if (count($errors) == 0){
359 * Internal method. Validates filepicker and filemanager files if they are
360 * set as required fields. Also, sets the error message if encountered one.
362 * @return bool|array with errors
364 protected function validate_draft_files() {
366 $mform =& $this->_form;
369 //Go through all the required elements and make sure you hit filepicker or
370 //filemanager element.
371 foreach ($mform->_rules as $elementname => $rules) {
372 $elementtype = $mform->getElementType($elementname);
373 //If element is of type filepicker then do validation
374 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
375 //Check if rule defined is required rule
376 foreach ($rules as $rule) {
377 if ($rule['type'] == 'required') {
378 $draftid = (int)$mform->getSubmitValue($elementname);
379 $fs = get_file_storage();
380 $context = get_context_instance(CONTEXT_USER, $USER->id);
381 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
382 $errors[$elementname] = $rule['message'];
388 if (empty($errors)) {
396 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
397 * form definition (new entry form); this function is used to load in data where values
398 * already exist and data is being edited (edit entry form).
400 * note: $slashed param removed
402 * @param stdClass|array $default_values object or array of default values
404 function set_data($default_values) {
405 if (is_object($default_values)) {
406 $default_values = (array)$default_values;
408 $this->_form->setDefaults($default_values);
412 * Sets file upload manager
414 * @deprecated since Moodle 2.0 Please don't used this API
415 * @todo MDL-31300 this api will be removed.
416 * @see MoodleQuickForm_filepicker
417 * @see MoodleQuickForm_filemanager
418 * @param bool $um upload manager
420 function set_upload_manager($um=false) {
421 debugging('Old file uploads can not be used any more, please use new filepicker element');
425 * Check that form was submitted. Does not check validity of submitted data.
427 * @return bool true if form properly submitted
429 function is_submitted() {
430 return $this->_form->isSubmitted();
434 * Checks if button pressed is not for submitting the form
436 * @staticvar bool $nosubmit keeps track of no submit button
439 function no_submit_button_pressed(){
440 static $nosubmit = null; // one check is enough
441 if (!is_null($nosubmit)){
444 $mform =& $this->_form;
446 if (!$this->is_submitted()){
449 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
450 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
460 * Check that form data is valid.
461 * You should almost always use this, rather than {@link validate_defined_fields}
463 * @return bool true if form data valid
465 function is_validated() {
466 //finalize the form definition before any processing
467 if (!$this->_definition_finalized) {
468 $this->_definition_finalized = true;
469 $this->definition_after_data();
472 return $this->validate_defined_fields();
478 * You almost always want to call {@link is_validated} instead of this
479 * because it calls {@link definition_after_data} first, before validating the form,
480 * which is what you want in 99% of cases.
482 * This is provided as a separate function for those special cases where
483 * you want the form validated before definition_after_data is called
484 * for example, to selectively add new elements depending on a no_submit_button press,
485 * but only when the form is valid when the no_submit_button is pressed,
487 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
488 * is NOT to validate the form when a no submit button has been pressed.
489 * pass true here to override this behaviour
491 * @return bool true if form data valid
493 function validate_defined_fields($validateonnosubmit=false) {
494 static $validated = null; // one validation is enough
495 $mform =& $this->_form;
496 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
498 } elseif ($validated === null) {
499 $internal_val = $mform->validate();
502 $file_val = $this->_validate_files($files);
503 //check draft files for validation and flag them if required files
504 //are not in draft area.
505 $draftfilevalue = $this->validate_draft_files();
507 if ($file_val !== true && $draftfilevalue !== true) {
508 $file_val = array_merge($file_val, $draftfilevalue);
509 } else if ($draftfilevalue !== true) {
510 $file_val = $draftfilevalue;
511 } //default is file_val, so no need to assign.
513 if ($file_val !== true) {
514 if (!empty($file_val)) {
515 foreach ($file_val as $element=>$msg) {
516 $mform->setElementError($element, $msg);
522 $data = $mform->exportValues();
523 $moodle_val = $this->validation($data, $files);
524 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
525 // non-empty array means errors
526 foreach ($moodle_val as $element=>$msg) {
527 $mform->setElementError($element, $msg);
532 // anything else means validation ok
536 $validated = ($internal_val and $moodle_val and $file_val);
542 * Return true if a cancel button has been pressed resulting in the form being submitted.
544 * @return bool true if a cancel button has been pressed
546 function is_cancelled(){
547 $mform =& $this->_form;
548 if ($mform->isSubmitted()){
549 foreach ($mform->_cancelButtons as $cancelbutton){
550 if (optional_param($cancelbutton, 0, PARAM_RAW)){
559 * Return submitted data if properly submitted or returns NULL if validation fails or
560 * if there is no submitted data.
562 * note: $slashed param removed
564 * @return object submitted data; NULL if not valid or not submitted or cancelled
566 function get_data() {
567 $mform =& $this->_form;
569 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
570 $data = $mform->exportValues();
571 unset($data['sesskey']); // we do not need to return sesskey
572 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
576 return (object)$data;
584 * Return submitted data without validation or NULL if there is no submitted data.
585 * note: $slashed param removed
587 * @return object submitted data; NULL if not submitted
589 function get_submitted_data() {
590 $mform =& $this->_form;
592 if ($this->is_submitted()) {
593 $data = $mform->exportValues();
594 unset($data['sesskey']); // we do not need to return sesskey
595 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
599 return (object)$data;
607 * Save verified uploaded files into directory. Upload process can be customised from definition()
609 * @deprecated since Moodle 2.0
610 * @todo MDL-31294 remove this api
611 * @see moodleform::save_stored_file()
612 * @see moodleform::save_file()
613 * @param string $destination path where file should be stored
614 * @return bool Always false
616 function save_files($destination) {
617 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
622 * Returns name of uploaded file.
624 * @param string $elname first element if null
625 * @return string|bool false in case of failure, string if ok
627 function get_new_filename($elname=null) {
630 if (!$this->is_submitted() or !$this->is_validated()) {
634 if (is_null($elname)) {
635 if (empty($_FILES)) {
639 $elname = key($_FILES);
642 if (empty($elname)) {
646 $element = $this->_form->getElement($elname);
648 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
649 $values = $this->_form->exportValues($elname);
650 if (empty($values[$elname])) {
653 $draftid = $values[$elname];
654 $fs = get_file_storage();
655 $context = get_context_instance(CONTEXT_USER, $USER->id);
656 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
659 $file = reset($files);
660 return $file->get_filename();
663 if (!isset($_FILES[$elname])) {
667 return $_FILES[$elname]['name'];
671 * Save file to standard filesystem
673 * @param string $elname name of element
674 * @param string $pathname full path name of file
675 * @param bool $override override file if exists
676 * @return bool success
678 function save_file($elname, $pathname, $override=false) {
681 if (!$this->is_submitted() or !$this->is_validated()) {
684 if (file_exists($pathname)) {
686 if (!@unlink($pathname)) {
694 $element = $this->_form->getElement($elname);
696 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
697 $values = $this->_form->exportValues($elname);
698 if (empty($values[$elname])) {
701 $draftid = $values[$elname];
702 $fs = get_file_storage();
703 $context = get_context_instance(CONTEXT_USER, $USER->id);
704 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
707 $file = reset($files);
709 return $file->copy_content_to($pathname);
711 } else if (isset($_FILES[$elname])) {
712 return copy($_FILES[$elname]['tmp_name'], $pathname);
719 * Returns a temporary file, do not forget to delete after not needed any more.
721 * @param string $elname name of the elmenet
722 * @return string|bool either string or false
724 function save_temp_file($elname) {
725 if (!$this->get_new_filename($elname)) {
728 if (!$dir = make_temp_directory('forms')) {
731 if (!$tempfile = tempnam($dir, 'tempup_')) {
734 if (!$this->save_file($elname, $tempfile, true)) {
735 // something went wrong
744 * Get draft files of a form element
745 * This is a protected method which will be used only inside moodleforms
747 * @param string $elname name of element
748 * @return array|bool|null
750 protected function get_draft_files($elname) {
753 if (!$this->is_submitted()) {
757 $element = $this->_form->getElement($elname);
759 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
760 $values = $this->_form->exportValues($elname);
761 if (empty($values[$elname])) {
764 $draftid = $values[$elname];
765 $fs = get_file_storage();
766 $context = get_context_instance(CONTEXT_USER, $USER->id);
767 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
776 * Save file to local filesystem pool
778 * @param string $elname name of element
779 * @param int $newcontextid id of context
780 * @param string $newcomponent name of the component
781 * @param string $newfilearea name of file area
782 * @param int $newitemid item id
783 * @param string $newfilepath path of file where it get stored
784 * @param string $newfilename use specified filename, if not specified name of uploaded file used
785 * @param bool $overwrite overwrite file if exists
786 * @param int $newuserid new userid if required
787 * @return mixed stored_file object or false if error; may throw exception if duplicate found
789 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
790 $newfilename=null, $overwrite=false, $newuserid=null) {
793 if (!$this->is_submitted() or !$this->is_validated()) {
797 if (empty($newuserid)) {
798 $newuserid = $USER->id;
801 $element = $this->_form->getElement($elname);
802 $fs = get_file_storage();
804 if ($element instanceof MoodleQuickForm_filepicker) {
805 $values = $this->_form->exportValues($elname);
806 if (empty($values[$elname])) {
809 $draftid = $values[$elname];
810 $context = get_context_instance(CONTEXT_USER, $USER->id);
811 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
814 $file = reset($files);
815 if (is_null($newfilename)) {
816 $newfilename = $file->get_filename();
820 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
821 if (!$oldfile->delete()) {
827 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
828 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
829 return $fs->create_file_from_storedfile($file_record, $file);
831 } else if (isset($_FILES[$elname])) {
832 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
835 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
836 if (!$oldfile->delete()) {
842 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
843 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
844 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
851 * Get content of uploaded file.
853 * @param string $elname name of file upload element
854 * @return string|bool false in case of failure, string if ok
856 function get_file_content($elname) {
859 if (!$this->is_submitted() or !$this->is_validated()) {
863 $element = $this->_form->getElement($elname);
865 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
866 $values = $this->_form->exportValues($elname);
867 if (empty($values[$elname])) {
870 $draftid = $values[$elname];
871 $fs = get_file_storage();
872 $context = get_context_instance(CONTEXT_USER, $USER->id);
873 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
876 $file = reset($files);
878 return $file->get_content();
880 } else if (isset($_FILES[$elname])) {
881 return file_get_contents($_FILES[$elname]['tmp_name']);
891 //finalize the form definition if not yet done
892 if (!$this->_definition_finalized) {
893 $this->_definition_finalized = true;
894 $this->definition_after_data();
896 $this->_form->display();
900 * Form definition. Abstract method - always override!
902 protected abstract function definition();
905 * Dummy stub method - override if you need to setup the form depending on current
906 * values. This method is called after definition(), data submission and set_data().
907 * All form setup that is dependent on form values should go in here.
909 function definition_after_data(){
913 * Dummy stub method - override if you needed to perform some extra validation.
914 * If there are errors return array of errors ("fieldname"=>"error message"),
915 * otherwise true if ok.
917 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
919 * @param array $data array of ("fieldname"=>value) of submitted data
920 * @param array $files array of uploaded files "element_name"=>tmp_file_path
921 * @return array of "element_name"=>"error_description" if there are errors,
922 * or an empty array if everything is OK (true allowed for backwards compatibility too).
924 function validation($data, $files) {
929 * Helper used by {@link repeat_elements()}.
931 * @param int $i the index of this element.
932 * @param HTML_QuickForm_element $elementclone
933 * @param array $namecloned array of names
935 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
936 $name = $elementclone->getName();
937 $namecloned[] = $name;
940 $elementclone->setName($name."[$i]");
943 if (is_a($elementclone, 'HTML_QuickForm_header')) {
944 $value = $elementclone->_text;
945 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
947 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
948 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
951 $value=$elementclone->getLabel();
952 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
957 * Method to add a repeating group of elements to a form.
959 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
960 * @param int $repeats no of times to repeat elements initially
961 * @param array $options Array of options to apply to elements. Array keys are element names.
962 * This is an array of arrays. The second sets of keys are the option types for the elements :
963 * 'default' - default value is value
964 * 'type' - PARAM_* constant is value
965 * 'helpbutton' - helpbutton params array is value
966 * 'disabledif' - last three moodleform::disabledIf()
967 * params are value as an array
968 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
969 * @param string $addfieldsname name for button to add more fields
970 * @param int $addfieldsno how many fields to add at a time
971 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
972 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
973 * @return int no of repeats of element in this page
975 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
976 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
977 if ($addstring===null){
978 $addstring = get_string('addfields', 'form', $addfieldsno);
980 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
982 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
983 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
984 if (!empty($addfields)){
985 $repeats += $addfieldsno;
987 $mform =& $this->_form;
988 $mform->registerNoSubmitButton($addfieldsname);
989 $mform->addElement('hidden', $repeathiddenname, $repeats);
990 $mform->setType($repeathiddenname, PARAM_INT);
991 //value not to be overridden by submitted value
992 $mform->setConstants(array($repeathiddenname=>$repeats));
993 $namecloned = array();
994 for ($i = 0; $i < $repeats; $i++) {
995 foreach ($elementobjs as $elementobj){
996 $elementclone = fullclone($elementobj);
997 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
999 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1000 foreach ($elementclone->getElements() as $el) {
1001 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1003 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1006 $mform->addElement($elementclone);
1009 for ($i=0; $i<$repeats; $i++) {
1010 foreach ($options as $elementname => $elementoptions){
1011 $pos=strpos($elementname, '[');
1013 $realelementname = substr($elementname, 0, $pos)."[$i]";
1014 $realelementname .= substr($elementname, $pos);
1016 $realelementname = $elementname."[$i]";
1018 foreach ($elementoptions as $option => $params){
1022 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1025 $params = array_merge(array($realelementname), $params);
1026 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1029 foreach ($namecloned as $num => $name){
1030 if ($params[0] == $name){
1031 $params[0] = $params[0]."[$i]";
1035 $params = array_merge(array($realelementname), $params);
1036 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1039 if (is_string($params)){
1040 $params = array(null, $params, null, 'client');
1042 $params = array_merge(array($realelementname), $params);
1043 call_user_func_array(array(&$mform, 'addRule'), $params);
1046 //Type should be set only once
1047 if (!isset($mform->_types[$elementname])) {
1048 $mform->setType($elementname, $params);
1055 $mform->addElement('submit', $addfieldsname, $addstring);
1057 if (!$addbuttoninside) {
1058 $mform->closeHeaderBefore($addfieldsname);
1065 * Adds a link/button that controls the checked state of a group of checkboxes.
1067 * @param int $groupid The id of the group of advcheckboxes this element controls
1068 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1069 * @param array $attributes associative array of HTML attributes
1070 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1072 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1075 // Name of the controller button
1076 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1077 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1078 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1080 // Set the default text if none was specified
1082 $text = get_string('selectallornone', 'form');
1085 $mform = $this->_form;
1086 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1087 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1089 $newselectvalue = $selectvalue;
1090 if (is_null($selectvalue)) {
1091 $newselectvalue = $originalValue;
1092 } else if (!is_null($contollerbutton)) {
1093 $newselectvalue = (int) !$selectvalue;
1095 // set checkbox state depending on orignal/submitted value by controoler button
1096 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1097 foreach ($mform->_elements as $element) {
1098 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1099 $element->getAttribute('class') == $checkboxgroupclass &&
1100 !$element->isFrozen()) {
1101 $mform->setConstants(array($element->getName() => $newselectvalue));
1106 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1107 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1108 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1110 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1112 array('groupid' => $groupid,
1113 'checkboxclass' => $checkboxgroupclass,
1114 'checkboxcontroller' => $checkboxcontrollerparam,
1115 'controllerbutton' => $checkboxcontrollername)
1119 require_once("$CFG->libdir/form/submit.php");
1120 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1121 $mform->addElement($submitlink);
1122 $mform->registerNoSubmitButton($checkboxcontrollername);
1123 $mform->setDefault($checkboxcontrollername, $text);
1127 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1128 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1129 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1130 * get data with get_data().
1132 * @param bool $cancel whether to show cancel button, default true
1133 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1135 function add_action_buttons($cancel = true, $submitlabel=null){
1136 if (is_null($submitlabel)){
1137 $submitlabel = get_string('savechanges');
1139 $mform =& $this->_form;
1141 //when two elements we need a group
1142 $buttonarray=array();
1143 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1144 $buttonarray[] = &$mform->createElement('cancel');
1145 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1146 $mform->closeHeaderBefore('buttonar');
1149 $mform->addElement('submit', 'submitbutton', $submitlabel);
1150 $mform->closeHeaderBefore('submitbutton');
1155 * Adds an initialisation call for a standard JavaScript enhancement.
1157 * This function is designed to add an initialisation call for a JavaScript
1158 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1162 * - smartselect: Turns a nbsp indented select box into a custom drop down
1163 * control that supports multilevel and category selection.
1164 * $enhancement = 'smartselect';
1165 * $options = array('selectablecategories' => true|false)
1168 * @param string|element $element form element for which Javascript needs to be initalized
1169 * @param string $enhancement which init function should be called
1170 * @param array $options options passed to javascript
1171 * @param array $strings strings for javascript
1173 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1175 if (is_string($element)) {
1176 $element = $this->_form->getElement($element);
1178 if (is_object($element)) {
1179 $element->_generateId();
1180 $elementid = $element->getAttribute('id');
1181 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1182 if (is_array($strings)) {
1183 foreach ($strings as $string) {
1184 if (is_array($string)) {
1185 call_user_method_array('string_for_js', $PAGE->requires, $string);
1187 $PAGE->requires->string_for_js($string, 'moodle');
1195 * Returns a JS module definition for the mforms JS
1199 public static function get_js_module() {
1203 'fullpath' => '/lib/form/form.js',
1204 'requires' => array('base', 'node'),
1206 array('showadvanced', 'form'),
1207 array('hideadvanced', 'form')
1214 * MoodleQuickForm implementation
1216 * You never extend this class directly. The class methods of this class are available from
1217 * the private $this->_form property on moodleform and its children. You generally only
1218 * call methods on this class from within abstract methods that you override on moodleform such
1219 * as definition and definition_after_data
1221 * @package core_form
1223 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1226 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1227 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1228 var $_types = array();
1230 /** @var array dependent state for the element/'s */
1231 var $_dependencies = array();
1233 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1234 var $_noSubmitButtons=array();
1236 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1237 var $_cancelButtons=array();
1239 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1240 var $_advancedElements = array();
1242 /** @var bool Whether to display advanced elements (on page load) */
1243 var $_showAdvanced = null;
1246 * The form name is derived from the class name of the wrapper minus the trailing form
1247 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1250 var $_formName = '';
1253 * String with the html for hidden params passed in as part of a moodle_url
1254 * object for the action. Output in the form.
1257 var $_pageparams = '';
1260 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1262 * @staticvar int $formcounter counts number of forms
1263 * @param string $formName Form's name.
1264 * @param string $method Form's method defaults to 'POST'
1265 * @param string|moodle_url $action Form's action
1266 * @param string $target (optional)Form's target defaults to none
1267 * @param mixed $attributes (optional)Extra attributes for <form> tag
1269 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1270 global $CFG, $OUTPUT;
1272 static $formcounter = 1;
1274 HTML_Common::HTML_Common($attributes);
1275 $target = empty($target) ? array() : array('target' => $target);
1276 $this->_formName = $formName;
1277 if (is_a($action, 'moodle_url')){
1278 $this->_pageparams = html_writer::input_hidden_params($action);
1279 $action = $action->out_omit_querystring();
1281 $this->_pageparams = '';
1283 //no 'name' atttribute for form in xhtml strict :
1284 $attributes = array('action'=>$action, 'method'=>$method,
1285 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1287 $this->updateAttributes($attributes);
1289 //this is custom stuff for Moodle :
1290 $oldclass= $this->getAttribute('class');
1291 if (!empty($oldclass)){
1292 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1294 $this->updateAttributes(array('class'=>'mform'));
1296 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1297 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1298 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1302 * Use this method to indicate an element in a form is an advanced field. If items in a form
1303 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1304 * form so the user can decide whether to display advanced form controls.
1306 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1308 * @param string $elementName group or element name (not the element name of something inside a group).
1309 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1311 function setAdvanced($elementName, $advanced=true){
1313 $this->_advancedElements[$elementName]='';
1314 } elseif (isset($this->_advancedElements[$elementName])) {
1315 unset($this->_advancedElements[$elementName]);
1317 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1318 $this->setShowAdvanced();
1319 $this->registerNoSubmitButton('mform_showadvanced');
1321 $this->addElement('hidden', 'mform_showadvanced_last');
1322 $this->setType('mform_showadvanced_last', PARAM_INT);
1326 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1327 * display advanced elements in the form until 'Show Advanced' is pressed.
1329 * You can get the last state of the form and possibly save it for this user by using
1330 * value 'mform_showadvanced_last' in submitted data.
1332 * @param bool $showadvancedNow if true will show adavance elements.
1334 function setShowAdvanced($showadvancedNow = null){
1335 if ($showadvancedNow === null){
1336 if ($this->_showAdvanced !== null){
1338 } else { //if setShowAdvanced is called without any preference
1339 //make the default to not show advanced elements.
1340 $showadvancedNow = get_user_preferences(
1341 textlib::strtolower($this->_formName.'_showadvanced', 0));
1344 //value of hidden element
1345 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1347 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1348 //toggle if button pressed or else stay the same
1349 if ($hiddenLast == -1) {
1350 $next = $showadvancedNow;
1351 } elseif ($buttonPressed) { //toggle on button press
1352 $next = !$hiddenLast;
1354 $next = $hiddenLast;
1356 $this->_showAdvanced = $next;
1357 if ($showadvancedNow != $next){
1358 set_user_preference($this->_formName.'_showadvanced', $next);
1360 $this->setConstants(array('mform_showadvanced_last'=>$next));
1364 * Gets show advance value, if advance elements are visible it will return true else false
1368 function getShowAdvanced(){
1369 return $this->_showAdvanced;
1374 * Accepts a renderer
1376 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1378 function accept(&$renderer) {
1379 if (method_exists($renderer, 'setAdvancedElements')){
1380 //check for visible fieldsets where all elements are advanced
1381 //and mark these headers as advanced as well.
1382 //And mark all elements in a advanced header as advanced
1383 $stopFields = $renderer->getStopFieldSetElements();
1385 $lastHeaderAdvanced = false;
1386 $anyAdvanced = false;
1387 foreach (array_keys($this->_elements) as $elementIndex){
1388 $element =& $this->_elements[$elementIndex];
1390 // if closing header and any contained element was advanced then mark it as advanced
1391 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1392 if ($anyAdvanced && !is_null($lastHeader)){
1393 $this->setAdvanced($lastHeader->getName());
1395 $lastHeaderAdvanced = false;
1398 } elseif ($lastHeaderAdvanced) {
1399 $this->setAdvanced($element->getName());
1402 if ($element->getType()=='header'){
1403 $lastHeader =& $element;
1404 $anyAdvanced = false;
1405 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1406 } elseif (isset($this->_advancedElements[$element->getName()])){
1407 $anyAdvanced = true;
1410 // the last header may not be closed yet...
1411 if ($anyAdvanced && !is_null($lastHeader)){
1412 $this->setAdvanced($lastHeader->getName());
1414 $renderer->setAdvancedElements($this->_advancedElements);
1417 parent::accept($renderer);
1421 * Adds one or more element names that indicate the end of a fieldset
1423 * @param string $elementName name of the element
1425 function closeHeaderBefore($elementName){
1426 $renderer =& $this->defaultRenderer();
1427 $renderer->addStopFieldsetElements($elementName);
1431 * Should be used for all elements of a form except for select, radio and checkboxes which
1432 * clean their own data.
1434 * @param string $elementname
1435 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1436 * {@link lib/moodlelib.php} for defined parameter types
1438 function setType($elementname, $paramtype) {
1439 $this->_types[$elementname] = $paramtype;
1443 * This can be used to set several types at once.
1445 * @param array $paramtypes types of parameters.
1446 * @see MoodleQuickForm::setType
1448 function setTypes($paramtypes) {
1449 $this->_types = $paramtypes + $this->_types;
1453 * Updates submitted values
1455 * @param array $submission submitted values
1456 * @param array $files list of files
1458 function updateSubmission($submission, $files) {
1459 $this->_flagSubmitted = false;
1461 if (empty($submission)) {
1462 $this->_submitValues = array();
1464 foreach ($submission as $key=>$s) {
1465 if (array_key_exists($key, $this->_types)) {
1466 $type = $this->_types[$key];
1471 $submission[$key] = clean_param_array($s, $type, true);
1473 $submission[$key] = clean_param($s, $type);
1476 $this->_submitValues = $submission;
1477 $this->_flagSubmitted = true;
1480 if (empty($files)) {
1481 $this->_submitFiles = array();
1483 $this->_submitFiles = $files;
1484 $this->_flagSubmitted = true;
1487 // need to tell all elements that they need to update their value attribute.
1488 foreach (array_keys($this->_elements) as $key) {
1489 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1494 * Returns HTML for required elements
1498 function getReqHTML(){
1499 return $this->_reqHTML;
1503 * Returns HTML for advanced elements
1507 function getAdvancedHTML(){
1508 return $this->_advancedHTML;
1512 * Initializes a default form value. Used to specify the default for a new entry where
1513 * no data is loaded in using moodleform::set_data()
1515 * note: $slashed param removed
1517 * @param string $elementName element name
1518 * @param mixed $defaultValue values for that element name
1520 function setDefault($elementName, $defaultValue){
1521 $this->setDefaults(array($elementName=>$defaultValue));
1525 * Add an array of buttons to the form
1527 * @param array $buttons An associative array representing help button to attach to
1528 * to the form. keys of array correspond to names of elements in form.
1529 * @param bool $suppresscheck if true then string check will be suppressed
1530 * @param string $function callback function to dispaly help button.
1531 * @deprecated since Moodle 2.0 use addHelpButton() call on each element manually
1532 * @todo MDL-31047 this api will be removed.
1533 * @see MoodleQuickForm::addHelpButton()
1535 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1537 debugging('function moodle_form::setHelpButtons() is deprecated');
1538 //foreach ($buttons as $elementname => $button){
1539 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1544 * Add a help button to element
1546 * @param string $elementname name of the element to add the item to
1547 * @param array $buttonargs arguments to pass to function $function
1548 * @param bool $suppresscheck whether to throw an error if the element
1550 * @param string $function - function to generate html from the arguments in $button
1551 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1552 * @todo MDL-31047 this api will be removed.
1553 * @see MoodleQuickForm::addHelpButton()
1555 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1558 debugging('function moodle_form::setHelpButton() is deprecated');
1559 if ($function !== 'helpbutton') {
1560 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1563 $buttonargs = (array)$buttonargs;
1565 if (array_key_exists($elementname, $this->_elementIndex)) {
1566 //_elements has a numeric index, this code accesses the elements by name
1567 $element = $this->_elements[$this->_elementIndex[$elementname]];
1569 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1570 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1571 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1572 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1574 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1576 } else if (!$suppresscheck) {
1577 print_error('nonexistentformelements', 'form', '', $elementname);
1582 * Add a help button to element, only one button per element is allowed.
1584 * This is new, simplified and preferable method of setting a help icon on form elements.
1585 * It uses the new $OUTPUT->help_icon().
1587 * Typically, you will provide the same identifier and the component as you have used for the
1588 * label of the element. The string identifier with the _help suffix added is then used
1589 * as the help string.
1591 * There has to be two strings defined:
1592 * 1/ get_string($identifier, $component) - the title of the help page
1593 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1596 * @param string $elementname name of the element to add the item to
1597 * @param string $identifier help string identifier without _help suffix
1598 * @param string $component component name to look the help string in
1599 * @param string $linktext optional text to display next to the icon
1600 * @param bool $suppresscheck set to true if the element may not exist
1602 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1604 if (array_key_exists($elementname, $this->_elementIndex)) {
1605 $element = $this->_elements[$this->_elementIndex[$elementname]];
1606 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1607 } else if (!$suppresscheck) {
1608 debugging(get_string('nonexistentformelements', 'form', $elementname));
1613 * Set constant value not overridden by _POST or _GET
1614 * note: this does not work for complex names with [] :-(
1616 * @param string $elname name of element
1617 * @param mixed $value
1619 function setConstant($elname, $value) {
1620 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1621 $element =& $this->getElement($elname);
1622 $element->onQuickFormEvent('updateValue', null, $this);
1626 * export submitted values
1628 * @param string $elementList list of elements in form
1631 function exportValues($elementList = null){
1632 $unfiltered = array();
1633 if (null === $elementList) {
1634 // iterate over all elements, calling their exportValue() methods
1635 $emptyarray = array();
1636 foreach (array_keys($this->_elements) as $key) {
1637 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1638 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1640 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1643 if (is_array($value)) {
1644 // This shit throws a bogus warning in PHP 4.3.x
1645 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1649 if (!is_array($elementList)) {
1650 $elementList = array_map('trim', explode(',', $elementList));
1652 foreach ($elementList as $elementName) {
1653 $value = $this->exportValue($elementName);
1654 if (@PEAR::isError($value)) {
1657 //oh, stock QuickFOrm was returning array of arrays!
1658 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1662 if (is_array($this->_constantValues)) {
1663 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1670 * Adds a validation rule for the given field
1672 * If the element is in fact a group, it will be considered as a whole.
1673 * To validate grouped elements as separated entities,
1674 * use addGroupRule instead of addRule.
1676 * @param string $element Form element name
1677 * @param string $message Message to display for invalid data
1678 * @param string $type Rule type, use getRegisteredRules() to get types
1679 * @param string $format (optional)Required for extra rule data
1680 * @param string $validation (optional)Where to perform validation: "server", "client"
1681 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1682 * @param bool $force Force the rule to be applied, even if the target form element does not exist
1684 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1686 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1687 if ($validation == 'client') {
1688 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1694 * Adds a validation rule for the given group of elements
1696 * Only groups with a name can be assigned a validation rule
1697 * Use addGroupRule when you need to validate elements inside the group.
1698 * Use addRule if you need to validate the group as a whole. In this case,
1699 * the same rule will be applied to all elements in the group.
1700 * Use addRule if you need to validate the group against a function.
1702 * @param string $group Form group name
1703 * @param array|string $arg1 Array for multiple elements or error message string for one element
1704 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1705 * @param string $format (optional)Required for extra rule data
1706 * @param int $howmany (optional)How many valid elements should be in the group
1707 * @param string $validation (optional)Where to perform validation: "server", "client"
1708 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1710 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1712 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1713 if (is_array($arg1)) {
1714 foreach ($arg1 as $rules) {
1715 foreach ($rules as $rule) {
1716 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1718 if ('client' == $validation) {
1719 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1723 } elseif (is_string($arg1)) {
1725 if ($validation == 'client') {
1726 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1732 * Returns the client side validation script
1734 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1735 * and slightly modified to run rules per-element
1736 * Needed to override this because of an error with client side validation of grouped elements.
1738 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1740 function getValidationScript()
1742 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1746 include_once('HTML/QuickForm/RuleRegistry.php');
1747 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1758 foreach ($this->_rules as $elementName => $rules) {
1759 foreach ($rules as $rule) {
1760 if ('client' == $rule['validation']) {
1761 unset($element); //TODO: find out how to properly initialize it
1763 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1764 $rule['message'] = strtr($rule['message'], $js_escape);
1766 if (isset($rule['group'])) {
1767 $group =& $this->getElement($rule['group']);
1768 // No JavaScript validation for frozen elements
1769 if ($group->isFrozen()) {
1772 $elements =& $group->getElements();
1773 foreach (array_keys($elements) as $key) {
1774 if ($elementName == $group->getElementName($key)) {
1775 $element =& $elements[$key];
1779 } elseif ($dependent) {
1781 $element[] =& $this->getElement($elementName);
1782 foreach ($rule['dependent'] as $elName) {
1783 $element[] =& $this->getElement($elName);
1786 $element =& $this->getElement($elementName);
1788 // No JavaScript validation for frozen elements
1789 if (is_object($element) && $element->isFrozen()) {
1791 } elseif (is_array($element)) {
1792 foreach (array_keys($element) as $key) {
1793 if ($element[$key]->isFrozen()) {
1798 //for editor element, [text] is appended to the name.
1799 if ($element->getType() == 'editor') {
1800 $elementName .= '[text]';
1801 //Add format to rule as moodleform check which format is supported by browser
1802 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1803 if (is_null($rule['format'])) {
1804 $rule['format'] = $element->getFormat();
1807 // Fix for bug displaying errors for elements in a group
1808 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1809 $test[$elementName][1]=$element;
1815 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1816 // the form, and then that form field gets corrupted by the code that follows.
1820 <script type="text/javascript">
1823 var skipClientValidation = false;
1825 function qf_errorHandler(element, _qfMsg) {
1826 div = element.parentNode;
1828 if ((div == undefined) || (element.name == undefined)) {
1829 //no checking can be done for undefined elements so let server handle it.
1833 if (_qfMsg != \'\') {
1834 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1836 errorSpan = document.createElement("span");
1837 errorSpan.id = \'id_error_\'+element.name;
1838 errorSpan.className = "error";
1839 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1842 while (errorSpan.firstChild) {
1843 errorSpan.removeChild(errorSpan.firstChild);
1846 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1847 errorSpan.appendChild(document.createElement("br"));
1849 if (div.className.substr(div.className.length - 6, 6) != " error"
1850 && div.className != "error") {
1851 div.className += " error";
1856 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1858 errorSpan.parentNode.removeChild(errorSpan);
1861 if (div.className.substr(div.className.length - 6, 6) == " error") {
1862 div.className = div.className.substr(0, div.className.length - 6);
1863 } else if (div.className == "error") {
1871 foreach ($test as $elementName => $jsandelement) {
1872 // Fix for bug displaying errors for elements in a group
1874 list($jsArr,$element)=$jsandelement;
1876 $escapedElementName = preg_replace_callback(
1878 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1881 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1882 if (undefined == element) {
1883 //required element was not found, then let form be submitted without client side validation
1887 var errFlag = new Array();
1890 var frm = element.parentNode;
1891 if ((undefined != element.name) && (frm != undefined)) {
1892 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1893 frm = frm.parentNode;
1895 ' . join("\n", $jsArr) . '
1896 return qf_errorHandler(element, _qfMsg);
1898 //element name should be defined else error msg will not be displayed.
1904 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1905 if (!ret && !first_focus) {
1907 frm.elements[\''.$elementName.'\'].focus();
1911 // Fix for bug displaying errors for elements in a group
1913 //$element =& $this->getElement($elementName);
1915 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1916 $onBlur = $element->getAttribute('onBlur');
1917 $onChange = $element->getAttribute('onChange');
1918 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1919 'onChange' => $onChange . $valFunc));
1921 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1923 function validate_' . $this->_formName . '(frm) {
1924 if (skipClientValidation) {
1929 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1930 var first_focus = false;
1931 ' . $validateJS . ';
1937 } // end func getValidationScript
1940 * Sets default error message
1942 function _setDefaultRuleMessages(){
1943 foreach ($this->_rules as $field => $rulesarr){
1944 foreach ($rulesarr as $key => $rule){
1945 if ($rule['message']===null){
1947 $a->format=$rule['format'];
1948 $str=get_string('err_'.$rule['type'], 'form', $a);
1949 if (strpos($str, '[[')!==0){
1950 $this->_rules[$field][$key]['message']=$str;
1958 * Get list of attributes which have dependencies
1962 function getLockOptionObject(){
1964 foreach ($this->_dependencies as $dependentOn => $conditions){
1965 $result[$dependentOn] = array();
1966 foreach ($conditions as $condition=>$values) {
1967 $result[$dependentOn][$condition] = array();
1968 foreach ($values as $value=>$dependents) {
1969 $result[$dependentOn][$condition][$value] = array();
1971 foreach ($dependents as $dependent) {
1972 $elements = $this->_getElNamesRecursive($dependent);
1973 if (empty($elements)) {
1974 // probably element inside of some group
1975 $elements = array($dependent);
1977 foreach($elements as $element) {
1978 if ($element == $dependentOn) {
1981 $result[$dependentOn][$condition][$value][] = $element;
1987 return array($this->getAttribute('id'), $result);
1991 * Get names of element or elements in a group.
1993 * @param HTML_QuickForm_group|element $element element group or element object
1996 function _getElNamesRecursive($element) {
1997 if (is_string($element)) {
1998 if (!$this->elementExists($element)) {
2001 $element = $this->getElement($element);
2004 if (is_a($element, 'HTML_QuickForm_group')) {
2005 $elsInGroup = $element->getElements();
2007 foreach ($elsInGroup as $elInGroup){
2008 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2009 // not sure if this would work - groups nested in groups
2010 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2012 $elNames[] = $element->getElementName($elInGroup->getName());
2016 } else if (is_a($element, 'HTML_QuickForm_header')) {
2019 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2022 } else if (method_exists($element, 'getPrivateName') &&
2023 !($element instanceof HTML_QuickForm_advcheckbox)) {
2024 // The advcheckbox element implements a method called getPrivateName,
2025 // but in a way that is not compatible with the generic API, so we
2026 // have to explicitly exclude it.
2027 return array($element->getPrivateName());
2030 $elNames = array($element->getName());
2037 * Adds a dependency for $elementName which will be disabled if $condition is met.
2038 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2039 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2040 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2041 * of the $dependentOn element is $condition (such as equal) to $value.
2043 * @param string $elementName the name of the element which will be disabled
2044 * @param string $dependentOn the name of the element whose state will be checked for condition
2045 * @param string $condition the condition to check
2046 * @param mixed $value used in conjunction with condition.
2048 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
2049 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2050 $this->_dependencies[$dependentOn] = array();
2052 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2053 $this->_dependencies[$dependentOn][$condition] = array();
2055 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2056 $this->_dependencies[$dependentOn][$condition][$value] = array();
2058 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2062 * Registers button as no submit button
2064 * @param string $buttonname name of the button
2066 function registerNoSubmitButton($buttonname){
2067 $this->_noSubmitButtons[]=$buttonname;
2071 * Checks if button is a no submit button, i.e it doesn't submit form
2073 * @param string $buttonname name of the button to check
2076 function isNoSubmitButton($buttonname){
2077 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2081 * Registers a button as cancel button
2083 * @param string $addfieldsname name of the button
2085 function _registerCancelButton($addfieldsname){
2086 $this->_cancelButtons[]=$addfieldsname;
2090 * Displays elements without HTML input tags.
2091 * This method is different to freeze() in that it makes sure no hidden
2092 * elements are included in the form.
2093 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2095 * This function also removes all previously defined rules.
2097 * @param string|array $elementList array or string of element(s) to be frozen
2098 * @return object|bool if element list is not empty then return error object, else true
2100 function hardFreeze($elementList=null)
2102 if (!isset($elementList)) {
2103 $this->_freezeAll = true;
2104 $elementList = array();
2106 if (!is_array($elementList)) {
2107 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2109 $elementList = array_flip($elementList);
2112 foreach (array_keys($this->_elements) as $key) {
2113 $name = $this->_elements[$key]->getName();
2114 if ($this->_freezeAll || isset($elementList[$name])) {
2115 $this->_elements[$key]->freeze();
2116 $this->_elements[$key]->setPersistantFreeze(false);
2117 unset($elementList[$name]);
2120 $this->_rules[$name] = array();
2121 // if field is required, remove the rule
2122 $unset = array_search($name, $this->_required);
2123 if ($unset !== false) {
2124 unset($this->_required[$unset]);
2129 if (!empty($elementList)) {
2130 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);
2136 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2138 * This function also removes all previously defined rules of elements it freezes.
2140 * @throws HTML_QuickForm_Error
2141 * @param array $elementList array or string of element(s) not to be frozen
2142 * @return bool returns true
2144 function hardFreezeAllVisibleExcept($elementList)
2146 $elementList = array_flip($elementList);
2147 foreach (array_keys($this->_elements) as $key) {
2148 $name = $this->_elements[$key]->getName();
2149 $type = $this->_elements[$key]->getType();
2151 if ($type == 'hidden'){
2152 // leave hidden types as they are
2153 } elseif (!isset($elementList[$name])) {
2154 $this->_elements[$key]->freeze();
2155 $this->_elements[$key]->setPersistantFreeze(false);
2158 $this->_rules[$name] = array();
2159 // if field is required, remove the rule
2160 $unset = array_search($name, $this->_required);
2161 if ($unset !== false) {
2162 unset($this->_required[$unset]);
2170 * Tells whether the form was already submitted
2172 * This is useful since the _submitFiles and _submitValues arrays
2173 * may be completely empty after the trackSubmit value is removed.
2177 function isSubmitted()
2179 return parent::isSubmitted() && (!$this->isFrozen());
2184 * MoodleQuickForm renderer
2186 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2187 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2189 * Stylesheet is part of standard theme and should be automatically included.
2191 * @package core_form
2192 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2193 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2195 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2197 /** @var array Element template array */
2198 var $_elementTemplates;
2201 * Template used when opening a hidden fieldset
2202 * (i.e. a fieldset that is opened when there is no header element)
2205 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2207 /** @var string Header Template string */
2208 var $_headerTemplate =
2209 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2211 /** @var string Template used when opening a fieldset */
2212 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2214 /** @var string Template used when closing a fieldset */
2215 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2217 /** @var string Required Note template string */
2218 var $_requiredNoteTemplate =
2219 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2221 /** @var array list of elements which are marked as advance and will be grouped together */
2222 var $_advancedElements = array();
2224 /** @var int Whether to display advanced elements (on page load) 1 => show, 0 => hide */
2230 function MoodleQuickForm_Renderer(){
2231 // switch next two lines for ol li containers for form items.
2232 // $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>');
2233 $this->_elementTemplates = array(
2234 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}"><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
2236 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2238 '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} {help}</label></div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2240 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element} </div></div>',
2242 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2246 parent::HTML_QuickForm_Renderer_Tableless();
2250 * Set element's as adavance element
2252 * @param array $elements form elements which needs to be grouped as advance elements.
2254 function setAdvancedElements($elements){
2255 $this->_advancedElements = $elements;
2259 * What to do when starting the form
2261 * @param MoodleQuickForm $form reference of the form
2263 function startForm(&$form){
2265 $this->_reqHTML = $form->getReqHTML();
2266 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2267 $this->_advancedHTML = $form->getAdvancedHTML();
2268 $this->_showAdvanced = $form->getShowAdvanced();
2269 parent::startForm($form);
2270 if ($form->isFrozen()){
2271 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2273 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2274 $this->_hiddenHtml .= $form->_pageparams;
2277 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2278 'M.core_formchangechecker.init',
2280 'formid' => $form->getAttribute('id')
2283 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2287 * Create advance group of elements
2289 * @param object $group Passed by reference
2290 * @param bool $required if input is required field
2291 * @param string $error error message to display
2293 function startGroup(&$group, $required, $error){
2294 // Make sure the element has an id.
2295 $group->_generateId();
2297 if (method_exists($group, 'getElementTemplateType')){
2298 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2300 $html = $this->_elementTemplates['default'];
2303 if ($this->_showAdvanced){
2304 $advclass = ' advanced';
2306 $advclass = ' advanced hide';
2308 if (isset($this->_advancedElements[$group->getName()])){
2309 $html =str_replace(' {advanced}', $advclass, $html);
2310 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2312 $html =str_replace(' {advanced}', '', $html);
2313 $html =str_replace('{advancedimg}', '', $html);
2315 if (method_exists($group, 'getHelpButton')){
2316 $html =str_replace('{help}', $group->getHelpButton(), $html);
2318 $html =str_replace('{help}', '', $html);
2320 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2321 $html =str_replace('{name}', $group->getName(), $html);
2322 $html =str_replace('{type}', 'fgroup', $html);
2324 $this->_templates[$group->getName()]=$html;
2325 // Fix for bug in tableless quickforms that didn't allow you to stop a
2326 // fieldset before a group of elements.
2327 // if the element name indicates the end of a fieldset, close the fieldset
2328 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2329 && $this->_fieldsetsOpen > 0
2331 $this->_html .= $this->_closeFieldsetTemplate;
2332 $this->_fieldsetsOpen--;
2334 parent::startGroup($group, $required, $error);
2339 * @param HTML_QuickForm_element $element element
2340 * @param bool $required if input is required field
2341 * @param string $error error message to display
2343 function renderElement(&$element, $required, $error){
2344 // Make sure the element has an id.
2345 $element->_generateId();
2347 //adding stuff to place holders in template
2348 //check if this is a group element first
2349 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2350 // so it gets substitutions for *each* element
2351 $html = $this->_groupElementTemplate;
2353 elseif (method_exists($element, 'getElementTemplateType')){
2354 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2356 $html = $this->_elementTemplates['default'];
2358 if ($this->_showAdvanced){
2359 $advclass = ' advanced';
2361 $advclass = ' advanced hide';
2363 if (isset($this->_advancedElements[$element->getName()])){
2364 $html =str_replace(' {advanced}', $advclass, $html);
2366 $html =str_replace(' {advanced}', '', $html);
2368 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2369 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2371 $html =str_replace('{advancedimg}', '', $html);
2373 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2374 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2375 $html =str_replace('{name}', $element->getName(), $html);
2376 if (method_exists($element, 'getHelpButton')){
2377 $html = str_replace('{help}', $element->getHelpButton(), $html);
2379 $html = str_replace('{help}', '', $html);
2382 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2383 $this->_groupElementTemplate = $html;
2385 elseif (!isset($this->_templates[$element->getName()])) {
2386 $this->_templates[$element->getName()] = $html;
2389 parent::renderElement($element, $required, $error);
2393 * Called when visiting a form, after processing all form elements
2394 * Adds required note, form attributes, validation javascript and form content.
2396 * @global moodle_page $PAGE
2397 * @param moodleform $form Passed by reference
2399 function finishForm(&$form){
2401 if ($form->isFrozen()){
2402 $this->_hiddenHtml = '';
2404 parent::finishForm($form);
2405 if (!$form->isFrozen()) {
2406 $args = $form->getLockOptionObject();
2407 if (count($args[1]) > 0) {
2408 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2413 * Called when visiting a header element
2415 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2416 * @global moodle_page $PAGE
2418 function renderHeader(&$header) {
2421 $name = $header->getName();
2423 $id = empty($name) ? '' : ' id="' . $name . '"';
2424 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2425 if (is_null($header->_text)) {
2427 } elseif (!empty($name) && isset($this->_templates[$name])) {
2428 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2430 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2433 if (isset($this->_advancedElements[$name])){
2434 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2435 $elementName='mform_showadvanced';
2436 if ($this->_showAdvanced==0){
2437 $buttonlabel = get_string('showadvanced', 'form');
2439 $buttonlabel = get_string('hideadvanced', 'form');
2441 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2442 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2443 $header_html = str_replace('{button}', $button, $header_html);
2445 $header_html =str_replace('{advancedimg}', '', $header_html);
2446 $header_html = str_replace('{button}', '', $header_html);
2449 if ($this->_fieldsetsOpen > 0) {
2450 $this->_html .= $this->_closeFieldsetTemplate;
2451 $this->_fieldsetsOpen--;
2454 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2455 if ($this->_showAdvanced){
2456 $advclass = ' class="advanced"';
2458 $advclass = ' class="advanced hide"';
2460 if (isset($this->_advancedElements[$name])){
2461 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2463 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2465 $this->_html .= $openFieldsetTemplate . $header_html;
2466 $this->_fieldsetsOpen++;
2470 * Return Array of element names that indicate the end of a fieldset
2474 function getStopFieldsetElements(){
2475 return $this->_stopFieldsetElements;
2480 * Required elements validation
2482 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2484 * @package core_form
2486 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2487 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2489 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2491 * Checks if an element is not empty.
2492 * This is a server-side validation, it works for both text fields and editor fields
2494 * @param string $value Value to check
2495 * @param int|string|array $options Not used yet
2496 * @return bool true if value is not empty
2498 function validate($value, $options = null) {
2500 if (is_array($value) && array_key_exists('text', $value)) {
2501 $value = $value['text'];
2503 if (is_array($value)) {
2504 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2505 $value = implode('', $value);
2507 $stripvalues = array(
2508 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2509 '#(\xc2|\xa0|\s| )#', //any whitespaces actually
2511 if (!empty($CFG->strictformsrequired)) {
2512 $value = preg_replace($stripvalues, '', (string)$value);
2514 if ((string)$value == '') {
2521 * This function returns Javascript code used to build client-side validation.
2522 * It checks if an element is not empty.
2524 * @param int $format format of data which needs to be validated.
2527 function getValidationScript($format = null) {
2529 if (!empty($CFG->strictformsrequired)) {
2530 if (!empty($format) && $format == FORMAT_HTML) {
2531 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)| |\s+/ig, '') == ''");
2533 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2536 return array('', "{jsVar} == ''");
2542 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2543 * @name $_HTML_QuickForm_default_renderer
2545 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2547 /** Please keep this list in alphabetical order. */
2548 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2549 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2550 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2551 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2552 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2553 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2554 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2555 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2556 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2557 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2558 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2559 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2560 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2561 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2562 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2563 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2564 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2565 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2566 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2567 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2568 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2569 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2570 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2571 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2572 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2573 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2574 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2575 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2576 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2577 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2578 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2579 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2580 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2581 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2582 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2583 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2584 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2586 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");