MDL-30506 navigation: Fixed up reference handling issue and added docs post integration
[moodle.git] / lib / formslib.php
blobac28eb8c005f180fb42971fafd57f05c6036b4d9
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('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
83 $PAGE->requires->yui_module($module, $function, $config);
84 $done = true;
88 /**
89 * Wrapper that separates quickforms syntax from moodle code
91 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
92 * use this class you should write a class definition which extends this class or a more specific
93 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
95 * You will write your own definition() method which performs the form set up.
97 * @package core_form
98 * @copyright 2006 Jamie Pratt <me@jamiep.org>
99 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
100 * @todo MDL-19380 rethink the file scanning
102 abstract class moodleform {
103 /** @var string name of the form */
104 protected $_formname; // form name
106 /** @var MoodleQuickForm quickform object definition */
107 protected $_form;
109 /** @var array globals workaround */
110 protected $_customdata;
112 /** @var object definition_after_data executed flag */
113 protected $_definition_finalized = false;
116 * The constructor function calls the abstract function definition() and it will then
117 * process and clean and attempt to validate incoming data.
119 * It will call your custom validate method to validate data and will also check any rules
120 * you have specified in definition using addRule
122 * The name of the form (id attribute of the form) is automatically generated depending on
123 * the name you gave the class extending moodleform. You should call your class something
124 * like
126 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
127 * current url. If a moodle_url object then outputs params as hidden variables.
128 * @param mixed $customdata if your form defintion method needs access to data such as $course
129 * $cm, etc. to construct the form definition then pass it in this array. You can
130 * use globals for somethings.
131 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
132 * be merged and used as incoming data to the form.
133 * @param string $target target frame for form submission. You will rarely use this. Don't use
134 * it if you don't need to as the target attribute is deprecated in xhtml strict.
135 * @param mixed $attributes you can pass a string of html attributes here or an array.
136 * @param bool $editable
138 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
139 global $CFG, $FULLME;
140 if (empty($CFG->xmlstrictheaders)) {
141 // no standard mform in moodle should allow autocomplete with the exception of user signup
142 // this is valid attribute in html5, sorry, we have to ignore validation errors in legacy xhtml 1.0
143 if (empty($attributes)) {
144 $attributes = array('autocomplete'=>'off');
145 } else if (is_array($attributes)) {
146 $attributes['autocomplete'] = 'off';
147 } else {
148 if (strpos($attributes, 'autocomplete') === false) {
149 $attributes .= ' autocomplete="off" ';
154 if (empty($action)){
155 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
156 $action = strip_querystring($FULLME);
157 if (!empty($CFG->sslproxy)) {
158 // return only https links when using SSL proxy
159 $action = preg_replace('/^http:/', 'https:', $action, 1);
161 //TODO: use following instead of FULLME - see MDL-33015
162 //$action = strip_querystring(qualified_me());
164 // Assign custom data first, so that get_form_identifier can use it.
165 $this->_customdata = $customdata;
166 $this->_formname = $this->get_form_identifier();
168 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
169 if (!$editable){
170 $this->_form->hardFreeze();
173 $this->definition();
175 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
176 $this->_form->setType('sesskey', PARAM_RAW);
177 $this->_form->setDefault('sesskey', sesskey());
178 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
179 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
180 $this->_form->setDefault('_qf__'.$this->_formname, 1);
181 $this->_form->_setDefaultRuleMessages();
183 // we have to know all input types before processing submission ;-)
184 $this->_process_submission($method);
188 * It should returns unique identifier for the form.
189 * Currently it will return class name, but in case two same forms have to be
190 * rendered on same page then override function to get unique form identifier.
191 * e.g This is used on multiple self enrollments page.
193 * @return string form identifier.
195 protected function get_form_identifier() {
196 return get_class($this);
200 * To autofocus on first form element or first element with error.
202 * @param string $name if this is set then the focus is forced to a field with this name
203 * @return string javascript to select form element with first error or
204 * first element if no errors. Use this as a parameter
205 * when calling print_header
207 function focus($name=NULL) {
208 $form =& $this->_form;
209 $elkeys = array_keys($form->_elementIndex);
210 $error = false;
211 if (isset($form->_errors) && 0 != count($form->_errors)){
212 $errorkeys = array_keys($form->_errors);
213 $elkeys = array_intersect($elkeys, $errorkeys);
214 $error = true;
217 if ($error or empty($name)) {
218 $names = array();
219 while (empty($names) and !empty($elkeys)) {
220 $el = array_shift($elkeys);
221 $names = $form->_getElNamesRecursive($el);
223 if (!empty($names)) {
224 $name = array_shift($names);
228 $focus = '';
229 if (!empty($name)) {
230 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
233 return $focus;
237 * Internal method. Alters submitted data to be suitable for quickforms processing.
238 * Must be called when the form is fully set up.
240 * @param string $method name of the method which alters submitted data
242 function _process_submission($method) {
243 $submission = array();
244 if ($method == 'post') {
245 if (!empty($_POST)) {
246 $submission = $_POST;
248 } else {
249 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
252 // following trick is needed to enable proper sesskey checks when using GET forms
253 // the _qf__.$this->_formname serves as a marker that form was actually submitted
254 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
255 if (!confirm_sesskey()) {
256 print_error('invalidsesskey');
258 $files = $_FILES;
259 } else {
260 $submission = array();
261 $files = array();
264 $this->_form->updateSubmission($submission, $files);
268 * Internal method. Validates all old-style deprecated uploaded files.
269 * The new way is to upload files via repository api.
271 * @param array $files list of files to be validated
272 * @return bool|array Success or an array of errors
274 function _validate_files(&$files) {
275 global $CFG, $COURSE;
277 $files = array();
279 if (empty($_FILES)) {
280 // we do not need to do any checks because no files were submitted
281 // note: server side rules do not work for files - use custom verification in validate() instead
282 return true;
285 $errors = array();
286 $filenames = array();
288 // now check that we really want each file
289 foreach ($_FILES as $elname=>$file) {
290 $required = $this->_form->isElementRequired($elname);
292 if ($file['error'] == 4 and $file['size'] == 0) {
293 if ($required) {
294 $errors[$elname] = get_string('required');
296 unset($_FILES[$elname]);
297 continue;
300 if (!empty($file['error'])) {
301 $errors[$elname] = file_get_upload_error($file['error']);
302 unset($_FILES[$elname]);
303 continue;
306 if (!is_uploaded_file($file['tmp_name'])) {
307 // TODO: improve error message
308 $errors[$elname] = get_string('error');
309 unset($_FILES[$elname]);
310 continue;
313 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
314 // hmm, this file was not requested
315 unset($_FILES[$elname]);
316 continue;
320 // TODO: rethink the file scanning MDL-19380
321 if ($CFG->runclamonupload) {
322 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
323 $errors[$elname] = $_FILES[$elname]['uploadlog'];
324 unset($_FILES[$elname]);
325 continue;
329 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
330 if ($filename === '') {
331 // TODO: improve error message - wrong chars
332 $errors[$elname] = get_string('error');
333 unset($_FILES[$elname]);
334 continue;
336 if (in_array($filename, $filenames)) {
337 // TODO: improve error message - duplicate name
338 $errors[$elname] = get_string('error');
339 unset($_FILES[$elname]);
340 continue;
342 $filenames[] = $filename;
343 $_FILES[$elname]['name'] = $filename;
345 $files[$elname] = $_FILES[$elname]['tmp_name'];
348 // return errors if found
349 if (count($errors) == 0){
350 return true;
352 } else {
353 $files = array();
354 return $errors;
359 * Internal method. Validates filepicker and filemanager files if they are
360 * set as required fields. Also, sets the error message if encountered one.
362 * @return bool|array with errors
364 protected function validate_draft_files() {
365 global $USER;
366 $mform =& $this->_form;
368 $errors = array();
369 //Go through all the required elements and make sure you hit filepicker or
370 //filemanager element.
371 foreach ($mform->_rules as $elementname => $rules) {
372 $elementtype = $mform->getElementType($elementname);
373 //If element is of type filepicker then do validation
374 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
375 //Check if rule defined is required rule
376 foreach ($rules as $rule) {
377 if ($rule['type'] == 'required') {
378 $draftid = (int)$mform->getSubmitValue($elementname);
379 $fs = get_file_storage();
380 $context = get_context_instance(CONTEXT_USER, $USER->id);
381 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
382 $errors[$elementname] = $rule['message'];
388 if (empty($errors)) {
389 return true;
390 } else {
391 return $errors;
396 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
397 * form definition (new entry form); this function is used to load in data where values
398 * already exist and data is being edited (edit entry form).
400 * note: $slashed param removed
402 * @param stdClass|array $default_values object or array of default values
404 function set_data($default_values) {
405 if (is_object($default_values)) {
406 $default_values = (array)$default_values;
408 $this->_form->setDefaults($default_values);
412 * Sets file upload manager
414 * @deprecated since Moodle 2.0 Please don't used this API
415 * @todo MDL-31300 this api will be removed.
416 * @see MoodleQuickForm_filepicker
417 * @see MoodleQuickForm_filemanager
418 * @param bool $um upload manager
420 function set_upload_manager($um=false) {
421 debugging('Old file uploads can not be used any more, please use new filepicker element');
425 * Check that form was submitted. Does not check validity of submitted data.
427 * @return bool true if form properly submitted
429 function is_submitted() {
430 return $this->_form->isSubmitted();
434 * Checks if button pressed is not for submitting the form
436 * @staticvar bool $nosubmit keeps track of no submit button
437 * @return bool
439 function no_submit_button_pressed(){
440 static $nosubmit = null; // one check is enough
441 if (!is_null($nosubmit)){
442 return $nosubmit;
444 $mform =& $this->_form;
445 $nosubmit = false;
446 if (!$this->is_submitted()){
447 return false;
449 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
450 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
451 $nosubmit = true;
452 break;
455 return $nosubmit;
460 * Check that form data is valid.
461 * You should almost always use this, rather than {@link validate_defined_fields}
463 * @return bool true if form data valid
465 function is_validated() {
466 //finalize the form definition before any processing
467 if (!$this->_definition_finalized) {
468 $this->_definition_finalized = true;
469 $this->definition_after_data();
472 return $this->validate_defined_fields();
476 * Validate the form.
478 * You almost always want to call {@link is_validated} instead of this
479 * because it calls {@link definition_after_data} first, before validating the form,
480 * which is what you want in 99% of cases.
482 * This is provided as a separate function for those special cases where
483 * you want the form validated before definition_after_data is called
484 * for example, to selectively add new elements depending on a no_submit_button press,
485 * but only when the form is valid when the no_submit_button is pressed,
487 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
488 * is NOT to validate the form when a no submit button has been pressed.
489 * pass true here to override this behaviour
491 * @return bool true if form data valid
493 function validate_defined_fields($validateonnosubmit=false) {
494 static $validated = null; // one validation is enough
495 $mform =& $this->_form;
496 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
497 return false;
498 } elseif ($validated === null) {
499 $internal_val = $mform->validate();
501 $files = array();
502 $file_val = $this->_validate_files($files);
503 //check draft files for validation and flag them if required files
504 //are not in draft area.
505 $draftfilevalue = $this->validate_draft_files();
507 if ($file_val !== true && $draftfilevalue !== true) {
508 $file_val = array_merge($file_val, $draftfilevalue);
509 } else if ($draftfilevalue !== true) {
510 $file_val = $draftfilevalue;
511 } //default is file_val, so no need to assign.
513 if ($file_val !== true) {
514 if (!empty($file_val)) {
515 foreach ($file_val as $element=>$msg) {
516 $mform->setElementError($element, $msg);
519 $file_val = false;
522 $data = $mform->exportValues();
523 $moodle_val = $this->validation($data, $files);
524 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
525 // non-empty array means errors
526 foreach ($moodle_val as $element=>$msg) {
527 $mform->setElementError($element, $msg);
529 $moodle_val = false;
531 } else {
532 // anything else means validation ok
533 $moodle_val = true;
536 $validated = ($internal_val and $moodle_val and $file_val);
538 return $validated;
542 * Return true if a cancel button has been pressed resulting in the form being submitted.
544 * @return bool true if a cancel button has been pressed
546 function is_cancelled(){
547 $mform =& $this->_form;
548 if ($mform->isSubmitted()){
549 foreach ($mform->_cancelButtons as $cancelbutton){
550 if (optional_param($cancelbutton, 0, PARAM_RAW)){
551 return true;
555 return false;
559 * Return submitted data if properly submitted or returns NULL if validation fails or
560 * if there is no submitted data.
562 * note: $slashed param removed
564 * @return object submitted data; NULL if not valid or not submitted or cancelled
566 function get_data() {
567 $mform =& $this->_form;
569 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
570 $data = $mform->exportValues();
571 unset($data['sesskey']); // we do not need to return sesskey
572 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
573 if (empty($data)) {
574 return NULL;
575 } else {
576 return (object)$data;
578 } else {
579 return NULL;
584 * Return submitted data without validation or NULL if there is no submitted data.
585 * note: $slashed param removed
587 * @return object submitted data; NULL if not submitted
589 function get_submitted_data() {
590 $mform =& $this->_form;
592 if ($this->is_submitted()) {
593 $data = $mform->exportValues();
594 unset($data['sesskey']); // we do not need to return sesskey
595 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
596 if (empty($data)) {
597 return NULL;
598 } else {
599 return (object)$data;
601 } else {
602 return NULL;
607 * Save verified uploaded files into directory. Upload process can be customised from definition()
609 * @deprecated since Moodle 2.0
610 * @todo MDL-31294 remove this api
611 * @see moodleform::save_stored_file()
612 * @see moodleform::save_file()
613 * @param string $destination path where file should be stored
614 * @return bool Always false
616 function save_files($destination) {
617 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
618 return false;
622 * Returns name of uploaded file.
624 * @param string $elname first element if null
625 * @return string|bool false in case of failure, string if ok
627 function get_new_filename($elname=null) {
628 global $USER;
630 if (!$this->is_submitted() or !$this->is_validated()) {
631 return false;
634 if (is_null($elname)) {
635 if (empty($_FILES)) {
636 return false;
638 reset($_FILES);
639 $elname = key($_FILES);
642 if (empty($elname)) {
643 return false;
646 $element = $this->_form->getElement($elname);
648 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
649 $values = $this->_form->exportValues($elname);
650 if (empty($values[$elname])) {
651 return false;
653 $draftid = $values[$elname];
654 $fs = get_file_storage();
655 $context = get_context_instance(CONTEXT_USER, $USER->id);
656 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
657 return false;
659 $file = reset($files);
660 return $file->get_filename();
663 if (!isset($_FILES[$elname])) {
664 return false;
667 return $_FILES[$elname]['name'];
671 * Save file to standard filesystem
673 * @param string $elname name of element
674 * @param string $pathname full path name of file
675 * @param bool $override override file if exists
676 * @return bool success
678 function save_file($elname, $pathname, $override=false) {
679 global $USER;
681 if (!$this->is_submitted() or !$this->is_validated()) {
682 return false;
684 if (file_exists($pathname)) {
685 if ($override) {
686 if (!@unlink($pathname)) {
687 return false;
689 } else {
690 return false;
694 $element = $this->_form->getElement($elname);
696 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
697 $values = $this->_form->exportValues($elname);
698 if (empty($values[$elname])) {
699 return false;
701 $draftid = $values[$elname];
702 $fs = get_file_storage();
703 $context = get_context_instance(CONTEXT_USER, $USER->id);
704 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
705 return false;
707 $file = reset($files);
709 return $file->copy_content_to($pathname);
711 } else if (isset($_FILES[$elname])) {
712 return copy($_FILES[$elname]['tmp_name'], $pathname);
715 return false;
719 * Returns a temporary file, do not forget to delete after not needed any more.
721 * @param string $elname name of the elmenet
722 * @return string|bool either string or false
724 function save_temp_file($elname) {
725 if (!$this->get_new_filename($elname)) {
726 return false;
728 if (!$dir = make_temp_directory('forms')) {
729 return false;
731 if (!$tempfile = tempnam($dir, 'tempup_')) {
732 return false;
734 if (!$this->save_file($elname, $tempfile, true)) {
735 // something went wrong
736 @unlink($tempfile);
737 return false;
740 return $tempfile;
744 * Get draft files of a form element
745 * This is a protected method which will be used only inside moodleforms
747 * @param string $elname name of element
748 * @return array|bool|null
750 protected function get_draft_files($elname) {
751 global $USER;
753 if (!$this->is_submitted()) {
754 return false;
757 $element = $this->_form->getElement($elname);
759 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
760 $values = $this->_form->exportValues($elname);
761 if (empty($values[$elname])) {
762 return false;
764 $draftid = $values[$elname];
765 $fs = get_file_storage();
766 $context = get_context_instance(CONTEXT_USER, $USER->id);
767 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
768 return null;
770 return $files;
772 return null;
776 * Save file to local filesystem pool
778 * @param string $elname name of element
779 * @param int $newcontextid id of context
780 * @param string $newcomponent name of the component
781 * @param string $newfilearea name of file area
782 * @param int $newitemid item id
783 * @param string $newfilepath path of file where it get stored
784 * @param string $newfilename use specified filename, if not specified name of uploaded file used
785 * @param bool $overwrite overwrite file if exists
786 * @param int $newuserid new userid if required
787 * @return mixed stored_file object or false if error; may throw exception if duplicate found
789 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
790 $newfilename=null, $overwrite=false, $newuserid=null) {
791 global $USER;
793 if (!$this->is_submitted() or !$this->is_validated()) {
794 return false;
797 if (empty($newuserid)) {
798 $newuserid = $USER->id;
801 $element = $this->_form->getElement($elname);
802 $fs = get_file_storage();
804 if ($element instanceof MoodleQuickForm_filepicker) {
805 $values = $this->_form->exportValues($elname);
806 if (empty($values[$elname])) {
807 return false;
809 $draftid = $values[$elname];
810 $context = get_context_instance(CONTEXT_USER, $USER->id);
811 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
812 return false;
814 $file = reset($files);
815 if (is_null($newfilename)) {
816 $newfilename = $file->get_filename();
819 if ($overwrite) {
820 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
821 if (!$oldfile->delete()) {
822 return false;
827 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
828 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
829 return $fs->create_file_from_storedfile($file_record, $file);
831 } else if (isset($_FILES[$elname])) {
832 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
834 if ($overwrite) {
835 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
836 if (!$oldfile->delete()) {
837 return false;
842 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
843 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
844 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
847 return false;
851 * Get content of uploaded file.
853 * @param string $elname name of file upload element
854 * @return string|bool false in case of failure, string if ok
856 function get_file_content($elname) {
857 global $USER;
859 if (!$this->is_submitted() or !$this->is_validated()) {
860 return false;
863 $element = $this->_form->getElement($elname);
865 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
866 $values = $this->_form->exportValues($elname);
867 if (empty($values[$elname])) {
868 return false;
870 $draftid = $values[$elname];
871 $fs = get_file_storage();
872 $context = get_context_instance(CONTEXT_USER, $USER->id);
873 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
874 return false;
876 $file = reset($files);
878 return $file->get_content();
880 } else if (isset($_FILES[$elname])) {
881 return file_get_contents($_FILES[$elname]['tmp_name']);
884 return false;
888 * Print html form.
890 function display() {
891 //finalize the form definition if not yet done
892 if (!$this->_definition_finalized) {
893 $this->_definition_finalized = true;
894 $this->definition_after_data();
896 $this->_form->display();
900 * Form definition. Abstract method - always override!
902 protected abstract function definition();
905 * Dummy stub method - override if you need to setup the form depending on current
906 * values. This method is called after definition(), data submission and set_data().
907 * All form setup that is dependent on form values should go in here.
909 function definition_after_data(){
913 * Dummy stub method - override if you needed to perform some extra validation.
914 * If there are errors return array of errors ("fieldname"=>"error message"),
915 * otherwise true if ok.
917 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
919 * @param array $data array of ("fieldname"=>value) of submitted data
920 * @param array $files array of uploaded files "element_name"=>tmp_file_path
921 * @return array of "element_name"=>"error_description" if there are errors,
922 * or an empty array if everything is OK (true allowed for backwards compatibility too).
924 function validation($data, $files) {
925 return array();
929 * Helper used by {@link repeat_elements()}.
931 * @param int $i the index of this element.
932 * @param HTML_QuickForm_element $elementclone
933 * @param array $namecloned array of names
935 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
936 $name = $elementclone->getName();
937 $namecloned[] = $name;
939 if (!empty($name)) {
940 $elementclone->setName($name."[$i]");
943 if (is_a($elementclone, 'HTML_QuickForm_header')) {
944 $value = $elementclone->_text;
945 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
947 } else {
948 $value=$elementclone->getLabel();
949 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
954 * Method to add a repeating group of elements to a form.
956 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
957 * @param int $repeats no of times to repeat elements initially
958 * @param array $options Array of options to apply to elements. Array keys are element names.
959 * This is an array of arrays. The second sets of keys are the option types for the elements :
960 * 'default' - default value is value
961 * 'type' - PARAM_* constant is value
962 * 'helpbutton' - helpbutton params array is value
963 * 'disabledif' - last three moodleform::disabledIf()
964 * params are value as an array
965 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
966 * @param string $addfieldsname name for button to add more fields
967 * @param int $addfieldsno how many fields to add at a time
968 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
969 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
970 * @return int no of repeats of element in this page
972 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
973 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
974 if ($addstring===null){
975 $addstring = get_string('addfields', 'form', $addfieldsno);
976 } else {
977 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
979 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
980 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
981 if (!empty($addfields)){
982 $repeats += $addfieldsno;
984 $mform =& $this->_form;
985 $mform->registerNoSubmitButton($addfieldsname);
986 $mform->addElement('hidden', $repeathiddenname, $repeats);
987 $mform->setType($repeathiddenname, PARAM_INT);
988 //value not to be overridden by submitted value
989 $mform->setConstants(array($repeathiddenname=>$repeats));
990 $namecloned = array();
991 for ($i = 0; $i < $repeats; $i++) {
992 foreach ($elementobjs as $elementobj){
993 $elementclone = fullclone($elementobj);
994 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
996 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
997 foreach ($elementclone->getElements() as $el) {
998 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1000 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1003 $mform->addElement($elementclone);
1006 for ($i=0; $i<$repeats; $i++) {
1007 foreach ($options as $elementname => $elementoptions){
1008 $pos=strpos($elementname, '[');
1009 if ($pos!==FALSE){
1010 $realelementname = substr($elementname, 0, $pos)."[$i]";
1011 $realelementname .= substr($elementname, $pos);
1012 }else {
1013 $realelementname = $elementname."[$i]";
1015 foreach ($elementoptions as $option => $params){
1017 switch ($option){
1018 case 'default' :
1019 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1020 break;
1021 case 'helpbutton' :
1022 $params = array_merge(array($realelementname), $params);
1023 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1024 break;
1025 case 'disabledif' :
1026 foreach ($namecloned as $num => $name){
1027 if ($params[0] == $name){
1028 $params[0] = $params[0]."[$i]";
1029 break;
1032 $params = array_merge(array($realelementname), $params);
1033 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1034 break;
1035 case 'rule' :
1036 if (is_string($params)){
1037 $params = array(null, $params, null, 'client');
1039 $params = array_merge(array($realelementname), $params);
1040 call_user_func_array(array(&$mform, 'addRule'), $params);
1041 break;
1042 case 'type' :
1043 //Type should be set only once
1044 if (!isset($mform->_types[$elementname])) {
1045 $mform->setType($elementname, $params);
1047 break;
1052 $mform->addElement('submit', $addfieldsname, $addstring);
1054 if (!$addbuttoninside) {
1055 $mform->closeHeaderBefore($addfieldsname);
1058 return $repeats;
1062 * Adds a link/button that controls the checked state of a group of checkboxes.
1064 * @param int $groupid The id of the group of advcheckboxes this element controls
1065 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1066 * @param array $attributes associative array of HTML attributes
1067 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1069 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1070 global $CFG, $PAGE;
1072 // Name of the controller button
1073 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1074 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1075 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1077 // Set the default text if none was specified
1078 if (empty($text)) {
1079 $text = get_string('selectallornone', 'form');
1082 $mform = $this->_form;
1083 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1084 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1086 $newselectvalue = $selectvalue;
1087 if (is_null($selectvalue)) {
1088 $newselectvalue = $originalValue;
1089 } else if (!is_null($contollerbutton)) {
1090 $newselectvalue = (int) !$selectvalue;
1092 // set checkbox state depending on orignal/submitted value by controoler button
1093 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1094 foreach ($mform->_elements as $element) {
1095 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1096 $element->getAttribute('class') == $checkboxgroupclass &&
1097 !$element->isFrozen()) {
1098 $mform->setConstants(array($element->getName() => $newselectvalue));
1103 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1104 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1105 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1107 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1108 array(
1109 array('groupid' => $groupid,
1110 'checkboxclass' => $checkboxgroupclass,
1111 'checkboxcontroller' => $checkboxcontrollerparam,
1112 'controllerbutton' => $checkboxcontrollername)
1116 require_once("$CFG->libdir/form/submit.php");
1117 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1118 $mform->addElement($submitlink);
1119 $mform->registerNoSubmitButton($checkboxcontrollername);
1120 $mform->setDefault($checkboxcontrollername, $text);
1124 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1125 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1126 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1127 * get data with get_data().
1129 * @param bool $cancel whether to show cancel button, default true
1130 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1132 function add_action_buttons($cancel = true, $submitlabel=null){
1133 if (is_null($submitlabel)){
1134 $submitlabel = get_string('savechanges');
1136 $mform =& $this->_form;
1137 if ($cancel){
1138 //when two elements we need a group
1139 $buttonarray=array();
1140 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1141 $buttonarray[] = &$mform->createElement('cancel');
1142 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1143 $mform->closeHeaderBefore('buttonar');
1144 } else {
1145 //no group needed
1146 $mform->addElement('submit', 'submitbutton', $submitlabel);
1147 $mform->closeHeaderBefore('submitbutton');
1152 * Adds an initialisation call for a standard JavaScript enhancement.
1154 * This function is designed to add an initialisation call for a JavaScript
1155 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1157 * Current options:
1158 * - Selectboxes
1159 * - smartselect: Turns a nbsp indented select box into a custom drop down
1160 * control that supports multilevel and category selection.
1161 * $enhancement = 'smartselect';
1162 * $options = array('selectablecategories' => true|false)
1164 * @since Moodle 2.0
1165 * @param string|element $element form element for which Javascript needs to be initalized
1166 * @param string $enhancement which init function should be called
1167 * @param array $options options passed to javascript
1168 * @param array $strings strings for javascript
1170 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1171 global $PAGE;
1172 if (is_string($element)) {
1173 $element = $this->_form->getElement($element);
1175 if (is_object($element)) {
1176 $element->_generateId();
1177 $elementid = $element->getAttribute('id');
1178 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1179 if (is_array($strings)) {
1180 foreach ($strings as $string) {
1181 if (is_array($string)) {
1182 call_user_method_array('string_for_js', $PAGE->requires, $string);
1183 } else {
1184 $PAGE->requires->string_for_js($string, 'moodle');
1192 * Returns a JS module definition for the mforms JS
1194 * @return array
1196 public static function get_js_module() {
1197 global $CFG;
1198 return array(
1199 'name' => 'mform',
1200 'fullpath' => '/lib/form/form.js',
1201 'requires' => array('base', 'node'),
1202 'strings' => array(
1203 array('showadvanced', 'form'),
1204 array('hideadvanced', 'form')
1211 * MoodleQuickForm implementation
1213 * You never extend this class directly. The class methods of this class are available from
1214 * the private $this->_form property on moodleform and its children. You generally only
1215 * call methods on this class from within abstract methods that you override on moodleform such
1216 * as definition and definition_after_data
1218 * @package core_form
1219 * @category form
1220 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1221 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1223 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1224 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1225 var $_types = array();
1227 /** @var array dependent state for the element/'s */
1228 var $_dependencies = array();
1230 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1231 var $_noSubmitButtons=array();
1233 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1234 var $_cancelButtons=array();
1236 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1237 var $_advancedElements = array();
1239 /** @var bool Whether to display advanced elements (on page load) */
1240 var $_showAdvanced = null;
1243 * The form name is derived from the class name of the wrapper minus the trailing form
1244 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1245 * @var string
1247 var $_formName = '';
1250 * String with the html for hidden params passed in as part of a moodle_url
1251 * object for the action. Output in the form.
1252 * @var string
1254 var $_pageparams = '';
1257 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1259 * @staticvar int $formcounter counts number of forms
1260 * @param string $formName Form's name.
1261 * @param string $method Form's method defaults to 'POST'
1262 * @param string|moodle_url $action Form's action
1263 * @param string $target (optional)Form's target defaults to none
1264 * @param mixed $attributes (optional)Extra attributes for <form> tag
1266 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1267 global $CFG, $OUTPUT;
1269 static $formcounter = 1;
1271 HTML_Common::HTML_Common($attributes);
1272 $target = empty($target) ? array() : array('target' => $target);
1273 $this->_formName = $formName;
1274 if (is_a($action, 'moodle_url')){
1275 $this->_pageparams = html_writer::input_hidden_params($action);
1276 $action = $action->out_omit_querystring();
1277 } else {
1278 $this->_pageparams = '';
1280 //no 'name' atttribute for form in xhtml strict :
1281 $attributes = array('action'=>$action, 'method'=>$method,
1282 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1283 $formcounter++;
1284 $this->updateAttributes($attributes);
1286 //this is custom stuff for Moodle :
1287 $oldclass= $this->getAttribute('class');
1288 if (!empty($oldclass)){
1289 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1290 }else {
1291 $this->updateAttributes(array('class'=>'mform'));
1293 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1294 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1295 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1299 * Use this method to indicate an element in a form is an advanced field. If items in a form
1300 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1301 * form so the user can decide whether to display advanced form controls.
1303 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1305 * @param string $elementName group or element name (not the element name of something inside a group).
1306 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1308 function setAdvanced($elementName, $advanced=true){
1309 if ($advanced){
1310 $this->_advancedElements[$elementName]='';
1311 } elseif (isset($this->_advancedElements[$elementName])) {
1312 unset($this->_advancedElements[$elementName]);
1314 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1315 $this->setShowAdvanced();
1316 $this->registerNoSubmitButton('mform_showadvanced');
1318 $this->addElement('hidden', 'mform_showadvanced_last');
1319 $this->setType('mform_showadvanced_last', PARAM_INT);
1323 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1324 * display advanced elements in the form until 'Show Advanced' is pressed.
1326 * You can get the last state of the form and possibly save it for this user by using
1327 * value 'mform_showadvanced_last' in submitted data.
1329 * @param bool $showadvancedNow if true will show adavance elements.
1331 function setShowAdvanced($showadvancedNow = null){
1332 if ($showadvancedNow === null){
1333 if ($this->_showAdvanced !== null){
1334 return;
1335 } else { //if setShowAdvanced is called without any preference
1336 //make the default to not show advanced elements.
1337 $showadvancedNow = get_user_preferences(
1338 textlib::strtolower($this->_formName.'_showadvanced', 0));
1341 //value of hidden element
1342 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1343 //value of button
1344 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1345 //toggle if button pressed or else stay the same
1346 if ($hiddenLast == -1) {
1347 $next = $showadvancedNow;
1348 } elseif ($buttonPressed) { //toggle on button press
1349 $next = !$hiddenLast;
1350 } else {
1351 $next = $hiddenLast;
1353 $this->_showAdvanced = $next;
1354 if ($showadvancedNow != $next){
1355 set_user_preference($this->_formName.'_showadvanced', $next);
1357 $this->setConstants(array('mform_showadvanced_last'=>$next));
1361 * Gets show advance value, if advance elements are visible it will return true else false
1363 * @return bool
1365 function getShowAdvanced(){
1366 return $this->_showAdvanced;
1371 * Accepts a renderer
1373 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1375 function accept(&$renderer) {
1376 if (method_exists($renderer, 'setAdvancedElements')){
1377 //check for visible fieldsets where all elements are advanced
1378 //and mark these headers as advanced as well.
1379 //And mark all elements in a advanced header as advanced
1380 $stopFields = $renderer->getStopFieldSetElements();
1381 $lastHeader = null;
1382 $lastHeaderAdvanced = false;
1383 $anyAdvanced = false;
1384 foreach (array_keys($this->_elements) as $elementIndex){
1385 $element =& $this->_elements[$elementIndex];
1387 // if closing header and any contained element was advanced then mark it as advanced
1388 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1389 if ($anyAdvanced && !is_null($lastHeader)){
1390 $this->setAdvanced($lastHeader->getName());
1392 $lastHeaderAdvanced = false;
1393 unset($lastHeader);
1394 $lastHeader = null;
1395 } elseif ($lastHeaderAdvanced) {
1396 $this->setAdvanced($element->getName());
1399 if ($element->getType()=='header'){
1400 $lastHeader =& $element;
1401 $anyAdvanced = false;
1402 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1403 } elseif (isset($this->_advancedElements[$element->getName()])){
1404 $anyAdvanced = true;
1407 // the last header may not be closed yet...
1408 if ($anyAdvanced && !is_null($lastHeader)){
1409 $this->setAdvanced($lastHeader->getName());
1411 $renderer->setAdvancedElements($this->_advancedElements);
1414 parent::accept($renderer);
1418 * Adds one or more element names that indicate the end of a fieldset
1420 * @param string $elementName name of the element
1422 function closeHeaderBefore($elementName){
1423 $renderer =& $this->defaultRenderer();
1424 $renderer->addStopFieldsetElements($elementName);
1428 * Should be used for all elements of a form except for select, radio and checkboxes which
1429 * clean their own data.
1431 * @param string $elementname
1432 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1433 * {@link lib/moodlelib.php} for defined parameter types
1435 function setType($elementname, $paramtype) {
1436 $this->_types[$elementname] = $paramtype;
1440 * This can be used to set several types at once.
1442 * @param array $paramtypes types of parameters.
1443 * @see MoodleQuickForm::setType
1445 function setTypes($paramtypes) {
1446 $this->_types = $paramtypes + $this->_types;
1450 * Updates submitted values
1452 * @param array $submission submitted values
1453 * @param array $files list of files
1455 function updateSubmission($submission, $files) {
1456 $this->_flagSubmitted = false;
1458 if (empty($submission)) {
1459 $this->_submitValues = array();
1460 } else {
1461 foreach ($submission as $key=>$s) {
1462 if (array_key_exists($key, $this->_types)) {
1463 $type = $this->_types[$key];
1464 } else {
1465 $type = PARAM_RAW;
1467 if (is_array($s)) {
1468 $submission[$key] = clean_param_array($s, $type, true);
1469 } else {
1470 $submission[$key] = clean_param($s, $type);
1473 $this->_submitValues = $submission;
1474 $this->_flagSubmitted = true;
1477 if (empty($files)) {
1478 $this->_submitFiles = array();
1479 } else {
1480 $this->_submitFiles = $files;
1481 $this->_flagSubmitted = true;
1484 // need to tell all elements that they need to update their value attribute.
1485 foreach (array_keys($this->_elements) as $key) {
1486 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1491 * Returns HTML for required elements
1493 * @return string
1495 function getReqHTML(){
1496 return $this->_reqHTML;
1500 * Returns HTML for advanced elements
1502 * @return string
1504 function getAdvancedHTML(){
1505 return $this->_advancedHTML;
1509 * Initializes a default form value. Used to specify the default for a new entry where
1510 * no data is loaded in using moodleform::set_data()
1512 * note: $slashed param removed
1514 * @param string $elementName element name
1515 * @param mixed $defaultValue values for that element name
1517 function setDefault($elementName, $defaultValue){
1518 $this->setDefaults(array($elementName=>$defaultValue));
1522 * Add an array of buttons to the form
1524 * @param array $buttons An associative array representing help button to attach to
1525 * to the form. keys of array correspond to names of elements in form.
1526 * @param bool $suppresscheck if true then string check will be suppressed
1527 * @param string $function callback function to dispaly help button.
1528 * @deprecated since Moodle 2.0 use addHelpButton() call on each element manually
1529 * @todo MDL-31047 this api will be removed.
1530 * @see MoodleQuickForm::addHelpButton()
1532 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1534 debugging('function moodle_form::setHelpButtons() is deprecated');
1535 //foreach ($buttons as $elementname => $button){
1536 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1541 * Add a help button to element
1543 * @param string $elementname name of the element to add the item to
1544 * @param array $buttonargs arguments to pass to function $function
1545 * @param bool $suppresscheck whether to throw an error if the element
1546 * doesn't exist.
1547 * @param string $function - function to generate html from the arguments in $button
1548 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1549 * @todo MDL-31047 this api will be removed.
1550 * @see MoodleQuickForm::addHelpButton()
1552 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1553 global $OUTPUT;
1555 debugging('function moodle_form::setHelpButton() is deprecated');
1556 if ($function !== 'helpbutton') {
1557 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1560 $buttonargs = (array)$buttonargs;
1562 if (array_key_exists($elementname, $this->_elementIndex)) {
1563 //_elements has a numeric index, this code accesses the elements by name
1564 $element = $this->_elements[$this->_elementIndex[$elementname]];
1566 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1567 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1568 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1569 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1571 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1573 } else if (!$suppresscheck) {
1574 print_error('nonexistentformelements', 'form', '', $elementname);
1579 * Add a help button to element, only one button per element is allowed.
1581 * This is new, simplified and preferable method of setting a help icon on form elements.
1582 * It uses the new $OUTPUT->help_icon().
1584 * Typically, you will provide the same identifier and the component as you have used for the
1585 * label of the element. The string identifier with the _help suffix added is then used
1586 * as the help string.
1588 * There has to be two strings defined:
1589 * 1/ get_string($identifier, $component) - the title of the help page
1590 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1592 * @since Moodle 2.0
1593 * @param string $elementname name of the element to add the item to
1594 * @param string $identifier help string identifier without _help suffix
1595 * @param string $component component name to look the help string in
1596 * @param string $linktext optional text to display next to the icon
1597 * @param bool $suppresscheck set to true if the element may not exist
1599 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1600 global $OUTPUT;
1601 if (array_key_exists($elementname, $this->_elementIndex)) {
1602 $element = $this->_elements[$this->_elementIndex[$elementname]];
1603 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1604 } else if (!$suppresscheck) {
1605 debugging(get_string('nonexistentformelements', 'form', $elementname));
1610 * Set constant value not overridden by _POST or _GET
1611 * note: this does not work for complex names with [] :-(
1613 * @param string $elname name of element
1614 * @param mixed $value
1616 function setConstant($elname, $value) {
1617 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1618 $element =& $this->getElement($elname);
1619 $element->onQuickFormEvent('updateValue', null, $this);
1623 * export submitted values
1625 * @param string $elementList list of elements in form
1626 * @return array
1628 function exportValues($elementList = null){
1629 $unfiltered = array();
1630 if (null === $elementList) {
1631 // iterate over all elements, calling their exportValue() methods
1632 $emptyarray = array();
1633 foreach (array_keys($this->_elements) as $key) {
1634 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1635 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1636 } else {
1637 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1640 if (is_array($value)) {
1641 // This shit throws a bogus warning in PHP 4.3.x
1642 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1645 } else {
1646 if (!is_array($elementList)) {
1647 $elementList = array_map('trim', explode(',', $elementList));
1649 foreach ($elementList as $elementName) {
1650 $value = $this->exportValue($elementName);
1651 if (@PEAR::isError($value)) {
1652 return $value;
1654 //oh, stock QuickFOrm was returning array of arrays!
1655 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1659 if (is_array($this->_constantValues)) {
1660 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1663 return $unfiltered;
1667 * Adds a validation rule for the given field
1669 * If the element is in fact a group, it will be considered as a whole.
1670 * To validate grouped elements as separated entities,
1671 * use addGroupRule instead of addRule.
1673 * @param string $element Form element name
1674 * @param string $message Message to display for invalid data
1675 * @param string $type Rule type, use getRegisteredRules() to get types
1676 * @param string $format (optional)Required for extra rule data
1677 * @param string $validation (optional)Where to perform validation: "server", "client"
1678 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1679 * @param bool $force Force the rule to be applied, even if the target form element does not exist
1681 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1683 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1684 if ($validation == 'client') {
1685 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1691 * Adds a validation rule for the given group of elements
1693 * Only groups with a name can be assigned a validation rule
1694 * Use addGroupRule when you need to validate elements inside the group.
1695 * Use addRule if you need to validate the group as a whole. In this case,
1696 * the same rule will be applied to all elements in the group.
1697 * Use addRule if you need to validate the group against a function.
1699 * @param string $group Form group name
1700 * @param array|string $arg1 Array for multiple elements or error message string for one element
1701 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1702 * @param string $format (optional)Required for extra rule data
1703 * @param int $howmany (optional)How many valid elements should be in the group
1704 * @param string $validation (optional)Where to perform validation: "server", "client"
1705 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1707 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1709 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1710 if (is_array($arg1)) {
1711 foreach ($arg1 as $rules) {
1712 foreach ($rules as $rule) {
1713 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1715 if ('client' == $validation) {
1716 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1720 } elseif (is_string($arg1)) {
1722 if ($validation == 'client') {
1723 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1729 * Returns the client side validation script
1731 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1732 * and slightly modified to run rules per-element
1733 * Needed to override this because of an error with client side validation of grouped elements.
1735 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1737 function getValidationScript()
1739 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1740 return '';
1743 include_once('HTML/QuickForm/RuleRegistry.php');
1744 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1745 $test = array();
1746 $js_escape = array(
1747 "\r" => '\r',
1748 "\n" => '\n',
1749 "\t" => '\t',
1750 "'" => "\\'",
1751 '"' => '\"',
1752 '\\' => '\\\\'
1755 foreach ($this->_rules as $elementName => $rules) {
1756 foreach ($rules as $rule) {
1757 if ('client' == $rule['validation']) {
1758 unset($element); //TODO: find out how to properly initialize it
1760 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1761 $rule['message'] = strtr($rule['message'], $js_escape);
1763 if (isset($rule['group'])) {
1764 $group =& $this->getElement($rule['group']);
1765 // No JavaScript validation for frozen elements
1766 if ($group->isFrozen()) {
1767 continue 2;
1769 $elements =& $group->getElements();
1770 foreach (array_keys($elements) as $key) {
1771 if ($elementName == $group->getElementName($key)) {
1772 $element =& $elements[$key];
1773 break;
1776 } elseif ($dependent) {
1777 $element = array();
1778 $element[] =& $this->getElement($elementName);
1779 foreach ($rule['dependent'] as $elName) {
1780 $element[] =& $this->getElement($elName);
1782 } else {
1783 $element =& $this->getElement($elementName);
1785 // No JavaScript validation for frozen elements
1786 if (is_object($element) && $element->isFrozen()) {
1787 continue 2;
1788 } elseif (is_array($element)) {
1789 foreach (array_keys($element) as $key) {
1790 if ($element[$key]->isFrozen()) {
1791 continue 3;
1795 //for editor element, [text] is appended to the name.
1796 if ($element->getType() == 'editor') {
1797 $elementName .= '[text]';
1798 //Add format to rule as moodleform check which format is supported by browser
1799 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1800 if (is_null($rule['format'])) {
1801 $rule['format'] = $element->getFormat();
1804 // Fix for bug displaying errors for elements in a group
1805 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1806 $test[$elementName][1]=$element;
1807 //end of fix
1812 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1813 // the form, and then that form field gets corrupted by the code that follows.
1814 unset($element);
1816 $js = '
1817 <script type="text/javascript">
1818 //<![CDATA[
1820 var skipClientValidation = false;
1822 function qf_errorHandler(element, _qfMsg) {
1823 div = element.parentNode;
1825 if ((div == undefined) || (element.name == undefined)) {
1826 //no checking can be done for undefined elements so let server handle it.
1827 return true;
1830 if (_qfMsg != \'\') {
1831 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1832 if (!errorSpan) {
1833 errorSpan = document.createElement("span");
1834 errorSpan.id = \'id_error_\'+element.name;
1835 errorSpan.className = "error";
1836 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1839 while (errorSpan.firstChild) {
1840 errorSpan.removeChild(errorSpan.firstChild);
1843 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1844 errorSpan.appendChild(document.createElement("br"));
1846 if (div.className.substr(div.className.length - 6, 6) != " error"
1847 && div.className != "error") {
1848 div.className += " error";
1851 return false;
1852 } else {
1853 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1854 if (errorSpan) {
1855 errorSpan.parentNode.removeChild(errorSpan);
1858 if (div.className.substr(div.className.length - 6, 6) == " error") {
1859 div.className = div.className.substr(0, div.className.length - 6);
1860 } else if (div.className == "error") {
1861 div.className = "";
1864 return true;
1867 $validateJS = '';
1868 foreach ($test as $elementName => $jsandelement) {
1869 // Fix for bug displaying errors for elements in a group
1870 //unset($element);
1871 list($jsArr,$element)=$jsandelement;
1872 //end of fix
1873 $escapedElementName = preg_replace_callback(
1874 '/[_\[\]]/',
1875 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1876 $elementName);
1877 $js .= '
1878 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1879 if (undefined == element) {
1880 //required element was not found, then let form be submitted without client side validation
1881 return true;
1883 var value = \'\';
1884 var errFlag = new Array();
1885 var _qfGroups = {};
1886 var _qfMsg = \'\';
1887 var frm = element.parentNode;
1888 if ((undefined != element.name) && (frm != undefined)) {
1889 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1890 frm = frm.parentNode;
1892 ' . join("\n", $jsArr) . '
1893 return qf_errorHandler(element, _qfMsg);
1894 } else {
1895 //element name should be defined else error msg will not be displayed.
1896 return true;
1900 $validateJS .= '
1901 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1902 if (!ret && !first_focus) {
1903 first_focus = true;
1904 frm.elements[\''.$elementName.'\'].focus();
1908 // Fix for bug displaying errors for elements in a group
1909 //unset($element);
1910 //$element =& $this->getElement($elementName);
1911 //end of fix
1912 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1913 $onBlur = $element->getAttribute('onBlur');
1914 $onChange = $element->getAttribute('onChange');
1915 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1916 'onChange' => $onChange . $valFunc));
1918 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1919 $js .= '
1920 function validate_' . $this->_formName . '(frm) {
1921 if (skipClientValidation) {
1922 return true;
1924 var ret = true;
1926 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1927 var first_focus = false;
1928 ' . $validateJS . ';
1929 return ret;
1931 //]]>
1932 </script>';
1933 return $js;
1934 } // end func getValidationScript
1937 * Sets default error message
1939 function _setDefaultRuleMessages(){
1940 foreach ($this->_rules as $field => $rulesarr){
1941 foreach ($rulesarr as $key => $rule){
1942 if ($rule['message']===null){
1943 $a=new stdClass();
1944 $a->format=$rule['format'];
1945 $str=get_string('err_'.$rule['type'], 'form', $a);
1946 if (strpos($str, '[[')!==0){
1947 $this->_rules[$field][$key]['message']=$str;
1955 * Get list of attributes which have dependencies
1957 * @return array
1959 function getLockOptionObject(){
1960 $result = array();
1961 foreach ($this->_dependencies as $dependentOn => $conditions){
1962 $result[$dependentOn] = array();
1963 foreach ($conditions as $condition=>$values) {
1964 $result[$dependentOn][$condition] = array();
1965 foreach ($values as $value=>$dependents) {
1966 $result[$dependentOn][$condition][$value] = array();
1967 $i = 0;
1968 foreach ($dependents as $dependent) {
1969 $elements = $this->_getElNamesRecursive($dependent);
1970 if (empty($elements)) {
1971 // probably element inside of some group
1972 $elements = array($dependent);
1974 foreach($elements as $element) {
1975 if ($element == $dependentOn) {
1976 continue;
1978 $result[$dependentOn][$condition][$value][] = $element;
1984 return array($this->getAttribute('id'), $result);
1988 * Get names of element or elements in a group.
1990 * @param HTML_QuickForm_group|element $element element group or element object
1991 * @return array
1993 function _getElNamesRecursive($element) {
1994 if (is_string($element)) {
1995 if (!$this->elementExists($element)) {
1996 return array();
1998 $element = $this->getElement($element);
2001 if (is_a($element, 'HTML_QuickForm_group')) {
2002 $elsInGroup = $element->getElements();
2003 $elNames = array();
2004 foreach ($elsInGroup as $elInGroup){
2005 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2006 // not sure if this would work - groups nested in groups
2007 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2008 } else {
2009 $elNames[] = $element->getElementName($elInGroup->getName());
2013 } else if (is_a($element, 'HTML_QuickForm_header')) {
2014 return array();
2016 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2017 return array();
2019 } else if (method_exists($element, 'getPrivateName') &&
2020 !($element instanceof HTML_QuickForm_advcheckbox)) {
2021 // The advcheckbox element implements a method called getPrivateName,
2022 // but in a way that is not compatible with the generic API, so we
2023 // have to explicitly exclude it.
2024 return array($element->getPrivateName());
2026 } else {
2027 $elNames = array($element->getName());
2030 return $elNames;
2034 * Adds a dependency for $elementName which will be disabled if $condition is met.
2035 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2036 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2037 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2038 * of the $dependentOn element is $condition (such as equal) to $value.
2040 * @param string $elementName the name of the element which will be disabled
2041 * @param string $dependentOn the name of the element whose state will be checked for condition
2042 * @param string $condition the condition to check
2043 * @param mixed $value used in conjunction with condition.
2045 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
2046 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2047 $this->_dependencies[$dependentOn] = array();
2049 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2050 $this->_dependencies[$dependentOn][$condition] = array();
2052 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2053 $this->_dependencies[$dependentOn][$condition][$value] = array();
2055 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2059 * Registers button as no submit button
2061 * @param string $buttonname name of the button
2063 function registerNoSubmitButton($buttonname){
2064 $this->_noSubmitButtons[]=$buttonname;
2068 * Checks if button is a no submit button, i.e it doesn't submit form
2070 * @param string $buttonname name of the button to check
2071 * @return bool
2073 function isNoSubmitButton($buttonname){
2074 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2078 * Registers a button as cancel button
2080 * @param string $addfieldsname name of the button
2082 function _registerCancelButton($addfieldsname){
2083 $this->_cancelButtons[]=$addfieldsname;
2087 * Displays elements without HTML input tags.
2088 * This method is different to freeze() in that it makes sure no hidden
2089 * elements are included in the form.
2090 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2092 * This function also removes all previously defined rules.
2094 * @param string|array $elementList array or string of element(s) to be frozen
2095 * @return object|bool if element list is not empty then return error object, else true
2097 function hardFreeze($elementList=null)
2099 if (!isset($elementList)) {
2100 $this->_freezeAll = true;
2101 $elementList = array();
2102 } else {
2103 if (!is_array($elementList)) {
2104 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2106 $elementList = array_flip($elementList);
2109 foreach (array_keys($this->_elements) as $key) {
2110 $name = $this->_elements[$key]->getName();
2111 if ($this->_freezeAll || isset($elementList[$name])) {
2112 $this->_elements[$key]->freeze();
2113 $this->_elements[$key]->setPersistantFreeze(false);
2114 unset($elementList[$name]);
2116 // remove all rules
2117 $this->_rules[$name] = array();
2118 // if field is required, remove the rule
2119 $unset = array_search($name, $this->_required);
2120 if ($unset !== false) {
2121 unset($this->_required[$unset]);
2126 if (!empty($elementList)) {
2127 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);
2129 return true;
2133 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2135 * This function also removes all previously defined rules of elements it freezes.
2137 * @throws HTML_QuickForm_Error
2138 * @param array $elementList array or string of element(s) not to be frozen
2139 * @return bool returns true
2141 function hardFreezeAllVisibleExcept($elementList)
2143 $elementList = array_flip($elementList);
2144 foreach (array_keys($this->_elements) as $key) {
2145 $name = $this->_elements[$key]->getName();
2146 $type = $this->_elements[$key]->getType();
2148 if ($type == 'hidden'){
2149 // leave hidden types as they are
2150 } elseif (!isset($elementList[$name])) {
2151 $this->_elements[$key]->freeze();
2152 $this->_elements[$key]->setPersistantFreeze(false);
2154 // remove all rules
2155 $this->_rules[$name] = array();
2156 // if field is required, remove the rule
2157 $unset = array_search($name, $this->_required);
2158 if ($unset !== false) {
2159 unset($this->_required[$unset]);
2163 return true;
2167 * Tells whether the form was already submitted
2169 * This is useful since the _submitFiles and _submitValues arrays
2170 * may be completely empty after the trackSubmit value is removed.
2172 * @return bool
2174 function isSubmitted()
2176 return parent::isSubmitted() && (!$this->isFrozen());
2181 * MoodleQuickForm renderer
2183 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2184 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2186 * Stylesheet is part of standard theme and should be automatically included.
2188 * @package core_form
2189 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2190 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2192 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2194 /** @var array Element template array */
2195 var $_elementTemplates;
2198 * Template used when opening a hidden fieldset
2199 * (i.e. a fieldset that is opened when there is no header element)
2200 * @var string
2202 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2204 /** @var string Header Template string */
2205 var $_headerTemplate =
2206 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2208 /** @var string Template used when opening a fieldset */
2209 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2211 /** @var string Template used when closing a fieldset */
2212 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2214 /** @var string Required Note template string */
2215 var $_requiredNoteTemplate =
2216 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2218 /** @var array list of elements which are marked as advance and will be grouped together */
2219 var $_advancedElements = array();
2221 /** @var int Whether to display advanced elements (on page load) 1 => show, 0 => hide */
2222 var $_showAdvanced;
2225 * Constructor
2227 function MoodleQuickForm_Renderer(){
2228 // switch next two lines for ol li containers for form items.
2229 // $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>');
2230 $this->_elementTemplates = array(
2231 '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>',
2233 '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>',
2235 '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>',
2237 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2239 'nodisplay'=>'');
2241 parent::HTML_QuickForm_Renderer_Tableless();
2245 * Set element's as adavance element
2247 * @param array $elements form elements which needs to be grouped as advance elements.
2249 function setAdvancedElements($elements){
2250 $this->_advancedElements = $elements;
2254 * What to do when starting the form
2256 * @param MoodleQuickForm $form reference of the form
2258 function startForm(&$form){
2259 global $PAGE;
2260 $this->_reqHTML = $form->getReqHTML();
2261 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2262 $this->_advancedHTML = $form->getAdvancedHTML();
2263 $this->_showAdvanced = $form->getShowAdvanced();
2264 parent::startForm($form);
2265 if ($form->isFrozen()){
2266 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2267 } else {
2268 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2269 $this->_hiddenHtml .= $form->_pageparams;
2272 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2273 'M.core_formchangechecker.init',
2274 array(array(
2275 'formid' => $form->getAttribute('id')
2278 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2282 * Create advance group of elements
2284 * @param object $group Passed by reference
2285 * @param bool $required if input is required field
2286 * @param string $error error message to display
2288 function startGroup(&$group, $required, $error){
2289 // Make sure the element has an id.
2290 $group->_generateId();
2292 if (method_exists($group, 'getElementTemplateType')){
2293 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2294 }else{
2295 $html = $this->_elementTemplates['default'];
2298 if ($this->_showAdvanced){
2299 $advclass = ' advanced';
2300 } else {
2301 $advclass = ' advanced hide';
2303 if (isset($this->_advancedElements[$group->getName()])){
2304 $html =str_replace(' {advanced}', $advclass, $html);
2305 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2306 } else {
2307 $html =str_replace(' {advanced}', '', $html);
2308 $html =str_replace('{advancedimg}', '', $html);
2310 if (method_exists($group, 'getHelpButton')){
2311 $html =str_replace('{help}', $group->getHelpButton(), $html);
2312 }else{
2313 $html =str_replace('{help}', '', $html);
2315 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2316 $html =str_replace('{name}', $group->getName(), $html);
2317 $html =str_replace('{type}', 'fgroup', $html);
2319 $this->_templates[$group->getName()]=$html;
2320 // Fix for bug in tableless quickforms that didn't allow you to stop a
2321 // fieldset before a group of elements.
2322 // if the element name indicates the end of a fieldset, close the fieldset
2323 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2324 && $this->_fieldsetsOpen > 0
2326 $this->_html .= $this->_closeFieldsetTemplate;
2327 $this->_fieldsetsOpen--;
2329 parent::startGroup($group, $required, $error);
2332 * Renders element
2334 * @param HTML_QuickForm_element $element element
2335 * @param bool $required if input is required field
2336 * @param string $error error message to display
2338 function renderElement(&$element, $required, $error){
2339 // Make sure the element has an id.
2340 $element->_generateId();
2342 //adding stuff to place holders in template
2343 //check if this is a group element first
2344 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2345 // so it gets substitutions for *each* element
2346 $html = $this->_groupElementTemplate;
2348 elseif (method_exists($element, 'getElementTemplateType')){
2349 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2350 }else{
2351 $html = $this->_elementTemplates['default'];
2353 if ($this->_showAdvanced){
2354 $advclass = ' advanced';
2355 } else {
2356 $advclass = ' advanced hide';
2358 if (isset($this->_advancedElements[$element->getName()])){
2359 $html =str_replace(' {advanced}', $advclass, $html);
2360 } else {
2361 $html =str_replace(' {advanced}', '', $html);
2363 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2364 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2365 } else {
2366 $html =str_replace('{advancedimg}', '', $html);
2368 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2369 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2370 $html =str_replace('{name}', $element->getName(), $html);
2371 if (method_exists($element, 'getHelpButton')){
2372 $html = str_replace('{help}', $element->getHelpButton(), $html);
2373 }else{
2374 $html = str_replace('{help}', '', $html);
2377 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2378 $this->_groupElementTemplate = $html;
2380 elseif (!isset($this->_templates[$element->getName()])) {
2381 $this->_templates[$element->getName()] = $html;
2384 parent::renderElement($element, $required, $error);
2388 * Called when visiting a form, after processing all form elements
2389 * Adds required note, form attributes, validation javascript and form content.
2391 * @global moodle_page $PAGE
2392 * @param moodleform $form Passed by reference
2394 function finishForm(&$form){
2395 global $PAGE;
2396 if ($form->isFrozen()){
2397 $this->_hiddenHtml = '';
2399 parent::finishForm($form);
2400 if (!$form->isFrozen()) {
2401 $args = $form->getLockOptionObject();
2402 if (count($args[1]) > 0) {
2403 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2408 * Called when visiting a header element
2410 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2411 * @global moodle_page $PAGE
2413 function renderHeader(&$header) {
2414 global $PAGE;
2416 $name = $header->getName();
2418 $id = empty($name) ? '' : ' id="' . $name . '"';
2419 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2420 if (is_null($header->_text)) {
2421 $header_html = '';
2422 } elseif (!empty($name) && isset($this->_templates[$name])) {
2423 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2424 } else {
2425 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2428 if (isset($this->_advancedElements[$name])){
2429 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2430 $elementName='mform_showadvanced';
2431 if ($this->_showAdvanced==0){
2432 $buttonlabel = get_string('showadvanced', 'form');
2433 } else {
2434 $buttonlabel = get_string('hideadvanced', 'form');
2436 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2437 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2438 $header_html = str_replace('{button}', $button, $header_html);
2439 } else {
2440 $header_html =str_replace('{advancedimg}', '', $header_html);
2441 $header_html = str_replace('{button}', '', $header_html);
2444 if ($this->_fieldsetsOpen > 0) {
2445 $this->_html .= $this->_closeFieldsetTemplate;
2446 $this->_fieldsetsOpen--;
2449 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2450 if ($this->_showAdvanced){
2451 $advclass = ' class="advanced"';
2452 } else {
2453 $advclass = ' class="advanced hide"';
2455 if (isset($this->_advancedElements[$name])){
2456 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2457 } else {
2458 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2460 $this->_html .= $openFieldsetTemplate . $header_html;
2461 $this->_fieldsetsOpen++;
2465 * Return Array of element names that indicate the end of a fieldset
2467 * @return array
2469 function getStopFieldsetElements(){
2470 return $this->_stopFieldsetElements;
2475 * Required elements validation
2477 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2479 * @package core_form
2480 * @category form
2481 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2484 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2486 * Checks if an element is not empty.
2487 * This is a server-side validation, it works for both text fields and editor fields
2489 * @param string $value Value to check
2490 * @param int|string|array $options Not used yet
2491 * @return bool true if value is not empty
2493 function validate($value, $options = null) {
2494 global $CFG;
2495 if (is_array($value) && array_key_exists('text', $value)) {
2496 $value = $value['text'];
2498 if (is_array($value)) {
2499 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2500 $value = implode('', $value);
2502 $stripvalues = array(
2503 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2504 '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
2506 if (!empty($CFG->strictformsrequired)) {
2507 $value = preg_replace($stripvalues, '', (string)$value);
2509 if ((string)$value == '') {
2510 return false;
2512 return true;
2516 * This function returns Javascript code used to build client-side validation.
2517 * It checks if an element is not empty.
2519 * @param int $format format of data which needs to be validated.
2520 * @return array
2522 function getValidationScript($format = null) {
2523 global $CFG;
2524 if (!empty($CFG->strictformsrequired)) {
2525 if (!empty($format) && $format == FORMAT_HTML) {
2526 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2527 } else {
2528 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2530 } else {
2531 return array('', "{jsVar} == ''");
2537 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2538 * @name $_HTML_QuickForm_default_renderer
2540 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2542 /** Please keep this list in alphabetical order. */
2543 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2544 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2545 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2546 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2547 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2548 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2549 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2550 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2551 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2552 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2553 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2554 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2555 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2556 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2557 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2558 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2559 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2560 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2561 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2562 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2563 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2564 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2565 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2566 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2567 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2568 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2569 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2570 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2571 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2572 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2573 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2574 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2575 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2576 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2577 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2578 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2579 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2581 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");