MDL-35129 add missing recordset closing in db transfer
[moodle.git] / lib / formslib.php
blob23f65cb21820ef2b77b6362e6ec86981281f4125
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 (!empty($CFG->debug) and ($CFG->debug >= DEBUG_ALL or $CFG->debug == -1)){
65 //TODO: this is a wrong place to init PEAR!
66 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
67 $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
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 $module = 'moodle-form-dateselector';
81 $function = 'M.form.dateselector.init_date_selectors';
82 $config = array(array(
83 'firstdayofweek' => get_string('firstdayofweek', 'langconfig'),
84 'mon' => strftime('%a', strtotime("Monday")),
85 'tue' => strftime('%a', strtotime("Tuesday")),
86 'wed' => strftime('%a', strtotime("Wednesday")),
87 'thu' => strftime('%a', strtotime("Thursday")),
88 'fri' => strftime('%a', strtotime("Friday")),
89 'sat' => strftime('%a', strtotime("Saturday")),
90 'sun' => strftime('%a', strtotime("Sunday")),
91 'january' => strftime('%B', strtotime("January 1")),
92 'february' => strftime('%B', strtotime("February 1")),
93 'march' => strftime('%B', strtotime("March 1")),
94 'april' => strftime('%B', strtotime("April 1")),
95 'may' => strftime('%B', strtotime("May 1")),
96 'june' => strftime('%B', strtotime("June 1")),
97 'july' => strftime('%B', strtotime("July 1")),
98 'august' => strftime('%B', strtotime("August 1")),
99 'september' => strftime('%B', strtotime("September 1")),
100 'october' => strftime('%B', strtotime("October 1")),
101 'november' => strftime('%B', strtotime("November 1")),
102 'december' => strftime('%B', strtotime("December 1"))
104 $PAGE->requires->yui_module($module, $function, $config);
105 $done = true;
110 * Wrapper that separates quickforms syntax from moodle code
112 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
113 * use this class you should write a class definition which extends this class or a more specific
114 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
116 * You will write your own definition() method which performs the form set up.
118 * @package core_form
119 * @copyright 2006 Jamie Pratt <me@jamiep.org>
120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
121 * @todo MDL-19380 rethink the file scanning
123 abstract class moodleform {
124 /** @var string name of the form */
125 protected $_formname; // form name
127 /** @var MoodleQuickForm quickform object definition */
128 protected $_form;
130 /** @var array globals workaround */
131 protected $_customdata;
133 /** @var object definition_after_data executed flag */
134 protected $_definition_finalized = false;
137 * The constructor function calls the abstract function definition() and it will then
138 * process and clean and attempt to validate incoming data.
140 * It will call your custom validate method to validate data and will also check any rules
141 * you have specified in definition using addRule
143 * The name of the form (id attribute of the form) is automatically generated depending on
144 * the name you gave the class extending moodleform. You should call your class something
145 * like
147 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
148 * current url. If a moodle_url object then outputs params as hidden variables.
149 * @param mixed $customdata if your form defintion method needs access to data such as $course
150 * $cm, etc. to construct the form definition then pass it in this array. You can
151 * use globals for somethings.
152 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
153 * be merged and used as incoming data to the form.
154 * @param string $target target frame for form submission. You will rarely use this. Don't use
155 * it if you don't need to as the target attribute is deprecated in xhtml strict.
156 * @param mixed $attributes you can pass a string of html attributes here or an array.
157 * @param bool $editable
159 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
160 global $CFG, $FULLME;
161 if (empty($CFG->xmlstrictheaders)) {
162 // no standard mform in moodle should allow autocomplete with the exception of user signup
163 // this is valid attribute in html5, sorry, we have to ignore validation errors in legacy xhtml 1.0
164 if (empty($attributes)) {
165 $attributes = array('autocomplete'=>'off');
166 } else if (is_array($attributes)) {
167 $attributes['autocomplete'] = 'off';
168 } else {
169 if (strpos($attributes, 'autocomplete') === false) {
170 $attributes .= ' autocomplete="off" ';
175 if (empty($action)){
176 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
177 $action = strip_querystring($FULLME);
178 if (!empty($CFG->sslproxy)) {
179 // return only https links when using SSL proxy
180 $action = preg_replace('/^http:/', 'https:', $action, 1);
182 //TODO: use following instead of FULLME - see MDL-33015
183 //$action = strip_querystring(qualified_me());
185 // Assign custom data first, so that get_form_identifier can use it.
186 $this->_customdata = $customdata;
187 $this->_formname = $this->get_form_identifier();
189 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
190 if (!$editable){
191 $this->_form->hardFreeze();
194 $this->definition();
196 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
197 $this->_form->setType('sesskey', PARAM_RAW);
198 $this->_form->setDefault('sesskey', sesskey());
199 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
200 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
201 $this->_form->setDefault('_qf__'.$this->_formname, 1);
202 $this->_form->_setDefaultRuleMessages();
204 // we have to know all input types before processing submission ;-)
205 $this->_process_submission($method);
209 * It should returns unique identifier for the form.
210 * Currently it will return class name, but in case two same forms have to be
211 * rendered on same page then override function to get unique form identifier.
212 * e.g This is used on multiple self enrollments page.
214 * @return string form identifier.
216 protected function get_form_identifier() {
217 return get_class($this);
221 * To autofocus on first form element or first element with error.
223 * @param string $name if this is set then the focus is forced to a field with this name
224 * @return string javascript to select form element with first error or
225 * first element if no errors. Use this as a parameter
226 * when calling print_header
228 function focus($name=NULL) {
229 $form =& $this->_form;
230 $elkeys = array_keys($form->_elementIndex);
231 $error = false;
232 if (isset($form->_errors) && 0 != count($form->_errors)){
233 $errorkeys = array_keys($form->_errors);
234 $elkeys = array_intersect($elkeys, $errorkeys);
235 $error = true;
238 if ($error or empty($name)) {
239 $names = array();
240 while (empty($names) and !empty($elkeys)) {
241 $el = array_shift($elkeys);
242 $names = $form->_getElNamesRecursive($el);
244 if (!empty($names)) {
245 $name = array_shift($names);
249 $focus = '';
250 if (!empty($name)) {
251 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
254 return $focus;
258 * Internal method. Alters submitted data to be suitable for quickforms processing.
259 * Must be called when the form is fully set up.
261 * @param string $method name of the method which alters submitted data
263 function _process_submission($method) {
264 $submission = array();
265 if ($method == 'post') {
266 if (!empty($_POST)) {
267 $submission = $_POST;
269 } else {
270 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
273 // following trick is needed to enable proper sesskey checks when using GET forms
274 // the _qf__.$this->_formname serves as a marker that form was actually submitted
275 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
276 if (!confirm_sesskey()) {
277 print_error('invalidsesskey');
279 $files = $_FILES;
280 } else {
281 $submission = array();
282 $files = array();
285 $this->_form->updateSubmission($submission, $files);
289 * Internal method. Validates all old-style deprecated uploaded files.
290 * The new way is to upload files via repository api.
292 * @param array $files list of files to be validated
293 * @return bool|array Success or an array of errors
295 function _validate_files(&$files) {
296 global $CFG, $COURSE;
298 $files = array();
300 if (empty($_FILES)) {
301 // we do not need to do any checks because no files were submitted
302 // note: server side rules do not work for files - use custom verification in validate() instead
303 return true;
306 $errors = array();
307 $filenames = array();
309 // now check that we really want each file
310 foreach ($_FILES as $elname=>$file) {
311 $required = $this->_form->isElementRequired($elname);
313 if ($file['error'] == 4 and $file['size'] == 0) {
314 if ($required) {
315 $errors[$elname] = get_string('required');
317 unset($_FILES[$elname]);
318 continue;
321 if (!empty($file['error'])) {
322 $errors[$elname] = file_get_upload_error($file['error']);
323 unset($_FILES[$elname]);
324 continue;
327 if (!is_uploaded_file($file['tmp_name'])) {
328 // TODO: improve error message
329 $errors[$elname] = get_string('error');
330 unset($_FILES[$elname]);
331 continue;
334 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
335 // hmm, this file was not requested
336 unset($_FILES[$elname]);
337 continue;
341 // TODO: rethink the file scanning MDL-19380
342 if ($CFG->runclamonupload) {
343 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
344 $errors[$elname] = $_FILES[$elname]['uploadlog'];
345 unset($_FILES[$elname]);
346 continue;
350 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
351 if ($filename === '') {
352 // TODO: improve error message - wrong chars
353 $errors[$elname] = get_string('error');
354 unset($_FILES[$elname]);
355 continue;
357 if (in_array($filename, $filenames)) {
358 // TODO: improve error message - duplicate name
359 $errors[$elname] = get_string('error');
360 unset($_FILES[$elname]);
361 continue;
363 $filenames[] = $filename;
364 $_FILES[$elname]['name'] = $filename;
366 $files[$elname] = $_FILES[$elname]['tmp_name'];
369 // return errors if found
370 if (count($errors) == 0){
371 return true;
373 } else {
374 $files = array();
375 return $errors;
380 * Internal method. Validates filepicker and filemanager files if they are
381 * set as required fields. Also, sets the error message if encountered one.
383 * @return bool|array with errors
385 protected function validate_draft_files() {
386 global $USER;
387 $mform =& $this->_form;
389 $errors = array();
390 //Go through all the required elements and make sure you hit filepicker or
391 //filemanager element.
392 foreach ($mform->_rules as $elementname => $rules) {
393 $elementtype = $mform->getElementType($elementname);
394 //If element is of type filepicker then do validation
395 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
396 //Check if rule defined is required rule
397 foreach ($rules as $rule) {
398 if ($rule['type'] == 'required') {
399 $draftid = (int)$mform->getSubmitValue($elementname);
400 $fs = get_file_storage();
401 $context = get_context_instance(CONTEXT_USER, $USER->id);
402 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
403 $errors[$elementname] = $rule['message'];
409 // Check all the filemanager elements to make sure they do not have too many
410 // files in them.
411 foreach ($mform->_elements as $element) {
412 if ($element->_type == 'filemanager') {
413 $maxfiles = $element->getMaxfiles();
414 if ($maxfiles > 0) {
415 $draftid = (int)$element->getValue();
416 $fs = get_file_storage();
417 $context = context_user::instance($USER->id);
418 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
419 if (count($files) > $maxfiles) {
420 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
425 if (empty($errors)) {
426 return true;
427 } else {
428 return $errors;
433 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
434 * form definition (new entry form); this function is used to load in data where values
435 * already exist and data is being edited (edit entry form).
437 * note: $slashed param removed
439 * @param stdClass|array $default_values object or array of default values
441 function set_data($default_values) {
442 if (is_object($default_values)) {
443 $default_values = (array)$default_values;
445 $this->_form->setDefaults($default_values);
449 * Sets file upload manager
451 * @deprecated since Moodle 2.0 Please don't used this API
452 * @todo MDL-31300 this api will be removed.
453 * @see MoodleQuickForm_filepicker
454 * @see MoodleQuickForm_filemanager
455 * @param bool $um upload manager
457 function set_upload_manager($um=false) {
458 debugging('Old file uploads can not be used any more, please use new filepicker element');
462 * Check that form was submitted. Does not check validity of submitted data.
464 * @return bool true if form properly submitted
466 function is_submitted() {
467 return $this->_form->isSubmitted();
471 * Checks if button pressed is not for submitting the form
473 * @staticvar bool $nosubmit keeps track of no submit button
474 * @return bool
476 function no_submit_button_pressed(){
477 static $nosubmit = null; // one check is enough
478 if (!is_null($nosubmit)){
479 return $nosubmit;
481 $mform =& $this->_form;
482 $nosubmit = false;
483 if (!$this->is_submitted()){
484 return false;
486 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
487 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
488 $nosubmit = true;
489 break;
492 return $nosubmit;
497 * Check that form data is valid.
498 * You should almost always use this, rather than {@link validate_defined_fields}
500 * @return bool true if form data valid
502 function is_validated() {
503 //finalize the form definition before any processing
504 if (!$this->_definition_finalized) {
505 $this->_definition_finalized = true;
506 $this->definition_after_data();
509 return $this->validate_defined_fields();
513 * Validate the form.
515 * You almost always want to call {@link is_validated} instead of this
516 * because it calls {@link definition_after_data} first, before validating the form,
517 * which is what you want in 99% of cases.
519 * This is provided as a separate function for those special cases where
520 * you want the form validated before definition_after_data is called
521 * for example, to selectively add new elements depending on a no_submit_button press,
522 * but only when the form is valid when the no_submit_button is pressed,
524 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
525 * is NOT to validate the form when a no submit button has been pressed.
526 * pass true here to override this behaviour
528 * @return bool true if form data valid
530 function validate_defined_fields($validateonnosubmit=false) {
531 static $validated = null; // one validation is enough
532 $mform =& $this->_form;
533 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
534 return false;
535 } elseif ($validated === null) {
536 $internal_val = $mform->validate();
538 $files = array();
539 $file_val = $this->_validate_files($files);
540 //check draft files for validation and flag them if required files
541 //are not in draft area.
542 $draftfilevalue = $this->validate_draft_files();
544 if ($file_val !== true && $draftfilevalue !== true) {
545 $file_val = array_merge($file_val, $draftfilevalue);
546 } else if ($draftfilevalue !== true) {
547 $file_val = $draftfilevalue;
548 } //default is file_val, so no need to assign.
550 if ($file_val !== true) {
551 if (!empty($file_val)) {
552 foreach ($file_val as $element=>$msg) {
553 $mform->setElementError($element, $msg);
556 $file_val = false;
559 $data = $mform->exportValues();
560 $moodle_val = $this->validation($data, $files);
561 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
562 // non-empty array means errors
563 foreach ($moodle_val as $element=>$msg) {
564 $mform->setElementError($element, $msg);
566 $moodle_val = false;
568 } else {
569 // anything else means validation ok
570 $moodle_val = true;
573 $validated = ($internal_val and $moodle_val and $file_val);
575 return $validated;
579 * Return true if a cancel button has been pressed resulting in the form being submitted.
581 * @return bool true if a cancel button has been pressed
583 function is_cancelled(){
584 $mform =& $this->_form;
585 if ($mform->isSubmitted()){
586 foreach ($mform->_cancelButtons as $cancelbutton){
587 if (optional_param($cancelbutton, 0, PARAM_RAW)){
588 return true;
592 return false;
596 * Return submitted data if properly submitted or returns NULL if validation fails or
597 * if there is no submitted data.
599 * note: $slashed param removed
601 * @return object submitted data; NULL if not valid or not submitted or cancelled
603 function get_data() {
604 $mform =& $this->_form;
606 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
607 $data = $mform->exportValues();
608 unset($data['sesskey']); // we do not need to return sesskey
609 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
610 if (empty($data)) {
611 return NULL;
612 } else {
613 return (object)$data;
615 } else {
616 return NULL;
621 * Return submitted data without validation or NULL if there is no submitted data.
622 * note: $slashed param removed
624 * @return object submitted data; NULL if not submitted
626 function get_submitted_data() {
627 $mform =& $this->_form;
629 if ($this->is_submitted()) {
630 $data = $mform->exportValues();
631 unset($data['sesskey']); // we do not need to return sesskey
632 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
633 if (empty($data)) {
634 return NULL;
635 } else {
636 return (object)$data;
638 } else {
639 return NULL;
644 * Save verified uploaded files into directory. Upload process can be customised from definition()
646 * @deprecated since Moodle 2.0
647 * @todo MDL-31294 remove this api
648 * @see moodleform::save_stored_file()
649 * @see moodleform::save_file()
650 * @param string $destination path where file should be stored
651 * @return bool Always false
653 function save_files($destination) {
654 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
655 return false;
659 * Returns name of uploaded file.
661 * @param string $elname first element if null
662 * @return string|bool false in case of failure, string if ok
664 function get_new_filename($elname=null) {
665 global $USER;
667 if (!$this->is_submitted() or !$this->is_validated()) {
668 return false;
671 if (is_null($elname)) {
672 if (empty($_FILES)) {
673 return false;
675 reset($_FILES);
676 $elname = key($_FILES);
679 if (empty($elname)) {
680 return false;
683 $element = $this->_form->getElement($elname);
685 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
686 $values = $this->_form->exportValues($elname);
687 if (empty($values[$elname])) {
688 return false;
690 $draftid = $values[$elname];
691 $fs = get_file_storage();
692 $context = get_context_instance(CONTEXT_USER, $USER->id);
693 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
694 return false;
696 $file = reset($files);
697 return $file->get_filename();
700 if (!isset($_FILES[$elname])) {
701 return false;
704 return $_FILES[$elname]['name'];
708 * Save file to standard filesystem
710 * @param string $elname name of element
711 * @param string $pathname full path name of file
712 * @param bool $override override file if exists
713 * @return bool success
715 function save_file($elname, $pathname, $override=false) {
716 global $USER;
718 if (!$this->is_submitted() or !$this->is_validated()) {
719 return false;
721 if (file_exists($pathname)) {
722 if ($override) {
723 if (!@unlink($pathname)) {
724 return false;
726 } else {
727 return false;
731 $element = $this->_form->getElement($elname);
733 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
734 $values = $this->_form->exportValues($elname);
735 if (empty($values[$elname])) {
736 return false;
738 $draftid = $values[$elname];
739 $fs = get_file_storage();
740 $context = get_context_instance(CONTEXT_USER, $USER->id);
741 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
742 return false;
744 $file = reset($files);
746 return $file->copy_content_to($pathname);
748 } else if (isset($_FILES[$elname])) {
749 return copy($_FILES[$elname]['tmp_name'], $pathname);
752 return false;
756 * Returns a temporary file, do not forget to delete after not needed any more.
758 * @param string $elname name of the elmenet
759 * @return string|bool either string or false
761 function save_temp_file($elname) {
762 if (!$this->get_new_filename($elname)) {
763 return false;
765 if (!$dir = make_temp_directory('forms')) {
766 return false;
768 if (!$tempfile = tempnam($dir, 'tempup_')) {
769 return false;
771 if (!$this->save_file($elname, $tempfile, true)) {
772 // something went wrong
773 @unlink($tempfile);
774 return false;
777 return $tempfile;
781 * Get draft files of a form element
782 * This is a protected method which will be used only inside moodleforms
784 * @param string $elname name of element
785 * @return array|bool|null
787 protected function get_draft_files($elname) {
788 global $USER;
790 if (!$this->is_submitted()) {
791 return false;
794 $element = $this->_form->getElement($elname);
796 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
797 $values = $this->_form->exportValues($elname);
798 if (empty($values[$elname])) {
799 return false;
801 $draftid = $values[$elname];
802 $fs = get_file_storage();
803 $context = get_context_instance(CONTEXT_USER, $USER->id);
804 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
805 return null;
807 return $files;
809 return null;
813 * Save file to local filesystem pool
815 * @param string $elname name of element
816 * @param int $newcontextid id of context
817 * @param string $newcomponent name of the component
818 * @param string $newfilearea name of file area
819 * @param int $newitemid item id
820 * @param string $newfilepath path of file where it get stored
821 * @param string $newfilename use specified filename, if not specified name of uploaded file used
822 * @param bool $overwrite overwrite file if exists
823 * @param int $newuserid new userid if required
824 * @return mixed stored_file object or false if error; may throw exception if duplicate found
826 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
827 $newfilename=null, $overwrite=false, $newuserid=null) {
828 global $USER;
830 if (!$this->is_submitted() or !$this->is_validated()) {
831 return false;
834 if (empty($newuserid)) {
835 $newuserid = $USER->id;
838 $element = $this->_form->getElement($elname);
839 $fs = get_file_storage();
841 if ($element instanceof MoodleQuickForm_filepicker) {
842 $values = $this->_form->exportValues($elname);
843 if (empty($values[$elname])) {
844 return false;
846 $draftid = $values[$elname];
847 $context = get_context_instance(CONTEXT_USER, $USER->id);
848 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
849 return false;
851 $file = reset($files);
852 if (is_null($newfilename)) {
853 $newfilename = $file->get_filename();
856 if ($overwrite) {
857 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
858 if (!$oldfile->delete()) {
859 return false;
864 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
865 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
866 return $fs->create_file_from_storedfile($file_record, $file);
868 } else if (isset($_FILES[$elname])) {
869 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
871 if ($overwrite) {
872 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
873 if (!$oldfile->delete()) {
874 return false;
879 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
880 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
881 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
884 return false;
888 * Get content of uploaded file.
890 * @param string $elname name of file upload element
891 * @return string|bool false in case of failure, string if ok
893 function get_file_content($elname) {
894 global $USER;
896 if (!$this->is_submitted() or !$this->is_validated()) {
897 return false;
900 $element = $this->_form->getElement($elname);
902 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
903 $values = $this->_form->exportValues($elname);
904 if (empty($values[$elname])) {
905 return false;
907 $draftid = $values[$elname];
908 $fs = get_file_storage();
909 $context = get_context_instance(CONTEXT_USER, $USER->id);
910 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
911 return false;
913 $file = reset($files);
915 return $file->get_content();
917 } else if (isset($_FILES[$elname])) {
918 return file_get_contents($_FILES[$elname]['tmp_name']);
921 return false;
925 * Print html form.
927 function display() {
928 //finalize the form definition if not yet done
929 if (!$this->_definition_finalized) {
930 $this->_definition_finalized = true;
931 $this->definition_after_data();
933 $this->_form->display();
937 * Form definition. Abstract method - always override!
939 protected abstract function definition();
942 * Dummy stub method - override if you need to setup the form depending on current
943 * values. This method is called after definition(), data submission and set_data().
944 * All form setup that is dependent on form values should go in here.
946 function definition_after_data(){
950 * Dummy stub method - override if you needed to perform some extra validation.
951 * If there are errors return array of errors ("fieldname"=>"error message"),
952 * otherwise true if ok.
954 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
956 * @param array $data array of ("fieldname"=>value) of submitted data
957 * @param array $files array of uploaded files "element_name"=>tmp_file_path
958 * @return array of "element_name"=>"error_description" if there are errors,
959 * or an empty array if everything is OK (true allowed for backwards compatibility too).
961 function validation($data, $files) {
962 return array();
966 * Helper used by {@link repeat_elements()}.
968 * @param int $i the index of this element.
969 * @param HTML_QuickForm_element $elementclone
970 * @param array $namecloned array of names
972 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
973 $name = $elementclone->getName();
974 $namecloned[] = $name;
976 if (!empty($name)) {
977 $elementclone->setName($name."[$i]");
980 if (is_a($elementclone, 'HTML_QuickForm_header')) {
981 $value = $elementclone->_text;
982 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
984 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
985 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
987 } else {
988 $value=$elementclone->getLabel();
989 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
994 * Method to add a repeating group of elements to a form.
996 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
997 * @param int $repeats no of times to repeat elements initially
998 * @param array $options Array of options to apply to elements. Array keys are element names.
999 * This is an array of arrays. The second sets of keys are the option types for the elements :
1000 * 'default' - default value is value
1001 * 'type' - PARAM_* constant is value
1002 * 'helpbutton' - helpbutton params array is value
1003 * 'disabledif' - last three moodleform::disabledIf()
1004 * params are value as an array
1005 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1006 * @param string $addfieldsname name for button to add more fields
1007 * @param int $addfieldsno how many fields to add at a time
1008 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1009 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1010 * @return int no of repeats of element in this page
1012 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1013 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1014 if ($addstring===null){
1015 $addstring = get_string('addfields', 'form', $addfieldsno);
1016 } else {
1017 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1019 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1020 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1021 if (!empty($addfields)){
1022 $repeats += $addfieldsno;
1024 $mform =& $this->_form;
1025 $mform->registerNoSubmitButton($addfieldsname);
1026 $mform->addElement('hidden', $repeathiddenname, $repeats);
1027 $mform->setType($repeathiddenname, PARAM_INT);
1028 //value not to be overridden by submitted value
1029 $mform->setConstants(array($repeathiddenname=>$repeats));
1030 $namecloned = array();
1031 for ($i = 0; $i < $repeats; $i++) {
1032 foreach ($elementobjs as $elementobj){
1033 $elementclone = fullclone($elementobj);
1034 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1036 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1037 foreach ($elementclone->getElements() as $el) {
1038 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1040 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1043 $mform->addElement($elementclone);
1046 for ($i=0; $i<$repeats; $i++) {
1047 foreach ($options as $elementname => $elementoptions){
1048 $pos=strpos($elementname, '[');
1049 if ($pos!==FALSE){
1050 $realelementname = substr($elementname, 0, $pos)."[$i]";
1051 $realelementname .= substr($elementname, $pos);
1052 }else {
1053 $realelementname = $elementname."[$i]";
1055 foreach ($elementoptions as $option => $params){
1057 switch ($option){
1058 case 'default' :
1059 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1060 break;
1061 case 'helpbutton' :
1062 $params = array_merge(array($realelementname), $params);
1063 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1064 break;
1065 case 'disabledif' :
1066 foreach ($namecloned as $num => $name){
1067 if ($params[0] == $name){
1068 $params[0] = $params[0]."[$i]";
1069 break;
1072 $params = array_merge(array($realelementname), $params);
1073 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1074 break;
1075 case 'rule' :
1076 if (is_string($params)){
1077 $params = array(null, $params, null, 'client');
1079 $params = array_merge(array($realelementname), $params);
1080 call_user_func_array(array(&$mform, 'addRule'), $params);
1081 break;
1082 case 'type' :
1083 //Type should be set only once
1084 if (!isset($mform->_types[$elementname])) {
1085 $mform->setType($elementname, $params);
1087 break;
1092 $mform->addElement('submit', $addfieldsname, $addstring);
1094 if (!$addbuttoninside) {
1095 $mform->closeHeaderBefore($addfieldsname);
1098 return $repeats;
1102 * Adds a link/button that controls the checked state of a group of checkboxes.
1104 * @param int $groupid The id of the group of advcheckboxes this element controls
1105 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1106 * @param array $attributes associative array of HTML attributes
1107 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1109 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1110 global $CFG, $PAGE;
1112 // Name of the controller button
1113 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1114 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1115 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1117 // Set the default text if none was specified
1118 if (empty($text)) {
1119 $text = get_string('selectallornone', 'form');
1122 $mform = $this->_form;
1123 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1124 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1126 $newselectvalue = $selectvalue;
1127 if (is_null($selectvalue)) {
1128 $newselectvalue = $originalValue;
1129 } else if (!is_null($contollerbutton)) {
1130 $newselectvalue = (int) !$selectvalue;
1132 // set checkbox state depending on orignal/submitted value by controoler button
1133 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1134 foreach ($mform->_elements as $element) {
1135 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1136 $element->getAttribute('class') == $checkboxgroupclass &&
1137 !$element->isFrozen()) {
1138 $mform->setConstants(array($element->getName() => $newselectvalue));
1143 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1144 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1145 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1147 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1148 array(
1149 array('groupid' => $groupid,
1150 'checkboxclass' => $checkboxgroupclass,
1151 'checkboxcontroller' => $checkboxcontrollerparam,
1152 'controllerbutton' => $checkboxcontrollername)
1156 require_once("$CFG->libdir/form/submit.php");
1157 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1158 $mform->addElement($submitlink);
1159 $mform->registerNoSubmitButton($checkboxcontrollername);
1160 $mform->setDefault($checkboxcontrollername, $text);
1164 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1165 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1166 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1167 * get data with get_data().
1169 * @param bool $cancel whether to show cancel button, default true
1170 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1172 function add_action_buttons($cancel = true, $submitlabel=null){
1173 if (is_null($submitlabel)){
1174 $submitlabel = get_string('savechanges');
1176 $mform =& $this->_form;
1177 if ($cancel){
1178 //when two elements we need a group
1179 $buttonarray=array();
1180 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1181 $buttonarray[] = &$mform->createElement('cancel');
1182 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1183 $mform->closeHeaderBefore('buttonar');
1184 } else {
1185 //no group needed
1186 $mform->addElement('submit', 'submitbutton', $submitlabel);
1187 $mform->closeHeaderBefore('submitbutton');
1192 * Adds an initialisation call for a standard JavaScript enhancement.
1194 * This function is designed to add an initialisation call for a JavaScript
1195 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1197 * Current options:
1198 * - Selectboxes
1199 * - smartselect: Turns a nbsp indented select box into a custom drop down
1200 * control that supports multilevel and category selection.
1201 * $enhancement = 'smartselect';
1202 * $options = array('selectablecategories' => true|false)
1204 * @since Moodle 2.0
1205 * @param string|element $element form element for which Javascript needs to be initalized
1206 * @param string $enhancement which init function should be called
1207 * @param array $options options passed to javascript
1208 * @param array $strings strings for javascript
1210 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1211 global $PAGE;
1212 if (is_string($element)) {
1213 $element = $this->_form->getElement($element);
1215 if (is_object($element)) {
1216 $element->_generateId();
1217 $elementid = $element->getAttribute('id');
1218 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1219 if (is_array($strings)) {
1220 foreach ($strings as $string) {
1221 if (is_array($string)) {
1222 call_user_method_array('string_for_js', $PAGE->requires, $string);
1223 } else {
1224 $PAGE->requires->string_for_js($string, 'moodle');
1232 * Returns a JS module definition for the mforms JS
1234 * @return array
1236 public static function get_js_module() {
1237 global $CFG;
1238 return array(
1239 'name' => 'mform',
1240 'fullpath' => '/lib/form/form.js',
1241 'requires' => array('base', 'node'),
1242 'strings' => array(
1243 array('showadvanced', 'form'),
1244 array('hideadvanced', 'form')
1251 * MoodleQuickForm implementation
1253 * You never extend this class directly. The class methods of this class are available from
1254 * the private $this->_form property on moodleform and its children. You generally only
1255 * call methods on this class from within abstract methods that you override on moodleform such
1256 * as definition and definition_after_data
1258 * @package core_form
1259 * @category form
1260 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1261 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1263 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1264 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1265 var $_types = array();
1267 /** @var array dependent state for the element/'s */
1268 var $_dependencies = array();
1270 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1271 var $_noSubmitButtons=array();
1273 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1274 var $_cancelButtons=array();
1276 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1277 var $_advancedElements = array();
1279 /** @var bool Whether to display advanced elements (on page load) */
1280 var $_showAdvanced = null;
1283 * The form name is derived from the class name of the wrapper minus the trailing form
1284 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1285 * @var string
1287 var $_formName = '';
1290 * String with the html for hidden params passed in as part of a moodle_url
1291 * object for the action. Output in the form.
1292 * @var string
1294 var $_pageparams = '';
1297 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1299 * @staticvar int $formcounter counts number of forms
1300 * @param string $formName Form's name.
1301 * @param string $method Form's method defaults to 'POST'
1302 * @param string|moodle_url $action Form's action
1303 * @param string $target (optional)Form's target defaults to none
1304 * @param mixed $attributes (optional)Extra attributes for <form> tag
1306 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1307 global $CFG, $OUTPUT;
1309 static $formcounter = 1;
1311 HTML_Common::HTML_Common($attributes);
1312 $target = empty($target) ? array() : array('target' => $target);
1313 $this->_formName = $formName;
1314 if (is_a($action, 'moodle_url')){
1315 $this->_pageparams = html_writer::input_hidden_params($action);
1316 $action = $action->out_omit_querystring();
1317 } else {
1318 $this->_pageparams = '';
1320 //no 'name' atttribute for form in xhtml strict :
1321 $attributes = array('action'=>$action, 'method'=>$method,
1322 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1323 $formcounter++;
1324 $this->updateAttributes($attributes);
1326 //this is custom stuff for Moodle :
1327 $oldclass= $this->getAttribute('class');
1328 if (!empty($oldclass)){
1329 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1330 }else {
1331 $this->updateAttributes(array('class'=>'mform'));
1333 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1334 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1335 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1339 * Use this method to indicate an element in a form is an advanced field. If items in a form
1340 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1341 * form so the user can decide whether to display advanced form controls.
1343 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1345 * @param string $elementName group or element name (not the element name of something inside a group).
1346 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1348 function setAdvanced($elementName, $advanced=true){
1349 if ($advanced){
1350 $this->_advancedElements[$elementName]='';
1351 } elseif (isset($this->_advancedElements[$elementName])) {
1352 unset($this->_advancedElements[$elementName]);
1354 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1355 $this->setShowAdvanced();
1356 $this->registerNoSubmitButton('mform_showadvanced');
1358 $this->addElement('hidden', 'mform_showadvanced_last');
1359 $this->setType('mform_showadvanced_last', PARAM_INT);
1363 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1364 * display advanced elements in the form until 'Show Advanced' is pressed.
1366 * You can get the last state of the form and possibly save it for this user by using
1367 * value 'mform_showadvanced_last' in submitted data.
1369 * @param bool $showadvancedNow if true will show adavance elements.
1371 function setShowAdvanced($showadvancedNow = null){
1372 if ($showadvancedNow === null){
1373 if ($this->_showAdvanced !== null){
1374 return;
1375 } else { //if setShowAdvanced is called without any preference
1376 //make the default to not show advanced elements.
1377 $showadvancedNow = get_user_preferences(
1378 textlib::strtolower($this->_formName.'_showadvanced', 0));
1381 //value of hidden element
1382 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1383 //value of button
1384 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1385 //toggle if button pressed or else stay the same
1386 if ($hiddenLast == -1) {
1387 $next = $showadvancedNow;
1388 } elseif ($buttonPressed) { //toggle on button press
1389 $next = !$hiddenLast;
1390 } else {
1391 $next = $hiddenLast;
1393 $this->_showAdvanced = $next;
1394 if ($showadvancedNow != $next){
1395 set_user_preference($this->_formName.'_showadvanced', $next);
1397 $this->setConstants(array('mform_showadvanced_last'=>$next));
1401 * Gets show advance value, if advance elements are visible it will return true else false
1403 * @return bool
1405 function getShowAdvanced(){
1406 return $this->_showAdvanced;
1411 * Accepts a renderer
1413 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1415 function accept(&$renderer) {
1416 if (method_exists($renderer, 'setAdvancedElements')){
1417 //check for visible fieldsets where all elements are advanced
1418 //and mark these headers as advanced as well.
1419 //And mark all elements in a advanced header as advanced
1420 $stopFields = $renderer->getStopFieldSetElements();
1421 $lastHeader = null;
1422 $lastHeaderAdvanced = false;
1423 $anyAdvanced = false;
1424 foreach (array_keys($this->_elements) as $elementIndex){
1425 $element =& $this->_elements[$elementIndex];
1427 // if closing header and any contained element was advanced then mark it as advanced
1428 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1429 if ($anyAdvanced && !is_null($lastHeader)){
1430 $this->setAdvanced($lastHeader->getName());
1432 $lastHeaderAdvanced = false;
1433 unset($lastHeader);
1434 $lastHeader = null;
1435 } elseif ($lastHeaderAdvanced) {
1436 $this->setAdvanced($element->getName());
1439 if ($element->getType()=='header'){
1440 $lastHeader =& $element;
1441 $anyAdvanced = false;
1442 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1443 } elseif (isset($this->_advancedElements[$element->getName()])){
1444 $anyAdvanced = true;
1447 // the last header may not be closed yet...
1448 if ($anyAdvanced && !is_null($lastHeader)){
1449 $this->setAdvanced($lastHeader->getName());
1451 $renderer->setAdvancedElements($this->_advancedElements);
1454 parent::accept($renderer);
1458 * Adds one or more element names that indicate the end of a fieldset
1460 * @param string $elementName name of the element
1462 function closeHeaderBefore($elementName){
1463 $renderer =& $this->defaultRenderer();
1464 $renderer->addStopFieldsetElements($elementName);
1468 * Should be used for all elements of a form except for select, radio and checkboxes which
1469 * clean their own data.
1471 * @param string $elementname
1472 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1473 * {@link lib/moodlelib.php} for defined parameter types
1475 function setType($elementname, $paramtype) {
1476 $this->_types[$elementname] = $paramtype;
1480 * This can be used to set several types at once.
1482 * @param array $paramtypes types of parameters.
1483 * @see MoodleQuickForm::setType
1485 function setTypes($paramtypes) {
1486 $this->_types = $paramtypes + $this->_types;
1490 * Updates submitted values
1492 * @param array $submission submitted values
1493 * @param array $files list of files
1495 function updateSubmission($submission, $files) {
1496 $this->_flagSubmitted = false;
1498 if (empty($submission)) {
1499 $this->_submitValues = array();
1500 } else {
1501 foreach ($submission as $key=>$s) {
1502 if (array_key_exists($key, $this->_types)) {
1503 $type = $this->_types[$key];
1504 } else {
1505 $type = PARAM_RAW;
1507 if (is_array($s)) {
1508 $submission[$key] = clean_param_array($s, $type, true);
1509 } else {
1510 $submission[$key] = clean_param($s, $type);
1513 $this->_submitValues = $submission;
1514 $this->_flagSubmitted = true;
1517 if (empty($files)) {
1518 $this->_submitFiles = array();
1519 } else {
1520 $this->_submitFiles = $files;
1521 $this->_flagSubmitted = true;
1524 // need to tell all elements that they need to update their value attribute.
1525 foreach (array_keys($this->_elements) as $key) {
1526 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1531 * Returns HTML for required elements
1533 * @return string
1535 function getReqHTML(){
1536 return $this->_reqHTML;
1540 * Returns HTML for advanced elements
1542 * @return string
1544 function getAdvancedHTML(){
1545 return $this->_advancedHTML;
1549 * Initializes a default form value. Used to specify the default for a new entry where
1550 * no data is loaded in using moodleform::set_data()
1552 * note: $slashed param removed
1554 * @param string $elementName element name
1555 * @param mixed $defaultValue values for that element name
1557 function setDefault($elementName, $defaultValue){
1558 $this->setDefaults(array($elementName=>$defaultValue));
1562 * Add an array of buttons to the form
1564 * @param array $buttons An associative array representing help button to attach to
1565 * to the form. keys of array correspond to names of elements in form.
1566 * @param bool $suppresscheck if true then string check will be suppressed
1567 * @param string $function callback function to dispaly help button.
1568 * @deprecated since Moodle 2.0 use addHelpButton() call on each element manually
1569 * @todo MDL-31047 this api will be removed.
1570 * @see MoodleQuickForm::addHelpButton()
1572 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1574 debugging('function moodle_form::setHelpButtons() is deprecated');
1575 //foreach ($buttons as $elementname => $button){
1576 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1581 * Add a help button to element
1583 * @param string $elementname name of the element to add the item to
1584 * @param array $buttonargs arguments to pass to function $function
1585 * @param bool $suppresscheck whether to throw an error if the element
1586 * doesn't exist.
1587 * @param string $function - function to generate html from the arguments in $button
1588 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1589 * @todo MDL-31047 this api will be removed.
1590 * @see MoodleQuickForm::addHelpButton()
1592 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1593 global $OUTPUT;
1595 debugging('function moodle_form::setHelpButton() is deprecated');
1596 if ($function !== 'helpbutton') {
1597 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1600 $buttonargs = (array)$buttonargs;
1602 if (array_key_exists($elementname, $this->_elementIndex)) {
1603 //_elements has a numeric index, this code accesses the elements by name
1604 $element = $this->_elements[$this->_elementIndex[$elementname]];
1606 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1607 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1608 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1609 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1611 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1613 } else if (!$suppresscheck) {
1614 print_error('nonexistentformelements', 'form', '', $elementname);
1619 * Add a help button to element, only one button per element is allowed.
1621 * This is new, simplified and preferable method of setting a help icon on form elements.
1622 * It uses the new $OUTPUT->help_icon().
1624 * Typically, you will provide the same identifier and the component as you have used for the
1625 * label of the element. The string identifier with the _help suffix added is then used
1626 * as the help string.
1628 * There has to be two strings defined:
1629 * 1/ get_string($identifier, $component) - the title of the help page
1630 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1632 * @since Moodle 2.0
1633 * @param string $elementname name of the element to add the item to
1634 * @param string $identifier help string identifier without _help suffix
1635 * @param string $component component name to look the help string in
1636 * @param string $linktext optional text to display next to the icon
1637 * @param bool $suppresscheck set to true if the element may not exist
1639 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1640 global $OUTPUT;
1641 if (array_key_exists($elementname, $this->_elementIndex)) {
1642 $element = $this->_elements[$this->_elementIndex[$elementname]];
1643 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1644 } else if (!$suppresscheck) {
1645 debugging(get_string('nonexistentformelements', 'form', $elementname));
1650 * Set constant value not overridden by _POST or _GET
1651 * note: this does not work for complex names with [] :-(
1653 * @param string $elname name of element
1654 * @param mixed $value
1656 function setConstant($elname, $value) {
1657 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1658 $element =& $this->getElement($elname);
1659 $element->onQuickFormEvent('updateValue', null, $this);
1663 * export submitted values
1665 * @param string $elementList list of elements in form
1666 * @return array
1668 function exportValues($elementList = null){
1669 $unfiltered = array();
1670 if (null === $elementList) {
1671 // iterate over all elements, calling their exportValue() methods
1672 foreach (array_keys($this->_elements) as $key) {
1673 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1674 $varname = $this->_elements[$key]->_attributes['name'];
1675 $value = '';
1676 // If we have a default value then export it.
1677 if (isset($this->_defaultValues[$varname])) {
1678 $value = array($varname => $this->_defaultValues[$varname]);
1680 } else {
1681 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1684 if (is_array($value)) {
1685 // This shit throws a bogus warning in PHP 4.3.x
1686 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1689 } else {
1690 if (!is_array($elementList)) {
1691 $elementList = array_map('trim', explode(',', $elementList));
1693 foreach ($elementList as $elementName) {
1694 $value = $this->exportValue($elementName);
1695 if (@PEAR::isError($value)) {
1696 return $value;
1698 //oh, stock QuickFOrm was returning array of arrays!
1699 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1703 if (is_array($this->_constantValues)) {
1704 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1706 return $unfiltered;
1710 * Adds a validation rule for the given field
1712 * If the element is in fact a group, it will be considered as a whole.
1713 * To validate grouped elements as separated entities,
1714 * use addGroupRule instead of addRule.
1716 * @param string $element Form element name
1717 * @param string $message Message to display for invalid data
1718 * @param string $type Rule type, use getRegisteredRules() to get types
1719 * @param string $format (optional)Required for extra rule data
1720 * @param string $validation (optional)Where to perform validation: "server", "client"
1721 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1722 * @param bool $force Force the rule to be applied, even if the target form element does not exist
1724 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1726 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1727 if ($validation == 'client') {
1728 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1734 * Adds a validation rule for the given group of elements
1736 * Only groups with a name can be assigned a validation rule
1737 * Use addGroupRule when you need to validate elements inside the group.
1738 * Use addRule if you need to validate the group as a whole. In this case,
1739 * the same rule will be applied to all elements in the group.
1740 * Use addRule if you need to validate the group against a function.
1742 * @param string $group Form group name
1743 * @param array|string $arg1 Array for multiple elements or error message string for one element
1744 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1745 * @param string $format (optional)Required for extra rule data
1746 * @param int $howmany (optional)How many valid elements should be in the group
1747 * @param string $validation (optional)Where to perform validation: "server", "client"
1748 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1750 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1752 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1753 if (is_array($arg1)) {
1754 foreach ($arg1 as $rules) {
1755 foreach ($rules as $rule) {
1756 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1758 if ('client' == $validation) {
1759 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1763 } elseif (is_string($arg1)) {
1765 if ($validation == 'client') {
1766 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1772 * Returns the client side validation script
1774 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1775 * and slightly modified to run rules per-element
1776 * Needed to override this because of an error with client side validation of grouped elements.
1778 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1780 function getValidationScript()
1782 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1783 return '';
1786 include_once('HTML/QuickForm/RuleRegistry.php');
1787 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1788 $test = array();
1789 $js_escape = array(
1790 "\r" => '\r',
1791 "\n" => '\n',
1792 "\t" => '\t',
1793 "'" => "\\'",
1794 '"' => '\"',
1795 '\\' => '\\\\'
1798 foreach ($this->_rules as $elementName => $rules) {
1799 foreach ($rules as $rule) {
1800 if ('client' == $rule['validation']) {
1801 unset($element); //TODO: find out how to properly initialize it
1803 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1804 $rule['message'] = strtr($rule['message'], $js_escape);
1806 if (isset($rule['group'])) {
1807 $group =& $this->getElement($rule['group']);
1808 // No JavaScript validation for frozen elements
1809 if ($group->isFrozen()) {
1810 continue 2;
1812 $elements =& $group->getElements();
1813 foreach (array_keys($elements) as $key) {
1814 if ($elementName == $group->getElementName($key)) {
1815 $element =& $elements[$key];
1816 break;
1819 } elseif ($dependent) {
1820 $element = array();
1821 $element[] =& $this->getElement($elementName);
1822 foreach ($rule['dependent'] as $elName) {
1823 $element[] =& $this->getElement($elName);
1825 } else {
1826 $element =& $this->getElement($elementName);
1828 // No JavaScript validation for frozen elements
1829 if (is_object($element) && $element->isFrozen()) {
1830 continue 2;
1831 } elseif (is_array($element)) {
1832 foreach (array_keys($element) as $key) {
1833 if ($element[$key]->isFrozen()) {
1834 continue 3;
1838 //for editor element, [text] is appended to the name.
1839 if ($element->getType() == 'editor') {
1840 $elementName .= '[text]';
1841 //Add format to rule as moodleform check which format is supported by browser
1842 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1843 if (is_null($rule['format'])) {
1844 $rule['format'] = $element->getFormat();
1847 // Fix for bug displaying errors for elements in a group
1848 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1849 $test[$elementName][1]=$element;
1850 //end of fix
1855 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1856 // the form, and then that form field gets corrupted by the code that follows.
1857 unset($element);
1859 $js = '
1860 <script type="text/javascript">
1861 //<![CDATA[
1863 var skipClientValidation = false;
1865 function qf_errorHandler(element, _qfMsg) {
1866 div = element.parentNode;
1868 if ((div == undefined) || (element.name == undefined)) {
1869 //no checking can be done for undefined elements so let server handle it.
1870 return true;
1873 if (_qfMsg != \'\') {
1874 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1875 if (!errorSpan) {
1876 errorSpan = document.createElement("span");
1877 errorSpan.id = \'id_error_\'+element.name;
1878 errorSpan.className = "error";
1879 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1882 while (errorSpan.firstChild) {
1883 errorSpan.removeChild(errorSpan.firstChild);
1886 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1887 errorSpan.appendChild(document.createElement("br"));
1889 if (div.className.substr(div.className.length - 6, 6) != " error"
1890 && div.className != "error") {
1891 div.className += " error";
1894 return false;
1895 } else {
1896 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1897 if (errorSpan) {
1898 errorSpan.parentNode.removeChild(errorSpan);
1901 if (div.className.substr(div.className.length - 6, 6) == " error") {
1902 div.className = div.className.substr(0, div.className.length - 6);
1903 } else if (div.className == "error") {
1904 div.className = "";
1907 return true;
1910 $validateJS = '';
1911 foreach ($test as $elementName => $jsandelement) {
1912 // Fix for bug displaying errors for elements in a group
1913 //unset($element);
1914 list($jsArr,$element)=$jsandelement;
1915 //end of fix
1916 $escapedElementName = preg_replace_callback(
1917 '/[_\[\]]/',
1918 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1919 $elementName);
1920 $js .= '
1921 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1922 if (undefined == element) {
1923 //required element was not found, then let form be submitted without client side validation
1924 return true;
1926 var value = \'\';
1927 var errFlag = new Array();
1928 var _qfGroups = {};
1929 var _qfMsg = \'\';
1930 var frm = element.parentNode;
1931 if ((undefined != element.name) && (frm != undefined)) {
1932 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1933 frm = frm.parentNode;
1935 ' . join("\n", $jsArr) . '
1936 return qf_errorHandler(element, _qfMsg);
1937 } else {
1938 //element name should be defined else error msg will not be displayed.
1939 return true;
1943 $validateJS .= '
1944 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1945 if (!ret && !first_focus) {
1946 first_focus = true;
1947 frm.elements[\''.$elementName.'\'].focus();
1951 // Fix for bug displaying errors for elements in a group
1952 //unset($element);
1953 //$element =& $this->getElement($elementName);
1954 //end of fix
1955 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1956 $onBlur = $element->getAttribute('onBlur');
1957 $onChange = $element->getAttribute('onChange');
1958 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1959 'onChange' => $onChange . $valFunc));
1961 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1962 $js .= '
1963 function validate_' . $this->_formName . '(frm) {
1964 if (skipClientValidation) {
1965 return true;
1967 var ret = true;
1969 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1970 var first_focus = false;
1971 ' . $validateJS . ';
1972 return ret;
1974 //]]>
1975 </script>';
1976 return $js;
1977 } // end func getValidationScript
1980 * Sets default error message
1982 function _setDefaultRuleMessages(){
1983 foreach ($this->_rules as $field => $rulesarr){
1984 foreach ($rulesarr as $key => $rule){
1985 if ($rule['message']===null){
1986 $a=new stdClass();
1987 $a->format=$rule['format'];
1988 $str=get_string('err_'.$rule['type'], 'form', $a);
1989 if (strpos($str, '[[')!==0){
1990 $this->_rules[$field][$key]['message']=$str;
1998 * Get list of attributes which have dependencies
2000 * @return array
2002 function getLockOptionObject(){
2003 $result = array();
2004 foreach ($this->_dependencies as $dependentOn => $conditions){
2005 $result[$dependentOn] = array();
2006 foreach ($conditions as $condition=>$values) {
2007 $result[$dependentOn][$condition] = array();
2008 foreach ($values as $value=>$dependents) {
2009 $result[$dependentOn][$condition][$value] = array();
2010 $i = 0;
2011 foreach ($dependents as $dependent) {
2012 $elements = $this->_getElNamesRecursive($dependent);
2013 if (empty($elements)) {
2014 // probably element inside of some group
2015 $elements = array($dependent);
2017 foreach($elements as $element) {
2018 if ($element == $dependentOn) {
2019 continue;
2021 $result[$dependentOn][$condition][$value][] = $element;
2027 return array($this->getAttribute('id'), $result);
2031 * Get names of element or elements in a group.
2033 * @param HTML_QuickForm_group|element $element element group or element object
2034 * @return array
2036 function _getElNamesRecursive($element) {
2037 if (is_string($element)) {
2038 if (!$this->elementExists($element)) {
2039 return array();
2041 $element = $this->getElement($element);
2044 if (is_a($element, 'HTML_QuickForm_group')) {
2045 $elsInGroup = $element->getElements();
2046 $elNames = array();
2047 foreach ($elsInGroup as $elInGroup){
2048 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2049 // not sure if this would work - groups nested in groups
2050 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2051 } else {
2052 $elNames[] = $element->getElementName($elInGroup->getName());
2056 } else if (is_a($element, 'HTML_QuickForm_header')) {
2057 return array();
2059 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2060 return array();
2062 } else if (method_exists($element, 'getPrivateName') &&
2063 !($element instanceof HTML_QuickForm_advcheckbox)) {
2064 // The advcheckbox element implements a method called getPrivateName,
2065 // but in a way that is not compatible with the generic API, so we
2066 // have to explicitly exclude it.
2067 return array($element->getPrivateName());
2069 } else {
2070 $elNames = array($element->getName());
2073 return $elNames;
2077 * Adds a dependency for $elementName which will be disabled if $condition is met.
2078 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2079 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2080 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2081 * of the $dependentOn element is $condition (such as equal) to $value.
2083 * @param string $elementName the name of the element which will be disabled
2084 * @param string $dependentOn the name of the element whose state will be checked for condition
2085 * @param string $condition the condition to check
2086 * @param mixed $value used in conjunction with condition.
2088 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
2089 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2090 $this->_dependencies[$dependentOn] = array();
2092 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2093 $this->_dependencies[$dependentOn][$condition] = array();
2095 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2096 $this->_dependencies[$dependentOn][$condition][$value] = array();
2098 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2102 * Registers button as no submit button
2104 * @param string $buttonname name of the button
2106 function registerNoSubmitButton($buttonname){
2107 $this->_noSubmitButtons[]=$buttonname;
2111 * Checks if button is a no submit button, i.e it doesn't submit form
2113 * @param string $buttonname name of the button to check
2114 * @return bool
2116 function isNoSubmitButton($buttonname){
2117 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2121 * Registers a button as cancel button
2123 * @param string $addfieldsname name of the button
2125 function _registerCancelButton($addfieldsname){
2126 $this->_cancelButtons[]=$addfieldsname;
2130 * Displays elements without HTML input tags.
2131 * This method is different to freeze() in that it makes sure no hidden
2132 * elements are included in the form.
2133 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2135 * This function also removes all previously defined rules.
2137 * @param string|array $elementList array or string of element(s) to be frozen
2138 * @return object|bool if element list is not empty then return error object, else true
2140 function hardFreeze($elementList=null)
2142 if (!isset($elementList)) {
2143 $this->_freezeAll = true;
2144 $elementList = array();
2145 } else {
2146 if (!is_array($elementList)) {
2147 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2149 $elementList = array_flip($elementList);
2152 foreach (array_keys($this->_elements) as $key) {
2153 $name = $this->_elements[$key]->getName();
2154 if ($this->_freezeAll || isset($elementList[$name])) {
2155 $this->_elements[$key]->freeze();
2156 $this->_elements[$key]->setPersistantFreeze(false);
2157 unset($elementList[$name]);
2159 // remove all rules
2160 $this->_rules[$name] = array();
2161 // if field is required, remove the rule
2162 $unset = array_search($name, $this->_required);
2163 if ($unset !== false) {
2164 unset($this->_required[$unset]);
2169 if (!empty($elementList)) {
2170 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);
2172 return true;
2176 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2178 * This function also removes all previously defined rules of elements it freezes.
2180 * @throws HTML_QuickForm_Error
2181 * @param array $elementList array or string of element(s) not to be frozen
2182 * @return bool returns true
2184 function hardFreezeAllVisibleExcept($elementList)
2186 $elementList = array_flip($elementList);
2187 foreach (array_keys($this->_elements) as $key) {
2188 $name = $this->_elements[$key]->getName();
2189 $type = $this->_elements[$key]->getType();
2191 if ($type == 'hidden'){
2192 // leave hidden types as they are
2193 } elseif (!isset($elementList[$name])) {
2194 $this->_elements[$key]->freeze();
2195 $this->_elements[$key]->setPersistantFreeze(false);
2197 // remove all rules
2198 $this->_rules[$name] = array();
2199 // if field is required, remove the rule
2200 $unset = array_search($name, $this->_required);
2201 if ($unset !== false) {
2202 unset($this->_required[$unset]);
2206 return true;
2210 * Tells whether the form was already submitted
2212 * This is useful since the _submitFiles and _submitValues arrays
2213 * may be completely empty after the trackSubmit value is removed.
2215 * @return bool
2217 function isSubmitted()
2219 return parent::isSubmitted() && (!$this->isFrozen());
2224 * MoodleQuickForm renderer
2226 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2227 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2229 * Stylesheet is part of standard theme and should be automatically included.
2231 * @package core_form
2232 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2233 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2235 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2237 /** @var array Element template array */
2238 var $_elementTemplates;
2241 * Template used when opening a hidden fieldset
2242 * (i.e. a fieldset that is opened when there is no header element)
2243 * @var string
2245 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2247 /** @var string Header Template string */
2248 var $_headerTemplate =
2249 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2251 /** @var string Template used when opening a fieldset */
2252 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2254 /** @var string Template used when closing a fieldset */
2255 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2257 /** @var string Required Note template string */
2258 var $_requiredNoteTemplate =
2259 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2261 /** @var array list of elements which are marked as advance and will be grouped together */
2262 var $_advancedElements = array();
2264 /** @var int Whether to display advanced elements (on page load) 1 => show, 0 => hide */
2265 var $_showAdvanced;
2268 * Constructor
2270 function MoodleQuickForm_Renderer(){
2271 // switch next two lines for ol li containers for form items.
2272 // $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>');
2273 $this->_elementTemplates = array(
2274 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}"><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
2276 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type}"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
2278 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}&nbsp;</div></div>',
2280 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2282 'nodisplay'=>'');
2284 parent::HTML_QuickForm_Renderer_Tableless();
2288 * Set element's as adavance element
2290 * @param array $elements form elements which needs to be grouped as advance elements.
2292 function setAdvancedElements($elements){
2293 $this->_advancedElements = $elements;
2297 * What to do when starting the form
2299 * @param MoodleQuickForm $form reference of the form
2301 function startForm(&$form){
2302 global $PAGE;
2303 $this->_reqHTML = $form->getReqHTML();
2304 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2305 $this->_advancedHTML = $form->getAdvancedHTML();
2306 $this->_showAdvanced = $form->getShowAdvanced();
2307 parent::startForm($form);
2308 if ($form->isFrozen()){
2309 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2310 } else {
2311 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2312 $this->_hiddenHtml .= $form->_pageparams;
2315 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2316 'M.core_formchangechecker.init',
2317 array(array(
2318 'formid' => $form->getAttribute('id')
2321 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2325 * Create advance group of elements
2327 * @param object $group Passed by reference
2328 * @param bool $required if input is required field
2329 * @param string $error error message to display
2331 function startGroup(&$group, $required, $error){
2332 // Make sure the element has an id.
2333 $group->_generateId();
2335 if (method_exists($group, 'getElementTemplateType')){
2336 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2337 }else{
2338 $html = $this->_elementTemplates['default'];
2341 if ($this->_showAdvanced){
2342 $advclass = ' advanced';
2343 } else {
2344 $advclass = ' advanced hide';
2346 if (isset($this->_advancedElements[$group->getName()])){
2347 $html =str_replace(' {advanced}', $advclass, $html);
2348 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2349 } else {
2350 $html =str_replace(' {advanced}', '', $html);
2351 $html =str_replace('{advancedimg}', '', $html);
2353 if (method_exists($group, 'getHelpButton')){
2354 $html =str_replace('{help}', $group->getHelpButton(), $html);
2355 }else{
2356 $html =str_replace('{help}', '', $html);
2358 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2359 $html =str_replace('{name}', $group->getName(), $html);
2360 $html =str_replace('{type}', 'fgroup', $html);
2362 $this->_templates[$group->getName()]=$html;
2363 // Fix for bug in tableless quickforms that didn't allow you to stop a
2364 // fieldset before a group of elements.
2365 // if the element name indicates the end of a fieldset, close the fieldset
2366 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2367 && $this->_fieldsetsOpen > 0
2369 $this->_html .= $this->_closeFieldsetTemplate;
2370 $this->_fieldsetsOpen--;
2372 parent::startGroup($group, $required, $error);
2375 * Renders element
2377 * @param HTML_QuickForm_element $element element
2378 * @param bool $required if input is required field
2379 * @param string $error error message to display
2381 function renderElement(&$element, $required, $error){
2382 // Make sure the element has an id.
2383 $element->_generateId();
2385 //adding stuff to place holders in template
2386 //check if this is a group element first
2387 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2388 // so it gets substitutions for *each* element
2389 $html = $this->_groupElementTemplate;
2391 elseif (method_exists($element, 'getElementTemplateType')){
2392 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2393 }else{
2394 $html = $this->_elementTemplates['default'];
2396 if ($this->_showAdvanced){
2397 $advclass = ' advanced';
2398 } else {
2399 $advclass = ' advanced hide';
2401 if (isset($this->_advancedElements[$element->getName()])){
2402 $html =str_replace(' {advanced}', $advclass, $html);
2403 } else {
2404 $html =str_replace(' {advanced}', '', $html);
2406 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2407 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2408 } else {
2409 $html =str_replace('{advancedimg}', '', $html);
2411 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2412 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2413 $html =str_replace('{name}', $element->getName(), $html);
2414 if (method_exists($element, 'getHelpButton')){
2415 $html = str_replace('{help}', $element->getHelpButton(), $html);
2416 }else{
2417 $html = str_replace('{help}', '', $html);
2420 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2421 $this->_groupElementTemplate = $html;
2423 elseif (!isset($this->_templates[$element->getName()])) {
2424 $this->_templates[$element->getName()] = $html;
2427 parent::renderElement($element, $required, $error);
2431 * Called when visiting a form, after processing all form elements
2432 * Adds required note, form attributes, validation javascript and form content.
2434 * @global moodle_page $PAGE
2435 * @param moodleform $form Passed by reference
2437 function finishForm(&$form){
2438 global $PAGE;
2439 if ($form->isFrozen()){
2440 $this->_hiddenHtml = '';
2442 parent::finishForm($form);
2443 if (!$form->isFrozen()) {
2444 $args = $form->getLockOptionObject();
2445 if (count($args[1]) > 0) {
2446 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2451 * Called when visiting a header element
2453 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2454 * @global moodle_page $PAGE
2456 function renderHeader(&$header) {
2457 global $PAGE;
2459 $name = $header->getName();
2461 $id = empty($name) ? '' : ' id="' . $name . '"';
2462 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2463 if (is_null($header->_text)) {
2464 $header_html = '';
2465 } elseif (!empty($name) && isset($this->_templates[$name])) {
2466 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2467 } else {
2468 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2471 if (isset($this->_advancedElements[$name])){
2472 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2473 $elementName='mform_showadvanced';
2474 if ($this->_showAdvanced==0){
2475 $buttonlabel = get_string('showadvanced', 'form');
2476 } else {
2477 $buttonlabel = get_string('hideadvanced', 'form');
2479 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2480 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2481 $header_html = str_replace('{button}', $button, $header_html);
2482 } else {
2483 $header_html =str_replace('{advancedimg}', '', $header_html);
2484 $header_html = str_replace('{button}', '', $header_html);
2487 if ($this->_fieldsetsOpen > 0) {
2488 $this->_html .= $this->_closeFieldsetTemplate;
2489 $this->_fieldsetsOpen--;
2492 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2493 if ($this->_showAdvanced){
2494 $advclass = ' class="advanced"';
2495 } else {
2496 $advclass = ' class="advanced hide"';
2498 if (isset($this->_advancedElements[$name])){
2499 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2500 } else {
2501 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2503 $this->_html .= $openFieldsetTemplate . $header_html;
2504 $this->_fieldsetsOpen++;
2508 * Return Array of element names that indicate the end of a fieldset
2510 * @return array
2512 function getStopFieldsetElements(){
2513 return $this->_stopFieldsetElements;
2518 * Required elements validation
2520 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2522 * @package core_form
2523 * @category form
2524 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2527 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2529 * Checks if an element is not empty.
2530 * This is a server-side validation, it works for both text fields and editor fields
2532 * @param string $value Value to check
2533 * @param int|string|array $options Not used yet
2534 * @return bool true if value is not empty
2536 function validate($value, $options = null) {
2537 global $CFG;
2538 if (is_array($value) && array_key_exists('text', $value)) {
2539 $value = $value['text'];
2541 if (is_array($value)) {
2542 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2543 $value = implode('', $value);
2545 $stripvalues = array(
2546 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2547 '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
2549 if (!empty($CFG->strictformsrequired)) {
2550 $value = preg_replace($stripvalues, '', (string)$value);
2552 if ((string)$value == '') {
2553 return false;
2555 return true;
2559 * This function returns Javascript code used to build client-side validation.
2560 * It checks if an element is not empty.
2562 * @param int $format format of data which needs to be validated.
2563 * @return array
2565 function getValidationScript($format = null) {
2566 global $CFG;
2567 if (!empty($CFG->strictformsrequired)) {
2568 if (!empty($format) && $format == FORMAT_HTML) {
2569 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2570 } else {
2571 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2573 } else {
2574 return array('', "{jsVar} == ''");
2580 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2581 * @name $_HTML_QuickForm_default_renderer
2583 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2585 /** Please keep this list in alphabetical order. */
2586 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2587 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2588 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2589 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2590 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2591 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2592 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2593 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2594 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2595 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2596 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2597 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2598 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2599 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2600 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2601 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2602 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2603 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2604 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2605 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2606 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2607 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2608 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2609 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2610 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2611 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2612 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2613 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2614 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2615 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2616 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2617 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2618 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2619 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2620 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2621 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2622 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2624 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");