Merge branch 'MDL-38315-m24' of git://github.com/sammarshallou/moodle into MOODLE_24_...
[moodle.git] / lib / formslib.php
blob03c8c334e83e6f975f4d884d713c543ffb1451da
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
20 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
21 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
22 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
23 * and validation.
25 * See examples of use of this library in course/edit.php and course/edit_form.php
27 * A few notes :
28 * form definition is used for both printing of form and processing and should be the same
29 * for both or you may lose some submitted data which won't be let through.
30 * you should be using setType for every form element except select, radio or checkbox
31 * elements, these elements clean themselves.
33 * @package core_form
34 * @copyright 2006 Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 defined('MOODLE_INTERNAL') || die();
40 /** setup.php includes our hacked pear libs first */
41 require_once 'HTML/QuickForm.php';
42 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
43 require_once 'HTML/QuickForm/Renderer/Tableless.php';
44 require_once 'HTML/QuickForm/Rule.php';
46 require_once $CFG->libdir.'/filelib.php';
48 /**
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
53 /**
54 * Callback called when PEAR throws an error
56 * @param PEAR_Error $error
58 function pear_handle_error($error){
59 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
60 echo '<br /> <strong>Backtrace </strong>:';
61 print_object($error->backtrace);
64 if (!empty($CFG->debug) and ($CFG->debug >= DEBUG_ALL or $CFG->debug == -1)){
65 //TODO: this is a wrong place to init PEAR!
66 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
67 $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
70 /**
71 * Initalize javascript for date type form element
73 * @staticvar bool $done make sure it gets initalize once.
74 * @global moodle_page $PAGE
76 function form_init_date_js() {
77 global $PAGE;
78 static $done = false;
79 if (!$done) {
80 $module = 'moodle-form-dateselector';
81 $function = 'M.form.dateselector.init_date_selectors';
82 $config = array(array(
83 'firstdayofweek' => get_string('firstdayofweek', 'langconfig'),
84 'mon' => date_format_string(strtotime("Monday"), '%a', 99),
85 'tue' => date_format_string(strtotime("Tuesday"), '%a', 99),
86 'wed' => date_format_string(strtotime("Wednesday"), '%a', 99),
87 'thu' => date_format_string(strtotime("Thursday"), '%a', 99),
88 'fri' => date_format_string(strtotime("Friday"), '%a', 99),
89 'sat' => date_format_string(strtotime("Saturday"), '%a', 99),
90 'sun' => date_format_string(strtotime("Sunday"), '%a', 99),
91 'january' => date_format_string(strtotime("January 1"), '%B', 99),
92 'february' => date_format_string(strtotime("February 1"), '%B', 99),
93 'march' => date_format_string(strtotime("March 1"), '%B', 99),
94 'april' => date_format_string(strtotime("April 1"), '%B', 99),
95 'may' => date_format_string(strtotime("May 1"), '%B', 99),
96 'june' => date_format_string(strtotime("June 1"), '%B', 99),
97 'july' => date_format_string(strtotime("July 1"), '%B', 99),
98 'august' => date_format_string(strtotime("August 1"), '%B', 99),
99 'september' => date_format_string(strtotime("September 1"), '%B', 99),
100 'october' => date_format_string(strtotime("October 1"), '%B', 99),
101 'november' => date_format_string(strtotime("November 1"), '%B', 99),
102 'december' => date_format_string(strtotime("December 1"), '%B', 99)
104 $PAGE->requires->yui_module($module, $function, $config);
105 $done = true;
110 * Wrapper that separates quickforms syntax from moodle code
112 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
113 * use this class you should write a class definition which extends this class or a more specific
114 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
116 * You will write your own definition() method which performs the form set up.
118 * @package core_form
119 * @copyright 2006 Jamie Pratt <me@jamiep.org>
120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
121 * @todo MDL-19380 rethink the file scanning
123 abstract class moodleform {
124 /** @var string name of the form */
125 protected $_formname; // form name
127 /** @var MoodleQuickForm quickform object definition */
128 protected $_form;
130 /** @var array globals workaround */
131 protected $_customdata;
133 /** @var object definition_after_data executed flag */
134 protected $_definition_finalized = false;
137 * The constructor function calls the abstract function definition() and it will then
138 * process and clean and attempt to validate incoming data.
140 * It will call your custom validate method to validate data and will also check any rules
141 * you have specified in definition using addRule
143 * The name of the form (id attribute of the form) is automatically generated depending on
144 * the name you gave the class extending moodleform. You should call your class something
145 * like
147 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
148 * current url. If a moodle_url object then outputs params as hidden variables.
149 * @param mixed $customdata if your form defintion method needs access to data such as $course
150 * $cm, etc. to construct the form definition then pass it in this array. You can
151 * use globals for somethings.
152 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
153 * be merged and used as incoming data to the form.
154 * @param string $target target frame for form submission. You will rarely use this. Don't use
155 * it if you don't need to as the target attribute is deprecated in xhtml strict.
156 * @param mixed $attributes you can pass a string of html attributes here or an array.
157 * @param bool $editable
159 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
160 global $CFG, $FULLME;
161 // no standard mform in moodle should allow autocomplete with the exception of user signup
162 if (empty($attributes)) {
163 $attributes = array('autocomplete'=>'off');
164 } else if (is_array($attributes)) {
165 $attributes['autocomplete'] = 'off';
166 } else {
167 if (strpos($attributes, 'autocomplete') === false) {
168 $attributes .= ' autocomplete="off" ';
172 if (empty($action)){
173 // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
174 $action = strip_querystring($FULLME);
175 if (!empty($CFG->sslproxy)) {
176 // return only https links when using SSL proxy
177 $action = preg_replace('/^http:/', 'https:', $action, 1);
179 //TODO: use following instead of FULLME - see MDL-33015
180 //$action = strip_querystring(qualified_me());
182 // Assign custom data first, so that get_form_identifier can use it.
183 $this->_customdata = $customdata;
184 $this->_formname = $this->get_form_identifier();
186 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
187 if (!$editable){
188 $this->_form->hardFreeze();
191 $this->definition();
193 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
194 $this->_form->setType('sesskey', PARAM_RAW);
195 $this->_form->setDefault('sesskey', sesskey());
196 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
197 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
198 $this->_form->setDefault('_qf__'.$this->_formname, 1);
199 $this->_form->_setDefaultRuleMessages();
201 // we have to know all input types before processing submission ;-)
202 $this->_process_submission($method);
206 * It should returns unique identifier for the form.
207 * Currently it will return class name, but in case two same forms have to be
208 * rendered on same page then override function to get unique form identifier.
209 * e.g This is used on multiple self enrollments page.
211 * @return string form identifier.
213 protected function get_form_identifier() {
214 return get_class($this);
218 * To autofocus on first form element or first element with error.
220 * @param string $name if this is set then the focus is forced to a field with this name
221 * @return string javascript to select form element with first error or
222 * first element if no errors. Use this as a parameter
223 * when calling print_header
225 function focus($name=NULL) {
226 $form =& $this->_form;
227 $elkeys = array_keys($form->_elementIndex);
228 $error = false;
229 if (isset($form->_errors) && 0 != count($form->_errors)){
230 $errorkeys = array_keys($form->_errors);
231 $elkeys = array_intersect($elkeys, $errorkeys);
232 $error = true;
235 if ($error or empty($name)) {
236 $names = array();
237 while (empty($names) and !empty($elkeys)) {
238 $el = array_shift($elkeys);
239 $names = $form->_getElNamesRecursive($el);
241 if (!empty($names)) {
242 $name = array_shift($names);
246 $focus = '';
247 if (!empty($name)) {
248 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
251 return $focus;
255 * Internal method. Alters submitted data to be suitable for quickforms processing.
256 * Must be called when the form is fully set up.
258 * @param string $method name of the method which alters submitted data
260 function _process_submission($method) {
261 $submission = array();
262 if ($method == 'post') {
263 if (!empty($_POST)) {
264 $submission = $_POST;
266 } else {
267 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
270 // following trick is needed to enable proper sesskey checks when using GET forms
271 // the _qf__.$this->_formname serves as a marker that form was actually submitted
272 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
273 if (!confirm_sesskey()) {
274 print_error('invalidsesskey');
276 $files = $_FILES;
277 } else {
278 $submission = array();
279 $files = array();
282 $this->_form->updateSubmission($submission, $files);
286 * Internal method. Validates all old-style deprecated uploaded files.
287 * The new way is to upload files via repository api.
289 * @param array $files list of files to be validated
290 * @return bool|array Success or an array of errors
292 function _validate_files(&$files) {
293 global $CFG, $COURSE;
295 $files = array();
297 if (empty($_FILES)) {
298 // we do not need to do any checks because no files were submitted
299 // note: server side rules do not work for files - use custom verification in validate() instead
300 return true;
303 $errors = array();
304 $filenames = array();
306 // now check that we really want each file
307 foreach ($_FILES as $elname=>$file) {
308 $required = $this->_form->isElementRequired($elname);
310 if ($file['error'] == 4 and $file['size'] == 0) {
311 if ($required) {
312 $errors[$elname] = get_string('required');
314 unset($_FILES[$elname]);
315 continue;
318 if (!empty($file['error'])) {
319 $errors[$elname] = file_get_upload_error($file['error']);
320 unset($_FILES[$elname]);
321 continue;
324 if (!is_uploaded_file($file['tmp_name'])) {
325 // TODO: improve error message
326 $errors[$elname] = get_string('error');
327 unset($_FILES[$elname]);
328 continue;
331 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
332 // hmm, this file was not requested
333 unset($_FILES[$elname]);
334 continue;
338 // TODO: rethink the file scanning MDL-19380
339 if ($CFG->runclamonupload) {
340 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
341 $errors[$elname] = $_FILES[$elname]['uploadlog'];
342 unset($_FILES[$elname]);
343 continue;
347 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
348 if ($filename === '') {
349 // TODO: improve error message - wrong chars
350 $errors[$elname] = get_string('error');
351 unset($_FILES[$elname]);
352 continue;
354 if (in_array($filename, $filenames)) {
355 // TODO: improve error message - duplicate name
356 $errors[$elname] = get_string('error');
357 unset($_FILES[$elname]);
358 continue;
360 $filenames[] = $filename;
361 $_FILES[$elname]['name'] = $filename;
363 $files[$elname] = $_FILES[$elname]['tmp_name'];
366 // return errors if found
367 if (count($errors) == 0){
368 return true;
370 } else {
371 $files = array();
372 return $errors;
377 * Internal method. Validates filepicker and filemanager files if they are
378 * set as required fields. Also, sets the error message if encountered one.
380 * @return bool|array with errors
382 protected function validate_draft_files() {
383 global $USER;
384 $mform =& $this->_form;
386 $errors = array();
387 //Go through all the required elements and make sure you hit filepicker or
388 //filemanager element.
389 foreach ($mform->_rules as $elementname => $rules) {
390 $elementtype = $mform->getElementType($elementname);
391 //If element is of type filepicker then do validation
392 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
393 //Check if rule defined is required rule
394 foreach ($rules as $rule) {
395 if ($rule['type'] == 'required') {
396 $draftid = (int)$mform->getSubmitValue($elementname);
397 $fs = get_file_storage();
398 $context = context_user::instance($USER->id);
399 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
400 $errors[$elementname] = $rule['message'];
406 // Check all the filemanager elements to make sure they do not have too many
407 // files in them.
408 foreach ($mform->_elements as $element) {
409 if ($element->_type == 'filemanager') {
410 $maxfiles = $element->getMaxfiles();
411 if ($maxfiles > 0) {
412 $draftid = (int)$element->getValue();
413 $fs = get_file_storage();
414 $context = context_user::instance($USER->id);
415 $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
416 if (count($files) > $maxfiles) {
417 $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
422 if (empty($errors)) {
423 return true;
424 } else {
425 return $errors;
430 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
431 * form definition (new entry form); this function is used to load in data where values
432 * already exist and data is being edited (edit entry form).
434 * note: $slashed param removed
436 * @param stdClass|array $default_values object or array of default values
438 function set_data($default_values) {
439 if (is_object($default_values)) {
440 $default_values = (array)$default_values;
442 $this->_form->setDefaults($default_values);
446 * Check that form was submitted. Does not check validity of submitted data.
448 * @return bool true if form properly submitted
450 function is_submitted() {
451 return $this->_form->isSubmitted();
455 * Checks if button pressed is not for submitting the form
457 * @staticvar bool $nosubmit keeps track of no submit button
458 * @return bool
460 function no_submit_button_pressed(){
461 static $nosubmit = null; // one check is enough
462 if (!is_null($nosubmit)){
463 return $nosubmit;
465 $mform =& $this->_form;
466 $nosubmit = false;
467 if (!$this->is_submitted()){
468 return false;
470 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
471 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
472 $nosubmit = true;
473 break;
476 return $nosubmit;
481 * Check that form data is valid.
482 * You should almost always use this, rather than {@link validate_defined_fields}
484 * @return bool true if form data valid
486 function is_validated() {
487 //finalize the form definition before any processing
488 if (!$this->_definition_finalized) {
489 $this->_definition_finalized = true;
490 $this->definition_after_data();
493 return $this->validate_defined_fields();
497 * Validate the form.
499 * You almost always want to call {@link is_validated} instead of this
500 * because it calls {@link definition_after_data} first, before validating the form,
501 * which is what you want in 99% of cases.
503 * This is provided as a separate function for those special cases where
504 * you want the form validated before definition_after_data is called
505 * for example, to selectively add new elements depending on a no_submit_button press,
506 * but only when the form is valid when the no_submit_button is pressed,
508 * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
509 * is NOT to validate the form when a no submit button has been pressed.
510 * pass true here to override this behaviour
512 * @return bool true if form data valid
514 function validate_defined_fields($validateonnosubmit=false) {
515 static $validated = null; // one validation is enough
516 $mform =& $this->_form;
517 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
518 return false;
519 } elseif ($validated === null) {
520 $internal_val = $mform->validate();
522 $files = array();
523 $file_val = $this->_validate_files($files);
524 //check draft files for validation and flag them if required files
525 //are not in draft area.
526 $draftfilevalue = $this->validate_draft_files();
528 if ($file_val !== true && $draftfilevalue !== true) {
529 $file_val = array_merge($file_val, $draftfilevalue);
530 } else if ($draftfilevalue !== true) {
531 $file_val = $draftfilevalue;
532 } //default is file_val, so no need to assign.
534 if ($file_val !== true) {
535 if (!empty($file_val)) {
536 foreach ($file_val as $element=>$msg) {
537 $mform->setElementError($element, $msg);
540 $file_val = false;
543 $data = $mform->exportValues();
544 $moodle_val = $this->validation($data, $files);
545 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
546 // non-empty array means errors
547 foreach ($moodle_val as $element=>$msg) {
548 $mform->setElementError($element, $msg);
550 $moodle_val = false;
552 } else {
553 // anything else means validation ok
554 $moodle_val = true;
557 $validated = ($internal_val and $moodle_val and $file_val);
559 return $validated;
563 * Return true if a cancel button has been pressed resulting in the form being submitted.
565 * @return bool true if a cancel button has been pressed
567 function is_cancelled(){
568 $mform =& $this->_form;
569 if ($mform->isSubmitted()){
570 foreach ($mform->_cancelButtons as $cancelbutton){
571 if (optional_param($cancelbutton, 0, PARAM_RAW)){
572 return true;
576 return false;
580 * Return submitted data if properly submitted or returns NULL if validation fails or
581 * if there is no submitted data.
583 * note: $slashed param removed
585 * @return object submitted data; NULL if not valid or not submitted or cancelled
587 function get_data() {
588 $mform =& $this->_form;
590 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
591 $data = $mform->exportValues();
592 unset($data['sesskey']); // we do not need to return sesskey
593 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
594 if (empty($data)) {
595 return NULL;
596 } else {
597 return (object)$data;
599 } else {
600 return NULL;
605 * Return submitted data without validation or NULL if there is no submitted data.
606 * note: $slashed param removed
608 * @return object submitted data; NULL if not submitted
610 function get_submitted_data() {
611 $mform =& $this->_form;
613 if ($this->is_submitted()) {
614 $data = $mform->exportValues();
615 unset($data['sesskey']); // we do not need to return sesskey
616 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
617 if (empty($data)) {
618 return NULL;
619 } else {
620 return (object)$data;
622 } else {
623 return NULL;
628 * Save verified uploaded files into directory. Upload process can be customised from definition()
630 * @deprecated since Moodle 2.0
631 * @todo MDL-31294 remove this api
632 * @see moodleform::save_stored_file()
633 * @see moodleform::save_file()
634 * @param string $destination path where file should be stored
635 * @return bool Always false
637 function save_files($destination) {
638 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
639 return false;
643 * Returns name of uploaded file.
645 * @param string $elname first element if null
646 * @return string|bool false in case of failure, string if ok
648 function get_new_filename($elname=null) {
649 global $USER;
651 if (!$this->is_submitted() or !$this->is_validated()) {
652 return false;
655 if (is_null($elname)) {
656 if (empty($_FILES)) {
657 return false;
659 reset($_FILES);
660 $elname = key($_FILES);
663 if (empty($elname)) {
664 return false;
667 $element = $this->_form->getElement($elname);
669 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
670 $values = $this->_form->exportValues($elname);
671 if (empty($values[$elname])) {
672 return false;
674 $draftid = $values[$elname];
675 $fs = get_file_storage();
676 $context = context_user::instance($USER->id);
677 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
678 return false;
680 $file = reset($files);
681 return $file->get_filename();
684 if (!isset($_FILES[$elname])) {
685 return false;
688 return $_FILES[$elname]['name'];
692 * Save file to standard filesystem
694 * @param string $elname name of element
695 * @param string $pathname full path name of file
696 * @param bool $override override file if exists
697 * @return bool success
699 function save_file($elname, $pathname, $override=false) {
700 global $USER;
702 if (!$this->is_submitted() or !$this->is_validated()) {
703 return false;
705 if (file_exists($pathname)) {
706 if ($override) {
707 if (!@unlink($pathname)) {
708 return false;
710 } else {
711 return false;
715 $element = $this->_form->getElement($elname);
717 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
718 $values = $this->_form->exportValues($elname);
719 if (empty($values[$elname])) {
720 return false;
722 $draftid = $values[$elname];
723 $fs = get_file_storage();
724 $context = context_user::instance($USER->id);
725 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
726 return false;
728 $file = reset($files);
730 return $file->copy_content_to($pathname);
732 } else if (isset($_FILES[$elname])) {
733 return copy($_FILES[$elname]['tmp_name'], $pathname);
736 return false;
740 * Returns a temporary file, do not forget to delete after not needed any more.
742 * @param string $elname name of the elmenet
743 * @return string|bool either string or false
745 function save_temp_file($elname) {
746 if (!$this->get_new_filename($elname)) {
747 return false;
749 if (!$dir = make_temp_directory('forms')) {
750 return false;
752 if (!$tempfile = tempnam($dir, 'tempup_')) {
753 return false;
755 if (!$this->save_file($elname, $tempfile, true)) {
756 // something went wrong
757 @unlink($tempfile);
758 return false;
761 return $tempfile;
765 * Get draft files of a form element
766 * This is a protected method which will be used only inside moodleforms
768 * @param string $elname name of element
769 * @return array|bool|null
771 protected function get_draft_files($elname) {
772 global $USER;
774 if (!$this->is_submitted()) {
775 return false;
778 $element = $this->_form->getElement($elname);
780 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
781 $values = $this->_form->exportValues($elname);
782 if (empty($values[$elname])) {
783 return false;
785 $draftid = $values[$elname];
786 $fs = get_file_storage();
787 $context = context_user::instance($USER->id);
788 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
789 return null;
791 return $files;
793 return null;
797 * Save file to local filesystem pool
799 * @param string $elname name of element
800 * @param int $newcontextid id of context
801 * @param string $newcomponent name of the component
802 * @param string $newfilearea name of file area
803 * @param int $newitemid item id
804 * @param string $newfilepath path of file where it get stored
805 * @param string $newfilename use specified filename, if not specified name of uploaded file used
806 * @param bool $overwrite overwrite file if exists
807 * @param int $newuserid new userid if required
808 * @return mixed stored_file object or false if error; may throw exception if duplicate found
810 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
811 $newfilename=null, $overwrite=false, $newuserid=null) {
812 global $USER;
814 if (!$this->is_submitted() or !$this->is_validated()) {
815 return false;
818 if (empty($newuserid)) {
819 $newuserid = $USER->id;
822 $element = $this->_form->getElement($elname);
823 $fs = get_file_storage();
825 if ($element instanceof MoodleQuickForm_filepicker) {
826 $values = $this->_form->exportValues($elname);
827 if (empty($values[$elname])) {
828 return false;
830 $draftid = $values[$elname];
831 $context = context_user::instance($USER->id);
832 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
833 return false;
835 $file = reset($files);
836 if (is_null($newfilename)) {
837 $newfilename = $file->get_filename();
840 if ($overwrite) {
841 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
842 if (!$oldfile->delete()) {
843 return false;
848 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
849 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
850 return $fs->create_file_from_storedfile($file_record, $file);
852 } else if (isset($_FILES[$elname])) {
853 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
855 if ($overwrite) {
856 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
857 if (!$oldfile->delete()) {
858 return false;
863 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
864 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
865 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
868 return false;
872 * Get content of uploaded file.
874 * @param string $elname name of file upload element
875 * @return string|bool false in case of failure, string if ok
877 function get_file_content($elname) {
878 global $USER;
880 if (!$this->is_submitted() or !$this->is_validated()) {
881 return false;
884 $element = $this->_form->getElement($elname);
886 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
887 $values = $this->_form->exportValues($elname);
888 if (empty($values[$elname])) {
889 return false;
891 $draftid = $values[$elname];
892 $fs = get_file_storage();
893 $context = context_user::instance($USER->id);
894 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
895 return false;
897 $file = reset($files);
899 return $file->get_content();
901 } else if (isset($_FILES[$elname])) {
902 return file_get_contents($_FILES[$elname]['tmp_name']);
905 return false;
909 * Print html form.
911 function display() {
912 //finalize the form definition if not yet done
913 if (!$this->_definition_finalized) {
914 $this->_definition_finalized = true;
915 $this->definition_after_data();
917 $this->_form->display();
921 * Form definition. Abstract method - always override!
923 protected abstract function definition();
926 * Dummy stub method - override if you need to setup the form depending on current
927 * values. This method is called after definition(), data submission and set_data().
928 * All form setup that is dependent on form values should go in here.
930 function definition_after_data(){
934 * Dummy stub method - override if you needed to perform some extra validation.
935 * If there are errors return array of errors ("fieldname"=>"error message"),
936 * otherwise true if ok.
938 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
940 * @param array $data array of ("fieldname"=>value) of submitted data
941 * @param array $files array of uploaded files "element_name"=>tmp_file_path
942 * @return array of "element_name"=>"error_description" if there are errors,
943 * or an empty array if everything is OK (true allowed for backwards compatibility too).
945 function validation($data, $files) {
946 return array();
950 * Helper used by {@link repeat_elements()}.
952 * @param int $i the index of this element.
953 * @param HTML_QuickForm_element $elementclone
954 * @param array $namecloned array of names
956 function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
957 $name = $elementclone->getName();
958 $namecloned[] = $name;
960 if (!empty($name)) {
961 $elementclone->setName($name."[$i]");
964 if (is_a($elementclone, 'HTML_QuickForm_header')) {
965 $value = $elementclone->_text;
966 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
968 } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
969 $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
971 } else {
972 $value=$elementclone->getLabel();
973 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
978 * Method to add a repeating group of elements to a form.
980 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
981 * @param int $repeats no of times to repeat elements initially
982 * @param array $options Array of options to apply to elements. Array keys are element names.
983 * This is an array of arrays. The second sets of keys are the option types for the elements :
984 * 'default' - default value is value
985 * 'type' - PARAM_* constant is value
986 * 'helpbutton' - helpbutton params array is value
987 * 'disabledif' - last three moodleform::disabledIf()
988 * params are value as an array
989 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
990 * @param string $addfieldsname name for button to add more fields
991 * @param int $addfieldsno how many fields to add at a time
992 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
993 * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
994 * @return int no of repeats of element in this page
996 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
997 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
998 if ($addstring===null){
999 $addstring = get_string('addfields', 'form', $addfieldsno);
1000 } else {
1001 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1003 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
1004 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
1005 if (!empty($addfields)){
1006 $repeats += $addfieldsno;
1008 $mform =& $this->_form;
1009 $mform->registerNoSubmitButton($addfieldsname);
1010 $mform->addElement('hidden', $repeathiddenname, $repeats);
1011 $mform->setType($repeathiddenname, PARAM_INT);
1012 //value not to be overridden by submitted value
1013 $mform->setConstants(array($repeathiddenname=>$repeats));
1014 $namecloned = array();
1015 for ($i = 0; $i < $repeats; $i++) {
1016 foreach ($elementobjs as $elementobj){
1017 $elementclone = fullclone($elementobj);
1018 $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1020 if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1021 foreach ($elementclone->getElements() as $el) {
1022 $this->repeat_elements_fix_clone($i, $el, $namecloned);
1024 $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1027 $mform->addElement($elementclone);
1030 for ($i=0; $i<$repeats; $i++) {
1031 foreach ($options as $elementname => $elementoptions){
1032 $pos=strpos($elementname, '[');
1033 if ($pos!==FALSE){
1034 $realelementname = substr($elementname, 0, $pos)."[$i]";
1035 $realelementname .= substr($elementname, $pos);
1036 }else {
1037 $realelementname = $elementname."[$i]";
1039 foreach ($elementoptions as $option => $params){
1041 switch ($option){
1042 case 'default' :
1043 $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1044 break;
1045 case 'helpbutton' :
1046 $params = array_merge(array($realelementname), $params);
1047 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1048 break;
1049 case 'disabledif' :
1050 foreach ($namecloned as $num => $name){
1051 if ($params[0] == $name){
1052 $params[0] = $params[0]."[$i]";
1053 break;
1056 $params = array_merge(array($realelementname), $params);
1057 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1058 break;
1059 case 'rule' :
1060 if (is_string($params)){
1061 $params = array(null, $params, null, 'client');
1063 $params = array_merge(array($realelementname), $params);
1064 call_user_func_array(array(&$mform, 'addRule'), $params);
1065 break;
1066 case 'type' :
1067 //Type should be set only once
1068 if (!isset($mform->_types[$elementname])) {
1069 $mform->setType($elementname, $params);
1071 break;
1076 $mform->addElement('submit', $addfieldsname, $addstring);
1078 if (!$addbuttoninside) {
1079 $mform->closeHeaderBefore($addfieldsname);
1082 return $repeats;
1086 * Adds a link/button that controls the checked state of a group of checkboxes.
1088 * @param int $groupid The id of the group of advcheckboxes this element controls
1089 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1090 * @param array $attributes associative array of HTML attributes
1091 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1093 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1094 global $CFG, $PAGE;
1096 // Name of the controller button
1097 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1098 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1099 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1101 // Set the default text if none was specified
1102 if (empty($text)) {
1103 $text = get_string('selectallornone', 'form');
1106 $mform = $this->_form;
1107 $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1108 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1110 $newselectvalue = $selectvalue;
1111 if (is_null($selectvalue)) {
1112 $newselectvalue = $originalValue;
1113 } else if (!is_null($contollerbutton)) {
1114 $newselectvalue = (int) !$selectvalue;
1116 // set checkbox state depending on orignal/submitted value by controoler button
1117 if (!is_null($contollerbutton) || is_null($selectvalue)) {
1118 foreach ($mform->_elements as $element) {
1119 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1120 $element->getAttribute('class') == $checkboxgroupclass &&
1121 !$element->isFrozen()) {
1122 $mform->setConstants(array($element->getName() => $newselectvalue));
1127 $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
1128 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1129 $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
1131 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1132 array(
1133 array('groupid' => $groupid,
1134 'checkboxclass' => $checkboxgroupclass,
1135 'checkboxcontroller' => $checkboxcontrollerparam,
1136 'controllerbutton' => $checkboxcontrollername)
1140 require_once("$CFG->libdir/form/submit.php");
1141 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1142 $mform->addElement($submitlink);
1143 $mform->registerNoSubmitButton($checkboxcontrollername);
1144 $mform->setDefault($checkboxcontrollername, $text);
1148 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1149 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1150 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1151 * get data with get_data().
1153 * @param bool $cancel whether to show cancel button, default true
1154 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1156 function add_action_buttons($cancel = true, $submitlabel=null){
1157 if (is_null($submitlabel)){
1158 $submitlabel = get_string('savechanges');
1160 $mform =& $this->_form;
1161 if ($cancel){
1162 //when two elements we need a group
1163 $buttonarray=array();
1164 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1165 $buttonarray[] = &$mform->createElement('cancel');
1166 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1167 $mform->closeHeaderBefore('buttonar');
1168 } else {
1169 //no group needed
1170 $mform->addElement('submit', 'submitbutton', $submitlabel);
1171 $mform->closeHeaderBefore('submitbutton');
1176 * Adds an initialisation call for a standard JavaScript enhancement.
1178 * This function is designed to add an initialisation call for a JavaScript
1179 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1181 * Current options:
1182 * - Selectboxes
1183 * - smartselect: Turns a nbsp indented select box into a custom drop down
1184 * control that supports multilevel and category selection.
1185 * $enhancement = 'smartselect';
1186 * $options = array('selectablecategories' => true|false)
1188 * @since Moodle 2.0
1189 * @param string|element $element form element for which Javascript needs to be initalized
1190 * @param string $enhancement which init function should be called
1191 * @param array $options options passed to javascript
1192 * @param array $strings strings for javascript
1194 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1195 global $PAGE;
1196 if (is_string($element)) {
1197 $element = $this->_form->getElement($element);
1199 if (is_object($element)) {
1200 $element->_generateId();
1201 $elementid = $element->getAttribute('id');
1202 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1203 if (is_array($strings)) {
1204 foreach ($strings as $string) {
1205 if (is_array($string)) {
1206 call_user_method_array('string_for_js', $PAGE->requires, $string);
1207 } else {
1208 $PAGE->requires->string_for_js($string, 'moodle');
1216 * Returns a JS module definition for the mforms JS
1218 * @return array
1220 public static function get_js_module() {
1221 global $CFG;
1222 return array(
1223 'name' => 'mform',
1224 'fullpath' => '/lib/form/form.js',
1225 'requires' => array('base', 'node'),
1226 'strings' => array(
1227 array('showadvanced', 'form'),
1228 array('hideadvanced', 'form')
1235 * MoodleQuickForm implementation
1237 * You never extend this class directly. The class methods of this class are available from
1238 * the private $this->_form property on moodleform and its children. You generally only
1239 * call methods on this class from within abstract methods that you override on moodleform such
1240 * as definition and definition_after_data
1242 * @package core_form
1243 * @category form
1244 * @copyright 2006 Jamie Pratt <me@jamiep.org>
1245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1247 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1248 /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
1249 var $_types = array();
1251 /** @var array dependent state for the element/'s */
1252 var $_dependencies = array();
1254 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1255 var $_noSubmitButtons=array();
1257 /** @var array Array of buttons that if pressed do not result in the processing of the form. */
1258 var $_cancelButtons=array();
1260 /** @var array Array whose keys are element names. If the key exists this is a advanced element */
1261 var $_advancedElements = array();
1263 /** @var bool Whether to display advanced elements (on page load) */
1264 var $_showAdvanced = null;
1266 /** @var bool whether to automatically initialise M.formchangechecker for this form. */
1267 protected $_use_form_change_checker = true;
1270 * The form name is derived from the class name of the wrapper minus the trailing form
1271 * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
1272 * @var string
1274 var $_formName = '';
1277 * String with the html for hidden params passed in as part of a moodle_url
1278 * object for the action. Output in the form.
1279 * @var string
1281 var $_pageparams = '';
1284 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1286 * @staticvar int $formcounter counts number of forms
1287 * @param string $formName Form's name.
1288 * @param string $method Form's method defaults to 'POST'
1289 * @param string|moodle_url $action Form's action
1290 * @param string $target (optional)Form's target defaults to none
1291 * @param mixed $attributes (optional)Extra attributes for <form> tag
1293 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1294 global $CFG, $OUTPUT;
1296 static $formcounter = 1;
1298 HTML_Common::HTML_Common($attributes);
1299 $target = empty($target) ? array() : array('target' => $target);
1300 $this->_formName = $formName;
1301 if (is_a($action, 'moodle_url')){
1302 $this->_pageparams = html_writer::input_hidden_params($action);
1303 $action = $action->out_omit_querystring();
1304 } else {
1305 $this->_pageparams = '';
1307 // No 'name' atttribute for form in xhtml strict :
1308 $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
1309 if (is_null($this->getAttribute('id'))) {
1310 $attributes['id'] = 'mform' . $formcounter;
1312 $formcounter++;
1313 $this->updateAttributes($attributes);
1315 // This is custom stuff for Moodle :
1316 $oldclass= $this->getAttribute('class');
1317 if (!empty($oldclass)){
1318 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1319 }else {
1320 $this->updateAttributes(array('class'=>'mform'));
1322 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1323 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1324 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1328 * Use this method to indicate an element in a form is an advanced field. If items in a form
1329 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1330 * form so the user can decide whether to display advanced form controls.
1332 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1334 * @param string $elementName group or element name (not the element name of something inside a group).
1335 * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
1337 function setAdvanced($elementName, $advanced=true){
1338 if ($advanced){
1339 $this->_advancedElements[$elementName]='';
1340 } elseif (isset($this->_advancedElements[$elementName])) {
1341 unset($this->_advancedElements[$elementName]);
1343 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1344 $this->setShowAdvanced();
1345 $this->registerNoSubmitButton('mform_showadvanced');
1347 $this->addElement('hidden', 'mform_showadvanced_last');
1348 $this->setType('mform_showadvanced_last', PARAM_INT);
1352 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1353 * display advanced elements in the form until 'Show Advanced' is pressed.
1355 * You can get the last state of the form and possibly save it for this user by using
1356 * value 'mform_showadvanced_last' in submitted data.
1358 * @param bool $showadvancedNow if true will show adavance elements.
1360 function setShowAdvanced($showadvancedNow = null){
1361 if ($showadvancedNow === null){
1362 if ($this->_showAdvanced !== null){
1363 return;
1364 } else { //if setShowAdvanced is called without any preference
1365 //make the default to not show advanced elements.
1366 $showadvancedNow = get_user_preferences(
1367 textlib::strtolower($this->_formName.'_showadvanced', 0));
1370 //value of hidden element
1371 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1372 //value of button
1373 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1374 //toggle if button pressed or else stay the same
1375 if ($hiddenLast == -1) {
1376 $next = $showadvancedNow;
1377 } elseif ($buttonPressed) { //toggle on button press
1378 $next = !$hiddenLast;
1379 } else {
1380 $next = $hiddenLast;
1382 $this->_showAdvanced = $next;
1383 if ($showadvancedNow != $next){
1384 set_user_preference($this->_formName.'_showadvanced', $next);
1386 $this->setConstants(array('mform_showadvanced_last'=>$next));
1390 * Gets show advance value, if advance elements are visible it will return true else false
1392 * @return bool
1394 function getShowAdvanced(){
1395 return $this->_showAdvanced;
1399 * Call this method if you don't want the formchangechecker JavaScript to be
1400 * automatically initialised for this form.
1402 public function disable_form_change_checker() {
1403 $this->_use_form_change_checker = false;
1407 * If you have called {@link disable_form_change_checker()} then you can use
1408 * this method to re-enable it. It is enabled by default, so normally you don't
1409 * need to call this.
1411 public function enable_form_change_checker() {
1412 $this->_use_form_change_checker = true;
1416 * @return bool whether this form should automatically initialise
1417 * formchangechecker for itself.
1419 public function is_form_change_checker_enabled() {
1420 return $this->_use_form_change_checker;
1424 * Accepts a renderer
1426 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
1428 function accept(&$renderer) {
1429 if (method_exists($renderer, 'setAdvancedElements')){
1430 //check for visible fieldsets where all elements are advanced
1431 //and mark these headers as advanced as well.
1432 //And mark all elements in a advanced header as advanced
1433 $stopFields = $renderer->getStopFieldSetElements();
1434 $lastHeader = null;
1435 $lastHeaderAdvanced = false;
1436 $anyAdvanced = false;
1437 foreach (array_keys($this->_elements) as $elementIndex){
1438 $element =& $this->_elements[$elementIndex];
1440 // if closing header and any contained element was advanced then mark it as advanced
1441 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1442 if ($anyAdvanced && !is_null($lastHeader)){
1443 $this->setAdvanced($lastHeader->getName());
1445 $lastHeaderAdvanced = false;
1446 unset($lastHeader);
1447 $lastHeader = null;
1448 } elseif ($lastHeaderAdvanced) {
1449 $this->setAdvanced($element->getName());
1452 if ($element->getType()=='header'){
1453 $lastHeader =& $element;
1454 $anyAdvanced = false;
1455 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1456 } elseif (isset($this->_advancedElements[$element->getName()])){
1457 $anyAdvanced = true;
1460 // the last header may not be closed yet...
1461 if ($anyAdvanced && !is_null($lastHeader)){
1462 $this->setAdvanced($lastHeader->getName());
1464 $renderer->setAdvancedElements($this->_advancedElements);
1467 parent::accept($renderer);
1471 * Adds one or more element names that indicate the end of a fieldset
1473 * @param string $elementName name of the element
1475 function closeHeaderBefore($elementName){
1476 $renderer =& $this->defaultRenderer();
1477 $renderer->addStopFieldsetElements($elementName);
1481 * Should be used for all elements of a form except for select, radio and checkboxes which
1482 * clean their own data.
1484 * @param string $elementname
1485 * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
1486 * {@link lib/moodlelib.php} for defined parameter types
1488 function setType($elementname, $paramtype) {
1489 $this->_types[$elementname] = $paramtype;
1493 * This can be used to set several types at once.
1495 * @param array $paramtypes types of parameters.
1496 * @see MoodleQuickForm::setType
1498 function setTypes($paramtypes) {
1499 $this->_types = $paramtypes + $this->_types;
1503 * Updates submitted values
1505 * @param array $submission submitted values
1506 * @param array $files list of files
1508 function updateSubmission($submission, $files) {
1509 $this->_flagSubmitted = false;
1511 if (empty($submission)) {
1512 $this->_submitValues = array();
1513 } else {
1514 foreach ($submission as $key=>$s) {
1515 if (array_key_exists($key, $this->_types)) {
1516 $type = $this->_types[$key];
1517 } else {
1518 $type = PARAM_RAW;
1520 if (is_array($s)) {
1521 $submission[$key] = clean_param_array($s, $type, true);
1522 } else {
1523 $submission[$key] = clean_param($s, $type);
1526 $this->_submitValues = $submission;
1527 $this->_flagSubmitted = true;
1530 if (empty($files)) {
1531 $this->_submitFiles = array();
1532 } else {
1533 $this->_submitFiles = $files;
1534 $this->_flagSubmitted = true;
1537 // need to tell all elements that they need to update their value attribute.
1538 foreach (array_keys($this->_elements) as $key) {
1539 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1544 * Returns HTML for required elements
1546 * @return string
1548 function getReqHTML(){
1549 return $this->_reqHTML;
1553 * Returns HTML for advanced elements
1555 * @return string
1557 function getAdvancedHTML(){
1558 return $this->_advancedHTML;
1562 * Initializes a default form value. Used to specify the default for a new entry where
1563 * no data is loaded in using moodleform::set_data()
1565 * note: $slashed param removed
1567 * @param string $elementName element name
1568 * @param mixed $defaultValue values for that element name
1570 function setDefault($elementName, $defaultValue){
1571 $this->setDefaults(array($elementName=>$defaultValue));
1575 * Add a help button to element, only one button per element is allowed.
1577 * This is new, simplified and preferable method of setting a help icon on form elements.
1578 * It uses the new $OUTPUT->help_icon().
1580 * Typically, you will provide the same identifier and the component as you have used for the
1581 * label of the element. The string identifier with the _help suffix added is then used
1582 * as the help string.
1584 * There has to be two strings defined:
1585 * 1/ get_string($identifier, $component) - the title of the help page
1586 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1588 * @since Moodle 2.0
1589 * @param string $elementname name of the element to add the item to
1590 * @param string $identifier help string identifier without _help suffix
1591 * @param string $component component name to look the help string in
1592 * @param string $linktext optional text to display next to the icon
1593 * @param bool $suppresscheck set to true if the element may not exist
1595 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1596 global $OUTPUT;
1597 if (array_key_exists($elementname, $this->_elementIndex)) {
1598 $element = $this->_elements[$this->_elementIndex[$elementname]];
1599 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1600 } else if (!$suppresscheck) {
1601 debugging(get_string('nonexistentformelements', 'form', $elementname));
1606 * Set constant value not overridden by _POST or _GET
1607 * note: this does not work for complex names with [] :-(
1609 * @param string $elname name of element
1610 * @param mixed $value
1612 function setConstant($elname, $value) {
1613 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1614 $element =& $this->getElement($elname);
1615 $element->onQuickFormEvent('updateValue', null, $this);
1619 * export submitted values
1621 * @param string $elementList list of elements in form
1622 * @return array
1624 function exportValues($elementList = null){
1625 $unfiltered = array();
1626 if (null === $elementList) {
1627 // iterate over all elements, calling their exportValue() methods
1628 foreach (array_keys($this->_elements) as $key) {
1629 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
1630 $varname = $this->_elements[$key]->_attributes['name'];
1631 $value = '';
1632 // If we have a default value then export it.
1633 if (isset($this->_defaultValues[$varname])) {
1634 $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
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);
1662 return $unfiltered;
1666 * This is a bit of a hack, and it duplicates the code in
1667 * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
1668 * reliably calling that code. (Think about date selectors, for example.)
1669 * @param string $name the element name.
1670 * @param mixed $value the fixed value to set.
1671 * @return mixed the appropriate array to add to the $unfiltered array.
1673 protected function prepare_fixed_value($name, $value) {
1674 if (null === $value) {
1675 return null;
1676 } else {
1677 if (!strpos($name, '[')) {
1678 return array($name => $value);
1679 } else {
1680 $valueAry = array();
1681 $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
1682 eval("\$valueAry$myIndex = \$value;");
1683 return $valueAry;
1689 * Adds a validation rule for the given field
1691 * If the element is in fact a group, it will be considered as a whole.
1692 * To validate grouped elements as separated entities,
1693 * use addGroupRule instead of addRule.
1695 * @param string $element Form element name
1696 * @param string $message Message to display for invalid data
1697 * @param string $type Rule type, use getRegisteredRules() to get types
1698 * @param string $format (optional)Required for extra rule data
1699 * @param string $validation (optional)Where to perform validation: "server", "client"
1700 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1701 * @param bool $force Force the rule to be applied, even if the target form element does not exist
1703 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1705 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1706 if ($validation == 'client') {
1707 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1713 * Adds a validation rule for the given group of elements
1715 * Only groups with a name can be assigned a validation rule
1716 * Use addGroupRule when you need to validate elements inside the group.
1717 * Use addRule if you need to validate the group as a whole. In this case,
1718 * the same rule will be applied to all elements in the group.
1719 * Use addRule if you need to validate the group against a function.
1721 * @param string $group Form group name
1722 * @param array|string $arg1 Array for multiple elements or error message string for one element
1723 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1724 * @param string $format (optional)Required for extra rule data
1725 * @param int $howmany (optional)How many valid elements should be in the group
1726 * @param string $validation (optional)Where to perform validation: "server", "client"
1727 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1729 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1731 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1732 if (is_array($arg1)) {
1733 foreach ($arg1 as $rules) {
1734 foreach ($rules as $rule) {
1735 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1737 if ('client' == $validation) {
1738 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1742 } elseif (is_string($arg1)) {
1744 if ($validation == 'client') {
1745 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1751 * Returns the client side validation script
1753 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1754 * and slightly modified to run rules per-element
1755 * Needed to override this because of an error with client side validation of grouped elements.
1757 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1759 function getValidationScript()
1761 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1762 return '';
1765 include_once('HTML/QuickForm/RuleRegistry.php');
1766 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1767 $test = array();
1768 $js_escape = array(
1769 "\r" => '\r',
1770 "\n" => '\n',
1771 "\t" => '\t',
1772 "'" => "\\'",
1773 '"' => '\"',
1774 '\\' => '\\\\'
1777 foreach ($this->_rules as $elementName => $rules) {
1778 foreach ($rules as $rule) {
1779 if ('client' == $rule['validation']) {
1780 unset($element); //TODO: find out how to properly initialize it
1782 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1783 $rule['message'] = strtr($rule['message'], $js_escape);
1785 if (isset($rule['group'])) {
1786 $group =& $this->getElement($rule['group']);
1787 // No JavaScript validation for frozen elements
1788 if ($group->isFrozen()) {
1789 continue 2;
1791 $elements =& $group->getElements();
1792 foreach (array_keys($elements) as $key) {
1793 if ($elementName == $group->getElementName($key)) {
1794 $element =& $elements[$key];
1795 break;
1798 } elseif ($dependent) {
1799 $element = array();
1800 $element[] =& $this->getElement($elementName);
1801 foreach ($rule['dependent'] as $elName) {
1802 $element[] =& $this->getElement($elName);
1804 } else {
1805 $element =& $this->getElement($elementName);
1807 // No JavaScript validation for frozen elements
1808 if (is_object($element) && $element->isFrozen()) {
1809 continue 2;
1810 } elseif (is_array($element)) {
1811 foreach (array_keys($element) as $key) {
1812 if ($element[$key]->isFrozen()) {
1813 continue 3;
1817 //for editor element, [text] is appended to the name.
1818 if ($element->getType() == 'editor') {
1819 $elementName .= '[text]';
1820 //Add format to rule as moodleform check which format is supported by browser
1821 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1822 if (is_null($rule['format'])) {
1823 $rule['format'] = $element->getFormat();
1826 // Fix for bug displaying errors for elements in a group
1827 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1828 $test[$elementName][1]=$element;
1829 //end of fix
1834 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1835 // the form, and then that form field gets corrupted by the code that follows.
1836 unset($element);
1838 $js = '
1839 <script type="text/javascript">
1840 //<![CDATA[
1842 var skipClientValidation = false;
1844 function qf_errorHandler(element, _qfMsg) {
1845 div = element.parentNode;
1847 if ((div == undefined) || (element.name == undefined)) {
1848 //no checking can be done for undefined elements so let server handle it.
1849 return true;
1852 if (_qfMsg != \'\') {
1853 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1854 if (!errorSpan) {
1855 errorSpan = document.createElement("span");
1856 errorSpan.id = \'id_error_\'+element.name;
1857 errorSpan.className = "error";
1858 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1861 while (errorSpan.firstChild) {
1862 errorSpan.removeChild(errorSpan.firstChild);
1865 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1866 errorSpan.appendChild(document.createElement("br"));
1868 if (div.className.substr(div.className.length - 6, 6) != " error"
1869 && div.className != "error") {
1870 div.className += " error";
1873 return false;
1874 } else {
1875 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1876 if (errorSpan) {
1877 errorSpan.parentNode.removeChild(errorSpan);
1880 if (div.className.substr(div.className.length - 6, 6) == " error") {
1881 div.className = div.className.substr(0, div.className.length - 6);
1882 } else if (div.className == "error") {
1883 div.className = "";
1886 return true;
1889 $validateJS = '';
1890 foreach ($test as $elementName => $jsandelement) {
1891 // Fix for bug displaying errors for elements in a group
1892 //unset($element);
1893 list($jsArr,$element)=$jsandelement;
1894 //end of fix
1895 $escapedElementName = preg_replace_callback(
1896 '/[_\[\]-]/',
1897 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1898 $elementName);
1899 $js .= '
1900 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1901 if (undefined == element) {
1902 //required element was not found, then let form be submitted without client side validation
1903 return true;
1905 var value = \'\';
1906 var errFlag = new Array();
1907 var _qfGroups = {};
1908 var _qfMsg = \'\';
1909 var frm = element.parentNode;
1910 if ((undefined != element.name) && (frm != undefined)) {
1911 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1912 frm = frm.parentNode;
1914 ' . join("\n", $jsArr) . '
1915 return qf_errorHandler(element, _qfMsg);
1916 } else {
1917 //element name should be defined else error msg will not be displayed.
1918 return true;
1922 $validateJS .= '
1923 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1924 if (!ret && !first_focus) {
1925 first_focus = true;
1926 frm.elements[\''.$elementName.'\'].focus();
1930 // Fix for bug displaying errors for elements in a group
1931 //unset($element);
1932 //$element =& $this->getElement($elementName);
1933 //end of fix
1934 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1935 $onBlur = $element->getAttribute('onBlur');
1936 $onChange = $element->getAttribute('onChange');
1937 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1938 'onChange' => $onChange . $valFunc));
1940 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1941 $js .= '
1942 function validate_' . $this->_formName . '(frm) {
1943 if (skipClientValidation) {
1944 return true;
1946 var ret = true;
1948 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1949 var first_focus = false;
1950 ' . $validateJS . ';
1951 return ret;
1953 //]]>
1954 </script>';
1955 return $js;
1956 } // end func getValidationScript
1959 * Sets default error message
1961 function _setDefaultRuleMessages(){
1962 foreach ($this->_rules as $field => $rulesarr){
1963 foreach ($rulesarr as $key => $rule){
1964 if ($rule['message']===null){
1965 $a=new stdClass();
1966 $a->format=$rule['format'];
1967 $str=get_string('err_'.$rule['type'], 'form', $a);
1968 if (strpos($str, '[[')!==0){
1969 $this->_rules[$field][$key]['message']=$str;
1977 * Get list of attributes which have dependencies
1979 * @return array
1981 function getLockOptionObject(){
1982 $result = array();
1983 foreach ($this->_dependencies as $dependentOn => $conditions){
1984 $result[$dependentOn] = array();
1985 foreach ($conditions as $condition=>$values) {
1986 $result[$dependentOn][$condition] = array();
1987 foreach ($values as $value=>$dependents) {
1988 $result[$dependentOn][$condition][$value] = array();
1989 $i = 0;
1990 foreach ($dependents as $dependent) {
1991 $elements = $this->_getElNamesRecursive($dependent);
1992 if (empty($elements)) {
1993 // probably element inside of some group
1994 $elements = array($dependent);
1996 foreach($elements as $element) {
1997 if ($element == $dependentOn) {
1998 continue;
2000 $result[$dependentOn][$condition][$value][] = $element;
2006 return array($this->getAttribute('id'), $result);
2010 * Get names of element or elements in a group.
2012 * @param HTML_QuickForm_group|element $element element group or element object
2013 * @return array
2015 function _getElNamesRecursive($element) {
2016 if (is_string($element)) {
2017 if (!$this->elementExists($element)) {
2018 return array();
2020 $element = $this->getElement($element);
2023 if (is_a($element, 'HTML_QuickForm_group')) {
2024 $elsInGroup = $element->getElements();
2025 $elNames = array();
2026 foreach ($elsInGroup as $elInGroup){
2027 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2028 // not sure if this would work - groups nested in groups
2029 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2030 } else {
2031 $elNames[] = $element->getElementName($elInGroup->getName());
2035 } else if (is_a($element, 'HTML_QuickForm_header')) {
2036 return array();
2038 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2039 return array();
2041 } else if (method_exists($element, 'getPrivateName') &&
2042 !($element instanceof HTML_QuickForm_advcheckbox)) {
2043 // The advcheckbox element implements a method called getPrivateName,
2044 // but in a way that is not compatible with the generic API, so we
2045 // have to explicitly exclude it.
2046 return array($element->getPrivateName());
2048 } else {
2049 $elNames = array($element->getName());
2052 return $elNames;
2056 * Adds a dependency for $elementName which will be disabled if $condition is met.
2057 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2058 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2059 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2060 * of the $dependentOn element is $condition (such as equal) to $value.
2062 * @param string $elementName the name of the element which will be disabled
2063 * @param string $dependentOn the name of the element whose state will be checked for condition
2064 * @param string $condition the condition to check
2065 * @param mixed $value used in conjunction with condition.
2067 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
2068 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2069 $this->_dependencies[$dependentOn] = array();
2071 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2072 $this->_dependencies[$dependentOn][$condition] = array();
2074 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2075 $this->_dependencies[$dependentOn][$condition][$value] = array();
2077 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2081 * Registers button as no submit button
2083 * @param string $buttonname name of the button
2085 function registerNoSubmitButton($buttonname){
2086 $this->_noSubmitButtons[]=$buttonname;
2090 * Checks if button is a no submit button, i.e it doesn't submit form
2092 * @param string $buttonname name of the button to check
2093 * @return bool
2095 function isNoSubmitButton($buttonname){
2096 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2100 * Registers a button as cancel button
2102 * @param string $addfieldsname name of the button
2104 function _registerCancelButton($addfieldsname){
2105 $this->_cancelButtons[]=$addfieldsname;
2109 * Displays elements without HTML input tags.
2110 * This method is different to freeze() in that it makes sure no hidden
2111 * elements are included in the form.
2112 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2114 * This function also removes all previously defined rules.
2116 * @param string|array $elementList array or string of element(s) to be frozen
2117 * @return object|bool if element list is not empty then return error object, else true
2119 function hardFreeze($elementList=null)
2121 if (!isset($elementList)) {
2122 $this->_freezeAll = true;
2123 $elementList = array();
2124 } else {
2125 if (!is_array($elementList)) {
2126 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2128 $elementList = array_flip($elementList);
2131 foreach (array_keys($this->_elements) as $key) {
2132 $name = $this->_elements[$key]->getName();
2133 if ($this->_freezeAll || isset($elementList[$name])) {
2134 $this->_elements[$key]->freeze();
2135 $this->_elements[$key]->setPersistantFreeze(false);
2136 unset($elementList[$name]);
2138 // remove all rules
2139 $this->_rules[$name] = array();
2140 // if field is required, remove the rule
2141 $unset = array_search($name, $this->_required);
2142 if ($unset !== false) {
2143 unset($this->_required[$unset]);
2148 if (!empty($elementList)) {
2149 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);
2151 return true;
2155 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2157 * This function also removes all previously defined rules of elements it freezes.
2159 * @throws HTML_QuickForm_Error
2160 * @param array $elementList array or string of element(s) not to be frozen
2161 * @return bool returns true
2163 function hardFreezeAllVisibleExcept($elementList)
2165 $elementList = array_flip($elementList);
2166 foreach (array_keys($this->_elements) as $key) {
2167 $name = $this->_elements[$key]->getName();
2168 $type = $this->_elements[$key]->getType();
2170 if ($type == 'hidden'){
2171 // leave hidden types as they are
2172 } elseif (!isset($elementList[$name])) {
2173 $this->_elements[$key]->freeze();
2174 $this->_elements[$key]->setPersistantFreeze(false);
2176 // remove all rules
2177 $this->_rules[$name] = array();
2178 // if field is required, remove the rule
2179 $unset = array_search($name, $this->_required);
2180 if ($unset !== false) {
2181 unset($this->_required[$unset]);
2185 return true;
2189 * Tells whether the form was already submitted
2191 * This is useful since the _submitFiles and _submitValues arrays
2192 * may be completely empty after the trackSubmit value is removed.
2194 * @return bool
2196 function isSubmitted()
2198 return parent::isSubmitted() && (!$this->isFrozen());
2203 * MoodleQuickForm renderer
2205 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2206 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2208 * Stylesheet is part of standard theme and should be automatically included.
2210 * @package core_form
2211 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2212 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2214 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2216 /** @var array Element template array */
2217 var $_elementTemplates;
2220 * Template used when opening a hidden fieldset
2221 * (i.e. a fieldset that is opened when there is no header element)
2222 * @var string
2224 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2226 /** @var string Header Template string */
2227 var $_headerTemplate =
2228 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2230 /** @var string Template used when opening a fieldset */
2231 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2233 /** @var string Template used when closing a fieldset */
2234 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2236 /** @var string Required Note template string */
2237 var $_requiredNoteTemplate =
2238 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2240 /** @var array list of elements which are marked as advance and will be grouped together */
2241 var $_advancedElements = array();
2243 /** @var int Whether to display advanced elements (on page load) 1 => show, 0 => hide */
2244 var $_showAdvanced;
2247 * Constructor
2249 function MoodleQuickForm_Renderer(){
2250 // switch next two lines for ol li containers for form items.
2251 // $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>');
2252 $this->_elementTemplates = array(
2253 '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>',
2255 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2257 '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>',
2259 '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>',
2261 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2263 'nodisplay'=>'');
2265 parent::HTML_QuickForm_Renderer_Tableless();
2269 * Set element's as adavance element
2271 * @param array $elements form elements which needs to be grouped as advance elements.
2273 function setAdvancedElements($elements){
2274 $this->_advancedElements = $elements;
2278 * What to do when starting the form
2280 * @param MoodleQuickForm $form reference of the form
2282 function startForm(&$form){
2283 global $PAGE;
2284 $this->_reqHTML = $form->getReqHTML();
2285 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2286 $this->_advancedHTML = $form->getAdvancedHTML();
2287 $this->_showAdvanced = $form->getShowAdvanced();
2288 parent::startForm($form);
2289 if ($form->isFrozen()){
2290 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2291 } else {
2292 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2293 $this->_hiddenHtml .= $form->_pageparams;
2296 if ($form->is_form_change_checker_enabled()) {
2297 $PAGE->requires->yui_module('moodle-core-formchangechecker',
2298 'M.core_formchangechecker.init',
2299 array(array(
2300 'formid' => $form->getAttribute('id')
2303 $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
2308 * Create advance group of elements
2310 * @param object $group Passed by reference
2311 * @param bool $required if input is required field
2312 * @param string $error error message to display
2314 function startGroup(&$group, $required, $error){
2315 // Make sure the element has an id.
2316 $group->_generateId();
2318 if (method_exists($group, 'getElementTemplateType')){
2319 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2320 }else{
2321 $html = $this->_elementTemplates['default'];
2324 if ($this->_showAdvanced){
2325 $advclass = ' advanced';
2326 } else {
2327 $advclass = ' advanced hide';
2329 if (isset($this->_advancedElements[$group->getName()])){
2330 $html =str_replace(' {advanced}', $advclass, $html);
2331 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2332 } else {
2333 $html =str_replace(' {advanced}', '', $html);
2334 $html =str_replace('{advancedimg}', '', $html);
2336 if (method_exists($group, 'getHelpButton')){
2337 $html =str_replace('{help}', $group->getHelpButton(), $html);
2338 }else{
2339 $html =str_replace('{help}', '', $html);
2341 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2342 $html =str_replace('{name}', $group->getName(), $html);
2343 $html =str_replace('{type}', 'fgroup', $html);
2345 $this->_templates[$group->getName()]=$html;
2346 // Fix for bug in tableless quickforms that didn't allow you to stop a
2347 // fieldset before a group of elements.
2348 // if the element name indicates the end of a fieldset, close the fieldset
2349 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2350 && $this->_fieldsetsOpen > 0
2352 $this->_html .= $this->_closeFieldsetTemplate;
2353 $this->_fieldsetsOpen--;
2355 parent::startGroup($group, $required, $error);
2358 * Renders element
2360 * @param HTML_QuickForm_element $element element
2361 * @param bool $required if input is required field
2362 * @param string $error error message to display
2364 function renderElement(&$element, $required, $error){
2365 // Make sure the element has an id.
2366 $element->_generateId();
2368 //adding stuff to place holders in template
2369 //check if this is a group element first
2370 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2371 // so it gets substitutions for *each* element
2372 $html = $this->_groupElementTemplate;
2374 elseif (method_exists($element, 'getElementTemplateType')){
2375 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2376 }else{
2377 $html = $this->_elementTemplates['default'];
2379 if ($this->_showAdvanced){
2380 $advclass = ' advanced';
2381 } else {
2382 $advclass = ' advanced hide';
2384 if (isset($this->_advancedElements[$element->getName()])){
2385 $html =str_replace(' {advanced}', $advclass, $html);
2386 } else {
2387 $html =str_replace(' {advanced}', '', $html);
2389 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2390 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2391 } else {
2392 $html =str_replace('{advancedimg}', '', $html);
2394 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2395 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2396 $html =str_replace('{name}', $element->getName(), $html);
2397 if (method_exists($element, 'getHelpButton')){
2398 $html = str_replace('{help}', $element->getHelpButton(), $html);
2399 }else{
2400 $html = str_replace('{help}', '', $html);
2403 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2404 $this->_groupElementTemplate = $html;
2406 elseif (!isset($this->_templates[$element->getName()])) {
2407 $this->_templates[$element->getName()] = $html;
2410 parent::renderElement($element, $required, $error);
2414 * Called when visiting a form, after processing all form elements
2415 * Adds required note, form attributes, validation javascript and form content.
2417 * @global moodle_page $PAGE
2418 * @param moodleform $form Passed by reference
2420 function finishForm(&$form){
2421 global $PAGE;
2422 if ($form->isFrozen()){
2423 $this->_hiddenHtml = '';
2425 parent::finishForm($form);
2426 if (!$form->isFrozen()) {
2427 $args = $form->getLockOptionObject();
2428 if (count($args[1]) > 0) {
2429 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2434 * Called when visiting a header element
2436 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2437 * @global moodle_page $PAGE
2439 function renderHeader(&$header) {
2440 global $PAGE;
2442 $name = $header->getName();
2444 $id = empty($name) ? '' : ' id="' . $name . '"';
2445 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2446 if (is_null($header->_text)) {
2447 $header_html = '';
2448 } elseif (!empty($name) && isset($this->_templates[$name])) {
2449 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2450 } else {
2451 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2454 if (isset($this->_advancedElements[$name])){
2455 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2456 $elementName='mform_showadvanced';
2457 if ($this->_showAdvanced==0){
2458 $buttonlabel = get_string('showadvanced', 'form');
2459 } else {
2460 $buttonlabel = get_string('hideadvanced', 'form');
2462 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2463 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2464 $header_html = str_replace('{button}', $button, $header_html);
2465 } else {
2466 $header_html =str_replace('{advancedimg}', '', $header_html);
2467 $header_html = str_replace('{button}', '', $header_html);
2470 if ($this->_fieldsetsOpen > 0) {
2471 $this->_html .= $this->_closeFieldsetTemplate;
2472 $this->_fieldsetsOpen--;
2475 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2476 if ($this->_showAdvanced){
2477 $advclass = ' class="advanced"';
2478 } else {
2479 $advclass = ' class="advanced hide"';
2481 if (isset($this->_advancedElements[$name])){
2482 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2483 } else {
2484 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2486 $this->_html .= $openFieldsetTemplate . $header_html;
2487 $this->_fieldsetsOpen++;
2491 * Return Array of element names that indicate the end of a fieldset
2493 * @return array
2495 function getStopFieldsetElements(){
2496 return $this->_stopFieldsetElements;
2501 * Required elements validation
2503 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2505 * @package core_form
2506 * @category form
2507 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2510 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2512 * Checks if an element is not empty.
2513 * This is a server-side validation, it works for both text fields and editor fields
2515 * @param string $value Value to check
2516 * @param int|string|array $options Not used yet
2517 * @return bool true if value is not empty
2519 function validate($value, $options = null) {
2520 global $CFG;
2521 if (is_array($value) && array_key_exists('text', $value)) {
2522 $value = $value['text'];
2524 if (is_array($value)) {
2525 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2526 $value = implode('', $value);
2528 $stripvalues = array(
2529 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2530 '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
2532 if (!empty($CFG->strictformsrequired)) {
2533 $value = preg_replace($stripvalues, '', (string)$value);
2535 if ((string)$value == '') {
2536 return false;
2538 return true;
2542 * This function returns Javascript code used to build client-side validation.
2543 * It checks if an element is not empty.
2545 * @param int $format format of data which needs to be validated.
2546 * @return array
2548 function getValidationScript($format = null) {
2549 global $CFG;
2550 if (!empty($CFG->strictformsrequired)) {
2551 if (!empty($format) && $format == FORMAT_HTML) {
2552 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2553 } else {
2554 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2556 } else {
2557 return array('', "{jsVar} == ''");
2563 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2564 * @name $_HTML_QuickForm_default_renderer
2566 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2568 /** Please keep this list in alphabetical order. */
2569 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2570 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2571 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2572 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2573 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2574 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2575 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2576 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2577 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2578 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2579 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2580 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2581 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2582 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2583 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2584 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2585 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2586 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2587 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2588 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2589 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2590 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2591 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2592 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2593 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2594 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2595 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2596 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2597 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2598 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2599 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2600 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2601 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2602 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2603 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2605 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");