Merge branch 'wip-MDL-25454-master' of git://github.com/marinaglancy/moodle
[moodle.git] / lib / formslib.php
blobd579b8773d0418686c21e957d95ecb8964580b6c
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.
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.
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.
25 * See examples of use of this library in course/edit.php and course/edit_form.php
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.
34 * @copyright Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 * @package core
37 * @subpackage form
40 defined('MOODLE_INTERNAL') || die();
42 /** setup.php includes our hacked pear libs first */
43 require_once 'HTML/QuickForm.php';
44 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
45 require_once 'HTML/QuickForm/Renderer/Tableless.php';
46 require_once 'HTML/QuickForm/Rule.php';
48 require_once $CFG->libdir.'/filelib.php';
50 define('EDITOR_UNLIMITED_FILES', -1);
52 /**
53 * Callback called when PEAR throws an error
55 * @param PEAR_Error $error
57 function pear_handle_error($error){
58 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
59 echo '<br /> <strong>Backtrace </strong>:';
60 print_object($error->backtrace);
63 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
64 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
67 /**
69 * @staticvar bool $done
70 * @global moodle_page $PAGE
72 function form_init_date_js() {
73 global $PAGE;
74 static $done = false;
75 if (!$done) {
76 $module = 'moodle-form-dateselector';
77 $function = 'M.form.dateselector.init_date_selectors';
78 $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
79 $PAGE->requires->yui_module($module, $function, $config);
80 $done = true;
84 /**
85 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
86 * use this class you should write a class definition which extends this class or a more specific
87 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
89 * You will write your own definition() method which performs the form set up.
91 * @package moodlecore
92 * @copyright Jamie Pratt <me@jamiep.org>
93 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
95 abstract class moodleform {
96 /** @var string */
97 protected $_formname; // form name
98 /**
99 * quickform object definition
101 * @var MoodleQuickForm MoodleQuickForm
103 protected $_form;
105 * globals workaround
107 * @var array
109 protected $_customdata;
111 * definition_after_data executed flag
112 * @var object definition_finalized
114 protected $_definition_finalized = false;
117 * The constructor function calls the abstract function definition() and it will then
118 * process and clean and attempt to validate incoming data.
120 * It will call your custom validate method to validate data and will also check any rules
121 * you have specified in definition using addRule
123 * The name of the form (id attribute of the form) is automatically generated depending on
124 * the name you gave the class extending moodleform. You should call your class something
125 * like
127 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
128 * current url. If a moodle_url object then outputs params as hidden variables.
129 * @param array $customdata if your form defintion method needs access to data such as $course
130 * $cm, etc. to construct the form definition then pass it in this array. You can
131 * use globals for somethings.
132 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
133 * be merged and used as incoming data to the form.
134 * @param string $target target frame for form submission. You will rarely use this. Don't use
135 * it if you don't need to as the target attribute is deprecated in xhtml
136 * strict.
137 * @param mixed $attributes you can pass a string of html attributes here or an array.
138 * @param bool $editable
139 * @return object moodleform
141 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
142 if (empty($action)){
143 $action = strip_querystring(qualified_me());
145 // Assign custom data first, so that get_form_identifier can use it.
146 $this->_customdata = $customdata;
147 $this->_formname = $this->get_form_identifier();
149 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
150 if (!$editable){
151 $this->_form->hardFreeze();
154 $this->definition();
156 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
157 $this->_form->setType('sesskey', PARAM_RAW);
158 $this->_form->setDefault('sesskey', sesskey());
159 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
160 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
161 $this->_form->setDefault('_qf__'.$this->_formname, 1);
162 $this->_form->_setDefaultRuleMessages();
164 // we have to know all input types before processing submission ;-)
165 $this->_process_submission($method);
169 * It should returns unique identifier for the form.
170 * Currently it will return class name, but in case two same forms have to be
171 * rendered on same page then override function to get unique form identifier.
172 * e.g This is used on multiple self enrollments page.
174 * @return string form identifier.
176 protected function get_form_identifier() {
177 return get_class($this);
181 * To autofocus on first form element or first element with error.
183 * @param string $name if this is set then the focus is forced to a field with this name
185 * @return string javascript to select form element with first error or
186 * first element if no errors. Use this as a parameter
187 * when calling print_header
189 function focus($name=NULL) {
190 $form =& $this->_form;
191 $elkeys = array_keys($form->_elementIndex);
192 $error = false;
193 if (isset($form->_errors) && 0 != count($form->_errors)){
194 $errorkeys = array_keys($form->_errors);
195 $elkeys = array_intersect($elkeys, $errorkeys);
196 $error = true;
199 if ($error or empty($name)) {
200 $names = array();
201 while (empty($names) and !empty($elkeys)) {
202 $el = array_shift($elkeys);
203 $names = $form->_getElNamesRecursive($el);
205 if (!empty($names)) {
206 $name = array_shift($names);
210 $focus = '';
211 if (!empty($name)) {
212 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
215 return $focus;
219 * Internal method. Alters submitted data to be suitable for quickforms processing.
220 * Must be called when the form is fully set up.
222 * @param string $method
224 function _process_submission($method) {
225 $submission = array();
226 if ($method == 'post') {
227 if (!empty($_POST)) {
228 $submission = $_POST;
230 } else {
231 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
234 // following trick is needed to enable proper sesskey checks when using GET forms
235 // the _qf__.$this->_formname serves as a marker that form was actually submitted
236 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
237 if (!confirm_sesskey()) {
238 print_error('invalidsesskey');
240 $files = $_FILES;
241 } else {
242 $submission = array();
243 $files = array();
246 $this->_form->updateSubmission($submission, $files);
250 * Internal method. Validates all old-style deprecated uploaded files.
251 * The new way is to upload files via repository api.
253 * @global object
254 * @global object
255 * @param array $files
256 * @return bool|array Success or an array of errors
258 function _validate_files(&$files) {
259 global $CFG, $COURSE;
261 $files = array();
263 if (empty($_FILES)) {
264 // we do not need to do any checks because no files were submitted
265 // note: server side rules do not work for files - use custom verification in validate() instead
266 return true;
269 $errors = array();
270 $filenames = array();
272 // now check that we really want each file
273 foreach ($_FILES as $elname=>$file) {
274 $required = $this->_form->isElementRequired($elname);
276 if ($file['error'] == 4 and $file['size'] == 0) {
277 if ($required) {
278 $errors[$elname] = get_string('required');
280 unset($_FILES[$elname]);
281 continue;
284 if (!empty($file['error'])) {
285 $errors[$elname] = file_get_upload_error($file['error']);
286 unset($_FILES[$elname]);
287 continue;
290 if (!is_uploaded_file($file['tmp_name'])) {
291 // TODO: improve error message
292 $errors[$elname] = get_string('error');
293 unset($_FILES[$elname]);
294 continue;
297 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
298 // hmm, this file was not requested
299 unset($_FILES[$elname]);
300 continue;
304 // TODO: rethink the file scanning MDL-19380
305 if ($CFG->runclamonupload) {
306 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
307 $errors[$elname] = $_FILES[$elname]['uploadlog'];
308 unset($_FILES[$elname]);
309 continue;
313 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
314 if ($filename === '') {
315 // TODO: improve error message - wrong chars
316 $errors[$elname] = get_string('error');
317 unset($_FILES[$elname]);
318 continue;
320 if (in_array($filename, $filenames)) {
321 // TODO: improve error message - duplicate name
322 $errors[$elname] = get_string('error');
323 unset($_FILES[$elname]);
324 continue;
326 $filenames[] = $filename;
327 $_FILES[$elname]['name'] = $filename;
329 $files[$elname] = $_FILES[$elname]['tmp_name'];
332 // return errors if found
333 if (count($errors) == 0){
334 return true;
336 } else {
337 $files = array();
338 return $errors;
343 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
344 * form definition (new entry form); this function is used to load in data where values
345 * already exist and data is being edited (edit entry form).
347 * note: $slashed param removed
349 * @param mixed $default_values object or array of default values
351 function set_data($default_values) {
352 if (is_object($default_values)) {
353 $default_values = (array)$default_values;
355 $this->_form->setDefaults($default_values);
359 * @deprecated
361 function set_upload_manager($um=false) {
362 debugging('Old file uploads can not be used any more, please use new filepicker element');
366 * Check that form was submitted. Does not check validity of submitted data.
368 * @return bool true if form properly submitted
370 function is_submitted() {
371 return $this->_form->isSubmitted();
375 * @staticvar bool $nosubmit
377 function no_submit_button_pressed(){
378 static $nosubmit = null; // one check is enough
379 if (!is_null($nosubmit)){
380 return $nosubmit;
382 $mform =& $this->_form;
383 $nosubmit = false;
384 if (!$this->is_submitted()){
385 return false;
387 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
388 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
389 $nosubmit = true;
390 break;
393 return $nosubmit;
398 * Check that form data is valid.
399 * You should almost always use this, rather than {@see validate_defined_fields}
401 * @staticvar bool $validated
402 * @return bool true if form data valid
404 function is_validated() {
405 //finalize the form definition before any processing
406 if (!$this->_definition_finalized) {
407 $this->_definition_finalized = true;
408 $this->definition_after_data();
411 return $this->validate_defined_fields();
415 * Validate the form.
417 * You almost always want to call {@see is_validated} instead of this
418 * because it calls {@see definition_after_data} first, before validating the form,
419 * which is what you want in 99% of cases.
421 * This is provided as a separate function for those special cases where
422 * you want the form validated before definition_after_data is called
423 * for example, to selectively add new elements depending on a no_submit_button press,
424 * but only when the form is valid when the no_submit_button is pressed,
426 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
427 * is NOT to validate the form when a no submit button has been pressed.
428 * pass true here to override this behaviour
430 * @return bool true if form data valid
432 function validate_defined_fields($validateonnosubmit=false) {
433 static $validated = null; // one validation is enough
434 $mform =& $this->_form;
435 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
436 return false;
437 } elseif ($validated === null) {
438 $internal_val = $mform->validate();
440 $files = array();
441 $file_val = $this->_validate_files($files);
442 if ($file_val !== true) {
443 if (!empty($file_val)) {
444 foreach ($file_val as $element=>$msg) {
445 $mform->setElementError($element, $msg);
448 $file_val = false;
451 $data = $mform->exportValues();
452 $moodle_val = $this->validation($data, $files);
453 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
454 // non-empty array means errors
455 foreach ($moodle_val as $element=>$msg) {
456 $mform->setElementError($element, $msg);
458 $moodle_val = false;
460 } else {
461 // anything else means validation ok
462 $moodle_val = true;
465 $validated = ($internal_val and $moodle_val and $file_val);
467 return $validated;
471 * Return true if a cancel button has been pressed resulting in the form being submitted.
473 * @return boolean true if a cancel button has been pressed
475 function is_cancelled(){
476 $mform =& $this->_form;
477 if ($mform->isSubmitted()){
478 foreach ($mform->_cancelButtons as $cancelbutton){
479 if (optional_param($cancelbutton, 0, PARAM_RAW)){
480 return true;
484 return false;
488 * Return submitted data if properly submitted or returns NULL if validation fails or
489 * if there is no submitted data.
491 * note: $slashed param removed
493 * @return object submitted data; NULL if not valid or not submitted or cancelled
495 function get_data() {
496 $mform =& $this->_form;
498 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
499 $data = $mform->exportValues();
500 unset($data['sesskey']); // we do not need to return sesskey
501 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
502 if (empty($data)) {
503 return NULL;
504 } else {
505 return (object)$data;
507 } else {
508 return NULL;
513 * Return submitted data without validation or NULL if there is no submitted data.
514 * note: $slashed param removed
516 * @return object submitted data; NULL if not submitted
518 function get_submitted_data() {
519 $mform =& $this->_form;
521 if ($this->is_submitted()) {
522 $data = $mform->exportValues();
523 unset($data['sesskey']); // we do not need to return sesskey
524 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
525 if (empty($data)) {
526 return NULL;
527 } else {
528 return (object)$data;
530 } else {
531 return NULL;
536 * Save verified uploaded files into directory. Upload process can be customised from definition()
537 * NOTE: please use save_stored_file() or save_file()
539 * @return bool Always false
541 function save_files($destination) {
542 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
543 return false;
547 * Returns name of uploaded file.
549 * @global object
550 * @param string $elname, first element if null
551 * @return mixed false in case of failure, string if ok
553 function get_new_filename($elname=null) {
554 global $USER;
556 if (!$this->is_submitted() or !$this->is_validated()) {
557 return false;
560 if (is_null($elname)) {
561 if (empty($_FILES)) {
562 return false;
564 reset($_FILES);
565 $elname = key($_FILES);
568 if (empty($elname)) {
569 return false;
572 $element = $this->_form->getElement($elname);
574 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
575 $values = $this->_form->exportValues($elname);
576 if (empty($values[$elname])) {
577 return false;
579 $draftid = $values[$elname];
580 $fs = get_file_storage();
581 $context = get_context_instance(CONTEXT_USER, $USER->id);
582 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
583 return false;
585 $file = reset($files);
586 return $file->get_filename();
589 if (!isset($_FILES[$elname])) {
590 return false;
593 return $_FILES[$elname]['name'];
597 * Save file to standard filesystem
599 * @global object
600 * @param string $elname name of element
601 * @param string $pathname full path name of file
602 * @param bool $override override file if exists
603 * @return bool success
605 function save_file($elname, $pathname, $override=false) {
606 global $USER;
608 if (!$this->is_submitted() or !$this->is_validated()) {
609 return false;
611 if (file_exists($pathname)) {
612 if ($override) {
613 if (!@unlink($pathname)) {
614 return false;
616 } else {
617 return false;
621 $element = $this->_form->getElement($elname);
623 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
624 $values = $this->_form->exportValues($elname);
625 if (empty($values[$elname])) {
626 return false;
628 $draftid = $values[$elname];
629 $fs = get_file_storage();
630 $context = get_context_instance(CONTEXT_USER, $USER->id);
631 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
632 return false;
634 $file = reset($files);
636 return $file->copy_content_to($pathname);
638 } else if (isset($_FILES[$elname])) {
639 return copy($_FILES[$elname]['tmp_name'], $pathname);
642 return false;
646 * Returns a temporary file, do not forget to delete after not needed any more.
648 * @param string $elname
649 * @return string or false
651 function save_temp_file($elname) {
652 if (!$this->get_new_filename($elname)) {
653 return false;
655 if (!$dir = make_temp_directory('forms')) {
656 return false;
658 if (!$tempfile = tempnam($dir, 'tempup_')) {
659 return false;
661 if (!$this->save_file($elname, $tempfile, true)) {
662 // something went wrong
663 @unlink($tempfile);
664 return false;
667 return $tempfile;
671 * Get draft files of a form element
672 * This is a protected method which will be used only inside moodleforms
674 * @global object $USER
675 * @param string $elname name of element
676 * @return array
678 protected function get_draft_files($elname) {
679 global $USER;
681 if (!$this->is_submitted()) {
682 return false;
685 $element = $this->_form->getElement($elname);
687 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
688 $values = $this->_form->exportValues($elname);
689 if (empty($values[$elname])) {
690 return false;
692 $draftid = $values[$elname];
693 $fs = get_file_storage();
694 $context = get_context_instance(CONTEXT_USER, $USER->id);
695 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
696 return null;
698 return $files;
700 return null;
704 * Save file to local filesystem pool
706 * @global object
707 * @param string $elname name of element
708 * @param int $newcontextid
709 * @param string $newfilearea
710 * @param string $newfilepath
711 * @param string $newfilename - use specified filename, if not specified name of uploaded file used
712 * @param bool $overwrite - overwrite file if exists
713 * @param int $newuserid - new userid if required
714 * @return mixed stored_file object or false if error; may throw exception if duplicate found
716 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
717 $newfilename=null, $overwrite=false, $newuserid=null) {
718 global $USER;
720 if (!$this->is_submitted() or !$this->is_validated()) {
721 return false;
724 if (empty($newuserid)) {
725 $newuserid = $USER->id;
728 $element = $this->_form->getElement($elname);
729 $fs = get_file_storage();
731 if ($element instanceof MoodleQuickForm_filepicker) {
732 $values = $this->_form->exportValues($elname);
733 if (empty($values[$elname])) {
734 return false;
736 $draftid = $values[$elname];
737 $context = get_context_instance(CONTEXT_USER, $USER->id);
738 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
739 return false;
741 $file = reset($files);
742 if (is_null($newfilename)) {
743 $newfilename = $file->get_filename();
746 if ($overwrite) {
747 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
748 if (!$oldfile->delete()) {
749 return false;
754 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
755 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
756 return $fs->create_file_from_storedfile($file_record, $file);
758 } else if (isset($_FILES[$elname])) {
759 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
761 if ($overwrite) {
762 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
763 if (!$oldfile->delete()) {
764 return false;
769 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
770 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
771 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
774 return false;
778 * Get content of uploaded file.
780 * @global object
781 * @param $element name of file upload element
782 * @return mixed false in case of failure, string if ok
784 function get_file_content($elname) {
785 global $USER;
787 if (!$this->is_submitted() or !$this->is_validated()) {
788 return false;
791 $element = $this->_form->getElement($elname);
793 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
794 $values = $this->_form->exportValues($elname);
795 if (empty($values[$elname])) {
796 return false;
798 $draftid = $values[$elname];
799 $fs = get_file_storage();
800 $context = get_context_instance(CONTEXT_USER, $USER->id);
801 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
802 return false;
804 $file = reset($files);
806 return $file->get_content();
808 } else if (isset($_FILES[$elname])) {
809 return file_get_contents($_FILES[$elname]['tmp_name']);
812 return false;
816 * Print html form.
818 function display() {
819 //finalize the form definition if not yet done
820 if (!$this->_definition_finalized) {
821 $this->_definition_finalized = true;
822 $this->definition_after_data();
824 $this->_form->display();
828 * Abstract method - always override!
830 protected abstract function definition();
833 * Dummy stub method - override if you need to setup the form depending on current
834 * values. This method is called after definition(), data submission and set_data().
835 * All form setup that is dependent on form values should go in here.
837 function definition_after_data(){
841 * Dummy stub method - override if you needed to perform some extra validation.
842 * If there are errors return array of errors ("fieldname"=>"error message"),
843 * otherwise true if ok.
845 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
847 * @param array $data array of ("fieldname"=>value) of submitted data
848 * @param array $files array of uploaded files "element_name"=>tmp_file_path
849 * @return array of "element_name"=>"error_description" if there are errors,
850 * or an empty array if everything is OK (true allowed for backwards compatibility too).
852 function validation($data, $files) {
853 return array();
857 * Method to add a repeating group of elements to a form.
859 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
860 * @param integer $repeats no of times to repeat elements initially
861 * @param array $options Array of options to apply to elements. Array keys are element names.
862 * This is an array of arrays. The second sets of keys are the option types
863 * for the elements :
864 * 'default' - default value is value
865 * 'type' - PARAM_* constant is value
866 * 'helpbutton' - helpbutton params array is value
867 * 'disabledif' - last three moodleform::disabledIf()
868 * params are value as an array
869 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
870 * @param string $addfieldsname name for button to add more fields
871 * @param int $addfieldsno how many fields to add at a time
872 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
873 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
874 * @return int no of repeats of element in this page
876 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
877 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
878 if ($addstring===null){
879 $addstring = get_string('addfields', 'form', $addfieldsno);
880 } else {
881 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
883 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
884 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
885 if (!empty($addfields)){
886 $repeats += $addfieldsno;
888 $mform =& $this->_form;
889 $mform->registerNoSubmitButton($addfieldsname);
890 $mform->addElement('hidden', $repeathiddenname, $repeats);
891 $mform->setType($repeathiddenname, PARAM_INT);
892 //value not to be overridden by submitted value
893 $mform->setConstants(array($repeathiddenname=>$repeats));
894 $namecloned = array();
895 for ($i = 0; $i < $repeats; $i++) {
896 foreach ($elementobjs as $elementobj){
897 $elementclone = fullclone($elementobj);
898 $name = $elementclone->getName();
899 $namecloned[] = $name;
900 if (!empty($name)) {
901 $elementclone->setName($name."[$i]");
903 if (is_a($elementclone, 'HTML_QuickForm_header')) {
904 $value = $elementclone->_text;
905 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
907 } else {
908 $value=$elementclone->getLabel();
909 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
913 $mform->addElement($elementclone);
916 for ($i=0; $i<$repeats; $i++) {
917 foreach ($options as $elementname => $elementoptions){
918 $pos=strpos($elementname, '[');
919 if ($pos!==FALSE){
920 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
921 $realelementname .= substr($elementname, $pos+1);
922 }else {
923 $realelementname = $elementname."[$i]";
925 foreach ($elementoptions as $option => $params){
927 switch ($option){
928 case 'default' :
929 $mform->setDefault($realelementname, $params);
930 break;
931 case 'helpbutton' :
932 $params = array_merge(array($realelementname), $params);
933 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
934 break;
935 case 'disabledif' :
936 foreach ($namecloned as $num => $name){
937 if ($params[0] == $name){
938 $params[0] = $params[0]."[$i]";
939 break;
942 $params = array_merge(array($realelementname), $params);
943 call_user_func_array(array(&$mform, 'disabledIf'), $params);
944 break;
945 case 'rule' :
946 if (is_string($params)){
947 $params = array(null, $params, null, 'client');
949 $params = array_merge(array($realelementname), $params);
950 call_user_func_array(array(&$mform, 'addRule'), $params);
951 break;
957 $mform->addElement('submit', $addfieldsname, $addstring);
959 if (!$addbuttoninside) {
960 $mform->closeHeaderBefore($addfieldsname);
963 return $repeats;
967 * Adds a link/button that controls the checked state of a group of checkboxes.
969 * @global object
970 * @param int $groupid The id of the group of advcheckboxes this element controls
971 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
972 * @param array $attributes associative array of HTML attributes
973 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
975 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
976 global $CFG;
978 // Set the default text if none was specified
979 if (empty($text)) {
980 $text = get_string('selectallornone', 'form');
983 $mform = $this->_form;
984 $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
986 if ($select_value == 0 || is_null($select_value)) {
987 $new_select_value = 1;
988 } else {
989 $new_select_value = 0;
992 $mform->addElement('hidden', "checkbox_controller$groupid");
993 $mform->setType("checkbox_controller$groupid", PARAM_INT);
994 $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
996 $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
997 $mform->registerNoSubmitButton($checkbox_controller_name);
999 // Prepare Javascript for submit element
1000 $js = "\n//<![CDATA[\n";
1001 if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
1002 $js .= <<<EOS
1003 function html_quickform_toggle_checkboxes(group) {
1004 var checkboxes = document.getElementsByClassName('checkboxgroup' + group);
1005 var newvalue = false;
1006 var global = eval('html_quickform_checkboxgroup' + group + ';');
1007 if (global == 1) {
1008 eval('html_quickform_checkboxgroup' + group + ' = 0;');
1009 newvalue = '';
1010 } else {
1011 eval('html_quickform_checkboxgroup' + group + ' = 1;');
1012 newvalue = 'checked';
1015 for (i = 0; i < checkboxes.length; i++) {
1016 checkboxes[i].checked = newvalue;
1019 EOS;
1020 define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
1022 $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
1024 $js .= "//]]>\n";
1026 require_once("$CFG->libdir/form/submitlink.php");
1027 $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
1028 $submitlink->_js = $js;
1029 $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
1030 $mform->addElement($submitlink);
1031 $mform->setDefault($checkbox_controller_name, $text);
1035 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1036 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1037 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1038 * get data with get_data().
1040 * @param boolean $cancel whether to show cancel button, default true
1041 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1043 function add_action_buttons($cancel = true, $submitlabel=null){
1044 if (is_null($submitlabel)){
1045 $submitlabel = get_string('savechanges');
1047 $mform =& $this->_form;
1048 if ($cancel){
1049 //when two elements we need a group
1050 $buttonarray=array();
1051 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1052 $buttonarray[] = &$mform->createElement('cancel');
1053 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1054 $mform->closeHeaderBefore('buttonar');
1055 } else {
1056 //no group needed
1057 $mform->addElement('submit', 'submitbutton', $submitlabel);
1058 $mform->closeHeaderBefore('submitbutton');
1063 * Adds an initialisation call for a standard JavaScript enhancement.
1065 * This function is designed to add an initialisation call for a JavaScript
1066 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1068 * Current options:
1069 * - Selectboxes
1070 * - smartselect: Turns a nbsp indented select box into a custom drop down
1071 * control that supports multilevel and category selection.
1072 * $enhancement = 'smartselect';
1073 * $options = array('selectablecategories' => true|false)
1075 * @since 2.0
1076 * @param string|element $element
1077 * @param string $enhancement
1078 * @param array $options
1079 * @param array $strings
1081 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1082 global $PAGE;
1083 if (is_string($element)) {
1084 $element = $this->_form->getElement($element);
1086 if (is_object($element)) {
1087 $element->_generateId();
1088 $elementid = $element->getAttribute('id');
1089 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1090 if (is_array($strings)) {
1091 foreach ($strings as $string) {
1092 if (is_array($string)) {
1093 call_user_method_array('string_for_js', $PAGE->requires, $string);
1094 } else {
1095 $PAGE->requires->string_for_js($string, 'moodle');
1103 * Returns a JS module definition for the mforms JS
1104 * @return array
1106 public static function get_js_module() {
1107 global $CFG;
1108 return array(
1109 'name' => 'mform',
1110 'fullpath' => '/lib/form/form.js',
1111 'requires' => array('base', 'node'),
1112 'strings' => array(
1113 array('showadvanced', 'form'),
1114 array('hideadvanced', 'form')
1121 * You never extend this class directly. The class methods of this class are available from
1122 * the private $this->_form property on moodleform and its children. You generally only
1123 * call methods on this class from within abstract methods that you override on moodleform such
1124 * as definition and definition_after_data
1126 * @package moodlecore
1127 * @copyright Jamie Pratt <me@jamiep.org>
1128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1130 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1131 /** @var array */
1132 var $_types = array();
1133 var $_dependencies = array();
1135 * Array of buttons that if pressed do not result in the processing of the form.
1137 * @var array
1139 var $_noSubmitButtons=array();
1141 * Array of buttons that if pressed do not result in the processing of the form.
1143 * @var array
1145 var $_cancelButtons=array();
1148 * Array whose keys are element names. If the key exists this is a advanced element
1150 * @var array
1152 var $_advancedElements = array();
1155 * Whether to display advanced elements (on page load)
1157 * @var boolean
1159 var $_showAdvanced = null;
1162 * The form name is derived from the class name of the wrapper minus the trailing form
1163 * It is a name with words joined by underscores whereas the id attribute is words joined by
1164 * underscores.
1166 * @var unknown_type
1168 var $_formName = '';
1171 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
1173 * @var string
1175 var $_pageparams = '';
1178 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1180 * @global object
1181 * @staticvar int $formcounter
1182 * @param string $formName Form's name.
1183 * @param string $method (optional)Form's method defaults to 'POST'
1184 * @param mixed $action (optional)Form's action - string or moodle_url
1185 * @param string $target (optional)Form's target defaults to none
1186 * @param mixed $attributes (optional)Extra attributes for <form> tag
1187 * @access public
1189 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1190 global $CFG, $OUTPUT;
1192 static $formcounter = 1;
1194 HTML_Common::HTML_Common($attributes);
1195 $target = empty($target) ? array() : array('target' => $target);
1196 $this->_formName = $formName;
1197 if (is_a($action, 'moodle_url')){
1198 $this->_pageparams = html_writer::input_hidden_params($action);
1199 $action = $action->out_omit_querystring();
1200 } else {
1201 $this->_pageparams = '';
1203 //no 'name' atttribute for form in xhtml strict :
1204 $attributes = array('action'=>$action, 'method'=>$method,
1205 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1206 $formcounter++;
1207 $this->updateAttributes($attributes);
1209 //this is custom stuff for Moodle :
1210 $oldclass= $this->getAttribute('class');
1211 if (!empty($oldclass)){
1212 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1213 }else {
1214 $this->updateAttributes(array('class'=>'mform'));
1216 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1217 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1218 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1222 * Use this method to indicate an element in a form is an advanced field. If items in a form
1223 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1224 * form so the user can decide whether to display advanced form controls.
1226 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1228 * @param string $elementName group or element name (not the element name of something inside a group).
1229 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
1231 function setAdvanced($elementName, $advanced=true){
1232 if ($advanced){
1233 $this->_advancedElements[$elementName]='';
1234 } elseif (isset($this->_advancedElements[$elementName])) {
1235 unset($this->_advancedElements[$elementName]);
1237 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1238 $this->setShowAdvanced();
1239 $this->registerNoSubmitButton('mform_showadvanced');
1241 $this->addElement('hidden', 'mform_showadvanced_last');
1242 $this->setType('mform_showadvanced_last', PARAM_INT);
1246 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1247 * display advanced elements in the form until 'Show Advanced' is pressed.
1249 * You can get the last state of the form and possibly save it for this user by using
1250 * value 'mform_showadvanced_last' in submitted data.
1252 * @param boolean $showadvancedNow
1254 function setShowAdvanced($showadvancedNow = null){
1255 if ($showadvancedNow === null){
1256 if ($this->_showAdvanced !== null){
1257 return;
1258 } else { //if setShowAdvanced is called without any preference
1259 //make the default to not show advanced elements.
1260 $showadvancedNow = get_user_preferences(
1261 moodle_strtolower($this->_formName.'_showadvanced', 0));
1264 //value of hidden element
1265 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1266 //value of button
1267 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1268 //toggle if button pressed or else stay the same
1269 if ($hiddenLast == -1) {
1270 $next = $showadvancedNow;
1271 } elseif ($buttonPressed) { //toggle on button press
1272 $next = !$hiddenLast;
1273 } else {
1274 $next = $hiddenLast;
1276 $this->_showAdvanced = $next;
1277 if ($showadvancedNow != $next){
1278 set_user_preference($this->_formName.'_showadvanced', $next);
1280 $this->setConstants(array('mform_showadvanced_last'=>$next));
1282 function getShowAdvanced(){
1283 return $this->_showAdvanced;
1288 * Accepts a renderer
1290 * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
1291 * @access public
1292 * @return void
1294 function accept(&$renderer) {
1295 if (method_exists($renderer, 'setAdvancedElements')){
1296 //check for visible fieldsets where all elements are advanced
1297 //and mark these headers as advanced as well.
1298 //And mark all elements in a advanced header as advanced
1299 $stopFields = $renderer->getStopFieldSetElements();
1300 $lastHeader = null;
1301 $lastHeaderAdvanced = false;
1302 $anyAdvanced = false;
1303 foreach (array_keys($this->_elements) as $elementIndex){
1304 $element =& $this->_elements[$elementIndex];
1306 // if closing header and any contained element was advanced then mark it as advanced
1307 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1308 if ($anyAdvanced && !is_null($lastHeader)){
1309 $this->setAdvanced($lastHeader->getName());
1311 $lastHeaderAdvanced = false;
1312 unset($lastHeader);
1313 $lastHeader = null;
1314 } elseif ($lastHeaderAdvanced) {
1315 $this->setAdvanced($element->getName());
1318 if ($element->getType()=='header'){
1319 $lastHeader =& $element;
1320 $anyAdvanced = false;
1321 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1322 } elseif (isset($this->_advancedElements[$element->getName()])){
1323 $anyAdvanced = true;
1326 // the last header may not be closed yet...
1327 if ($anyAdvanced && !is_null($lastHeader)){
1328 $this->setAdvanced($lastHeader->getName());
1330 $renderer->setAdvancedElements($this->_advancedElements);
1333 parent::accept($renderer);
1337 * @param string $elementName
1339 function closeHeaderBefore($elementName){
1340 $renderer =& $this->defaultRenderer();
1341 $renderer->addStopFieldsetElements($elementName);
1345 * Should be used for all elements of a form except for select, radio and checkboxes which
1346 * clean their own data.
1348 * @param string $elementname
1349 * @param integer $paramtype use the constants PARAM_*.
1350 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
1351 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
1352 * It will strip all html tags. But will still let tags for multilang support
1353 * through.
1354 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
1355 * html editor. Data from the editor is later cleaned before display using
1356 * format_text() function. PARAM_RAW can also be used for data that is validated
1357 * by some other way or printed by p() or s().
1358 * * PARAM_INT should be used for integers.
1359 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
1360 * form actions.
1362 function setType($elementname, $paramtype) {
1363 $this->_types[$elementname] = $paramtype;
1367 * See description of setType above. This can be used to set several types at once.
1369 * @param array $paramtypes
1371 function setTypes($paramtypes) {
1372 $this->_types = $paramtypes + $this->_types;
1376 * @param array $submission
1377 * @param array $files
1379 function updateSubmission($submission, $files) {
1380 $this->_flagSubmitted = false;
1382 if (empty($submission)) {
1383 $this->_submitValues = array();
1384 } else {
1385 foreach ($submission as $key=>$s) {
1386 if (array_key_exists($key, $this->_types)) {
1387 $type = $this->_types[$key];
1388 } else {
1389 $type = PARAM_RAW;
1391 if (is_array($s)) {
1392 $submission[$key] = clean_param_array($s, $type, true);
1393 } else {
1394 $submission[$key] = clean_param($s, $type);
1397 $this->_submitValues = $submission;
1398 $this->_flagSubmitted = true;
1401 if (empty($files)) {
1402 $this->_submitFiles = array();
1403 } else {
1404 $this->_submitFiles = $files;
1405 $this->_flagSubmitted = true;
1408 // need to tell all elements that they need to update their value attribute.
1409 foreach (array_keys($this->_elements) as $key) {
1410 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1415 * @return string
1417 function getReqHTML(){
1418 return $this->_reqHTML;
1422 * @return string
1424 function getAdvancedHTML(){
1425 return $this->_advancedHTML;
1429 * Initializes a default form value. Used to specify the default for a new entry where
1430 * no data is loaded in using moodleform::set_data()
1432 * note: $slashed param removed
1434 * @param string $elementname element name
1435 * @param mixed $values values for that element name
1436 * @access public
1437 * @return void
1439 function setDefault($elementName, $defaultValue){
1440 $this->setDefaults(array($elementName=>$defaultValue));
1441 } // end func setDefault
1443 * Add an array of buttons to the form
1444 * @param array $buttons An associative array representing help button to attach to
1445 * to the form. keys of array correspond to names of elements in form.
1446 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1447 * @param bool $suppresscheck
1448 * @param string $function
1449 * @access public
1451 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1453 debugging('function moodle_form::setHelpButtons() is deprecated');
1454 //foreach ($buttons as $elementname => $button){
1455 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1459 * Add a single button.
1461 * @deprecated use addHelpButton() instead
1462 * @param string $elementname name of the element to add the item to
1463 * @param array $button arguments to pass to function $function
1464 * @param boolean $suppresscheck whether to throw an error if the element
1465 * doesn't exist.
1466 * @param string $function - function to generate html from the arguments in $button
1467 * @param string $function
1469 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1470 global $OUTPUT;
1472 debugging('function moodle_form::setHelpButton() is deprecated');
1473 if ($function !== 'helpbutton') {
1474 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1477 $buttonargs = (array)$buttonargs;
1479 if (array_key_exists($elementname, $this->_elementIndex)) {
1480 //_elements has a numeric index, this code accesses the elements by name
1481 $element = $this->_elements[$this->_elementIndex[$elementname]];
1483 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1484 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1485 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1486 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1488 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1490 } else if (!$suppresscheck) {
1491 print_error('nonexistentformelements', 'form', '', $elementname);
1496 * Add a help button to element, only one button per element is allowed.
1498 * This is new, simplified and preferable method of setting a help icon on form elements.
1499 * It uses the new $OUTPUT->help_icon().
1501 * Typically, you will provide the same identifier and the component as you have used for the
1502 * label of the element. The string identifier with the _help suffix added is then used
1503 * as the help string.
1505 * There has to be two strings defined:
1506 * 1/ get_string($identifier, $component) - the title of the help page
1507 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1509 * @since 2.0
1510 * @param string $elementname name of the element to add the item to
1511 * @param string $identifier help string identifier without _help suffix
1512 * @param string $component component name to look the help string in
1513 * @param string $linktext optional text to display next to the icon
1514 * @param boolean $suppresscheck set to true if the element may not exist
1515 * @return void
1517 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1518 global $OUTPUT;
1519 if (array_key_exists($elementname, $this->_elementIndex)) {
1520 $element = $this->_elements[$this->_elementIndex[$elementname]];
1521 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1522 } else if (!$suppresscheck) {
1523 debugging(get_string('nonexistentformelements', 'form', $elementname));
1528 * Set constant value not overridden by _POST or _GET
1529 * note: this does not work for complex names with [] :-(
1531 * @param string $elname name of element
1532 * @param mixed $value
1533 * @return void
1535 function setConstant($elname, $value) {
1536 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1537 $element =& $this->getElement($elname);
1538 $element->onQuickFormEvent('updateValue', null, $this);
1542 * @param string $elementList
1544 function exportValues($elementList = null){
1545 $unfiltered = array();
1546 if (null === $elementList) {
1547 // iterate over all elements, calling their exportValue() methods
1548 $emptyarray = array();
1549 foreach (array_keys($this->_elements) as $key) {
1550 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1551 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1552 } else {
1553 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1556 if (is_array($value)) {
1557 // This shit throws a bogus warning in PHP 4.3.x
1558 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1561 } else {
1562 if (!is_array($elementList)) {
1563 $elementList = array_map('trim', explode(',', $elementList));
1565 foreach ($elementList as $elementName) {
1566 $value = $this->exportValue($elementName);
1567 if (PEAR::isError($value)) {
1568 return $value;
1570 //oh, stock QuickFOrm was returning array of arrays!
1571 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1575 if (is_array($this->_constantValues)) {
1576 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1579 return $unfiltered;
1582 * Adds a validation rule for the given field
1584 * If the element is in fact a group, it will be considered as a whole.
1585 * To validate grouped elements as separated entities,
1586 * use addGroupRule instead of addRule.
1588 * @param string $element Form element name
1589 * @param string $message Message to display for invalid data
1590 * @param string $type Rule type, use getRegisteredRules() to get types
1591 * @param string $format (optional)Required for extra rule data
1592 * @param string $validation (optional)Where to perform validation: "server", "client"
1593 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1594 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1595 * @access public
1597 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1599 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1600 if ($validation == 'client') {
1601 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1604 } // end func addRule
1606 * Adds a validation rule for the given group of elements
1608 * Only groups with a name can be assigned a validation rule
1609 * Use addGroupRule when you need to validate elements inside the group.
1610 * Use addRule if you need to validate the group as a whole. In this case,
1611 * the same rule will be applied to all elements in the group.
1612 * Use addRule if you need to validate the group against a function.
1614 * @param string $group Form group name
1615 * @param mixed $arg1 Array for multiple elements or error message string for one element
1616 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1617 * @param string $format (optional)Required for extra rule data
1618 * @param int $howmany (optional)How many valid elements should be in the group
1619 * @param string $validation (optional)Where to perform validation: "server", "client"
1620 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1621 * @access public
1623 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1625 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1626 if (is_array($arg1)) {
1627 foreach ($arg1 as $rules) {
1628 foreach ($rules as $rule) {
1629 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1631 if ('client' == $validation) {
1632 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1636 } elseif (is_string($arg1)) {
1638 if ($validation == 'client') {
1639 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1642 } // end func addGroupRule
1644 // }}}
1646 * Returns the client side validation script
1648 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1649 * and slightly modified to run rules per-element
1650 * Needed to override this because of an error with client side validation of grouped elements.
1652 * @access public
1653 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1655 function getValidationScript()
1657 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1658 return '';
1661 include_once('HTML/QuickForm/RuleRegistry.php');
1662 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1663 $test = array();
1664 $js_escape = array(
1665 "\r" => '\r',
1666 "\n" => '\n',
1667 "\t" => '\t',
1668 "'" => "\\'",
1669 '"' => '\"',
1670 '\\' => '\\\\'
1673 foreach ($this->_rules as $elementName => $rules) {
1674 foreach ($rules as $rule) {
1675 if ('client' == $rule['validation']) {
1676 unset($element); //TODO: find out how to properly initialize it
1678 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1679 $rule['message'] = strtr($rule['message'], $js_escape);
1681 if (isset($rule['group'])) {
1682 $group =& $this->getElement($rule['group']);
1683 // No JavaScript validation for frozen elements
1684 if ($group->isFrozen()) {
1685 continue 2;
1687 $elements =& $group->getElements();
1688 foreach (array_keys($elements) as $key) {
1689 if ($elementName == $group->getElementName($key)) {
1690 $element =& $elements[$key];
1691 break;
1694 } elseif ($dependent) {
1695 $element = array();
1696 $element[] =& $this->getElement($elementName);
1697 foreach ($rule['dependent'] as $elName) {
1698 $element[] =& $this->getElement($elName);
1700 } else {
1701 $element =& $this->getElement($elementName);
1703 // No JavaScript validation for frozen elements
1704 if (is_object($element) && $element->isFrozen()) {
1705 continue 2;
1706 } elseif (is_array($element)) {
1707 foreach (array_keys($element) as $key) {
1708 if ($element[$key]->isFrozen()) {
1709 continue 3;
1713 //for editor element, [text] is appended to the name.
1714 if ($element->getType() == 'editor') {
1715 $elementName .= '[text]';
1716 //Add format to rule as moodleform check which format is supported by browser
1717 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1718 if (is_null($rule['format'])) {
1719 $rule['format'] = $element->getFormat();
1722 // Fix for bug displaying errors for elements in a group
1723 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1724 $test[$elementName][1]=$element;
1725 //end of fix
1730 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1731 // the form, and then that form field gets corrupted by the code that follows.
1732 unset($element);
1734 $js = '
1735 <script type="text/javascript">
1736 //<![CDATA[
1738 var skipClientValidation = false;
1740 function qf_errorHandler(element, _qfMsg) {
1741 div = element.parentNode;
1743 if ((div == undefined) || (element.name == undefined)) {
1744 //no checking can be done for undefined elements so let server handle it.
1745 return true;
1748 if (_qfMsg != \'\') {
1749 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1750 if (!errorSpan) {
1751 errorSpan = document.createElement("span");
1752 errorSpan.id = \'id_error_\'+element.name;
1753 errorSpan.className = "error";
1754 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1757 while (errorSpan.firstChild) {
1758 errorSpan.removeChild(errorSpan.firstChild);
1761 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1762 errorSpan.appendChild(document.createElement("br"));
1764 if (div.className.substr(div.className.length - 6, 6) != " error"
1765 && div.className != "error") {
1766 div.className += " error";
1769 return false;
1770 } else {
1771 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1772 if (errorSpan) {
1773 errorSpan.parentNode.removeChild(errorSpan);
1776 if (div.className.substr(div.className.length - 6, 6) == " error") {
1777 div.className = div.className.substr(0, div.className.length - 6);
1778 } else if (div.className == "error") {
1779 div.className = "";
1782 return true;
1785 $validateJS = '';
1786 foreach ($test as $elementName => $jsandelement) {
1787 // Fix for bug displaying errors for elements in a group
1788 //unset($element);
1789 list($jsArr,$element)=$jsandelement;
1790 //end of fix
1791 $escapedElementName = preg_replace_callback(
1792 '/[_\[\]]/',
1793 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1794 $elementName);
1795 $js .= '
1796 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1797 if (undefined == element) {
1798 //required element was not found, then let form be submitted without client side validation
1799 return true;
1801 var value = \'\';
1802 var errFlag = new Array();
1803 var _qfGroups = {};
1804 var _qfMsg = \'\';
1805 var frm = element.parentNode;
1806 if ((undefined != element.name) && (frm != undefined)) {
1807 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1808 frm = frm.parentNode;
1810 ' . join("\n", $jsArr) . '
1811 return qf_errorHandler(element, _qfMsg);
1812 } else {
1813 //element name should be defined else error msg will not be displayed.
1814 return true;
1818 $validateJS .= '
1819 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1820 if (!ret && !first_focus) {
1821 first_focus = true;
1822 frm.elements[\''.$elementName.'\'].focus();
1826 // Fix for bug displaying errors for elements in a group
1827 //unset($element);
1828 //$element =& $this->getElement($elementName);
1829 //end of fix
1830 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1831 $onBlur = $element->getAttribute('onBlur');
1832 $onChange = $element->getAttribute('onChange');
1833 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1834 'onChange' => $onChange . $valFunc));
1836 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1837 $js .= '
1838 function validate_' . $this->_formName . '(frm) {
1839 if (skipClientValidation) {
1840 return true;
1842 var ret = true;
1844 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1845 var first_focus = false;
1846 ' . $validateJS . ';
1847 return ret;
1849 //]]>
1850 </script>';
1851 return $js;
1852 } // end func getValidationScript
1853 function _setDefaultRuleMessages(){
1854 foreach ($this->_rules as $field => $rulesarr){
1855 foreach ($rulesarr as $key => $rule){
1856 if ($rule['message']===null){
1857 $a=new stdClass();
1858 $a->format=$rule['format'];
1859 $str=get_string('err_'.$rule['type'], 'form', $a);
1860 if (strpos($str, '[[')!==0){
1861 $this->_rules[$field][$key]['message']=$str;
1868 function getLockOptionObject(){
1869 $result = array();
1870 foreach ($this->_dependencies as $dependentOn => $conditions){
1871 $result[$dependentOn] = array();
1872 foreach ($conditions as $condition=>$values) {
1873 $result[$dependentOn][$condition] = array();
1874 foreach ($values as $value=>$dependents) {
1875 $result[$dependentOn][$condition][$value] = array();
1876 $i = 0;
1877 foreach ($dependents as $dependent) {
1878 $elements = $this->_getElNamesRecursive($dependent);
1879 if (empty($elements)) {
1880 // probably element inside of some group
1881 $elements = array($dependent);
1883 foreach($elements as $element) {
1884 if ($element == $dependentOn) {
1885 continue;
1887 $result[$dependentOn][$condition][$value][] = $element;
1893 return array($this->getAttribute('id'), $result);
1897 * @param mixed $element
1898 * @return array
1900 function _getElNamesRecursive($element) {
1901 if (is_string($element)) {
1902 if (!$this->elementExists($element)) {
1903 return array();
1905 $element = $this->getElement($element);
1908 if (is_a($element, 'HTML_QuickForm_group')) {
1909 $elsInGroup = $element->getElements();
1910 $elNames = array();
1911 foreach ($elsInGroup as $elInGroup){
1912 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1913 // not sure if this would work - groups nested in groups
1914 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1915 } else {
1916 $elNames[] = $element->getElementName($elInGroup->getName());
1920 } else if (is_a($element, 'HTML_QuickForm_header')) {
1921 return array();
1923 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1924 return array();
1926 } else if (method_exists($element, 'getPrivateName')) {
1927 return array($element->getPrivateName());
1929 } else {
1930 $elNames = array($element->getName());
1933 return $elNames;
1937 * Adds a dependency for $elementName which will be disabled if $condition is met.
1938 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1939 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1940 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
1941 * of the $dependentOn element is $condition (such as equal) to $value.
1943 * @param string $elementName the name of the element which will be disabled
1944 * @param string $dependentOn the name of the element whose state will be checked for
1945 * condition
1946 * @param string $condition the condition to check
1947 * @param mixed $value used in conjunction with condition.
1949 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
1950 if (!array_key_exists($dependentOn, $this->_dependencies)) {
1951 $this->_dependencies[$dependentOn] = array();
1953 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
1954 $this->_dependencies[$dependentOn][$condition] = array();
1956 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
1957 $this->_dependencies[$dependentOn][$condition][$value] = array();
1959 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
1962 function registerNoSubmitButton($buttonname){
1963 $this->_noSubmitButtons[]=$buttonname;
1967 * @param string $buttonname
1968 * @return mixed
1970 function isNoSubmitButton($buttonname){
1971 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
1975 * @param string $buttonname
1977 function _registerCancelButton($addfieldsname){
1978 $this->_cancelButtons[]=$addfieldsname;
1981 * Displays elements without HTML input tags.
1982 * This method is different to freeze() in that it makes sure no hidden
1983 * elements are included in the form.
1984 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
1986 * This function also removes all previously defined rules.
1988 * @param mixed $elementList array or string of element(s) to be frozen
1989 * @access public
1991 function hardFreeze($elementList=null)
1993 if (!isset($elementList)) {
1994 $this->_freezeAll = true;
1995 $elementList = array();
1996 } else {
1997 if (!is_array($elementList)) {
1998 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2000 $elementList = array_flip($elementList);
2003 foreach (array_keys($this->_elements) as $key) {
2004 $name = $this->_elements[$key]->getName();
2005 if ($this->_freezeAll || isset($elementList[$name])) {
2006 $this->_elements[$key]->freeze();
2007 $this->_elements[$key]->setPersistantFreeze(false);
2008 unset($elementList[$name]);
2010 // remove all rules
2011 $this->_rules[$name] = array();
2012 // if field is required, remove the rule
2013 $unset = array_search($name, $this->_required);
2014 if ($unset !== false) {
2015 unset($this->_required[$unset]);
2020 if (!empty($elementList)) {
2021 return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
2023 return true;
2026 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2028 * This function also removes all previously defined rules of elements it freezes.
2030 * throws HTML_QuickForm_Error
2032 * @param array $elementList array or string of element(s) not to be frozen
2033 * @access public
2035 function hardFreezeAllVisibleExcept($elementList)
2037 $elementList = array_flip($elementList);
2038 foreach (array_keys($this->_elements) as $key) {
2039 $name = $this->_elements[$key]->getName();
2040 $type = $this->_elements[$key]->getType();
2042 if ($type == 'hidden'){
2043 // leave hidden types as they are
2044 } elseif (!isset($elementList[$name])) {
2045 $this->_elements[$key]->freeze();
2046 $this->_elements[$key]->setPersistantFreeze(false);
2048 // remove all rules
2049 $this->_rules[$name] = array();
2050 // if field is required, remove the rule
2051 $unset = array_search($name, $this->_required);
2052 if ($unset !== false) {
2053 unset($this->_required[$unset]);
2057 return true;
2060 * Tells whether the form was already submitted
2062 * This is useful since the _submitFiles and _submitValues arrays
2063 * may be completely empty after the trackSubmit value is removed.
2065 * @access public
2066 * @return bool
2068 function isSubmitted()
2070 return parent::isSubmitted() && (!$this->isFrozen());
2076 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2077 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2079 * Stylesheet is part of standard theme and should be automatically included.
2081 * @package moodlecore
2082 * @copyright Jamie Pratt <me@jamiep.org>
2083 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2085 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2088 * Element template array
2089 * @var array
2090 * @access private
2092 var $_elementTemplates;
2094 * Template used when opening a hidden fieldset
2095 * (i.e. a fieldset that is opened when there is no header element)
2096 * @var string
2097 * @access private
2099 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2101 * Header Template string
2102 * @var string
2103 * @access private
2105 var $_headerTemplate =
2106 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2109 * Template used when opening a fieldset
2110 * @var string
2111 * @access private
2113 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2116 * Template used when closing a fieldset
2117 * @var string
2118 * @access private
2120 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2123 * Required Note template string
2124 * @var string
2125 * @access private
2127 var $_requiredNoteTemplate =
2128 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2130 var $_advancedElements = array();
2133 * Whether to display advanced elements (on page load)
2135 * @var integer 1 means show 0 means hide
2137 var $_showAdvanced;
2139 function MoodleQuickForm_Renderer(){
2140 // switch next two lines for ol li containers for form items.
2141 // $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>');
2142 $this->_elementTemplates = array(
2143 'default'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><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>',
2145 'fieldset'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><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>',
2147 '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}&nbsp;</div></div>',
2149 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2151 'nodisplay'=>'');
2153 parent::HTML_QuickForm_Renderer_Tableless();
2157 * @param array $elements
2159 function setAdvancedElements($elements){
2160 $this->_advancedElements = $elements;
2164 * What to do when starting the form
2166 * @param object $form MoodleQuickForm
2168 function startForm(&$form){
2169 $this->_reqHTML = $form->getReqHTML();
2170 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2171 $this->_advancedHTML = $form->getAdvancedHTML();
2172 $this->_showAdvanced = $form->getShowAdvanced();
2173 parent::startForm($form);
2174 if ($form->isFrozen()){
2175 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2176 } else {
2177 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2178 $this->_hiddenHtml .= $form->_pageparams;
2185 * @param object $group Passed by reference
2186 * @param mixed $required
2187 * @param mixed $error
2189 function startGroup(&$group, $required, $error){
2190 if (method_exists($group, 'getElementTemplateType')){
2191 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2192 }else{
2193 $html = $this->_elementTemplates['default'];
2196 if ($this->_showAdvanced){
2197 $advclass = ' advanced';
2198 } else {
2199 $advclass = ' advanced hide';
2201 if (isset($this->_advancedElements[$group->getName()])){
2202 $html =str_replace(' {advanced}', $advclass, $html);
2203 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2204 } else {
2205 $html =str_replace(' {advanced}', '', $html);
2206 $html =str_replace('{advancedimg}', '', $html);
2208 if (method_exists($group, 'getHelpButton')){
2209 $html =str_replace('{help}', $group->getHelpButton(), $html);
2210 }else{
2211 $html =str_replace('{help}', '', $html);
2213 $html =str_replace('{name}', $group->getName(), $html);
2214 $html =str_replace('{type}', 'fgroup', $html);
2216 $this->_templates[$group->getName()]=$html;
2217 // Fix for bug in tableless quickforms that didn't allow you to stop a
2218 // fieldset before a group of elements.
2219 // if the element name indicates the end of a fieldset, close the fieldset
2220 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2221 && $this->_fieldsetsOpen > 0
2223 $this->_html .= $this->_closeFieldsetTemplate;
2224 $this->_fieldsetsOpen--;
2226 parent::startGroup($group, $required, $error);
2229 * @param object $element
2230 * @param mixed $required
2231 * @param mixed $error
2233 function renderElement(&$element, $required, $error){
2234 //manipulate id of all elements before rendering
2235 if (!is_null($element->getAttribute('id'))) {
2236 $id = $element->getAttribute('id');
2237 } else {
2238 $id = $element->getName();
2240 //strip qf_ prefix and replace '[' with '_' and strip ']'
2241 $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
2242 if (strpos($id, 'id_') !== 0){
2243 $element->updateAttributes(array('id'=>'id_'.$id));
2246 //adding stuff to place holders in template
2247 //check if this is a group element first
2248 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2249 // so it gets substitutions for *each* element
2250 $html = $this->_groupElementTemplate;
2252 elseif (method_exists($element, 'getElementTemplateType')){
2253 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2254 }else{
2255 $html = $this->_elementTemplates['default'];
2257 if ($this->_showAdvanced){
2258 $advclass = ' advanced';
2259 } else {
2260 $advclass = ' advanced hide';
2262 if (isset($this->_advancedElements[$element->getName()])){
2263 $html =str_replace(' {advanced}', $advclass, $html);
2264 } else {
2265 $html =str_replace(' {advanced}', '', $html);
2267 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2268 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2269 } else {
2270 $html =str_replace('{advancedimg}', '', $html);
2272 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2273 $html =str_replace('{name}', $element->getName(), $html);
2274 if (method_exists($element, 'getHelpButton')){
2275 $html = str_replace('{help}', $element->getHelpButton(), $html);
2276 }else{
2277 $html = str_replace('{help}', '', $html);
2280 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2281 $this->_groupElementTemplate = $html;
2283 elseif (!isset($this->_templates[$element->getName()])) {
2284 $this->_templates[$element->getName()] = $html;
2287 parent::renderElement($element, $required, $error);
2291 * @global moodle_page $PAGE
2292 * @param object $form Passed by reference
2294 function finishForm(&$form){
2295 global $PAGE;
2296 if ($form->isFrozen()){
2297 $this->_hiddenHtml = '';
2299 parent::finishForm($form);
2300 if (!$form->isFrozen()) {
2301 $args = $form->getLockOptionObject();
2302 if (count($args[1]) > 0) {
2303 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, false, moodleform::get_js_module());
2308 * Called when visiting a header element
2310 * @param object $header An HTML_QuickForm_header element being visited
2311 * @access public
2312 * @return void
2313 * @global moodle_page $PAGE
2315 function renderHeader(&$header) {
2316 global $PAGE;
2318 $name = $header->getName();
2320 $id = empty($name) ? '' : ' id="' . $name . '"';
2321 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2322 if (is_null($header->_text)) {
2323 $header_html = '';
2324 } elseif (!empty($name) && isset($this->_templates[$name])) {
2325 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2326 } else {
2327 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2330 if (isset($this->_advancedElements[$name])){
2331 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2332 $elementName='mform_showadvanced';
2333 if ($this->_showAdvanced==0){
2334 $buttonlabel = get_string('showadvanced', 'form');
2335 } else {
2336 $buttonlabel = get_string('hideadvanced', 'form');
2338 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2339 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2340 $header_html = str_replace('{button}', $button, $header_html);
2341 } else {
2342 $header_html =str_replace('{advancedimg}', '', $header_html);
2343 $header_html = str_replace('{button}', '', $header_html);
2346 if ($this->_fieldsetsOpen > 0) {
2347 $this->_html .= $this->_closeFieldsetTemplate;
2348 $this->_fieldsetsOpen--;
2351 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2352 if ($this->_showAdvanced){
2353 $advclass = ' class="advanced"';
2354 } else {
2355 $advclass = ' class="advanced hide"';
2357 if (isset($this->_advancedElements[$name])){
2358 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2359 } else {
2360 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2362 $this->_html .= $openFieldsetTemplate . $header_html;
2363 $this->_fieldsetsOpen++;
2364 } // end func renderHeader
2366 function getStopFieldsetElements(){
2367 return $this->_stopFieldsetElements;
2372 * Required elements validation
2373 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2375 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2377 * Checks if an element is not empty.
2378 * This is a server-side validation, it works for both text fields and editor fields
2380 * @param string $value Value to check
2381 * @param mixed $options Not used yet
2382 * @return boolean true if value is not empty
2384 function validate($value, $options = null) {
2385 global $CFG;
2386 if (is_array($value) && array_key_exists('text', $value)) {
2387 $value = $value['text'];
2389 $stripvalues = array(
2390 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2391 '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
2393 if (!empty($CFG->strictformsrequired)) {
2394 $value = preg_replace($stripvalues, '', (string)$value);
2396 if ((string)$value == '') {
2397 return false;
2399 return true;
2403 * This function returns Javascript code used to build client-side validation.
2404 * It checks if an element is not empty.
2406 * @param int $format
2407 * @return array
2409 function getValidationScript($format = null) {
2410 global $CFG;
2411 if (!empty($CFG->strictformsrequired)) {
2412 if (!empty($format) && $format == FORMAT_HTML) {
2413 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2414 } else {
2415 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2417 } else {
2418 return array('', "{jsVar} == ''");
2424 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2425 * @name $_HTML_QuickForm_default_renderer
2427 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2429 /** Please keep this list in alphabetical order. */
2430 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2431 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2432 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2433 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2434 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2435 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2436 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2437 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2438 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2439 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2440 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2441 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2442 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2443 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2444 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2445 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2446 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2447 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2448 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2449 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2450 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2451 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2452 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2453 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2454 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2455 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2456 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2457 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2458 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2459 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2460 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2461 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2462 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2463 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2464 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2465 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2467 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");