Merge branch 'MDL-44952-30' of git://github.com/marinaglancy/moodle into MOODLE_30_STABLE
[moodle.git] / lib / formslib.php
blob700821dc1fbe645c11f8b8eb3ce9fd0cc564bcc2
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.
33 * @package core_form
34 * @copyright 2006 Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /** setup.php includes our hacked pear libs first */
41 require_once 'HTML/QuickForm.php';
42 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43 require_once 'HTML/QuickForm/Renderer/Tableless.php';
44 require_once 'HTML/QuickForm/Rule.php';
46 require_once $CFG->libdir.'/filelib.php';
48 /**
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
53 /**
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 ($CFG->debugdeveloper) {
65 //TODO: this is a wrong place to init PEAR!
66 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
67 $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
70 /**
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() {
77 global $PAGE;
78 static $done = false;
79 if (!$done) {
80 $calendar = \core_calendar\type_factory::get_calendar_instance();
81 $module = 'moodle-form-dateselector';
82 $function = 'M.form.dateselector.init_date_selectors';
83 $config = array(array(
84 'firstdayofweek' => $calendar->get_starting_weekday(),
85 'mon' => date_format_string(strtotime("Monday"), '%a', 99),
86 'tue' => date_format_string(strtotime("Tuesday"), '%a', 99),
87 'wed' => date_format_string(strtotime("Wednesday"), '%a', 99),
88 'thu' => date_format_string(strtotime("Thursday"), '%a', 99),
89 'fri' => date_format_string(strtotime("Friday"), '%a', 99),
90 'sat' => date_format_string(strtotime("Saturday"), '%a', 99),
91 'sun' => date_format_string(strtotime("Sunday"), '%a', 99),
92 'january' => date_format_string(strtotime("January 1"), '%B', 99),
93 'february' => date_format_string(strtotime("February 1"), '%B', 99),
94 'march' => date_format_string(strtotime("March 1"), '%B', 99),
95 'april' => date_format_string(strtotime("April 1"), '%B', 99),
96 'may' => date_format_string(strtotime("May 1"), '%B', 99),
97 'june' => date_format_string(strtotime("June 1"), '%B', 99),
98 'july' => date_format_string(strtotime("July 1"), '%B', 99),
99 'august' => date_format_string(strtotime("August 1"), '%B', 99),
100 'september' => date_format_string(strtotime("September 1"), '%B', 99),
101 'october' => date_format_string(strtotime("October 1"), '%B', 99),
102 'november' => date_format_string(strtotime("November 1"), '%B', 99),
103 'december' => date_format_string(strtotime("December 1"), '%B', 99)
105 $PAGE->requires->yui_module($module, $function, $config);
106 $done = true;
111 * Wrapper that separates quickforms syntax from moodle code
113 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
114 * use this class you should write a class definition which extends this class or a more specific
115 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
117 * You will write your own definition() method which performs the form set up.
119 * @package core_form
120 * @copyright 2006 Jamie Pratt <me@jamiep.org>
121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
122 * @todo MDL-19380 rethink the file scanning
124 abstract class moodleform {
125 /** @var string name of the form */
126 protected $_formname; // form name
128 /** @var MoodleQuickForm quickform object definition */
129 protected $_form;
131 /** @var array globals workaround */
132 protected $_customdata;
134 /** @var object definition_after_data executed flag */
135 protected $_definition_finalized = false;
138 * The constructor function calls the abstract function definition() and it will then
139 * process and clean and attempt to validate incoming data.
141 * It will call your custom validate method to validate data and will also check any rules
142 * you have specified in definition using addRule
144 * The name of the form (id attribute of the form) is automatically generated depending on
145 * the name you gave the class extending moodleform. You should call your class something
146 * like
148 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
149 * current url. If a moodle_url object then outputs params as hidden variables.
150 * @param mixed $customdata if your form defintion method needs access to data such as $course
151 * $cm, etc. to construct the form definition then pass it in this array. You can
152 * use globals for somethings.
153 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
154 * be merged and used as incoming data to the form.
155 * @param string $target target frame for form submission. You will rarely use this. Don't use
156 * it if you don't need to as the target attribute is deprecated in xhtml strict.
157 * @param mixed $attributes you can pass a string of html attributes here or an array.
158 * @param bool $editable
160 public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
161 global $CFG, $FULLME;
162 // no standard mform in moodle should allow autocomplete with the exception of user signup
163 if (empty($attributes)) {
164 $attributes = array('autocomplete'=>'off');
165 } else if (is_array($attributes)) {
166 $attributes['autocomplete'] = 'off';
167 } else {
168 if (strpos($attributes, 'autocomplete') === false) {
169 $attributes .= ' autocomplete="off" ';
173 if (empty($action)){
174 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
175 $action = strip_querystring($FULLME);
176 if (!empty($CFG->sslproxy)) {
177 // return only https links when using SSL proxy
178 $action = preg_replace('/^http:/', 'https:', $action, 1);
180 //TODO: use following instead of FULLME - see MDL-33015
181 //$action = strip_querystring(qualified_me());
183 // Assign custom data first, so that get_form_identifier can use it.
184 $this->_customdata = $customdata;
185 $this->_formname = $this->get_form_identifier();
187 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
188 if (!$editable){
189 $this->_form->hardFreeze();
192 // HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
193 $element = $this->_form->addElement('hidden');
194 $element->setType('password');
196 $this->definition();
198 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
199 $this->_form->setType('sesskey', PARAM_RAW);
200 $this->_form->setDefault('sesskey', sesskey());
201 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
202 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
203 $this->_form->setDefault('_qf__'.$this->_formname, 1);
204 $this->_form->_setDefaultRuleMessages();
206 // we have to know all input types before processing submission ;-)
207 $this->_process_submission($method);
211 * Old syntax of class constructor for backward compatibility.
213 public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
214 self::__construct($action, $customdata, $method, $target, $attributes, $editable);
218 * It should returns unique identifier for the form.
219 * Currently it will return class name, but in case two same forms have to be
220 * rendered on same page then override function to get unique form identifier.
221 * e.g This is used on multiple self enrollments page.
223 * @return string form identifier.
225 protected function get_form_identifier() {
226 $class = get_class($this);
228 return preg_replace('/[^a-z0-9_]/i', '_', $class);
232 * To autofocus on first form element or first element with error.
234 * @param string $name if this is set then the focus is forced to a field with this name
235 * @return string javascript to select form element with first error or
236 * first element if no errors. Use this as a parameter
237 * when calling print_header
239 function focus($name=NULL) {
240 $form =& $this->_form;
241 $elkeys = array_keys($form->_elementIndex);
242 $error = false;
243 if (isset($form->_errors) && 0 != count($form->_errors)){
244 $errorkeys = array_keys($form->_errors);
245 $elkeys = array_intersect($elkeys, $errorkeys);
246 $error = true;
249 if ($error or empty($name)) {
250 $names = array();
251 while (empty($names) and !empty($elkeys)) {
252 $el = array_shift($elkeys);
253 $names = $form->_getElNamesRecursive($el);
255 if (!empty($names)) {
256 $name = array_shift($names);
260 $focus = '';
261 if (!empty($name)) {
262 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
265 return $focus;
269 * Internal method. Alters submitted data to be suitable for quickforms processing.
270 * Must be called when the form is fully set up.
272 * @param string $method name of the method which alters submitted data
274 function _process_submission($method) {
275 $submission = array();
276 if ($method == 'post') {
277 if (!empty($_POST)) {
278 $submission = $_POST;
280 } else {
281 $submission = $_GET;
282 merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
285 // following trick is needed to enable proper sesskey checks when using GET forms
286 // the _qf__.$this->_formname serves as a marker that form was actually submitted
287 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
288 if (!confirm_sesskey()) {
289 print_error('invalidsesskey');
291 $files = $_FILES;
292 } else {
293 $submission = array();
294 $files = array();
296 $this->detectMissingSetType();
298 $this->_form->updateSubmission($submission, $files);
302 * Internal method - should not be used anywhere.
303 * @deprecated since 2.6
304 * @return array $_POST.
306 protected function _get_post_params() {
307 return $_POST;
311 * Internal method. Validates all old-style deprecated uploaded files.
312 * The new way is to upload files via repository api.
314 * @param array $files list of files to be validated
315 * @return bool|array Success or an array of errors
317 function _validate_files(&$files) {
318 global $CFG, $COURSE;
320 $files = array();
322 if (empty($_FILES)) {
323 // we do not need to do any checks because no files were submitted
324 // note: server side rules do not work for files - use custom verification in validate() instead
325 return true;
328 $errors = array();
329 $filenames = array();
331 // now check that we really want each file
332 foreach ($_FILES as $elname=>$file) {
333 $required = $this->_form->isElementRequired($elname);
335 if ($file['error'] == 4 and $file['size'] == 0) {
336 if ($required) {
337 $errors[$elname] = get_string('required');
339 unset($_FILES[$elname]);
340 continue;
343 if (!empty($file['error'])) {
344 $errors[$elname] = file_get_upload_error($file['error']);
345 unset($_FILES[$elname]);
346 continue;
349 if (!is_uploaded_file($file['tmp_name'])) {
350 // TODO: improve error message
351 $errors[$elname] = get_string('error');
352 unset($_FILES[$elname]);
353 continue;
356 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
357 // hmm, this file was not requested
358 unset($_FILES[$elname]);
359 continue;
362 // NOTE: the viruses are scanned in file picker, no need to deal with them here.
364 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
365 if ($filename === '') {
366 // TODO: improve error message - wrong chars
367 $errors[$elname] = get_string('error');
368 unset($_FILES[$elname]);
369 continue;
371 if (in_array($filename, $filenames)) {
372 // TODO: improve error message - duplicate name
373 $errors[$elname] = get_string('error');
374 unset($_FILES[$elname]);
375 continue;
377 $filenames[] = $filename;
378 $_FILES[$elname]['name'] = $filename;
380 $files[$elname] = $_FILES[$elname]['tmp_name'];
383 // return errors if found
384 if (count($errors) == 0){
385 return true;
387 } else {
388 $files = array();
389 return $errors;
394 * Internal method. Validates filepicker and filemanager files if they are
395 * set as required fields. Also, sets the error message if encountered one.
397 * @return bool|array with errors
399 protected function validate_draft_files() {
400 global $USER;
401 $mform =& $this->_form;
403 $errors = array();
404 //Go through all the required elements and make sure you hit filepicker or
405 //filemanager element.
406 foreach ($mform->_rules as $elementname => $rules) {
407 $elementtype = $mform->getElementType($elementname);
408 //If element is of type filepicker then do validation
409 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
410 //Check if rule defined is required rule
411 foreach ($rules as $rule) {
412 if ($rule['type'] == 'required') {
413 $draftid = (int)$mform->getSubmitValue($elementname);
414 $fs = get_file_storage();
415 $context = context_user::instance($USER->id);
416 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
417 $errors[$elementname] = $rule['message'];
423 // Check all the filemanager elements to make sure they do not have too many
424 // files in them.
425 foreach ($mform->_elements as $element) {
426 if ($element->_type == 'filemanager') {
427 $maxfiles = $element->getMaxfiles();
428 if ($maxfiles > 0) {
429 $draftid = (int)$element->getValue();
430 $fs = get_file_storage();
431 $context = context_user::instance($USER->id);
432 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
433 if (count($files) > $maxfiles) {
434 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
439 if (empty($errors)) {
440 return true;
441 } else {
442 return $errors;
447 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
448 * form definition (new entry form); this function is used to load in data where values
449 * already exist and data is being edited (edit entry form).
451 * note: $slashed param removed
453 * @param stdClass|array $default_values object or array of default values
455 function set_data($default_values) {
456 if (is_object($default_values)) {
457 $default_values = (array)$default_values;
459 $this->_form->setDefaults($default_values);
463 * Check that form was submitted. Does not check validity of submitted data.
465 * @return bool true if form properly submitted
467 function is_submitted() {
468 return $this->_form->isSubmitted();
472 * Checks if button pressed is not for submitting the form
474 * @staticvar bool $nosubmit keeps track of no submit button
475 * @return bool
477 function no_submit_button_pressed(){
478 static $nosubmit = null; // one check is enough
479 if (!is_null($nosubmit)){
480 return $nosubmit;
482 $mform =& $this->_form;
483 $nosubmit = false;
484 if (!$this->is_submitted()){
485 return false;
487 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
488 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
489 $nosubmit = true;
490 break;
493 return $nosubmit;
498 * Check that form data is valid.
499 * You should almost always use this, rather than {@link validate_defined_fields}
501 * @return bool true if form data valid
503 function is_validated() {
504 //finalize the form definition before any processing
505 if (!$this->_definition_finalized) {
506 $this->_definition_finalized = true;
507 $this->definition_after_data();
510 return $this->validate_defined_fields();
514 * Validate the form.
516 * You almost always want to call {@link is_validated} instead of this
517 * because it calls {@link definition_after_data} first, before validating the form,
518 * which is what you want in 99% of cases.
520 * This is provided as a separate function for those special cases where
521 * you want the form validated before definition_after_data is called
522 * for example, to selectively add new elements depending on a no_submit_button press,
523 * but only when the form is valid when the no_submit_button is pressed,
525 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
526 * is NOT to validate the form when a no submit button has been pressed.
527 * pass true here to override this behaviour
529 * @return bool true if form data valid
531 function validate_defined_fields($validateonnosubmit=false) {
532 static $validated = null; // one validation is enough
533 $mform =& $this->_form;
534 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
535 return false;
536 } elseif ($validated === null) {
537 $internal_val = $mform->validate();
539 $files = array();
540 $file_val = $this->_validate_files($files);
541 //check draft files for validation and flag them if required files
542 //are not in draft area.
543 $draftfilevalue = $this->validate_draft_files();
545 if ($file_val !== true && $draftfilevalue !== true) {
546 $file_val = array_merge($file_val, $draftfilevalue);
547 } else if ($draftfilevalue !== true) {
548 $file_val = $draftfilevalue;
549 } //default is file_val, so no need to assign.
551 if ($file_val !== true) {
552 if (!empty($file_val)) {
553 foreach ($file_val as $element=>$msg) {
554 $mform->setElementError($element, $msg);
557 $file_val = false;
560 $data = $mform->exportValues();
561 $moodle_val = $this->validation($data, $files);
562 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
563 // non-empty array means errors
564 foreach ($moodle_val as $element=>$msg) {
565 $mform->setElementError($element, $msg);
567 $moodle_val = false;
569 } else {
570 // anything else means validation ok
571 $moodle_val = true;
574 $validated = ($internal_val and $moodle_val and $file_val);
576 return $validated;
580 * Return true if a cancel button has been pressed resulting in the form being submitted.
582 * @return bool true if a cancel button has been pressed
584 function is_cancelled(){
585 $mform =& $this->_form;
586 if ($mform->isSubmitted()){
587 foreach ($mform->_cancelButtons as $cancelbutton){
588 if (optional_param($cancelbutton, 0, PARAM_RAW)){
589 return true;
593 return false;
597 * Return submitted data if properly submitted or returns NULL if validation fails or
598 * if there is no submitted data.
600 * note: $slashed param removed
602 * @return object submitted data; NULL if not valid or not submitted or cancelled
604 function get_data() {
605 $mform =& $this->_form;
607 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
608 $data = $mform->exportValues();
609 unset($data['sesskey']); // we do not need to return sesskey
610 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
611 if (empty($data)) {
612 return NULL;
613 } else {
614 return (object)$data;
616 } else {
617 return NULL;
622 * Return submitted data without validation or NULL if there is no submitted data.
623 * note: $slashed param removed
625 * @return object submitted data; NULL if not submitted
627 function get_submitted_data() {
628 $mform =& $this->_form;
630 if ($this->is_submitted()) {
631 $data = $mform->exportValues();
632 unset($data['sesskey']); // we do not need to return sesskey
633 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
634 if (empty($data)) {
635 return NULL;
636 } else {
637 return (object)$data;
639 } else {
640 return NULL;
645 * Save verified uploaded files into directory. Upload process can be customised from definition()
647 * @deprecated since Moodle 2.0
648 * @todo MDL-31294 remove this api
649 * @see moodleform::save_stored_file()
650 * @see moodleform::save_file()
651 * @param string $destination path where file should be stored
652 * @return bool Always false
654 function save_files($destination) {
655 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
656 return false;
660 * Returns name of uploaded file.
662 * @param string $elname first element if null
663 * @return string|bool false in case of failure, string if ok
665 function get_new_filename($elname=null) {
666 global $USER;
668 if (!$this->is_submitted() or !$this->is_validated()) {
669 return false;
672 if (is_null($elname)) {
673 if (empty($_FILES)) {
674 return false;
676 reset($_FILES);
677 $elname = key($_FILES);
680 if (empty($elname)) {
681 return false;
684 $element = $this->_form->getElement($elname);
686 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
687 $values = $this->_form->exportValues($elname);
688 if (empty($values[$elname])) {
689 return false;
691 $draftid = $values[$elname];
692 $fs = get_file_storage();
693 $context = context_user::instance($USER->id);
694 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
695 return false;
697 $file = reset($files);
698 return $file->get_filename();
701 if (!isset($_FILES[$elname])) {
702 return false;
705 return $_FILES[$elname]['name'];
709 * Save file to standard filesystem
711 * @param string $elname name of element
712 * @param string $pathname full path name of file
713 * @param bool $override override file if exists
714 * @return bool success
716 function save_file($elname, $pathname, $override=false) {
717 global $USER;
719 if (!$this->is_submitted() or !$this->is_validated()) {
720 return false;
722 if (file_exists($pathname)) {
723 if ($override) {
724 if (!@unlink($pathname)) {
725 return false;
727 } else {
728 return false;
732 $element = $this->_form->getElement($elname);
734 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
735 $values = $this->_form->exportValues($elname);
736 if (empty($values[$elname])) {
737 return false;
739 $draftid = $values[$elname];
740 $fs = get_file_storage();
741 $context = context_user::instance($USER->id);
742 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
743 return false;
745 $file = reset($files);
747 return $file->copy_content_to($pathname);
749 } else if (isset($_FILES[$elname])) {
750 return copy($_FILES[$elname]['tmp_name'], $pathname);
753 return false;
757 * Returns a temporary file, do not forget to delete after not needed any more.
759 * @param string $elname name of the elmenet
760 * @return string|bool either string or false
762 function save_temp_file($elname) {
763 if (!$this->get_new_filename($elname)) {
764 return false;
766 if (!$dir = make_temp_directory('forms')) {
767 return false;
769 if (!$tempfile = tempnam($dir, 'tempup_')) {
770 return false;
772 if (!$this->save_file($elname, $tempfile, true)) {
773 // something went wrong
774 @unlink($tempfile);
775 return false;
778 return $tempfile;
782 * Get draft files of a form element
783 * This is a protected method which will be used only inside moodleforms
785 * @param string $elname name of element
786 * @return array|bool|null
788 protected function get_draft_files($elname) {
789 global $USER;
791 if (!$this->is_submitted()) {
792 return false;
795 $element = $this->_form->getElement($elname);
797 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
798 $values = $this->_form->exportValues($elname);
799 if (empty($values[$elname])) {
800 return false;
802 $draftid = $values[$elname];
803 $fs = get_file_storage();
804 $context = context_user::instance($USER->id);
805 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
806 return null;
808 return $files;
810 return null;
814 * Save file to local filesystem pool
816 * @param string $elname name of element
817 * @param int $newcontextid id of context
818 * @param string $newcomponent name of the component
819 * @param string $newfilearea name of file area
820 * @param int $newitemid item id
821 * @param string $newfilepath path of file where it get stored
822 * @param string $newfilename use specified filename, if not specified name of uploaded file used
823 * @param bool $overwrite overwrite file if exists
824 * @param int $newuserid new userid if required
825 * @return mixed stored_file object or false if error; may throw exception if duplicate found
827 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
828 $newfilename=null, $overwrite=false, $newuserid=null) {
829 global $USER;
831 if (!$this->is_submitted() or !$this->is_validated()) {
832 return false;
835 if (empty($newuserid)) {
836 $newuserid = $USER->id;
839 $element = $this->_form->getElement($elname);
840 $fs = get_file_storage();
842 if ($element instanceof MoodleQuickForm_filepicker) {
843 $values = $this->_form->exportValues($elname);
844 if (empty($values[$elname])) {
845 return false;
847 $draftid = $values[$elname];
848 $context = context_user::instance($USER->id);
849 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
850 return false;
852 $file = reset($files);
853 if (is_null($newfilename)) {
854 $newfilename = $file->get_filename();
857 if ($overwrite) {
858 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
859 if (!$oldfile->delete()) {
860 return false;
865 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
866 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
867 return $fs->create_file_from_storedfile($file_record, $file);
869 } else if (isset($_FILES[$elname])) {
870 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
872 if ($overwrite) {
873 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
874 if (!$oldfile->delete()) {
875 return false;
880 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
881 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
882 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
885 return false;
889 * Get content of uploaded file.
891 * @param string $elname name of file upload element
892 * @return string|bool false in case of failure, string if ok
894 function get_file_content($elname) {
895 global $USER;
897 if (!$this->is_submitted() or !$this->is_validated()) {
898 return false;
901 $element = $this->_form->getElement($elname);
903 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
904 $values = $this->_form->exportValues($elname);
905 if (empty($values[$elname])) {
906 return false;
908 $draftid = $values[$elname];
909 $fs = get_file_storage();
910 $context = context_user::instance($USER->id);
911 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
912 return false;
914 $file = reset($files);
916 return $file->get_content();
918 } else if (isset($_FILES[$elname])) {
919 return file_get_contents($_FILES[$elname]['tmp_name']);
922 return false;
926 * Print html form.
928 function display() {
929 //finalize the form definition if not yet done
930 if (!$this->_definition_finalized) {
931 $this->_definition_finalized = true;
932 $this->definition_after_data();
935 $this->_form->display();
939 * Renders the html form (same as display, but returns the result).
941 * Note that you can only output this rendered result once per page, as
942 * it contains IDs which must be unique.
944 * @return string HTML code for the form
946 public function render() {
947 ob_start();
948 $this->display();
949 $out = ob_get_contents();
950 ob_end_clean();
951 return $out;
955 * Form definition. Abstract method - always override!
957 protected abstract function definition();
960 * Dummy stub method - override if you need to setup the form depending on current
961 * values. This method is called after definition(), data submission and set_data().
962 * All form setup that is dependent on form values should go in here.
964 function definition_after_data(){
968 * Dummy stub method - override if you needed to perform some extra validation.
969 * If there are errors return array of errors ("fieldname"=>"error message"),
970 * otherwise true if ok.
972 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
974 * @param array $data array of ("fieldname"=>value) of submitted data
975 * @param array $files array of uploaded files "element_name"=>tmp_file_path
976 * @return array of "element_name"=>"error_description" if there are errors,
977 * or an empty array if everything is OK (true allowed for backwards compatibility too).
979 function validation($data, $files) {
980 return array();
984 * Helper used by {@link repeat_elements()}.
986 * @param int $i the index of this element.
987 * @param HTML_QuickForm_element $elementclone
988 * @param array $namecloned array of names
990 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
991 $name = $elementclone->getName();
992 $namecloned[] = $name;
994 if (!empty($name)) {
995 $elementclone->setName($name."[$i]");
998 if (is_a($elementclone, 'HTML_QuickForm_header')) {
999 $value = $elementclone->_text;
1000 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1002 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1003 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1005 } else {
1006 $value=$elementclone->getLabel();
1007 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1012 * Method to add a repeating group of elements to a form.
1014 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1015 * @param int $repeats no of times to repeat elements initially
1016 * @param array $options a nested array. The first array key is the element name.
1017 * the second array key is the type of option to set, and depend on that option,
1018 * the value takes different forms.
1019 * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
1020 * 'type' - PARAM_* type.
1021 * 'helpbutton' - array containing the helpbutton params.
1022 * 'disabledif' - array containing the disabledIf() arguments after the element name.
1023 * 'rule' - array containing the addRule arguments after the element name.
1024 * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
1025 * 'advanced' - whether this element is hidden by 'Show more ...'.
1026 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1027 * @param string $addfieldsname name for button to add more fields
1028 * @param int $addfieldsno how many fields to add at a time
1029 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1030 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1031 * @return int no of repeats of element in this page
1033 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1034 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1035 if ($addstring===null){
1036 $addstring = get_string('addfields', 'form', $addfieldsno);
1037 } else {
1038 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1040 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1041 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1042 if (!empty($addfields)){
1043 $repeats += $addfieldsno;
1045 $mform =& $this->_form;
1046 $mform->registerNoSubmitButton($addfieldsname);
1047 $mform->addElement('hidden', $repeathiddenname, $repeats);
1048 $mform->setType($repeathiddenname, PARAM_INT);
1049 //value not to be overridden by submitted value
1050 $mform->setConstants(array($repeathiddenname=>$repeats));
1051 $namecloned = array();
1052 for ($i = 0; $i < $repeats; $i++) {
1053 foreach ($elementobjs as $elementobj){
1054 $elementclone = fullclone($elementobj);
1055 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1057 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1058 foreach ($elementclone->getElements() as $el) {
1059 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1061 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1064 $mform->addElement($elementclone);
1067 for ($i=0; $i<$repeats; $i++) {
1068 foreach ($options as $elementname => $elementoptions){
1069 $pos=strpos($elementname, '[');
1070 if ($pos!==FALSE){
1071 $realelementname = substr($elementname, 0, $pos)."[$i]";
1072 $realelementname .= substr($elementname, $pos);
1073 }else {
1074 $realelementname = $elementname."[$i]";
1076 foreach ($elementoptions as $option => $params){
1078 switch ($option){
1079 case 'default' :
1080 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1081 break;
1082 case 'helpbutton' :
1083 $params = array_merge(array($realelementname), $params);
1084 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1085 break;
1086 case 'disabledif' :
1087 foreach ($namecloned as $num => $name){
1088 if ($params[0] == $name){
1089 $params[0] = $params[0]."[$i]";
1090 break;
1093 $params = array_merge(array($realelementname), $params);
1094 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1095 break;
1096 case 'rule' :
1097 if (is_string($params)){
1098 $params = array(null, $params, null, 'client');
1100 $params = array_merge(array($realelementname), $params);
1101 call_user_func_array(array(&$mform, 'addRule'), $params);
1102 break;
1104 case 'type':
1105 $mform->setType($realelementname, $params);
1106 break;
1108 case 'expanded':
1109 $mform->setExpanded($realelementname, $params);
1110 break;
1112 case 'advanced' :
1113 $mform->setAdvanced($realelementname, $params);
1114 break;
1119 $mform->addElement('submit', $addfieldsname, $addstring);
1121 if (!$addbuttoninside) {
1122 $mform->closeHeaderBefore($addfieldsname);
1125 return $repeats;
1129 * Adds a link/button that controls the checked state of a group of checkboxes.
1131 * @param int $groupid The id of the group of advcheckboxes this element controls
1132 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1133 * @param array $attributes associative array of HTML attributes
1134 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1136 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1137 global $CFG, $PAGE;
1139 // Name of the controller button
1140 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1141 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1142 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1144 // Set the default text if none was specified
1145 if (empty($text)) {
1146 $text = get_string('selectallornone', 'form');
1149 $mform = $this->_form;
1150 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1151 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1153 $newselectvalue = $selectvalue;
1154 if (is_null($selectvalue)) {
1155 $newselectvalue = $originalValue;
1156 } else if (!is_null($contollerbutton)) {
1157 $newselectvalue = (int) !$selectvalue;
1159 // set checkbox state depending on orignal/submitted value by controoler button
1160 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1161 foreach ($mform->_elements as $element) {
1162 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1163 $element->getAttribute('class') == $checkboxgroupclass &&
1164 !$element->isFrozen()) {
1165 $mform->setConstants(array($element->getName() => $newselectvalue));
1170 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1171 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1172 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1174 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1175 array(
1176 array('groupid' => $groupid,
1177 'checkboxclass' => $checkboxgroupclass,
1178 'checkboxcontroller' => $checkboxcontrollerparam,
1179 'controllerbutton' => $checkboxcontrollername)
1183 require_once("$CFG->libdir/form/submit.php");
1184 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1185 $mform->addElement($submitlink);
1186 $mform->registerNoSubmitButton($checkboxcontrollername);
1187 $mform->setDefault($checkboxcontrollername, $text);
1191 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1192 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1193 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1194 * get data with get_data().
1196 * @param bool $cancel whether to show cancel button, default true
1197 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1199 function add_action_buttons($cancel = true, $submitlabel=null){
1200 if (is_null($submitlabel)){
1201 $submitlabel = get_string('savechanges');
1203 $mform =& $this->_form;
1204 if ($cancel){
1205 //when two elements we need a group
1206 $buttonarray=array();
1207 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1208 $buttonarray[] = &$mform->createElement('cancel');
1209 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1210 $mform->closeHeaderBefore('buttonar');
1211 } else {
1212 //no group needed
1213 $mform->addElement('submit', 'submitbutton', $submitlabel);
1214 $mform->closeHeaderBefore('submitbutton');
1219 * Adds an initialisation call for a standard JavaScript enhancement.
1221 * This function is designed to add an initialisation call for a JavaScript
1222 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1224 * Current options:
1225 * - Selectboxes
1226 * - smartselect: Turns a nbsp indented select box into a custom drop down
1227 * control that supports multilevel and category selection.
1228 * $enhancement = 'smartselect';
1229 * $options = array('selectablecategories' => true|false)
1231 * @since Moodle 2.0
1232 * @param string|element $element form element for which Javascript needs to be initalized
1233 * @param string $enhancement which init function should be called
1234 * @param array $options options passed to javascript
1235 * @param array $strings strings for javascript
1237 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1238 global $PAGE;
1239 if (is_string($element)) {
1240 $element = $this->_form->getElement($element);
1242 if (is_object($element)) {
1243 $element->_generateId();
1244 $elementid = $element->getAttribute('id');
1245 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1246 if (is_array($strings)) {
1247 foreach ($strings as $string) {
1248 if (is_array($string)) {
1249 call_user_func_array(array($PAGE->requires, 'string_for_js'), $string);
1250 } else {
1251 $PAGE->requires->string_for_js($string, 'moodle');
1259 * Returns a JS module definition for the mforms JS
1261 * @return array
1263 public static function get_js_module() {
1264 global $CFG;
1265 return array(
1266 'name' => 'mform',
1267 'fullpath' => '/lib/form/form.js',
1268 'requires' => array('base', 'node')
1273 * Detects elements with missing setType() declerations.
1275 * Finds elements in the form which should a PARAM_ type set and throws a
1276 * developer debug warning for any elements without it. This is to reduce the
1277 * risk of potential security issues by developers mistakenly forgetting to set
1278 * the type.
1280 * @return void
1282 private function detectMissingSetType() {
1283 global $CFG;
1285 if (!$CFG->debugdeveloper) {
1286 // Only for devs.
1287 return;
1290 $mform = $this->_form;
1291 foreach ($mform->_elements as $element) {
1292 $group = false;
1293 $elements = array($element);
1295 if ($element->getType() == 'group') {
1296 $group = $element;
1297 $elements = $element->getElements();
1300 foreach ($elements as $index => $element) {
1301 switch ($element->getType()) {
1302 case 'hidden':
1303 case 'text':
1304 case 'url':
1305 if ($group) {
1306 $name = $group->getElementName($index);
1307 } else {
1308 $name = $element->getName();
1310 $key = $name;
1311 $found = array_key_exists($key, $mform->_types);
1312 // For repeated elements we need to look for
1313 // the "main" type, not for the one present
1314 // on each repetition. All the stuff in formslib
1315 // (repeat_elements(), updateSubmission()... seems
1316 // to work that way.
1317 while (!$found && strrpos($key, '[') !== false) {
1318 $pos = strrpos($key, '[');
1319 $key = substr($key, 0, $pos);
1320 $found = array_key_exists($key, $mform->_types);
1322 if (!$found) {
1323 debugging("Did you remember to call setType() for '$name'? ".
1324 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
1326 break;
1333 * Used by tests to simulate submitted form data submission from the user.
1335 * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
1336 * get_data.
1338 * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
1339 * global arrays after each test.
1341 * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
1342 * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
1343 * @param string $method 'post' or 'get', defaults to 'post'.
1344 * @param null $formidentifier the default is to use the class name for this class but you may need to provide
1345 * a different value here for some forms that are used more than once on the
1346 * same page.
1348 public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
1349 $formidentifier = null) {
1350 $_FILES = $simulatedsubmittedfiles;
1351 if ($formidentifier === null) {
1352 $formidentifier = get_called_class();
1354 $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
1355 $simulatedsubmitteddata['sesskey'] = sesskey();
1356 if (strtolower($method) === 'get') {
1357 $_GET = $simulatedsubmitteddata;
1358 } else {
1359 $_POST = $simulatedsubmitteddata;
1365 * MoodleQuickForm implementation
1367 * You never extend this class directly. The class methods of this class are available from
1368 * the private $this->_form property on moodleform and its children. You generally only
1369 * call methods on this class from within abstract methods that you override on moodleform such
1370 * as definition and definition_after_data
1372 * @package core_form
1373 * @category form
1374 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1375 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1377 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1378 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1379 var $_types = array();
1381 /** @var array dependent state for the element/'s */
1382 var $_dependencies = array();
1384 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1385 var $_noSubmitButtons=array();
1387 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1388 var $_cancelButtons=array();
1390 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1391 var $_advancedElements = array();
1394 * Array whose keys are element names and values are the desired collapsible state.
1395 * True for collapsed, False for expanded. If not present, set to default in
1396 * {@link self::accept()}.
1398 * @var array
1400 var $_collapsibleElements = array();
1403 * Whether to enable shortforms for this form
1405 * @var boolean
1407 var $_disableShortforms = false;
1409 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1410 protected $_use_form_change_checker = true;
1413 * The form name is derived from the class name of the wrapper minus the trailing form
1414 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1415 * @var string
1417 var $_formName = '';
1420 * String with the html for hidden params passed in as part of a moodle_url
1421 * object for the action. Output in the form.
1422 * @var string
1424 var $_pageparams = '';
1427 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1429 * @staticvar int $formcounter counts number of forms
1430 * @param string $formName Form's name.
1431 * @param string $method Form's method defaults to 'POST'
1432 * @param string|moodle_url $action Form's action
1433 * @param string $target (optional)Form's target defaults to none
1434 * @param mixed $attributes (optional)Extra attributes for <form> tag
1436 public function __construct($formName, $method, $action, $target='', $attributes=null) {
1437 global $CFG, $OUTPUT;
1439 static $formcounter = 1;
1441 // TODO MDL-52313 Replace with the call to parent::__construct().
1442 HTML_Common::__construct($attributes);
1443 $target = empty($target) ? array() : array('target' => $target);
1444 $this->_formName = $formName;
1445 if (is_a($action, 'moodle_url')){
1446 $this->_pageparams = html_writer::input_hidden_params($action);
1447 $action = $action->out_omit_querystring();
1448 } else {
1449 $this->_pageparams = '';
1451 // No 'name' atttribute for form in xhtml strict :
1452 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1453 if (is_null($this->getAttribute('id'))) {
1454 $attributes['id'] = 'mform' . $formcounter;
1456 $formcounter++;
1457 $this->updateAttributes($attributes);
1459 // This is custom stuff for Moodle :
1460 $oldclass= $this->getAttribute('class');
1461 if (!empty($oldclass)){
1462 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1463 }else {
1464 $this->updateAttributes(array('class'=>'mform'));
1466 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1467 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1468 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1472 * Old syntax of class constructor for backward compatibility.
1474 public function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null) {
1475 self::__construct($formName, $method, $action, $target, $attributes);
1479 * Use this method to indicate an element in a form is an advanced field. If items in a form
1480 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1481 * form so the user can decide whether to display advanced form controls.
1483 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1485 * @param string $elementName group or element name (not the element name of something inside a group).
1486 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1488 function setAdvanced($elementName, $advanced = true) {
1489 if ($advanced){
1490 $this->_advancedElements[$elementName]='';
1491 } elseif (isset($this->_advancedElements[$elementName])) {
1492 unset($this->_advancedElements[$elementName]);
1497 * Use this method to indicate that the fieldset should be shown as expanded.
1498 * The method is applicable to header elements only.
1500 * @param string $headername header element name
1501 * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
1502 * @param boolean $ignoreuserstate override the state regardless of the state it was on when
1503 * the form was submitted.
1504 * @return void
1506 function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
1507 if (empty($headername)) {
1508 return;
1510 $element = $this->getElement($headername);
1511 if ($element->getType() != 'header') {
1512 debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
1513 return;
1515 if (!$headerid = $element->getAttribute('id')) {
1516 $element->_generateId();
1517 $headerid = $element->getAttribute('id');
1519 if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
1520 // See if the form has been submitted already.
1521 $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
1522 if (!$ignoreuserstate && $formexpanded != -1) {
1523 // Override expanded state with the form variable.
1524 $expanded = $formexpanded;
1526 // Create the form element for storing expanded state.
1527 $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
1528 $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
1529 $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
1531 $this->_collapsibleElements[$headername] = !$expanded;
1535 * Use this method to add show more/less status element required for passing
1536 * over the advanced elements visibility status on the form submission.
1538 * @param string $headerName header element name.
1539 * @param boolean $showmore default false sets the advanced elements to be hidden.
1541 function addAdvancedStatusElement($headerid, $showmore=false){
1542 // Add extra hidden element to store advanced items state for each section.
1543 if ($this->getElementType('mform_showmore_' . $headerid) === false) {
1544 // See if we the form has been submitted already.
1545 $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
1546 if (!$showmore && $formshowmore != -1) {
1547 // Override showmore state with the form variable.
1548 $showmore = $formshowmore;
1550 // Create the form element for storing advanced items state.
1551 $this->addElement('hidden', 'mform_showmore_' . $headerid);
1552 $this->setType('mform_showmore_' . $headerid, PARAM_INT);
1553 $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
1558 * This function has been deprecated. Show advanced has been replaced by
1559 * "Show more.../Show less..." in the shortforms javascript module.
1561 * @deprecated since Moodle 2.5
1562 * @param bool $showadvancedNow if true will show advanced elements.
1564 function setShowAdvanced($showadvancedNow = null){
1565 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1569 * This function has been deprecated. Show advanced has been replaced by
1570 * "Show more.../Show less..." in the shortforms javascript module.
1572 * @deprecated since Moodle 2.5
1573 * @return bool (Always false)
1575 function getShowAdvanced(){
1576 debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
1577 return false;
1581 * Use this method to indicate that the form will not be using shortforms.
1583 * @param boolean $disable default true, controls if the shortforms are disabled.
1585 function setDisableShortforms ($disable = true) {
1586 $this->_disableShortforms = $disable;
1590 * Call this method if you don't want the formchangechecker JavaScript to be
1591 * automatically initialised for this form.
1593 public function disable_form_change_checker() {
1594 $this->_use_form_change_checker = false;
1598 * If you have called {@link disable_form_change_checker()} then you can use
1599 * this method to re-enable it. It is enabled by default, so normally you don't
1600 * need to call this.
1602 public function enable_form_change_checker() {
1603 $this->_use_form_change_checker = true;
1607 * @return bool whether this form should automatically initialise
1608 * formchangechecker for itself.
1610 public function is_form_change_checker_enabled() {
1611 return $this->_use_form_change_checker;
1615 * Accepts a renderer
1617 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1619 function accept(&$renderer) {
1620 if (method_exists($renderer, 'setAdvancedElements')){
1621 //Check for visible fieldsets where all elements are advanced
1622 //and mark these headers as advanced as well.
1623 //Also mark all elements in a advanced header as advanced.
1624 $stopFields = $renderer->getStopFieldSetElements();
1625 $lastHeader = null;
1626 $lastHeaderAdvanced = false;
1627 $anyAdvanced = false;
1628 $anyError = false;
1629 foreach (array_keys($this->_elements) as $elementIndex){
1630 $element =& $this->_elements[$elementIndex];
1632 // if closing header and any contained element was advanced then mark it as advanced
1633 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1634 if ($anyAdvanced && !is_null($lastHeader)) {
1635 $lastHeader->_generateId();
1636 $this->setAdvanced($lastHeader->getName());
1637 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1639 $lastHeaderAdvanced = false;
1640 unset($lastHeader);
1641 $lastHeader = null;
1642 } elseif ($lastHeaderAdvanced) {
1643 $this->setAdvanced($element->getName());
1646 if ($element->getType()=='header'){
1647 $lastHeader =& $element;
1648 $anyAdvanced = false;
1649 $anyError = false;
1650 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1651 } elseif (isset($this->_advancedElements[$element->getName()])){
1652 $anyAdvanced = true;
1653 if (isset($this->_errors[$element->getName()])) {
1654 $anyError = true;
1658 // the last header may not be closed yet...
1659 if ($anyAdvanced && !is_null($lastHeader)){
1660 $this->setAdvanced($lastHeader->getName());
1661 $lastHeader->_generateId();
1662 $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
1664 $renderer->setAdvancedElements($this->_advancedElements);
1666 if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
1668 // Count the number of sections.
1669 $headerscount = 0;
1670 foreach (array_keys($this->_elements) as $elementIndex){
1671 $element =& $this->_elements[$elementIndex];
1672 if ($element->getType() == 'header') {
1673 $headerscount++;
1677 $anyrequiredorerror = false;
1678 $headercounter = 0;
1679 $headername = null;
1680 foreach (array_keys($this->_elements) as $elementIndex){
1681 $element =& $this->_elements[$elementIndex];
1683 if ($element->getType() == 'header') {
1684 $headercounter++;
1685 $element->_generateId();
1686 $headername = $element->getName();
1687 $anyrequiredorerror = false;
1688 } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
1689 $anyrequiredorerror = true;
1690 } else {
1691 // Do not reset $anyrequiredorerror to false because we do not want any other element
1692 // in this header (fieldset) to possibly revert the state given.
1695 if ($element->getType() == 'header') {
1696 if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
1697 // By default the first section is always expanded, except if a state has already been set.
1698 $this->setExpanded($headername, true);
1699 } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
1700 // The second section is always expanded if the form only contains 2 sections),
1701 // except if a state has already been set.
1702 $this->setExpanded($headername, true);
1704 } else if ($anyrequiredorerror) {
1705 // If any error or required field are present within the header, we need to expand it.
1706 $this->setExpanded($headername, true, true);
1707 } else if (!isset($this->_collapsibleElements[$headername])) {
1708 // Define element as collapsed by default.
1709 $this->setExpanded($headername, false);
1713 // Pass the array to renderer object.
1714 $renderer->setCollapsibleElements($this->_collapsibleElements);
1716 parent::accept($renderer);
1720 * Adds one or more element names that indicate the end of a fieldset
1722 * @param string $elementName name of the element
1724 function closeHeaderBefore($elementName){
1725 $renderer =& $this->defaultRenderer();
1726 $renderer->addStopFieldsetElements($elementName);
1730 * Should be used for all elements of a form except for select, radio and checkboxes which
1731 * clean their own data.
1733 * @param string $elementname
1734 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1735 * {@link lib/moodlelib.php} for defined parameter types
1737 function setType($elementname, $paramtype) {
1738 $this->_types[$elementname] = $paramtype;
1742 * This can be used to set several types at once.
1744 * @param array $paramtypes types of parameters.
1745 * @see MoodleQuickForm::setType
1747 function setTypes($paramtypes) {
1748 $this->_types = $paramtypes + $this->_types;
1752 * Return the type(s) to use to clean an element.
1754 * In the case where the element has an array as a value, we will try to obtain a
1755 * type defined for that specific key, and recursively until done.
1757 * This method does not work reverse, you cannot pass a nested element and hoping to
1758 * fallback on the clean type of a parent. This method intends to be used with the
1759 * main element, which will generate child types if needed, not the other way around.
1761 * Example scenario:
1763 * You have defined a new repeated element containing a text field called 'foo'.
1764 * By default there will always be 2 occurence of 'foo' in the form. Even though
1765 * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
1766 * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
1767 * $mform->setType('foo[0]', PARAM_FLOAT).
1769 * Now if you call this method passing 'foo', along with the submitted values of 'foo':
1770 * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
1771 * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
1772 * get the default clean type returned (param $default).
1774 * @param string $elementname name of the element.
1775 * @param mixed $value value that should be cleaned.
1776 * @param int $default default constant value to be returned (PARAM_...)
1777 * @return string|array constant value or array of constant values (PARAM_...)
1779 public function getCleanType($elementname, $value, $default = PARAM_RAW) {
1780 $type = $default;
1781 if (array_key_exists($elementname, $this->_types)) {
1782 $type = $this->_types[$elementname];
1784 if (is_array($value)) {
1785 $default = $type;
1786 $type = array();
1787 foreach ($value as $subkey => $subvalue) {
1788 $typekey = "$elementname" . "[$subkey]";
1789 if (array_key_exists($typekey, $this->_types)) {
1790 $subtype = $this->_types[$typekey];
1791 } else {
1792 $subtype = $default;
1794 if (is_array($subvalue)) {
1795 $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
1796 } else {
1797 $type[$subkey] = $subtype;
1801 return $type;
1805 * Return the cleaned value using the passed type(s).
1807 * @param mixed $value value that has to be cleaned.
1808 * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
1809 * @return mixed cleaned up value.
1811 public function getCleanedValue($value, $type) {
1812 if (is_array($type) && is_array($value)) {
1813 foreach ($type as $key => $param) {
1814 $value[$key] = $this->getCleanedValue($value[$key], $param);
1816 } else if (!is_array($type) && !is_array($value)) {
1817 $value = clean_param($value, $type);
1818 } else if (!is_array($type) && is_array($value)) {
1819 $value = clean_param_array($value, $type, true);
1820 } else {
1821 throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
1823 return $value;
1827 * Updates submitted values
1829 * @param array $submission submitted values
1830 * @param array $files list of files
1832 function updateSubmission($submission, $files) {
1833 $this->_flagSubmitted = false;
1835 if (empty($submission)) {
1836 $this->_submitValues = array();
1837 } else {
1838 foreach ($submission as $key => $s) {
1839 $type = $this->getCleanType($key, $s);
1840 $submission[$key] = $this->getCleanedValue($s, $type);
1842 $this->_submitValues = $submission;
1843 $this->_flagSubmitted = true;
1846 if (empty($files)) {
1847 $this->_submitFiles = array();
1848 } else {
1849 $this->_submitFiles = $files;
1850 $this->_flagSubmitted = true;
1853 // need to tell all elements that they need to update their value attribute.
1854 foreach (array_keys($this->_elements) as $key) {
1855 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1860 * Returns HTML for required elements
1862 * @return string
1864 function getReqHTML(){
1865 return $this->_reqHTML;
1869 * Returns HTML for advanced elements
1871 * @return string
1873 function getAdvancedHTML(){
1874 return $this->_advancedHTML;
1878 * Initializes a default form value. Used to specify the default for a new entry where
1879 * no data is loaded in using moodleform::set_data()
1881 * note: $slashed param removed
1883 * @param string $elementName element name
1884 * @param mixed $defaultValue values for that element name
1886 function setDefault($elementName, $defaultValue){
1887 $this->setDefaults(array($elementName=>$defaultValue));
1891 * Add a help button to element, only one button per element is allowed.
1893 * This is new, simplified and preferable method of setting a help icon on form elements.
1894 * It uses the new $OUTPUT->help_icon().
1896 * Typically, you will provide the same identifier and the component as you have used for the
1897 * label of the element. The string identifier with the _help suffix added is then used
1898 * as the help string.
1900 * There has to be two strings defined:
1901 * 1/ get_string($identifier, $component) - the title of the help page
1902 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1904 * @since Moodle 2.0
1905 * @param string $elementname name of the element to add the item to
1906 * @param string $identifier help string identifier without _help suffix
1907 * @param string $component component name to look the help string in
1908 * @param string $linktext optional text to display next to the icon
1909 * @param bool $suppresscheck set to true if the element may not exist
1911 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1912 global $OUTPUT;
1913 if (array_key_exists($elementname, $this->_elementIndex)) {
1914 $element = $this->_elements[$this->_elementIndex[$elementname]];
1915 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1916 } else if (!$suppresscheck) {
1917 debugging(get_string('nonexistentformelements', 'form', $elementname));
1922 * Set constant value not overridden by _POST or _GET
1923 * note: this does not work for complex names with [] :-(
1925 * @param string $elname name of element
1926 * @param mixed $value
1928 function setConstant($elname, $value) {
1929 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1930 $element =& $this->getElement($elname);
1931 $element->onQuickFormEvent('updateValue', null, $this);
1935 * export submitted values
1937 * @param string $elementList list of elements in form
1938 * @return array
1940 function exportValues($elementList = null){
1941 $unfiltered = array();
1942 if (null === $elementList) {
1943 // iterate over all elements, calling their exportValue() methods
1944 foreach (array_keys($this->_elements) as $key) {
1945 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1946 $varname = $this->_elements[$key]->_attributes['name'];
1947 $value = '';
1948 // If we have a default value then export it.
1949 if (isset($this->_defaultValues[$varname])) {
1950 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
1952 } else {
1953 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1956 if (is_array($value)) {
1957 // This shit throws a bogus warning in PHP 4.3.x
1958 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1961 } else {
1962 if (!is_array($elementList)) {
1963 $elementList = array_map('trim', explode(',', $elementList));
1965 foreach ($elementList as $elementName) {
1966 $value = $this->exportValue($elementName);
1967 if (@PEAR::isError($value)) {
1968 return $value;
1970 //oh, stock QuickFOrm was returning array of arrays!
1971 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1975 if (is_array($this->_constantValues)) {
1976 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1978 return $unfiltered;
1982 * This is a bit of a hack, and it duplicates the code in
1983 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
1984 * reliably calling that code. (Think about date selectors, for example.)
1985 * @param string $name the element name.
1986 * @param mixed $value the fixed value to set.
1987 * @return mixed the appropriate array to add to the $unfiltered array.
1989 protected function prepare_fixed_value($name, $value) {
1990 if (null === $value) {
1991 return null;
1992 } else {
1993 if (!strpos($name, '[')) {
1994 return array($name => $value);
1995 } else {
1996 $valueAry = array();
1997 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
1998 eval("\$valueAry$myIndex = \$value;");
1999 return $valueAry;
2005 * Adds a validation rule for the given field
2007 * If the element is in fact a group, it will be considered as a whole.
2008 * To validate grouped elements as separated entities,
2009 * use addGroupRule instead of addRule.
2011 * @param string $element Form element name
2012 * @param string $message Message to display for invalid data
2013 * @param string $type Rule type, use getRegisteredRules() to get types
2014 * @param string $format (optional)Required for extra rule data
2015 * @param string $validation (optional)Where to perform validation: "server", "client"
2016 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
2017 * @param bool $force Force the rule to be applied, even if the target form element does not exist
2019 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
2021 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
2022 if ($validation == 'client') {
2023 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2029 * Adds a validation rule for the given group of elements
2031 * Only groups with a name can be assigned a validation rule
2032 * Use addGroupRule when you need to validate elements inside the group.
2033 * Use addRule if you need to validate the group as a whole. In this case,
2034 * the same rule will be applied to all elements in the group.
2035 * Use addRule if you need to validate the group against a function.
2037 * @param string $group Form group name
2038 * @param array|string $arg1 Array for multiple elements or error message string for one element
2039 * @param string $type (optional)Rule type use getRegisteredRules() to get types
2040 * @param string $format (optional)Required for extra rule data
2041 * @param int $howmany (optional)How many valid elements should be in the group
2042 * @param string $validation (optional)Where to perform validation: "server", "client"
2043 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
2045 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
2047 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
2048 if (is_array($arg1)) {
2049 foreach ($arg1 as $rules) {
2050 foreach ($rules as $rule) {
2051 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
2053 if ('client' == $validation) {
2054 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2058 } elseif (is_string($arg1)) {
2060 if ($validation == 'client') {
2061 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
2067 * Returns the client side validation script
2069 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
2070 * and slightly modified to run rules per-element
2071 * Needed to override this because of an error with client side validation of grouped elements.
2073 * @return string Javascript to perform validation, empty string if no 'client' rules were added
2075 function getValidationScript()
2077 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
2078 return '';
2081 include_once('HTML/QuickForm/RuleRegistry.php');
2082 $registry =& HTML_QuickForm_RuleRegistry::singleton();
2083 $test = array();
2084 $js_escape = array(
2085 "\r" => '\r',
2086 "\n" => '\n',
2087 "\t" => '\t',
2088 "'" => "\\'",
2089 '"' => '\"',
2090 '\\' => '\\\\'
2093 foreach ($this->_rules as $elementName => $rules) {
2094 foreach ($rules as $rule) {
2095 if ('client' == $rule['validation']) {
2096 unset($element); //TODO: find out how to properly initialize it
2098 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
2099 $rule['message'] = strtr($rule['message'], $js_escape);
2101 if (isset($rule['group'])) {
2102 $group =& $this->getElement($rule['group']);
2103 // No JavaScript validation for frozen elements
2104 if ($group->isFrozen()) {
2105 continue 2;
2107 $elements =& $group->getElements();
2108 foreach (array_keys($elements) as $key) {
2109 if ($elementName == $group->getElementName($key)) {
2110 $element =& $elements[$key];
2111 break;
2114 } elseif ($dependent) {
2115 $element = array();
2116 $element[] =& $this->getElement($elementName);
2117 foreach ($rule['dependent'] as $elName) {
2118 $element[] =& $this->getElement($elName);
2120 } else {
2121 $element =& $this->getElement($elementName);
2123 // No JavaScript validation for frozen elements
2124 if (is_object($element) && $element->isFrozen()) {
2125 continue 2;
2126 } elseif (is_array($element)) {
2127 foreach (array_keys($element) as $key) {
2128 if ($element[$key]->isFrozen()) {
2129 continue 3;
2133 //for editor element, [text] is appended to the name.
2134 $fullelementname = $elementName;
2135 if ($element->getType() == 'editor') {
2136 $fullelementname .= '[text]';
2137 //Add format to rule as moodleform check which format is supported by browser
2138 //it is not set anywhere... So small hack to make sure we pass it down to quickform
2139 if (is_null($rule['format'])) {
2140 $rule['format'] = $element->getFormat();
2143 // Fix for bug displaying errors for elements in a group
2144 $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
2145 $test[$fullelementname][1]=$element;
2146 //end of fix
2151 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
2152 // the form, and then that form field gets corrupted by the code that follows.
2153 unset($element);
2155 $js = '
2156 <script type="text/javascript">
2157 //<![CDATA[
2159 var skipClientValidation = false;
2161 function qf_errorHandler(element, _qfMsg, escapedName) {
2162 div = element.parentNode;
2164 if ((div == undefined) || (element.name == undefined)) {
2165 //no checking can be done for undefined elements so let server handle it.
2166 return true;
2169 if (_qfMsg != \'\') {
2170 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2171 if (!errorSpan) {
2172 errorSpan = document.createElement("span");
2173 errorSpan.id = \'id_error_\' + escapedName;
2174 errorSpan.className = "error";
2175 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
2176 document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
2177 document.getElementById(errorSpan.id).focus();
2180 while (errorSpan.firstChild) {
2181 errorSpan.removeChild(errorSpan.firstChild);
2184 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
2186 if (div.className.substr(div.className.length - 6, 6) != " error"
2187 && div.className != "error") {
2188 div.className += " error";
2189 linebreak = document.createElement("br");
2190 linebreak.className = "error";
2191 linebreak.id = \'id_error_break_\' + escapedName;
2192 errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
2195 return false;
2196 } else {
2197 var errorSpan = document.getElementById(\'id_error_\' + escapedName);
2198 if (errorSpan) {
2199 errorSpan.parentNode.removeChild(errorSpan);
2201 var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
2202 if (linebreak) {
2203 linebreak.parentNode.removeChild(linebreak);
2206 if (div.className.substr(div.className.length - 6, 6) == " error") {
2207 div.className = div.className.substr(0, div.className.length - 6);
2208 } else if (div.className == "error") {
2209 div.className = "";
2212 return true;
2215 $validateJS = '';
2216 foreach ($test as $elementName => $jsandelement) {
2217 // Fix for bug displaying errors for elements in a group
2218 //unset($element);
2219 list($jsArr,$element)=$jsandelement;
2220 //end of fix
2221 $escapedElementName = preg_replace_callback(
2222 '/[_\[\]-]/',
2223 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
2224 $elementName);
2225 $js .= '
2226 function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
2227 if (undefined == element) {
2228 //required element was not found, then let form be submitted without client side validation
2229 return true;
2231 var value = \'\';
2232 var errFlag = new Array();
2233 var _qfGroups = {};
2234 var _qfMsg = \'\';
2235 var frm = element.parentNode;
2236 if ((undefined != element.name) && (frm != undefined)) {
2237 while (frm && frm.nodeName.toUpperCase() != "FORM") {
2238 frm = frm.parentNode;
2240 ' . join("\n", $jsArr) . '
2241 return qf_errorHandler(element, _qfMsg, escapedName);
2242 } else {
2243 //element name should be defined else error msg will not be displayed.
2244 return true;
2248 $validateJS .= '
2249 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
2250 if (!ret && !first_focus) {
2251 first_focus = true;
2252 Y.use(\'moodle-core-event\', function() {
2253 Y.Global.fire(M.core.globalEvents.FORM_ERROR, {formid: \'' . $this->_attributes['id'] . '\',
2254 elementid: \'id_error_' . $escapedElementName . '\'});
2255 document.getElementById(\'id_error_' . $escapedElementName . '\').focus();
2260 // Fix for bug displaying errors for elements in a group
2261 //unset($element);
2262 //$element =& $this->getElement($elementName);
2263 //end of fix
2264 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this, \''.$escapedElementName.'\')';
2265 $onBlur = $element->getAttribute('onBlur');
2266 $onChange = $element->getAttribute('onChange');
2267 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
2268 'onChange' => $onChange . $valFunc));
2270 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
2271 $js .= '
2272 function validate_' . $this->_formName . '(frm) {
2273 if (skipClientValidation) {
2274 return true;
2276 var ret = true;
2278 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
2279 var first_focus = false;
2280 ' . $validateJS . ';
2281 return ret;
2283 //]]>
2284 </script>';
2285 return $js;
2286 } // end func getValidationScript
2289 * Sets default error message
2291 function _setDefaultRuleMessages(){
2292 foreach ($this->_rules as $field => $rulesarr){
2293 foreach ($rulesarr as $key => $rule){
2294 if ($rule['message']===null){
2295 $a=new stdClass();
2296 $a->format=$rule['format'];
2297 $str=get_string('err_'.$rule['type'], 'form', $a);
2298 if (strpos($str, '[[')!==0){
2299 $this->_rules[$field][$key]['message']=$str;
2307 * Get list of attributes which have dependencies
2309 * @return array
2311 function getLockOptionObject(){
2312 $result = array();
2313 foreach ($this->_dependencies as $dependentOn => $conditions){
2314 $result[$dependentOn] = array();
2315 foreach ($conditions as $condition=>$values) {
2316 $result[$dependentOn][$condition] = array();
2317 foreach ($values as $value=>$dependents) {
2318 $result[$dependentOn][$condition][$value] = array();
2319 $i = 0;
2320 foreach ($dependents as $dependent) {
2321 $elements = $this->_getElNamesRecursive($dependent);
2322 if (empty($elements)) {
2323 // probably element inside of some group
2324 $elements = array($dependent);
2326 foreach($elements as $element) {
2327 if ($element == $dependentOn) {
2328 continue;
2330 $result[$dependentOn][$condition][$value][] = $element;
2336 return array($this->getAttribute('id'), $result);
2340 * Get names of element or elements in a group.
2342 * @param HTML_QuickForm_group|element $element element group or element object
2343 * @return array
2345 function _getElNamesRecursive($element) {
2346 if (is_string($element)) {
2347 if (!$this->elementExists($element)) {
2348 return array();
2350 $element = $this->getElement($element);
2353 if (is_a($element, 'HTML_QuickForm_group')) {
2354 $elsInGroup = $element->getElements();
2355 $elNames = array();
2356 foreach ($elsInGroup as $elInGroup){
2357 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2358 // not sure if this would work - groups nested in groups
2359 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2360 } else {
2361 $elNames[] = $element->getElementName($elInGroup->getName());
2365 } else if (is_a($element, 'HTML_QuickForm_header')) {
2366 return array();
2368 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2369 return array();
2371 } else if (method_exists($element, 'getPrivateName') &&
2372 !($element instanceof HTML_QuickForm_advcheckbox)) {
2373 // The advcheckbox element implements a method called getPrivateName,
2374 // but in a way that is not compatible with the generic API, so we
2375 // have to explicitly exclude it.
2376 return array($element->getPrivateName());
2378 } else {
2379 $elNames = array($element->getName());
2382 return $elNames;
2386 * Adds a dependency for $elementName which will be disabled if $condition is met.
2387 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2388 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2389 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2390 * of the $dependentOn element is $condition (such as equal) to $value.
2392 * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
2393 * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
2394 * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
2396 * @param string $elementName the name of the element which will be disabled
2397 * @param string $dependentOn the name of the element whose state will be checked for condition
2398 * @param string $condition the condition to check
2399 * @param mixed $value used in conjunction with condition.
2401 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
2402 // Multiple selects allow for a multiple selection, we transform the array to string here as
2403 // an array cannot be used as a key in an associative array.
2404 if (is_array($value)) {
2405 $value = implode('|', $value);
2407 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2408 $this->_dependencies[$dependentOn] = array();
2410 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2411 $this->_dependencies[$dependentOn][$condition] = array();
2413 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2414 $this->_dependencies[$dependentOn][$condition][$value] = array();
2416 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2420 * Registers button as no submit button
2422 * @param string $buttonname name of the button
2424 function registerNoSubmitButton($buttonname){
2425 $this->_noSubmitButtons[]=$buttonname;
2429 * Checks if button is a no submit button, i.e it doesn't submit form
2431 * @param string $buttonname name of the button to check
2432 * @return bool
2434 function isNoSubmitButton($buttonname){
2435 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2439 * Registers a button as cancel button
2441 * @param string $addfieldsname name of the button
2443 function _registerCancelButton($addfieldsname){
2444 $this->_cancelButtons[]=$addfieldsname;
2448 * Displays elements without HTML input tags.
2449 * This method is different to freeze() in that it makes sure no hidden
2450 * elements are included in the form.
2451 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2453 * This function also removes all previously defined rules.
2455 * @param string|array $elementList array or string of element(s) to be frozen
2456 * @return object|bool if element list is not empty then return error object, else true
2458 function hardFreeze($elementList=null)
2460 if (!isset($elementList)) {
2461 $this->_freezeAll = true;
2462 $elementList = array();
2463 } else {
2464 if (!is_array($elementList)) {
2465 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2467 $elementList = array_flip($elementList);
2470 foreach (array_keys($this->_elements) as $key) {
2471 $name = $this->_elements[$key]->getName();
2472 if ($this->_freezeAll || isset($elementList[$name])) {
2473 $this->_elements[$key]->freeze();
2474 $this->_elements[$key]->setPersistantFreeze(false);
2475 unset($elementList[$name]);
2477 // remove all rules
2478 $this->_rules[$name] = array();
2479 // if field is required, remove the rule
2480 $unset = array_search($name, $this->_required);
2481 if ($unset !== false) {
2482 unset($this->_required[$unset]);
2487 if (!empty($elementList)) {
2488 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);
2490 return true;
2494 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2496 * This function also removes all previously defined rules of elements it freezes.
2498 * @throws HTML_QuickForm_Error
2499 * @param array $elementList array or string of element(s) not to be frozen
2500 * @return bool returns true
2502 function hardFreezeAllVisibleExcept($elementList)
2504 $elementList = array_flip($elementList);
2505 foreach (array_keys($this->_elements) as $key) {
2506 $name = $this->_elements[$key]->getName();
2507 $type = $this->_elements[$key]->getType();
2509 if ($type == 'hidden'){
2510 // leave hidden types as they are
2511 } elseif (!isset($elementList[$name])) {
2512 $this->_elements[$key]->freeze();
2513 $this->_elements[$key]->setPersistantFreeze(false);
2515 // remove all rules
2516 $this->_rules[$name] = array();
2517 // if field is required, remove the rule
2518 $unset = array_search($name, $this->_required);
2519 if ($unset !== false) {
2520 unset($this->_required[$unset]);
2524 return true;
2528 * Tells whether the form was already submitted
2530 * This is useful since the _submitFiles and _submitValues arrays
2531 * may be completely empty after the trackSubmit value is removed.
2533 * @return bool
2535 function isSubmitted()
2537 return parent::isSubmitted() && (!$this->isFrozen());
2542 * MoodleQuickForm renderer
2544 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2545 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2547 * Stylesheet is part of standard theme and should be automatically included.
2549 * @package core_form
2550 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2553 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2555 /** @var array Element template array */
2556 var $_elementTemplates;
2559 * Template used when opening a hidden fieldset
2560 * (i.e. a fieldset that is opened when there is no header element)
2561 * @var string
2563 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2565 /** @var string Header Template string */
2566 var $_headerTemplate =
2567 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
2569 /** @var string Template used when opening a fieldset */
2570 var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
2572 /** @var string Template used when closing a fieldset */
2573 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2575 /** @var string Required Note template string */
2576 var $_requiredNoteTemplate =
2577 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2580 * Collapsible buttons string template.
2582 * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
2583 * until the Javascript has been fully loaded.
2585 * @var string
2587 var $_collapseButtonsTemplate =
2588 "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
2591 * Array whose keys are element names. If the key exists this is a advanced element
2593 * @var array
2595 var $_advancedElements = array();
2598 * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
2600 * @var array
2602 var $_collapsibleElements = array();
2605 * @var string Contains the collapsible buttons to add to the form.
2607 var $_collapseButtons = '';
2610 * Constructor
2612 public function __construct() {
2613 // switch next two lines for ol li containers for form items.
2614 // $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>');
2615 $this->_elementTemplates = array(
2616 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}" {aria-live}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2618 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2620 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2622 'static'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}"><div class="fitemtitle"><div class="fstaticlabel">{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error" tabindex="0">{error}</span><br /><!-- END error -->{element}</div></div>',
2624 'warning'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}">{element}</div>',
2626 'nodisplay'=>'');
2628 parent::__construct();
2632 * Old syntax of class constructor for backward compatibility.
2634 public function MoodleQuickForm_Renderer() {
2635 self::__construct();
2639 * Set element's as adavance element
2641 * @param array $elements form elements which needs to be grouped as advance elements.
2643 function setAdvancedElements($elements){
2644 $this->_advancedElements = $elements;
2648 * Setting collapsible elements
2650 * @param array $elements
2652 function setCollapsibleElements($elements) {
2653 $this->_collapsibleElements = $elements;
2657 * What to do when starting the form
2659 * @param MoodleQuickForm $form reference of the form
2661 function startForm(&$form){
2662 global $PAGE;
2663 $this->_reqHTML = $form->getReqHTML();
2664 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2665 $this->_advancedHTML = $form->getAdvancedHTML();
2666 $this->_collapseButtons = '';
2667 $formid = $form->getAttribute('id');
2668 parent::startForm($form);
2669 if ($form->isFrozen()){
2670 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2671 } else {
2672 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
2673 $this->_hiddenHtml .= $form->_pageparams;
2676 if ($form->is_form_change_checker_enabled()) {
2677 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2678 'M.core_formchangechecker.init',
2679 array(array(
2680 'formid' => $formid
2683 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2685 if (!empty($this->_collapsibleElements)) {
2686 if (count($this->_collapsibleElements) > 1) {
2687 $this->_collapseButtons = $this->_collapseButtonsTemplate;
2688 $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
2689 $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
2691 $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
2693 if (!empty($this->_advancedElements)){
2694 $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
2695 $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
2700 * Create advance group of elements
2702 * @param object $group Passed by reference
2703 * @param bool $required if input is required field
2704 * @param string $error error message to display
2706 function startGroup(&$group, $required, $error){
2707 // Make sure the element has an id.
2708 $group->_generateId();
2710 if (method_exists($group, 'getElementTemplateType')){
2711 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2712 }else{
2713 $html = $this->_elementTemplates['default'];
2717 if (isset($this->_advancedElements[$group->getName()])){
2718 $html =str_replace(' {advanced}', ' advanced', $html);
2719 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2720 } else {
2721 $html =str_replace(' {advanced}', '', $html);
2722 $html =str_replace('{advancedimg}', '', $html);
2724 if (method_exists($group, 'getHelpButton')){
2725 $html =str_replace('{help}', $group->getHelpButton(), $html);
2726 }else{
2727 $html =str_replace('{help}', '', $html);
2729 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2730 $html =str_replace('{name}', $group->getName(), $html);
2731 $html =str_replace('{type}', 'fgroup', $html);
2732 $emptylabel = '';
2733 if ($group->getLabel() == '') {
2734 $emptylabel = 'femptylabel';
2736 $html = str_replace('{emptylabel}', $emptylabel, $html);
2738 $this->_templates[$group->getName()]=$html;
2739 // Fix for bug in tableless quickforms that didn't allow you to stop a
2740 // fieldset before a group of elements.
2741 // if the element name indicates the end of a fieldset, close the fieldset
2742 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2743 && $this->_fieldsetsOpen > 0
2745 $this->_html .= $this->_closeFieldsetTemplate;
2746 $this->_fieldsetsOpen--;
2748 parent::startGroup($group, $required, $error);
2752 * Renders element
2754 * @param HTML_QuickForm_element $element element
2755 * @param bool $required if input is required field
2756 * @param string $error error message to display
2758 function renderElement(&$element, $required, $error){
2759 // Make sure the element has an id.
2760 $element->_generateId();
2762 //adding stuff to place holders in template
2763 //check if this is a group element first
2764 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2765 // so it gets substitutions for *each* element
2766 $html = $this->_groupElementTemplate;
2768 elseif (method_exists($element, 'getElementTemplateType')){
2769 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2770 }else{
2771 $html = $this->_elementTemplates['default'];
2773 if (isset($this->_advancedElements[$element->getName()])){
2774 $html = str_replace(' {advanced}', ' advanced', $html);
2775 $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
2776 } else {
2777 $html = str_replace(' {advanced}', '', $html);
2778 $html = str_replace(' {aria-live}', '', $html);
2780 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2781 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2782 } else {
2783 $html =str_replace('{advancedimg}', '', $html);
2785 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2786 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2787 $html =str_replace('{name}', $element->getName(), $html);
2788 $emptylabel = '';
2789 if ($element->getLabel() == '') {
2790 $emptylabel = 'femptylabel';
2792 $html = str_replace('{emptylabel}', $emptylabel, $html);
2793 if (method_exists($element, 'getHelpButton')){
2794 $html = str_replace('{help}', $element->getHelpButton(), $html);
2795 }else{
2796 $html = str_replace('{help}', '', $html);
2799 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2800 $this->_groupElementTemplate = $html;
2802 elseif (!isset($this->_templates[$element->getName()])) {
2803 $this->_templates[$element->getName()] = $html;
2806 parent::renderElement($element, $required, $error);
2810 * Called when visiting a form, after processing all form elements
2811 * Adds required note, form attributes, validation javascript and form content.
2813 * @global moodle_page $PAGE
2814 * @param moodleform $form Passed by reference
2816 function finishForm(&$form){
2817 global $PAGE;
2818 if ($form->isFrozen()){
2819 $this->_hiddenHtml = '';
2821 parent::finishForm($form);
2822 $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
2823 if (!$form->isFrozen()) {
2824 $args = $form->getLockOptionObject();
2825 if (count($args[1]) > 0) {
2826 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2831 * Called when visiting a header element
2833 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2834 * @global moodle_page $PAGE
2836 function renderHeader(&$header) {
2837 global $PAGE;
2839 $header->_generateId();
2840 $name = $header->getName();
2842 $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
2843 if (is_null($header->_text)) {
2844 $header_html = '';
2845 } elseif (!empty($name) && isset($this->_templates[$name])) {
2846 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2847 } else {
2848 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2851 if ($this->_fieldsetsOpen > 0) {
2852 $this->_html .= $this->_closeFieldsetTemplate;
2853 $this->_fieldsetsOpen--;
2856 // Define collapsible classes for fieldsets.
2857 $arialive = '';
2858 $fieldsetclasses = array('clearfix');
2859 if (isset($this->_collapsibleElements[$header->getName()])) {
2860 $fieldsetclasses[] = 'collapsible';
2861 if ($this->_collapsibleElements[$header->getName()]) {
2862 $fieldsetclasses[] = 'collapsed';
2866 if (isset($this->_advancedElements[$name])){
2867 $fieldsetclasses[] = 'containsadvancedelements';
2870 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2871 $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
2873 $this->_html .= $openFieldsetTemplate . $header_html;
2874 $this->_fieldsetsOpen++;
2878 * Return Array of element names that indicate the end of a fieldset
2880 * @return array
2882 function getStopFieldsetElements(){
2883 return $this->_stopFieldsetElements;
2888 * Required elements validation
2890 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2892 * @package core_form
2893 * @category form
2894 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2895 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2897 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2899 * Checks if an element is not empty.
2900 * This is a server-side validation, it works for both text fields and editor fields
2902 * @param string $value Value to check
2903 * @param int|string|array $options Not used yet
2904 * @return bool true if value is not empty
2906 function validate($value, $options = null) {
2907 global $CFG;
2908 if (is_array($value) && array_key_exists('text', $value)) {
2909 $value = $value['text'];
2911 if (is_array($value)) {
2912 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2913 $value = implode('', $value);
2915 $stripvalues = array(
2916 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2917 '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
2919 if (!empty($CFG->strictformsrequired)) {
2920 $value = preg_replace($stripvalues, '', (string)$value);
2922 if ((string)$value == '') {
2923 return false;
2925 return true;
2929 * This function returns Javascript code used to build client-side validation.
2930 * It checks if an element is not empty.
2932 * @param int $format format of data which needs to be validated.
2933 * @return array
2935 function getValidationScript($format = null) {
2936 global $CFG;
2937 if (!empty($CFG->strictformsrequired)) {
2938 if (!empty($format) && $format == FORMAT_HTML) {
2939 return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
2940 } else {
2941 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2943 } else {
2944 return array('', "{jsVar} == ''");
2950 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2951 * @name $_HTML_QuickForm_default_renderer
2953 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2955 /** Please keep this list in alphabetical order. */
2956 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2957 MoodleQuickForm::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
2958 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2959 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2960 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2961 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2962 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2963 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2964 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2965 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2966 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2967 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2968 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2969 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2970 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2971 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2972 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2973 MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
2974 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2975 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2976 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2977 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2978 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2979 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2980 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2981 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2982 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2983 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2984 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2985 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2986 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2987 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2988 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2989 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2990 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2991 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2992 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2994 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");