MDL-32843 import YUI 3.5.1
[moodle.git] / lib / formslib.php
blobf66b1d7b90beb8534f33a909016c432c8c0ab6be
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;
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 $action = strip_querystring(qualified_me());
157 // Assign custom data first, so that get_form_identifier can use it.
158 $this->_customdata = $customdata;
159 $this->_formname = $this->get_form_identifier();
161 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
162 if (!$editable){
163 $this->_form->hardFreeze();
166 $this->definition();
168 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
169 $this->_form->setType('sesskey', PARAM_RAW);
170 $this->_form->setDefault('sesskey', sesskey());
171 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
172 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
173 $this->_form->setDefault('_qf__'.$this->_formname, 1);
174 $this->_form->_setDefaultRuleMessages();
176 // we have to know all input types before processing submission ;-)
177 $this->_process_submission($method);
181 * It should returns unique identifier for the form.
182 * Currently it will return class name, but in case two same forms have to be
183 * rendered on same page then override function to get unique form identifier.
184 * e.g This is used on multiple self enrollments page.
186 * @return string form identifier.
188 protected function get_form_identifier() {
189 return get_class($this);
193 * To autofocus on first form element or first element with error.
195 * @param string $name if this is set then the focus is forced to a field with this name
196 * @return string javascript to select form element with first error or
197 * first element if no errors. Use this as a parameter
198 * when calling print_header
200 function focus($name=NULL) {
201 $form =& $this->_form;
202 $elkeys = array_keys($form->_elementIndex);
203 $error = false;
204 if (isset($form->_errors) && 0 != count($form->_errors)){
205 $errorkeys = array_keys($form->_errors);
206 $elkeys = array_intersect($elkeys, $errorkeys);
207 $error = true;
210 if ($error or empty($name)) {
211 $names = array();
212 while (empty($names) and !empty($elkeys)) {
213 $el = array_shift($elkeys);
214 $names = $form->_getElNamesRecursive($el);
216 if (!empty($names)) {
217 $name = array_shift($names);
221 $focus = '';
222 if (!empty($name)) {
223 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
226 return $focus;
230 * Internal method. Alters submitted data to be suitable for quickforms processing.
231 * Must be called when the form is fully set up.
233 * @param string $method name of the method which alters submitted data
235 function _process_submission($method) {
236 $submission = array();
237 if ($method == 'post') {
238 if (!empty($_POST)) {
239 $submission = $_POST;
241 } else {
242 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
245 // following trick is needed to enable proper sesskey checks when using GET forms
246 // the _qf__.$this->_formname serves as a marker that form was actually submitted
247 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
248 if (!confirm_sesskey()) {
249 print_error('invalidsesskey');
251 $files = $_FILES;
252 } else {
253 $submission = array();
254 $files = array();
257 $this->_form->updateSubmission($submission, $files);
261 * Internal method. Validates all old-style deprecated uploaded files.
262 * The new way is to upload files via repository api.
264 * @param array $files list of files to be validated
265 * @return bool|array Success or an array of errors
267 function _validate_files(&$files) {
268 global $CFG, $COURSE;
270 $files = array();
272 if (empty($_FILES)) {
273 // we do not need to do any checks because no files were submitted
274 // note: server side rules do not work for files - use custom verification in validate() instead
275 return true;
278 $errors = array();
279 $filenames = array();
281 // now check that we really want each file
282 foreach ($_FILES as $elname=>$file) {
283 $required = $this->_form->isElementRequired($elname);
285 if ($file['error'] == 4 and $file['size'] == 0) {
286 if ($required) {
287 $errors[$elname] = get_string('required');
289 unset($_FILES[$elname]);
290 continue;
293 if (!empty($file['error'])) {
294 $errors[$elname] = file_get_upload_error($file['error']);
295 unset($_FILES[$elname]);
296 continue;
299 if (!is_uploaded_file($file['tmp_name'])) {
300 // TODO: improve error message
301 $errors[$elname] = get_string('error');
302 unset($_FILES[$elname]);
303 continue;
306 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
307 // hmm, this file was not requested
308 unset($_FILES[$elname]);
309 continue;
313 // TODO: rethink the file scanning MDL-19380
314 if ($CFG->runclamonupload) {
315 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
316 $errors[$elname] = $_FILES[$elname]['uploadlog'];
317 unset($_FILES[$elname]);
318 continue;
322 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
323 if ($filename === '') {
324 // TODO: improve error message - wrong chars
325 $errors[$elname] = get_string('error');
326 unset($_FILES[$elname]);
327 continue;
329 if (in_array($filename, $filenames)) {
330 // TODO: improve error message - duplicate name
331 $errors[$elname] = get_string('error');
332 unset($_FILES[$elname]);
333 continue;
335 $filenames[] = $filename;
336 $_FILES[$elname]['name'] = $filename;
338 $files[$elname] = $_FILES[$elname]['tmp_name'];
341 // return errors if found
342 if (count($errors) == 0){
343 return true;
345 } else {
346 $files = array();
347 return $errors;
352 * Internal method. Validates filepicker and filemanager files if they are
353 * set as required fields. Also, sets the error message if encountered one.
355 * @return bool|array with errors
357 protected function validate_draft_files() {
358 global $USER;
359 $mform =& $this->_form;
361 $errors = array();
362 //Go through all the required elements and make sure you hit filepicker or
363 //filemanager element.
364 foreach ($mform->_rules as $elementname => $rules) {
365 $elementtype = $mform->getElementType($elementname);
366 //If element is of type filepicker then do validation
367 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
368 //Check if rule defined is required rule
369 foreach ($rules as $rule) {
370 if ($rule['type'] == 'required') {
371 $draftid = (int)$mform->getSubmitValue($elementname);
372 $fs = get_file_storage();
373 $context = get_context_instance(CONTEXT_USER, $USER->id);
374 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
375 $errors[$elementname] = $rule['message'];
381 if (empty($errors)) {
382 return true;
383 } else {
384 return $errors;
389 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
390 * form definition (new entry form); this function is used to load in data where values
391 * already exist and data is being edited (edit entry form).
393 * note: $slashed param removed
395 * @param stdClass|array $default_values object or array of default values
397 function set_data($default_values) {
398 if (is_object($default_values)) {
399 $default_values = (array)$default_values;
401 $this->_form->setDefaults($default_values);
405 * Sets file upload manager
407 * @deprecated since Moodle 2.0 Please don't used this API
408 * @todo MDL-31300 this api will be removed.
409 * @see MoodleQuickForm_filepicker
410 * @see MoodleQuickForm_filemanager
411 * @param bool $um upload manager
413 function set_upload_manager($um=false) {
414 debugging('Old file uploads can not be used any more, please use new filepicker element');
418 * Check that form was submitted. Does not check validity of submitted data.
420 * @return bool true if form properly submitted
422 function is_submitted() {
423 return $this->_form->isSubmitted();
427 * Checks if button pressed is not for submitting the form
429 * @staticvar bool $nosubmit keeps track of no submit button
430 * @return bool
432 function no_submit_button_pressed(){
433 static $nosubmit = null; // one check is enough
434 if (!is_null($nosubmit)){
435 return $nosubmit;
437 $mform =& $this->_form;
438 $nosubmit = false;
439 if (!$this->is_submitted()){
440 return false;
442 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
443 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
444 $nosubmit = true;
445 break;
448 return $nosubmit;
453 * Check that form data is valid.
454 * You should almost always use this, rather than {@link validate_defined_fields}
456 * @return bool true if form data valid
458 function is_validated() {
459 //finalize the form definition before any processing
460 if (!$this->_definition_finalized) {
461 $this->_definition_finalized = true;
462 $this->definition_after_data();
465 return $this->validate_defined_fields();
469 * Validate the form.
471 * You almost always want to call {@link is_validated} instead of this
472 * because it calls {@link definition_after_data} first, before validating the form,
473 * which is what you want in 99% of cases.
475 * This is provided as a separate function for those special cases where
476 * you want the form validated before definition_after_data is called
477 * for example, to selectively add new elements depending on a no_submit_button press,
478 * but only when the form is valid when the no_submit_button is pressed,
480 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
481 * is NOT to validate the form when a no submit button has been pressed.
482 * pass true here to override this behaviour
484 * @return bool true if form data valid
486 function validate_defined_fields($validateonnosubmit=false) {
487 static $validated = null; // one validation is enough
488 $mform =& $this->_form;
489 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
490 return false;
491 } elseif ($validated === null) {
492 $internal_val = $mform->validate();
494 $files = array();
495 $file_val = $this->_validate_files($files);
496 //check draft files for validation and flag them if required files
497 //are not in draft area.
498 $draftfilevalue = $this->validate_draft_files();
500 if ($file_val !== true && $draftfilevalue !== true) {
501 $file_val = array_merge($file_val, $draftfilevalue);
502 } else if ($draftfilevalue !== true) {
503 $file_val = $draftfilevalue;
504 } //default is file_val, so no need to assign.
506 if ($file_val !== true) {
507 if (!empty($file_val)) {
508 foreach ($file_val as $element=>$msg) {
509 $mform->setElementError($element, $msg);
512 $file_val = false;
515 $data = $mform->exportValues();
516 $moodle_val = $this->validation($data, $files);
517 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
518 // non-empty array means errors
519 foreach ($moodle_val as $element=>$msg) {
520 $mform->setElementError($element, $msg);
522 $moodle_val = false;
524 } else {
525 // anything else means validation ok
526 $moodle_val = true;
529 $validated = ($internal_val and $moodle_val and $file_val);
531 return $validated;
535 * Return true if a cancel button has been pressed resulting in the form being submitted.
537 * @return bool true if a cancel button has been pressed
539 function is_cancelled(){
540 $mform =& $this->_form;
541 if ($mform->isSubmitted()){
542 foreach ($mform->_cancelButtons as $cancelbutton){
543 if (optional_param($cancelbutton, 0, PARAM_RAW)){
544 return true;
548 return false;
552 * Return submitted data if properly submitted or returns NULL if validation fails or
553 * if there is no submitted data.
555 * note: $slashed param removed
557 * @return object submitted data; NULL if not valid or not submitted or cancelled
559 function get_data() {
560 $mform =& $this->_form;
562 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
563 $data = $mform->exportValues();
564 unset($data['sesskey']); // we do not need to return sesskey
565 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
566 if (empty($data)) {
567 return NULL;
568 } else {
569 return (object)$data;
571 } else {
572 return NULL;
577 * Return submitted data without validation or NULL if there is no submitted data.
578 * note: $slashed param removed
580 * @return object submitted data; NULL if not submitted
582 function get_submitted_data() {
583 $mform =& $this->_form;
585 if ($this->is_submitted()) {
586 $data = $mform->exportValues();
587 unset($data['sesskey']); // we do not need to return sesskey
588 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
589 if (empty($data)) {
590 return NULL;
591 } else {
592 return (object)$data;
594 } else {
595 return NULL;
600 * Save verified uploaded files into directory. Upload process can be customised from definition()
602 * @deprecated since Moodle 2.0
603 * @todo MDL-31294 remove this api
604 * @see moodleform::save_stored_file()
605 * @see moodleform::save_file()
606 * @param string $destination path where file should be stored
607 * @return bool Always false
609 function save_files($destination) {
610 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
611 return false;
615 * Returns name of uploaded file.
617 * @param string $elname first element if null
618 * @return string|bool false in case of failure, string if ok
620 function get_new_filename($elname=null) {
621 global $USER;
623 if (!$this->is_submitted() or !$this->is_validated()) {
624 return false;
627 if (is_null($elname)) {
628 if (empty($_FILES)) {
629 return false;
631 reset($_FILES);
632 $elname = key($_FILES);
635 if (empty($elname)) {
636 return false;
639 $element = $this->_form->getElement($elname);
641 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
642 $values = $this->_form->exportValues($elname);
643 if (empty($values[$elname])) {
644 return false;
646 $draftid = $values[$elname];
647 $fs = get_file_storage();
648 $context = get_context_instance(CONTEXT_USER, $USER->id);
649 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
650 return false;
652 $file = reset($files);
653 return $file->get_filename();
656 if (!isset($_FILES[$elname])) {
657 return false;
660 return $_FILES[$elname]['name'];
664 * Save file to standard filesystem
666 * @param string $elname name of element
667 * @param string $pathname full path name of file
668 * @param bool $override override file if exists
669 * @return bool success
671 function save_file($elname, $pathname, $override=false) {
672 global $USER;
674 if (!$this->is_submitted() or !$this->is_validated()) {
675 return false;
677 if (file_exists($pathname)) {
678 if ($override) {
679 if (!@unlink($pathname)) {
680 return false;
682 } else {
683 return false;
687 $element = $this->_form->getElement($elname);
689 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
690 $values = $this->_form->exportValues($elname);
691 if (empty($values[$elname])) {
692 return false;
694 $draftid = $values[$elname];
695 $fs = get_file_storage();
696 $context = get_context_instance(CONTEXT_USER, $USER->id);
697 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
698 return false;
700 $file = reset($files);
702 return $file->copy_content_to($pathname);
704 } else if (isset($_FILES[$elname])) {
705 return copy($_FILES[$elname]['tmp_name'], $pathname);
708 return false;
712 * Returns a temporary file, do not forget to delete after not needed any more.
714 * @param string $elname name of the elmenet
715 * @return string|bool either string or false
717 function save_temp_file($elname) {
718 if (!$this->get_new_filename($elname)) {
719 return false;
721 if (!$dir = make_temp_directory('forms')) {
722 return false;
724 if (!$tempfile = tempnam($dir, 'tempup_')) {
725 return false;
727 if (!$this->save_file($elname, $tempfile, true)) {
728 // something went wrong
729 @unlink($tempfile);
730 return false;
733 return $tempfile;
737 * Get draft files of a form element
738 * This is a protected method which will be used only inside moodleforms
740 * @param string $elname name of element
741 * @return array|bool|null
743 protected function get_draft_files($elname) {
744 global $USER;
746 if (!$this->is_submitted()) {
747 return false;
750 $element = $this->_form->getElement($elname);
752 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
753 $values = $this->_form->exportValues($elname);
754 if (empty($values[$elname])) {
755 return false;
757 $draftid = $values[$elname];
758 $fs = get_file_storage();
759 $context = get_context_instance(CONTEXT_USER, $USER->id);
760 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
761 return null;
763 return $files;
765 return null;
769 * Save file to local filesystem pool
771 * @param string $elname name of element
772 * @param int $newcontextid id of context
773 * @param string $newcomponent name of the component
774 * @param string $newfilearea name of file area
775 * @param int $newitemid item id
776 * @param string $newfilepath path of file where it get stored
777 * @param string $newfilename use specified filename, if not specified name of uploaded file used
778 * @param bool $overwrite overwrite file if exists
779 * @param int $newuserid new userid if required
780 * @return mixed stored_file object or false if error; may throw exception if duplicate found
782 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
783 $newfilename=null, $overwrite=false, $newuserid=null) {
784 global $USER;
786 if (!$this->is_submitted() or !$this->is_validated()) {
787 return false;
790 if (empty($newuserid)) {
791 $newuserid = $USER->id;
794 $element = $this->_form->getElement($elname);
795 $fs = get_file_storage();
797 if ($element instanceof MoodleQuickForm_filepicker) {
798 $values = $this->_form->exportValues($elname);
799 if (empty($values[$elname])) {
800 return false;
802 $draftid = $values[$elname];
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 false;
807 $file = reset($files);
808 if (is_null($newfilename)) {
809 $newfilename = $file->get_filename();
812 if ($overwrite) {
813 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
814 if (!$oldfile->delete()) {
815 return false;
820 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
821 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
822 return $fs->create_file_from_storedfile($file_record, $file);
824 } else if (isset($_FILES[$elname])) {
825 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
827 if ($overwrite) {
828 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
829 if (!$oldfile->delete()) {
830 return false;
835 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
836 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
837 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
840 return false;
844 * Get content of uploaded file.
846 * @param string $elname name of file upload element
847 * @return string|bool false in case of failure, string if ok
849 function get_file_content($elname) {
850 global $USER;
852 if (!$this->is_submitted() or !$this->is_validated()) {
853 return false;
856 $element = $this->_form->getElement($elname);
858 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
859 $values = $this->_form->exportValues($elname);
860 if (empty($values[$elname])) {
861 return false;
863 $draftid = $values[$elname];
864 $fs = get_file_storage();
865 $context = get_context_instance(CONTEXT_USER, $USER->id);
866 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
867 return false;
869 $file = reset($files);
871 return $file->get_content();
873 } else if (isset($_FILES[$elname])) {
874 return file_get_contents($_FILES[$elname]['tmp_name']);
877 return false;
881 * Print html form.
883 function display() {
884 //finalize the form definition if not yet done
885 if (!$this->_definition_finalized) {
886 $this->_definition_finalized = true;
887 $this->definition_after_data();
889 $this->_form->display();
893 * Form definition. Abstract method - always override!
895 protected abstract function definition();
898 * Dummy stub method - override if you need to setup the form depending on current
899 * values. This method is called after definition(), data submission and set_data().
900 * All form setup that is dependent on form values should go in here.
902 function definition_after_data(){
906 * Dummy stub method - override if you needed to perform some extra validation.
907 * If there are errors return array of errors ("fieldname"=>"error message"),
908 * otherwise true if ok.
910 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
912 * @param array $data array of ("fieldname"=>value) of submitted data
913 * @param array $files array of uploaded files "element_name"=>tmp_file_path
914 * @return array of "element_name"=>"error_description" if there are errors,
915 * or an empty array if everything is OK (true allowed for backwards compatibility too).
917 function validation($data, $files) {
918 return array();
922 * Helper used by {@link repeat_elements()}.
924 * @param int $i the index of this element.
925 * @param HTML_QuickForm_element $elementclone
926 * @param array $namecloned array of names
928 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
929 $name = $elementclone->getName();
930 $namecloned[] = $name;
932 if (!empty($name)) {
933 $elementclone->setName($name."[$i]");
936 if (is_a($elementclone, 'HTML_QuickForm_header')) {
937 $value = $elementclone->_text;
938 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
940 } else {
941 $value=$elementclone->getLabel();
942 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
947 * Method to add a repeating group of elements to a form.
949 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
950 * @param int $repeats no of times to repeat elements initially
951 * @param array $options Array of options to apply to elements. Array keys are element names.
952 * This is an array of arrays. The second sets of keys are the option types for the elements :
953 * 'default' - default value is value
954 * 'type' - PARAM_* constant is value
955 * 'helpbutton' - helpbutton params array is value
956 * 'disabledif' - last three moodleform::disabledIf()
957 * params are value as an array
958 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
959 * @param string $addfieldsname name for button to add more fields
960 * @param int $addfieldsno how many fields to add at a time
961 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
962 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
963 * @return int no of repeats of element in this page
965 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
966 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
967 if ($addstring===null){
968 $addstring = get_string('addfields', 'form', $addfieldsno);
969 } else {
970 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
972 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
973 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
974 if (!empty($addfields)){
975 $repeats += $addfieldsno;
977 $mform =& $this->_form;
978 $mform->registerNoSubmitButton($addfieldsname);
979 $mform->addElement('hidden', $repeathiddenname, $repeats);
980 $mform->setType($repeathiddenname, PARAM_INT);
981 //value not to be overridden by submitted value
982 $mform->setConstants(array($repeathiddenname=>$repeats));
983 $namecloned = array();
984 for ($i = 0; $i < $repeats; $i++) {
985 foreach ($elementobjs as $elementobj){
986 $elementclone = fullclone($elementobj);
987 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
989 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
990 foreach ($elementclone->getElements() as $el) {
991 $this->repeat_elements_fix_clone($i, $el, $namecloned);
993 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
996 $mform->addElement($elementclone);
999 for ($i=0; $i<$repeats; $i++) {
1000 foreach ($options as $elementname => $elementoptions){
1001 $pos=strpos($elementname, '[');
1002 if ($pos!==FALSE){
1003 $realelementname = substr($elementname, 0, $pos+1)."[$i]";
1004 $realelementname .= substr($elementname, $pos+1);
1005 }else {
1006 $realelementname = $elementname."[$i]";
1008 foreach ($elementoptions as $option => $params){
1010 switch ($option){
1011 case 'default' :
1012 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1013 break;
1014 case 'helpbutton' :
1015 $params = array_merge(array($realelementname), $params);
1016 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1017 break;
1018 case 'disabledif' :
1019 foreach ($namecloned as $num => $name){
1020 if ($params[0] == $name){
1021 $params[0] = $params[0]."[$i]";
1022 break;
1025 $params = array_merge(array($realelementname), $params);
1026 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1027 break;
1028 case 'rule' :
1029 if (is_string($params)){
1030 $params = array(null, $params, null, 'client');
1032 $params = array_merge(array($realelementname), $params);
1033 call_user_func_array(array(&$mform, 'addRule'), $params);
1034 break;
1035 case 'type' :
1036 //Type should be set only once
1037 if (!isset($mform->_types[$elementname])) {
1038 $mform->setType($elementname, $params);
1040 break;
1045 $mform->addElement('submit', $addfieldsname, $addstring);
1047 if (!$addbuttoninside) {
1048 $mform->closeHeaderBefore($addfieldsname);
1051 return $repeats;
1055 * Adds a link/button that controls the checked state of a group of checkboxes.
1057 * @param int $groupid The id of the group of advcheckboxes this element controls
1058 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1059 * @param array $attributes associative array of HTML attributes
1060 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1062 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1063 global $CFG, $PAGE;
1065 // Name of the controller button
1066 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1067 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1068 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1070 // Set the default text if none was specified
1071 if (empty($text)) {
1072 $text = get_string('selectallornone', 'form');
1075 $mform = $this->_form;
1076 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1077 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1079 $newselectvalue = $selectvalue;
1080 if (is_null($selectvalue)) {
1081 $newselectvalue = $originalValue;
1082 } else if (!is_null($contollerbutton)) {
1083 $newselectvalue = (int) !$selectvalue;
1085 // set checkbox state depending on orignal/submitted value by controoler button
1086 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1087 foreach ($mform->_elements as $element) {
1088 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1089 $element->getAttribute('class') == $checkboxgroupclass &&
1090 !$element->isFrozen()) {
1091 $mform->setConstants(array($element->getName() => $newselectvalue));
1096 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1097 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1098 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1100 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1101 array(
1102 array('groupid' => $groupid,
1103 'checkboxclass' => $checkboxgroupclass,
1104 'checkboxcontroller' => $checkboxcontrollerparam,
1105 'controllerbutton' => $checkboxcontrollername)
1109 require_once("$CFG->libdir/form/submit.php");
1110 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1111 $mform->addElement($submitlink);
1112 $mform->registerNoSubmitButton($checkboxcontrollername);
1113 $mform->setDefault($checkboxcontrollername, $text);
1117 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1118 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1119 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1120 * get data with get_data().
1122 * @param bool $cancel whether to show cancel button, default true
1123 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1125 function add_action_buttons($cancel = true, $submitlabel=null){
1126 if (is_null($submitlabel)){
1127 $submitlabel = get_string('savechanges');
1129 $mform =& $this->_form;
1130 if ($cancel){
1131 //when two elements we need a group
1132 $buttonarray=array();
1133 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1134 $buttonarray[] = &$mform->createElement('cancel');
1135 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1136 $mform->closeHeaderBefore('buttonar');
1137 } else {
1138 //no group needed
1139 $mform->addElement('submit', 'submitbutton', $submitlabel);
1140 $mform->closeHeaderBefore('submitbutton');
1145 * Adds an initialisation call for a standard JavaScript enhancement.
1147 * This function is designed to add an initialisation call for a JavaScript
1148 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1150 * Current options:
1151 * - Selectboxes
1152 * - smartselect: Turns a nbsp indented select box into a custom drop down
1153 * control that supports multilevel and category selection.
1154 * $enhancement = 'smartselect';
1155 * $options = array('selectablecategories' => true|false)
1157 * @since Moodle 2.0
1158 * @param string|element $element form element for which Javascript needs to be initalized
1159 * @param string $enhancement which init function should be called
1160 * @param array $options options passed to javascript
1161 * @param array $strings strings for javascript
1163 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1164 global $PAGE;
1165 if (is_string($element)) {
1166 $element = $this->_form->getElement($element);
1168 if (is_object($element)) {
1169 $element->_generateId();
1170 $elementid = $element->getAttribute('id');
1171 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1172 if (is_array($strings)) {
1173 foreach ($strings as $string) {
1174 if (is_array($string)) {
1175 call_user_method_array('string_for_js', $PAGE->requires, $string);
1176 } else {
1177 $PAGE->requires->string_for_js($string, 'moodle');
1185 * Returns a JS module definition for the mforms JS
1187 * @return array
1189 public static function get_js_module() {
1190 global $CFG;
1191 return array(
1192 'name' => 'mform',
1193 'fullpath' => '/lib/form/form.js',
1194 'requires' => array('base', 'node'),
1195 'strings' => array(
1196 array('showadvanced', 'form'),
1197 array('hideadvanced', 'form')
1204 * MoodleQuickForm implementation
1206 * You never extend this class directly. The class methods of this class are available from
1207 * the private $this->_form property on moodleform and its children. You generally only
1208 * call methods on this class from within abstract methods that you override on moodleform such
1209 * as definition and definition_after_data
1211 * @package core_form
1212 * @category form
1213 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1216 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1217 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1218 var $_types = array();
1220 /** @var array dependent state for the element/'s */
1221 var $_dependencies = array();
1223 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1224 var $_noSubmitButtons=array();
1226 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1227 var $_cancelButtons=array();
1229 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1230 var $_advancedElements = array();
1232 /** @var bool Whether to display advanced elements (on page load) */
1233 var $_showAdvanced = null;
1236 * The form name is derived from the class name of the wrapper minus the trailing form
1237 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1238 * @var string
1240 var $_formName = '';
1243 * String with the html for hidden params passed in as part of a moodle_url
1244 * object for the action. Output in the form.
1245 * @var string
1247 var $_pageparams = '';
1250 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1252 * @staticvar int $formcounter counts number of forms
1253 * @param string $formName Form's name.
1254 * @param string $method Form's method defaults to 'POST'
1255 * @param string|moodle_url $action Form's action
1256 * @param string $target (optional)Form's target defaults to none
1257 * @param mixed $attributes (optional)Extra attributes for <form> tag
1259 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1260 global $CFG, $OUTPUT;
1262 static $formcounter = 1;
1264 HTML_Common::HTML_Common($attributes);
1265 $target = empty($target) ? array() : array('target' => $target);
1266 $this->_formName = $formName;
1267 if (is_a($action, 'moodle_url')){
1268 $this->_pageparams = html_writer::input_hidden_params($action);
1269 $action = $action->out_omit_querystring();
1270 } else {
1271 $this->_pageparams = '';
1273 //no 'name' atttribute for form in xhtml strict :
1274 $attributes = array('action'=>$action, 'method'=>$method,
1275 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1276 $formcounter++;
1277 $this->updateAttributes($attributes);
1279 //this is custom stuff for Moodle :
1280 $oldclass= $this->getAttribute('class');
1281 if (!empty($oldclass)){
1282 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1283 }else {
1284 $this->updateAttributes(array('class'=>'mform'));
1286 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1287 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1288 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1292 * Use this method to indicate an element in a form is an advanced field. If items in a form
1293 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1294 * form so the user can decide whether to display advanced form controls.
1296 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1298 * @param string $elementName group or element name (not the element name of something inside a group).
1299 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1301 function setAdvanced($elementName, $advanced=true){
1302 if ($advanced){
1303 $this->_advancedElements[$elementName]='';
1304 } elseif (isset($this->_advancedElements[$elementName])) {
1305 unset($this->_advancedElements[$elementName]);
1307 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1308 $this->setShowAdvanced();
1309 $this->registerNoSubmitButton('mform_showadvanced');
1311 $this->addElement('hidden', 'mform_showadvanced_last');
1312 $this->setType('mform_showadvanced_last', PARAM_INT);
1316 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1317 * display advanced elements in the form until 'Show Advanced' is pressed.
1319 * You can get the last state of the form and possibly save it for this user by using
1320 * value 'mform_showadvanced_last' in submitted data.
1322 * @param bool $showadvancedNow if true will show adavance elements.
1324 function setShowAdvanced($showadvancedNow = null){
1325 if ($showadvancedNow === null){
1326 if ($this->_showAdvanced !== null){
1327 return;
1328 } else { //if setShowAdvanced is called without any preference
1329 //make the default to not show advanced elements.
1330 $showadvancedNow = get_user_preferences(
1331 textlib::strtolower($this->_formName.'_showadvanced', 0));
1334 //value of hidden element
1335 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1336 //value of button
1337 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1338 //toggle if button pressed or else stay the same
1339 if ($hiddenLast == -1) {
1340 $next = $showadvancedNow;
1341 } elseif ($buttonPressed) { //toggle on button press
1342 $next = !$hiddenLast;
1343 } else {
1344 $next = $hiddenLast;
1346 $this->_showAdvanced = $next;
1347 if ($showadvancedNow != $next){
1348 set_user_preference($this->_formName.'_showadvanced', $next);
1350 $this->setConstants(array('mform_showadvanced_last'=>$next));
1354 * Gets show advance value, if advance elements are visible it will return true else false
1356 * @return bool
1358 function getShowAdvanced(){
1359 return $this->_showAdvanced;
1364 * Accepts a renderer
1366 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1368 function accept(&$renderer) {
1369 if (method_exists($renderer, 'setAdvancedElements')){
1370 //check for visible fieldsets where all elements are advanced
1371 //and mark these headers as advanced as well.
1372 //And mark all elements in a advanced header as advanced
1373 $stopFields = $renderer->getStopFieldSetElements();
1374 $lastHeader = null;
1375 $lastHeaderAdvanced = false;
1376 $anyAdvanced = false;
1377 foreach (array_keys($this->_elements) as $elementIndex){
1378 $element =& $this->_elements[$elementIndex];
1380 // if closing header and any contained element was advanced then mark it as advanced
1381 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1382 if ($anyAdvanced && !is_null($lastHeader)){
1383 $this->setAdvanced($lastHeader->getName());
1385 $lastHeaderAdvanced = false;
1386 unset($lastHeader);
1387 $lastHeader = null;
1388 } elseif ($lastHeaderAdvanced) {
1389 $this->setAdvanced($element->getName());
1392 if ($element->getType()=='header'){
1393 $lastHeader =& $element;
1394 $anyAdvanced = false;
1395 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1396 } elseif (isset($this->_advancedElements[$element->getName()])){
1397 $anyAdvanced = true;
1400 // the last header may not be closed yet...
1401 if ($anyAdvanced && !is_null($lastHeader)){
1402 $this->setAdvanced($lastHeader->getName());
1404 $renderer->setAdvancedElements($this->_advancedElements);
1407 parent::accept($renderer);
1411 * Adds one or more element names that indicate the end of a fieldset
1413 * @param string $elementName name of the element
1415 function closeHeaderBefore($elementName){
1416 $renderer =& $this->defaultRenderer();
1417 $renderer->addStopFieldsetElements($elementName);
1421 * Should be used for all elements of a form except for select, radio and checkboxes which
1422 * clean their own data.
1424 * @param string $elementname
1425 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1426 * {@link lib/moodlelib.php} for defined parameter types
1428 function setType($elementname, $paramtype) {
1429 $this->_types[$elementname] = $paramtype;
1433 * This can be used to set several types at once.
1435 * @param array $paramtypes types of parameters.
1436 * @see MoodleQuickForm::setType
1438 function setTypes($paramtypes) {
1439 $this->_types = $paramtypes + $this->_types;
1443 * Updates submitted values
1445 * @param array $submission submitted values
1446 * @param array $files list of files
1448 function updateSubmission($submission, $files) {
1449 $this->_flagSubmitted = false;
1451 if (empty($submission)) {
1452 $this->_submitValues = array();
1453 } else {
1454 foreach ($submission as $key=>$s) {
1455 if (array_key_exists($key, $this->_types)) {
1456 $type = $this->_types[$key];
1457 } else {
1458 $type = PARAM_RAW;
1460 if (is_array($s)) {
1461 $submission[$key] = clean_param_array($s, $type, true);
1462 } else {
1463 $submission[$key] = clean_param($s, $type);
1466 $this->_submitValues = $submission;
1467 $this->_flagSubmitted = true;
1470 if (empty($files)) {
1471 $this->_submitFiles = array();
1472 } else {
1473 $this->_submitFiles = $files;
1474 $this->_flagSubmitted = true;
1477 // need to tell all elements that they need to update their value attribute.
1478 foreach (array_keys($this->_elements) as $key) {
1479 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1484 * Returns HTML for required elements
1486 * @return string
1488 function getReqHTML(){
1489 return $this->_reqHTML;
1493 * Returns HTML for advanced elements
1495 * @return string
1497 function getAdvancedHTML(){
1498 return $this->_advancedHTML;
1502 * Initializes a default form value. Used to specify the default for a new entry where
1503 * no data is loaded in using moodleform::set_data()
1505 * note: $slashed param removed
1507 * @param string $elementName element name
1508 * @param mixed $defaultValue values for that element name
1510 function setDefault($elementName, $defaultValue){
1511 $this->setDefaults(array($elementName=>$defaultValue));
1515 * Add an array of buttons to the form
1517 * @param array $buttons An associative array representing help button to attach to
1518 * to the form. keys of array correspond to names of elements in form.
1519 * @param bool $suppresscheck if true then string check will be suppressed
1520 * @param string $function callback function to dispaly help button.
1521 * @deprecated since Moodle 2.0 use addHelpButton() call on each element manually
1522 * @todo MDL-31047 this api will be removed.
1523 * @see MoodleQuickForm::addHelpButton()
1525 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1527 debugging('function moodle_form::setHelpButtons() is deprecated');
1528 //foreach ($buttons as $elementname => $button){
1529 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1534 * Add a help button to element
1536 * @param string $elementname name of the element to add the item to
1537 * @param array $buttonargs arguments to pass to function $function
1538 * @param bool $suppresscheck whether to throw an error if the element
1539 * doesn't exist.
1540 * @param string $function - function to generate html from the arguments in $button
1541 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1542 * @todo MDL-31047 this api will be removed.
1543 * @see MoodleQuickForm::addHelpButton()
1545 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1546 global $OUTPUT;
1548 debugging('function moodle_form::setHelpButton() is deprecated');
1549 if ($function !== 'helpbutton') {
1550 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1553 $buttonargs = (array)$buttonargs;
1555 if (array_key_exists($elementname, $this->_elementIndex)) {
1556 //_elements has a numeric index, this code accesses the elements by name
1557 $element = $this->_elements[$this->_elementIndex[$elementname]];
1559 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1560 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1561 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1562 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1564 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1566 } else if (!$suppresscheck) {
1567 print_error('nonexistentformelements', 'form', '', $elementname);
1572 * Add a help button to element, only one button per element is allowed.
1574 * This is new, simplified and preferable method of setting a help icon on form elements.
1575 * It uses the new $OUTPUT->help_icon().
1577 * Typically, you will provide the same identifier and the component as you have used for the
1578 * label of the element. The string identifier with the _help suffix added is then used
1579 * as the help string.
1581 * There has to be two strings defined:
1582 * 1/ get_string($identifier, $component) - the title of the help page
1583 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1585 * @since Moodle 2.0
1586 * @param string $elementname name of the element to add the item to
1587 * @param string $identifier help string identifier without _help suffix
1588 * @param string $component component name to look the help string in
1589 * @param string $linktext optional text to display next to the icon
1590 * @param bool $suppresscheck set to true if the element may not exist
1592 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1593 global $OUTPUT;
1594 if (array_key_exists($elementname, $this->_elementIndex)) {
1595 $element = $this->_elements[$this->_elementIndex[$elementname]];
1596 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1597 } else if (!$suppresscheck) {
1598 debugging(get_string('nonexistentformelements', 'form', $elementname));
1603 * Set constant value not overridden by _POST or _GET
1604 * note: this does not work for complex names with [] :-(
1606 * @param string $elname name of element
1607 * @param mixed $value
1609 function setConstant($elname, $value) {
1610 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1611 $element =& $this->getElement($elname);
1612 $element->onQuickFormEvent('updateValue', null, $this);
1616 * export submitted values
1618 * @param string $elementList list of elements in form
1619 * @return array
1621 function exportValues($elementList = null){
1622 $unfiltered = array();
1623 if (null === $elementList) {
1624 // iterate over all elements, calling their exportValue() methods
1625 $emptyarray = array();
1626 foreach (array_keys($this->_elements) as $key) {
1627 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1628 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1629 } else {
1630 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1633 if (is_array($value)) {
1634 // This shit throws a bogus warning in PHP 4.3.x
1635 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1638 } else {
1639 if (!is_array($elementList)) {
1640 $elementList = array_map('trim', explode(',', $elementList));
1642 foreach ($elementList as $elementName) {
1643 $value = $this->exportValue($elementName);
1644 if (@PEAR::isError($value)) {
1645 return $value;
1647 //oh, stock QuickFOrm was returning array of arrays!
1648 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1652 if (is_array($this->_constantValues)) {
1653 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1656 return $unfiltered;
1660 * Adds a validation rule for the given field
1662 * If the element is in fact a group, it will be considered as a whole.
1663 * To validate grouped elements as separated entities,
1664 * use addGroupRule instead of addRule.
1666 * @param string $element Form element name
1667 * @param string $message Message to display for invalid data
1668 * @param string $type Rule type, use getRegisteredRules() to get types
1669 * @param string $format (optional)Required for extra rule data
1670 * @param string $validation (optional)Where to perform validation: "server", "client"
1671 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1672 * @param bool $force Force the rule to be applied, even if the target form element does not exist
1674 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1676 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1677 if ($validation == 'client') {
1678 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1684 * Adds a validation rule for the given group of elements
1686 * Only groups with a name can be assigned a validation rule
1687 * Use addGroupRule when you need to validate elements inside the group.
1688 * Use addRule if you need to validate the group as a whole. In this case,
1689 * the same rule will be applied to all elements in the group.
1690 * Use addRule if you need to validate the group against a function.
1692 * @param string $group Form group name
1693 * @param array|string $arg1 Array for multiple elements or error message string for one element
1694 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1695 * @param string $format (optional)Required for extra rule data
1696 * @param int $howmany (optional)How many valid elements should be in the group
1697 * @param string $validation (optional)Where to perform validation: "server", "client"
1698 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1700 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1702 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1703 if (is_array($arg1)) {
1704 foreach ($arg1 as $rules) {
1705 foreach ($rules as $rule) {
1706 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1708 if ('client' == $validation) {
1709 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1713 } elseif (is_string($arg1)) {
1715 if ($validation == 'client') {
1716 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1722 * Returns the client side validation script
1724 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1725 * and slightly modified to run rules per-element
1726 * Needed to override this because of an error with client side validation of grouped elements.
1728 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1730 function getValidationScript()
1732 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1733 return '';
1736 include_once('HTML/QuickForm/RuleRegistry.php');
1737 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1738 $test = array();
1739 $js_escape = array(
1740 "\r" => '\r',
1741 "\n" => '\n',
1742 "\t" => '\t',
1743 "'" => "\\'",
1744 '"' => '\"',
1745 '\\' => '\\\\'
1748 foreach ($this->_rules as $elementName => $rules) {
1749 foreach ($rules as $rule) {
1750 if ('client' == $rule['validation']) {
1751 unset($element); //TODO: find out how to properly initialize it
1753 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1754 $rule['message'] = strtr($rule['message'], $js_escape);
1756 if (isset($rule['group'])) {
1757 $group =& $this->getElement($rule['group']);
1758 // No JavaScript validation for frozen elements
1759 if ($group->isFrozen()) {
1760 continue 2;
1762 $elements =& $group->getElements();
1763 foreach (array_keys($elements) as $key) {
1764 if ($elementName == $group->getElementName($key)) {
1765 $element =& $elements[$key];
1766 break;
1769 } elseif ($dependent) {
1770 $element = array();
1771 $element[] =& $this->getElement($elementName);
1772 foreach ($rule['dependent'] as $elName) {
1773 $element[] =& $this->getElement($elName);
1775 } else {
1776 $element =& $this->getElement($elementName);
1778 // No JavaScript validation for frozen elements
1779 if (is_object($element) && $element->isFrozen()) {
1780 continue 2;
1781 } elseif (is_array($element)) {
1782 foreach (array_keys($element) as $key) {
1783 if ($element[$key]->isFrozen()) {
1784 continue 3;
1788 //for editor element, [text] is appended to the name.
1789 if ($element->getType() == 'editor') {
1790 $elementName .= '[text]';
1791 //Add format to rule as moodleform check which format is supported by browser
1792 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1793 if (is_null($rule['format'])) {
1794 $rule['format'] = $element->getFormat();
1797 // Fix for bug displaying errors for elements in a group
1798 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1799 $test[$elementName][1]=$element;
1800 //end of fix
1805 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1806 // the form, and then that form field gets corrupted by the code that follows.
1807 unset($element);
1809 $js = '
1810 <script type="text/javascript">
1811 //<![CDATA[
1813 var skipClientValidation = false;
1815 function qf_errorHandler(element, _qfMsg) {
1816 div = element.parentNode;
1818 if ((div == undefined) || (element.name == undefined)) {
1819 //no checking can be done for undefined elements so let server handle it.
1820 return true;
1823 if (_qfMsg != \'\') {
1824 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1825 if (!errorSpan) {
1826 errorSpan = document.createElement("span");
1827 errorSpan.id = \'id_error_\'+element.name;
1828 errorSpan.className = "error";
1829 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1832 while (errorSpan.firstChild) {
1833 errorSpan.removeChild(errorSpan.firstChild);
1836 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1837 errorSpan.appendChild(document.createElement("br"));
1839 if (div.className.substr(div.className.length - 6, 6) != " error"
1840 && div.className != "error") {
1841 div.className += " error";
1844 return false;
1845 } else {
1846 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1847 if (errorSpan) {
1848 errorSpan.parentNode.removeChild(errorSpan);
1851 if (div.className.substr(div.className.length - 6, 6) == " error") {
1852 div.className = div.className.substr(0, div.className.length - 6);
1853 } else if (div.className == "error") {
1854 div.className = "";
1857 return true;
1860 $validateJS = '';
1861 foreach ($test as $elementName => $jsandelement) {
1862 // Fix for bug displaying errors for elements in a group
1863 //unset($element);
1864 list($jsArr,$element)=$jsandelement;
1865 //end of fix
1866 $escapedElementName = preg_replace_callback(
1867 '/[_\[\]]/',
1868 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1869 $elementName);
1870 $js .= '
1871 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1872 if (undefined == element) {
1873 //required element was not found, then let form be submitted without client side validation
1874 return true;
1876 var value = \'\';
1877 var errFlag = new Array();
1878 var _qfGroups = {};
1879 var _qfMsg = \'\';
1880 var frm = element.parentNode;
1881 if ((undefined != element.name) && (frm != undefined)) {
1882 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1883 frm = frm.parentNode;
1885 ' . join("\n", $jsArr) . '
1886 return qf_errorHandler(element, _qfMsg);
1887 } else {
1888 //element name should be defined else error msg will not be displayed.
1889 return true;
1893 $validateJS .= '
1894 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1895 if (!ret && !first_focus) {
1896 first_focus = true;
1897 frm.elements[\''.$elementName.'\'].focus();
1901 // Fix for bug displaying errors for elements in a group
1902 //unset($element);
1903 //$element =& $this->getElement($elementName);
1904 //end of fix
1905 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1906 $onBlur = $element->getAttribute('onBlur');
1907 $onChange = $element->getAttribute('onChange');
1908 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1909 'onChange' => $onChange . $valFunc));
1911 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1912 $js .= '
1913 function validate_' . $this->_formName . '(frm) {
1914 if (skipClientValidation) {
1915 return true;
1917 var ret = true;
1919 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1920 var first_focus = false;
1921 ' . $validateJS . ';
1922 return ret;
1924 //]]>
1925 </script>';
1926 return $js;
1927 } // end func getValidationScript
1930 * Sets default error message
1932 function _setDefaultRuleMessages(){
1933 foreach ($this->_rules as $field => $rulesarr){
1934 foreach ($rulesarr as $key => $rule){
1935 if ($rule['message']===null){
1936 $a=new stdClass();
1937 $a->format=$rule['format'];
1938 $str=get_string('err_'.$rule['type'], 'form', $a);
1939 if (strpos($str, '[[')!==0){
1940 $this->_rules[$field][$key]['message']=$str;
1948 * Get list of attributes which have dependencies
1950 * @return array
1952 function getLockOptionObject(){
1953 $result = array();
1954 foreach ($this->_dependencies as $dependentOn => $conditions){
1955 $result[$dependentOn] = array();
1956 foreach ($conditions as $condition=>$values) {
1957 $result[$dependentOn][$condition] = array();
1958 foreach ($values as $value=>$dependents) {
1959 $result[$dependentOn][$condition][$value] = array();
1960 $i = 0;
1961 foreach ($dependents as $dependent) {
1962 $elements = $this->_getElNamesRecursive($dependent);
1963 if (empty($elements)) {
1964 // probably element inside of some group
1965 $elements = array($dependent);
1967 foreach($elements as $element) {
1968 if ($element == $dependentOn) {
1969 continue;
1971 $result[$dependentOn][$condition][$value][] = $element;
1977 return array($this->getAttribute('id'), $result);
1981 * Get names of element or elements in a group.
1983 * @param HTML_QuickForm_group|element $element element group or element object
1984 * @return array
1986 function _getElNamesRecursive($element) {
1987 if (is_string($element)) {
1988 if (!$this->elementExists($element)) {
1989 return array();
1991 $element = $this->getElement($element);
1994 if (is_a($element, 'HTML_QuickForm_group')) {
1995 $elsInGroup = $element->getElements();
1996 $elNames = array();
1997 foreach ($elsInGroup as $elInGroup){
1998 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1999 // not sure if this would work - groups nested in groups
2000 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2001 } else {
2002 $elNames[] = $element->getElementName($elInGroup->getName());
2006 } else if (is_a($element, 'HTML_QuickForm_header')) {
2007 return array();
2009 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2010 return array();
2012 } else if (method_exists($element, 'getPrivateName') &&
2013 !($element instanceof HTML_QuickForm_advcheckbox)) {
2014 // The advcheckbox element implements a method called getPrivateName,
2015 // but in a way that is not compatible with the generic API, so we
2016 // have to explicitly exclude it.
2017 return array($element->getPrivateName());
2019 } else {
2020 $elNames = array($element->getName());
2023 return $elNames;
2027 * Adds a dependency for $elementName which will be disabled if $condition is met.
2028 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2029 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2030 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2031 * of the $dependentOn element is $condition (such as equal) to $value.
2033 * @param string $elementName the name of the element which will be disabled
2034 * @param string $dependentOn the name of the element whose state will be checked for condition
2035 * @param string $condition the condition to check
2036 * @param mixed $value used in conjunction with condition.
2038 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
2039 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2040 $this->_dependencies[$dependentOn] = array();
2042 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2043 $this->_dependencies[$dependentOn][$condition] = array();
2045 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2046 $this->_dependencies[$dependentOn][$condition][$value] = array();
2048 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2052 * Registers button as no submit button
2054 * @param string $buttonname name of the button
2056 function registerNoSubmitButton($buttonname){
2057 $this->_noSubmitButtons[]=$buttonname;
2061 * Checks if button is a no submit button, i.e it doesn't submit form
2063 * @param string $buttonname name of the button to check
2064 * @return bool
2066 function isNoSubmitButton($buttonname){
2067 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2071 * Registers a button as cancel button
2073 * @param string $addfieldsname name of the button
2075 function _registerCancelButton($addfieldsname){
2076 $this->_cancelButtons[]=$addfieldsname;
2080 * Displays elements without HTML input tags.
2081 * This method is different to freeze() in that it makes sure no hidden
2082 * elements are included in the form.
2083 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2085 * This function also removes all previously defined rules.
2087 * @param string|array $elementList array or string of element(s) to be frozen
2088 * @return object|bool if element list is not empty then return error object, else true
2090 function hardFreeze($elementList=null)
2092 if (!isset($elementList)) {
2093 $this->_freezeAll = true;
2094 $elementList = array();
2095 } else {
2096 if (!is_array($elementList)) {
2097 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2099 $elementList = array_flip($elementList);
2102 foreach (array_keys($this->_elements) as $key) {
2103 $name = $this->_elements[$key]->getName();
2104 if ($this->_freezeAll || isset($elementList[$name])) {
2105 $this->_elements[$key]->freeze();
2106 $this->_elements[$key]->setPersistantFreeze(false);
2107 unset($elementList[$name]);
2109 // remove all rules
2110 $this->_rules[$name] = array();
2111 // if field is required, remove the rule
2112 $unset = array_search($name, $this->_required);
2113 if ($unset !== false) {
2114 unset($this->_required[$unset]);
2119 if (!empty($elementList)) {
2120 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);
2122 return true;
2126 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2128 * This function also removes all previously defined rules of elements it freezes.
2130 * @throws HTML_QuickForm_Error
2131 * @param array $elementList array or string of element(s) not to be frozen
2132 * @return bool returns true
2134 function hardFreezeAllVisibleExcept($elementList)
2136 $elementList = array_flip($elementList);
2137 foreach (array_keys($this->_elements) as $key) {
2138 $name = $this->_elements[$key]->getName();
2139 $type = $this->_elements[$key]->getType();
2141 if ($type == 'hidden'){
2142 // leave hidden types as they are
2143 } elseif (!isset($elementList[$name])) {
2144 $this->_elements[$key]->freeze();
2145 $this->_elements[$key]->setPersistantFreeze(false);
2147 // remove all rules
2148 $this->_rules[$name] = array();
2149 // if field is required, remove the rule
2150 $unset = array_search($name, $this->_required);
2151 if ($unset !== false) {
2152 unset($this->_required[$unset]);
2156 return true;
2160 * Tells whether the form was already submitted
2162 * This is useful since the _submitFiles and _submitValues arrays
2163 * may be completely empty after the trackSubmit value is removed.
2165 * @return bool
2167 function isSubmitted()
2169 return parent::isSubmitted() && (!$this->isFrozen());
2174 * MoodleQuickForm renderer
2176 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2177 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2179 * Stylesheet is part of standard theme and should be automatically included.
2181 * @package core_form
2182 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2185 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2187 /** @var array Element template array */
2188 var $_elementTemplates;
2191 * Template used when opening a hidden fieldset
2192 * (i.e. a fieldset that is opened when there is no header element)
2193 * @var string
2195 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2197 /** @var string Header Template string */
2198 var $_headerTemplate =
2199 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2201 /** @var string Template used when opening a fieldset */
2202 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2204 /** @var string Template used when closing a fieldset */
2205 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2207 /** @var string Required Note template string */
2208 var $_requiredNoteTemplate =
2209 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2211 /** @var array list of elements which are marked as advance and will be grouped together */
2212 var $_advancedElements = array();
2214 /** @var int Whether to display advanced elements (on page load) 1 => show, 0 => hide */
2215 var $_showAdvanced;
2218 * Constructor
2220 function MoodleQuickForm_Renderer(){
2221 // switch next two lines for ol li containers for form items.
2222 // $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>');
2223 $this->_elementTemplates = array(
2224 '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>',
2226 '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>',
2228 '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>',
2230 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2232 'nodisplay'=>'');
2234 parent::HTML_QuickForm_Renderer_Tableless();
2238 * Set element's as adavance element
2240 * @param array $elements form elements which needs to be grouped as advance elements.
2242 function setAdvancedElements($elements){
2243 $this->_advancedElements = $elements;
2247 * What to do when starting the form
2249 * @param MoodleQuickForm $form reference of the form
2251 function startForm(&$form){
2252 global $PAGE;
2253 $this->_reqHTML = $form->getReqHTML();
2254 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2255 $this->_advancedHTML = $form->getAdvancedHTML();
2256 $this->_showAdvanced = $form->getShowAdvanced();
2257 parent::startForm($form);
2258 if ($form->isFrozen()){
2259 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2260 } else {
2261 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2262 $this->_hiddenHtml .= $form->_pageparams;
2265 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2266 'M.core_formchangechecker.init',
2267 array(array(
2268 'formid' => $form->getAttribute('id')
2271 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2275 * Create advance group of elements
2277 * @param object $group Passed by reference
2278 * @param bool $required if input is required field
2279 * @param string $error error message to display
2281 function startGroup(&$group, $required, $error){
2282 // Make sure the element has an id.
2283 $group->_generateId();
2285 if (method_exists($group, 'getElementTemplateType')){
2286 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2287 }else{
2288 $html = $this->_elementTemplates['default'];
2291 if ($this->_showAdvanced){
2292 $advclass = ' advanced';
2293 } else {
2294 $advclass = ' advanced hide';
2296 if (isset($this->_advancedElements[$group->getName()])){
2297 $html =str_replace(' {advanced}', $advclass, $html);
2298 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2299 } else {
2300 $html =str_replace(' {advanced}', '', $html);
2301 $html =str_replace('{advancedimg}', '', $html);
2303 if (method_exists($group, 'getHelpButton')){
2304 $html =str_replace('{help}', $group->getHelpButton(), $html);
2305 }else{
2306 $html =str_replace('{help}', '', $html);
2308 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2309 $html =str_replace('{name}', $group->getName(), $html);
2310 $html =str_replace('{type}', 'fgroup', $html);
2312 $this->_templates[$group->getName()]=$html;
2313 // Fix for bug in tableless quickforms that didn't allow you to stop a
2314 // fieldset before a group of elements.
2315 // if the element name indicates the end of a fieldset, close the fieldset
2316 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2317 && $this->_fieldsetsOpen > 0
2319 $this->_html .= $this->_closeFieldsetTemplate;
2320 $this->_fieldsetsOpen--;
2322 parent::startGroup($group, $required, $error);
2325 * Renders element
2327 * @param HTML_QuickForm_element $element element
2328 * @param bool $required if input is required field
2329 * @param string $error error message to display
2331 function renderElement(&$element, $required, $error){
2332 // Make sure the element has an id.
2333 $element->_generateId();
2335 //adding stuff to place holders in template
2336 //check if this is a group element first
2337 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2338 // so it gets substitutions for *each* element
2339 $html = $this->_groupElementTemplate;
2341 elseif (method_exists($element, 'getElementTemplateType')){
2342 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2343 }else{
2344 $html = $this->_elementTemplates['default'];
2346 if ($this->_showAdvanced){
2347 $advclass = ' advanced';
2348 } else {
2349 $advclass = ' advanced hide';
2351 if (isset($this->_advancedElements[$element->getName()])){
2352 $html =str_replace(' {advanced}', $advclass, $html);
2353 } else {
2354 $html =str_replace(' {advanced}', '', $html);
2356 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2357 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2358 } else {
2359 $html =str_replace('{advancedimg}', '', $html);
2361 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2362 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2363 $html =str_replace('{name}', $element->getName(), $html);
2364 if (method_exists($element, 'getHelpButton')){
2365 $html = str_replace('{help}', $element->getHelpButton(), $html);
2366 }else{
2367 $html = str_replace('{help}', '', $html);
2370 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2371 $this->_groupElementTemplate = $html;
2373 elseif (!isset($this->_templates[$element->getName()])) {
2374 $this->_templates[$element->getName()] = $html;
2377 parent::renderElement($element, $required, $error);
2381 * Called when visiting a form, after processing all form elements
2382 * Adds required note, form attributes, validation javascript and form content.
2384 * @global moodle_page $PAGE
2385 * @param moodleform $form Passed by reference
2387 function finishForm(&$form){
2388 global $PAGE;
2389 if ($form->isFrozen()){
2390 $this->_hiddenHtml = '';
2392 parent::finishForm($form);
2393 if (!$form->isFrozen()) {
2394 $args = $form->getLockOptionObject();
2395 if (count($args[1]) > 0) {
2396 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2401 * Called when visiting a header element
2403 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2404 * @global moodle_page $PAGE
2406 function renderHeader(&$header) {
2407 global $PAGE;
2409 $name = $header->getName();
2411 $id = empty($name) ? '' : ' id="' . $name . '"';
2412 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2413 if (is_null($header->_text)) {
2414 $header_html = '';
2415 } elseif (!empty($name) && isset($this->_templates[$name])) {
2416 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2417 } else {
2418 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2421 if (isset($this->_advancedElements[$name])){
2422 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2423 $elementName='mform_showadvanced';
2424 if ($this->_showAdvanced==0){
2425 $buttonlabel = get_string('showadvanced', 'form');
2426 } else {
2427 $buttonlabel = get_string('hideadvanced', 'form');
2429 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2430 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2431 $header_html = str_replace('{button}', $button, $header_html);
2432 } else {
2433 $header_html =str_replace('{advancedimg}', '', $header_html);
2434 $header_html = str_replace('{button}', '', $header_html);
2437 if ($this->_fieldsetsOpen > 0) {
2438 $this->_html .= $this->_closeFieldsetTemplate;
2439 $this->_fieldsetsOpen--;
2442 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2443 if ($this->_showAdvanced){
2444 $advclass = ' class="advanced"';
2445 } else {
2446 $advclass = ' class="advanced hide"';
2448 if (isset($this->_advancedElements[$name])){
2449 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2450 } else {
2451 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2453 $this->_html .= $openFieldsetTemplate . $header_html;
2454 $this->_fieldsetsOpen++;
2458 * Return Array of element names that indicate the end of a fieldset
2460 * @return array
2462 function getStopFieldsetElements(){
2463 return $this->_stopFieldsetElements;
2468 * Required elements validation
2470 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2472 * @package core_form
2473 * @category form
2474 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2477 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2479 * Checks if an element is not empty.
2480 * This is a server-side validation, it works for both text fields and editor fields
2482 * @param string $value Value to check
2483 * @param int|string|array $options Not used yet
2484 * @return bool true if value is not empty
2486 function validate($value, $options = null) {
2487 global $CFG;
2488 if (is_array($value) && array_key_exists('text', $value)) {
2489 $value = $value['text'];
2491 if (is_array($value)) {
2492 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2493 $value = implode('', $value);
2495 $stripvalues = array(
2496 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2497 '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
2499 if (!empty($CFG->strictformsrequired)) {
2500 $value = preg_replace($stripvalues, '', (string)$value);
2502 if ((string)$value == '') {
2503 return false;
2505 return true;
2509 * This function returns Javascript code used to build client-side validation.
2510 * It checks if an element is not empty.
2512 * @param int $format format of data which needs to be validated.
2513 * @return array
2515 function getValidationScript($format = null) {
2516 global $CFG;
2517 if (!empty($CFG->strictformsrequired)) {
2518 if (!empty($format) && $format == FORMAT_HTML) {
2519 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2520 } else {
2521 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2523 } else {
2524 return array('', "{jsVar} == ''");
2530 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2531 * @name $_HTML_QuickForm_default_renderer
2533 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2535 /** Please keep this list in alphabetical order. */
2536 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2537 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2538 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2539 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2540 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2541 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2542 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2543 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2544 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2545 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2546 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2547 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2548 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2549 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2550 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2551 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2552 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2553 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2554 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2555 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2556 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2557 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2558 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2559 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2560 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2561 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2562 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2563 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2564 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2565 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2566 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2567 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2568 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2569 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2570 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2571 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2572 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2574 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");