weekly release 2.1.6+
[moodle.git] / lib / formslib.php
blob526bf363a565f45ffa63a8cfed533f0a116ce01e
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.
34 * @copyright Jamie Pratt <me@jamiep.org>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 * @package core
37 * @subpackage form
40 defined('MOODLE_INTERNAL') || die();
42 /** setup.php includes our hacked pear libs first */
43 require_once 'HTML/QuickForm.php';
44 require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
45 require_once 'HTML/QuickForm/Renderer/Tableless.php';
46 require_once 'HTML/QuickForm/Rule.php';
48 require_once $CFG->libdir.'/filelib.php';
50 define('EDITOR_UNLIMITED_FILES', -1);
52 /**
53 * Callback called when PEAR throws an error
55 * @param PEAR_Error $error
57 function pear_handle_error($error){
58 echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
59 echo '<br /> <strong>Backtrace </strong>:';
60 print_object($error->backtrace);
63 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
64 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
67 /**
69 * @staticvar bool $done
70 * @global moodle_page $PAGE
72 function form_init_date_js() {
73 global $PAGE;
74 static $done = false;
75 if (!$done) {
76 $module = 'moodle-form-dateselector';
77 $function = 'M.form.dateselector.init_date_selectors';
78 $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
79 $PAGE->requires->yui_module($module, $function, $config);
80 $done = true;
84 /**
85 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
86 * use this class you should write a class definition which extends this class or a more specific
87 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
89 * You will write your own definition() method which performs the form set up.
91 * @package moodlecore
92 * @copyright Jamie Pratt <me@jamiep.org>
93 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
95 abstract class moodleform {
96 /** @var string */
97 protected $_formname; // form name
98 /**
99 * quickform object definition
101 * @var MoodleQuickForm MoodleQuickForm
103 protected $_form;
105 * globals workaround
107 * @var array
109 protected $_customdata;
111 * definition_after_data executed flag
112 * @var object definition_finalized
114 protected $_definition_finalized = false;
117 * The constructor function calls the abstract function definition() and it will then
118 * process and clean and attempt to validate incoming data.
120 * It will call your custom validate method to validate data and will also check any rules
121 * you have specified in definition using addRule
123 * The name of the form (id attribute of the form) is automatically generated depending on
124 * the name you gave the class extending moodleform. You should call your class something
125 * like
127 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
128 * current url. If a moodle_url object then outputs params as hidden variables.
129 * @param array $customdata if your form defintion method needs access to data such as $course
130 * $cm, etc. to construct the form definition then pass it in this array. You can
131 * use globals for somethings.
132 * @param string $method if you set this to anything other than 'post' then _GET and _POST will
133 * be merged and used as incoming data to the form.
134 * @param string $target target frame for form submission. You will rarely use this. Don't use
135 * it if you don't need to as the target attribute is deprecated in xhtml
136 * strict.
137 * @param mixed $attributes you can pass a string of html attributes here or an array.
138 * @param bool $editable
139 * @return object moodleform
141 function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
142 global $CFG;
143 if (empty($CFG->xmlstrictheaders)) {
144 // no standard mform in moodle should allow autocomplete with the exception of user signup
145 // this is valid attribute in html5, sorry, we have to ignore validation errors in legacy xhtml 1.0
146 if (empty($attributes)) {
147 $attributes = array('autocomplete'=>'off');
148 } else if (is_array($attributes)) {
149 $attributes['autocomplete'] = 'off';
150 } else {
151 if (strpos($attributes, 'autocomplete') === false) {
152 $attributes .= ' autocomplete="off" ';
157 if (empty($action)){
158 $action = strip_querystring(qualified_me());
160 // Assign custom data first, so that get_form_identifier can use it.
161 $this->_customdata = $customdata;
162 $this->_formname = $this->get_form_identifier();
164 $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
165 if (!$editable){
166 $this->_form->hardFreeze();
169 $this->definition();
171 $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
172 $this->_form->setType('sesskey', PARAM_RAW);
173 $this->_form->setDefault('sesskey', sesskey());
174 $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
175 $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
176 $this->_form->setDefault('_qf__'.$this->_formname, 1);
177 $this->_form->_setDefaultRuleMessages();
179 // we have to know all input types before processing submission ;-)
180 $this->_process_submission($method);
184 * It should returns unique identifier for the form.
185 * Currently it will return class name, but in case two same forms have to be
186 * rendered on same page then override function to get unique form identifier.
187 * e.g This is used on multiple self enrollments page.
189 * @return string form identifier.
191 protected function get_form_identifier() {
192 return get_class($this);
196 * To autofocus on first form element or first element with error.
198 * @param string $name if this is set then the focus is forced to a field with this name
200 * @return string javascript to select form element with first error or
201 * first element if no errors. Use this as a parameter
202 * when calling print_header
204 function focus($name=NULL) {
205 $form =& $this->_form;
206 $elkeys = array_keys($form->_elementIndex);
207 $error = false;
208 if (isset($form->_errors) && 0 != count($form->_errors)){
209 $errorkeys = array_keys($form->_errors);
210 $elkeys = array_intersect($elkeys, $errorkeys);
211 $error = true;
214 if ($error or empty($name)) {
215 $names = array();
216 while (empty($names) and !empty($elkeys)) {
217 $el = array_shift($elkeys);
218 $names = $form->_getElNamesRecursive($el);
220 if (!empty($names)) {
221 $name = array_shift($names);
225 $focus = '';
226 if (!empty($name)) {
227 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
230 return $focus;
234 * Internal method. Alters submitted data to be suitable for quickforms processing.
235 * Must be called when the form is fully set up.
237 * @param string $method
239 function _process_submission($method) {
240 $submission = array();
241 if ($method == 'post') {
242 if (!empty($_POST)) {
243 $submission = $_POST;
245 } else {
246 $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
249 // following trick is needed to enable proper sesskey checks when using GET forms
250 // the _qf__.$this->_formname serves as a marker that form was actually submitted
251 if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
252 if (!confirm_sesskey()) {
253 print_error('invalidsesskey');
255 $files = $_FILES;
256 } else {
257 $submission = array();
258 $files = array();
261 $this->_form->updateSubmission($submission, $files);
265 * Internal method. Validates all old-style deprecated uploaded files.
266 * The new way is to upload files via repository api.
268 * @global object
269 * @global object
270 * @param array $files
271 * @return bool|array Success or an array of errors
273 function _validate_files(&$files) {
274 global $CFG, $COURSE;
276 $files = array();
278 if (empty($_FILES)) {
279 // we do not need to do any checks because no files were submitted
280 // note: server side rules do not work for files - use custom verification in validate() instead
281 return true;
284 $errors = array();
285 $filenames = array();
287 // now check that we really want each file
288 foreach ($_FILES as $elname=>$file) {
289 $required = $this->_form->isElementRequired($elname);
291 if ($file['error'] == 4 and $file['size'] == 0) {
292 if ($required) {
293 $errors[$elname] = get_string('required');
295 unset($_FILES[$elname]);
296 continue;
299 if (!empty($file['error'])) {
300 $errors[$elname] = file_get_upload_error($file['error']);
301 unset($_FILES[$elname]);
302 continue;
305 if (!is_uploaded_file($file['tmp_name'])) {
306 // TODO: improve error message
307 $errors[$elname] = get_string('error');
308 unset($_FILES[$elname]);
309 continue;
312 if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
313 // hmm, this file was not requested
314 unset($_FILES[$elname]);
315 continue;
319 // TODO: rethink the file scanning MDL-19380
320 if ($CFG->runclamonupload) {
321 if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
322 $errors[$elname] = $_FILES[$elname]['uploadlog'];
323 unset($_FILES[$elname]);
324 continue;
328 $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
329 if ($filename === '') {
330 // TODO: improve error message - wrong chars
331 $errors[$elname] = get_string('error');
332 unset($_FILES[$elname]);
333 continue;
335 if (in_array($filename, $filenames)) {
336 // TODO: improve error message - duplicate name
337 $errors[$elname] = get_string('error');
338 unset($_FILES[$elname]);
339 continue;
341 $filenames[] = $filename;
342 $_FILES[$elname]['name'] = $filename;
344 $files[$elname] = $_FILES[$elname]['tmp_name'];
347 // return errors if found
348 if (count($errors) == 0){
349 return true;
351 } else {
352 $files = array();
353 return $errors;
358 * Internal method. Validates filepicker and filemanager files if they are
359 * set as required fields. Also, sets the error message if encountered one.
361 * @return bool/array with errors
363 protected function validate_draft_files() {
364 global $USER;
365 $mform =& $this->_form;
367 $errors = array();
368 //Go through all the required elements and make sure you hit filepicker or
369 //filemanager element.
370 foreach ($mform->_rules as $elementname => $rules) {
371 $elementtype = $mform->getElementType($elementname);
372 //If element is of type filepicker then do validation
373 if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
374 //Check if rule defined is required rule
375 foreach ($rules as $rule) {
376 if ($rule['type'] == 'required') {
377 $draftid = (int)$mform->getSubmitValue($elementname);
378 $fs = get_file_storage();
379 $context = get_context_instance(CONTEXT_USER, $USER->id);
380 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
381 $errors[$elementname] = $rule['message'];
387 if (empty($errors)) {
388 return true;
389 } else {
390 return $errors;
395 * Load in existing data as form defaults. Usually new entry defaults are stored directly in
396 * form definition (new entry form); this function is used to load in data where values
397 * already exist and data is being edited (edit entry form).
399 * note: $slashed param removed
401 * @param mixed $default_values object or array of default values
403 function set_data($default_values) {
404 if (is_object($default_values)) {
405 $default_values = (array)$default_values;
407 $this->_form->setDefaults($default_values);
411 * @deprecated
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 * @staticvar bool $nosubmit
429 function no_submit_button_pressed(){
430 static $nosubmit = null; // one check is enough
431 if (!is_null($nosubmit)){
432 return $nosubmit;
434 $mform =& $this->_form;
435 $nosubmit = false;
436 if (!$this->is_submitted()){
437 return false;
439 foreach ($mform->_noSubmitButtons as $nosubmitbutton){
440 if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
441 $nosubmit = true;
442 break;
445 return $nosubmit;
450 * Check that form data is valid.
451 * You should almost always use this, rather than {@see validate_defined_fields}
453 * @staticvar bool $validated
454 * @return bool true if form data valid
456 function is_validated() {
457 //finalize the form definition before any processing
458 if (!$this->_definition_finalized) {
459 $this->_definition_finalized = true;
460 $this->definition_after_data();
463 return $this->validate_defined_fields();
467 * Validate the form.
469 * You almost always want to call {@see is_validated} instead of this
470 * because it calls {@see definition_after_data} first, before validating the form,
471 * which is what you want in 99% of cases.
473 * This is provided as a separate function for those special cases where
474 * you want the form validated before definition_after_data is called
475 * for example, to selectively add new elements depending on a no_submit_button press,
476 * but only when the form is valid when the no_submit_button is pressed,
478 * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
479 * is NOT to validate the form when a no submit button has been pressed.
480 * pass true here to override this behaviour
482 * @return bool true if form data valid
484 function validate_defined_fields($validateonnosubmit=false) {
485 static $validated = null; // one validation is enough
486 $mform =& $this->_form;
487 if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
488 return false;
489 } elseif ($validated === null) {
490 $internal_val = $mform->validate();
492 $files = array();
493 $file_val = $this->_validate_files($files);
494 //check draft files for validation and flag them if required files
495 //are not in draft area.
496 $draftfilevalue = $this->validate_draft_files();
498 if ($file_val !== true && $draftfilevalue !== true) {
499 $file_val = array_merge($file_val, $draftfilevalue);
500 } else if ($draftfilevalue !== true) {
501 $file_val = $draftfilevalue;
502 } //default is file_val, so no need to assign.
504 if ($file_val !== true) {
505 if (!empty($file_val)) {
506 foreach ($file_val as $element=>$msg) {
507 $mform->setElementError($element, $msg);
510 $file_val = false;
513 $data = $mform->exportValues();
514 $moodle_val = $this->validation($data, $files);
515 if ((is_array($moodle_val) && count($moodle_val)!==0)) {
516 // non-empty array means errors
517 foreach ($moodle_val as $element=>$msg) {
518 $mform->setElementError($element, $msg);
520 $moodle_val = false;
522 } else {
523 // anything else means validation ok
524 $moodle_val = true;
527 $validated = ($internal_val and $moodle_val and $file_val);
529 return $validated;
533 * Return true if a cancel button has been pressed resulting in the form being submitted.
535 * @return boolean true if a cancel button has been pressed
537 function is_cancelled(){
538 $mform =& $this->_form;
539 if ($mform->isSubmitted()){
540 foreach ($mform->_cancelButtons as $cancelbutton){
541 if (optional_param($cancelbutton, 0, PARAM_RAW)){
542 return true;
546 return false;
550 * Return submitted data if properly submitted or returns NULL if validation fails or
551 * if there is no submitted data.
553 * note: $slashed param removed
555 * @return object submitted data; NULL if not valid or not submitted or cancelled
557 function get_data() {
558 $mform =& $this->_form;
560 if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
561 $data = $mform->exportValues();
562 unset($data['sesskey']); // we do not need to return sesskey
563 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
564 if (empty($data)) {
565 return NULL;
566 } else {
567 return (object)$data;
569 } else {
570 return NULL;
575 * Return submitted data without validation or NULL if there is no submitted data.
576 * note: $slashed param removed
578 * @return object submitted data; NULL if not submitted
580 function get_submitted_data() {
581 $mform =& $this->_form;
583 if ($this->is_submitted()) {
584 $data = $mform->exportValues();
585 unset($data['sesskey']); // we do not need to return sesskey
586 unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
587 if (empty($data)) {
588 return NULL;
589 } else {
590 return (object)$data;
592 } else {
593 return NULL;
598 * Save verified uploaded files into directory. Upload process can be customised from definition()
599 * NOTE: please use save_stored_file() or save_file()
601 * @return bool Always false
603 function save_files($destination) {
604 debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
605 return false;
609 * Returns name of uploaded file.
611 * @global object
612 * @param string $elname, first element if null
613 * @return mixed false in case of failure, string if ok
615 function get_new_filename($elname=null) {
616 global $USER;
618 if (!$this->is_submitted() or !$this->is_validated()) {
619 return false;
622 if (is_null($elname)) {
623 if (empty($_FILES)) {
624 return false;
626 reset($_FILES);
627 $elname = key($_FILES);
630 if (empty($elname)) {
631 return false;
634 $element = $this->_form->getElement($elname);
636 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
637 $values = $this->_form->exportValues($elname);
638 if (empty($values[$elname])) {
639 return false;
641 $draftid = $values[$elname];
642 $fs = get_file_storage();
643 $context = get_context_instance(CONTEXT_USER, $USER->id);
644 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
645 return false;
647 $file = reset($files);
648 return $file->get_filename();
651 if (!isset($_FILES[$elname])) {
652 return false;
655 return $_FILES[$elname]['name'];
659 * Save file to standard filesystem
661 * @global object
662 * @param string $elname name of element
663 * @param string $pathname full path name of file
664 * @param bool $override override file if exists
665 * @return bool success
667 function save_file($elname, $pathname, $override=false) {
668 global $USER;
670 if (!$this->is_submitted() or !$this->is_validated()) {
671 return false;
673 if (file_exists($pathname)) {
674 if ($override) {
675 if (!@unlink($pathname)) {
676 return false;
678 } else {
679 return false;
683 $element = $this->_form->getElement($elname);
685 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
686 $values = $this->_form->exportValues($elname);
687 if (empty($values[$elname])) {
688 return false;
690 $draftid = $values[$elname];
691 $fs = get_file_storage();
692 $context = get_context_instance(CONTEXT_USER, $USER->id);
693 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
694 return false;
696 $file = reset($files);
698 return $file->copy_content_to($pathname);
700 } else if (isset($_FILES[$elname])) {
701 return copy($_FILES[$elname]['tmp_name'], $pathname);
704 return false;
708 * Returns a temporary file, do not forget to delete after not needed any more.
710 * @param string $elname
711 * @return string or false
713 function save_temp_file($elname) {
714 if (!$this->get_new_filename($elname)) {
715 return false;
717 if (!$dir = make_upload_directory('temp/forms')) {
718 return false;
720 if (!$tempfile = tempnam($dir, 'tempup_')) {
721 return false;
723 if (!$this->save_file($elname, $tempfile, true)) {
724 // something went wrong
725 @unlink($tempfile);
726 return false;
729 return $tempfile;
733 * Get draft files of a form element
734 * This is a protected method which will be used only inside moodleforms
736 * @global object $USER
737 * @param string $elname name of element
738 * @return array
740 protected function get_draft_files($elname) {
741 global $USER;
743 if (!$this->is_submitted()) {
744 return false;
747 $element = $this->_form->getElement($elname);
749 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
750 $values = $this->_form->exportValues($elname);
751 if (empty($values[$elname])) {
752 return false;
754 $draftid = $values[$elname];
755 $fs = get_file_storage();
756 $context = get_context_instance(CONTEXT_USER, $USER->id);
757 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
758 return null;
760 return $files;
762 return null;
766 * Save file to local filesystem pool
768 * @global object
769 * @param string $elname name of element
770 * @param int $newcontextid
771 * @param string $newfilearea
772 * @param string $newfilepath
773 * @param string $newfilename - use specified filename, if not specified name of uploaded file used
774 * @param bool $overwrite - overwrite file if exists
775 * @param int $newuserid - new userid if required
776 * @return mixed stored_file object or false if error; may throw exception if duplicate found
778 function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
779 $newfilename=null, $overwrite=false, $newuserid=null) {
780 global $USER;
782 if (!$this->is_submitted() or !$this->is_validated()) {
783 return false;
786 if (empty($newuserid)) {
787 $newuserid = $USER->id;
790 $element = $this->_form->getElement($elname);
791 $fs = get_file_storage();
793 if ($element instanceof MoodleQuickForm_filepicker) {
794 $values = $this->_form->exportValues($elname);
795 if (empty($values[$elname])) {
796 return false;
798 $draftid = $values[$elname];
799 $context = get_context_instance(CONTEXT_USER, $USER->id);
800 if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
801 return false;
803 $file = reset($files);
804 if (is_null($newfilename)) {
805 $newfilename = $file->get_filename();
808 if ($overwrite) {
809 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
810 if (!$oldfile->delete()) {
811 return false;
816 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
817 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
818 return $fs->create_file_from_storedfile($file_record, $file);
820 } else if (isset($_FILES[$elname])) {
821 $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
823 if ($overwrite) {
824 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
825 if (!$oldfile->delete()) {
826 return false;
831 $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
832 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
833 return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
836 return false;
840 * Get content of uploaded file.
842 * @global object
843 * @param $element name of file upload element
844 * @return mixed false in case of failure, string if ok
846 function get_file_content($elname) {
847 global $USER;
849 if (!$this->is_submitted() or !$this->is_validated()) {
850 return false;
853 $element = $this->_form->getElement($elname);
855 if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
856 $values = $this->_form->exportValues($elname);
857 if (empty($values[$elname])) {
858 return false;
860 $draftid = $values[$elname];
861 $fs = get_file_storage();
862 $context = get_context_instance(CONTEXT_USER, $USER->id);
863 if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
864 return false;
866 $file = reset($files);
868 return $file->get_content();
870 } else if (isset($_FILES[$elname])) {
871 return file_get_contents($_FILES[$elname]['tmp_name']);
874 return false;
878 * Print html form.
880 function display() {
881 //finalize the form definition if not yet done
882 if (!$this->_definition_finalized) {
883 $this->_definition_finalized = true;
884 $this->definition_after_data();
886 $this->_form->display();
890 * Abstract method - always override!
892 protected abstract function definition();
895 * Dummy stub method - override if you need to setup the form depending on current
896 * values. This method is called after definition(), data submission and set_data().
897 * All form setup that is dependent on form values should go in here.
899 function definition_after_data(){
903 * Dummy stub method - override if you needed to perform some extra validation.
904 * If there are errors return array of errors ("fieldname"=>"error message"),
905 * otherwise true if ok.
907 * Server side rules do not work for uploaded files, implement serverside rules here if needed.
909 * @param array $data array of ("fieldname"=>value) of submitted data
910 * @param array $files array of uploaded files "element_name"=>tmp_file_path
911 * @return array of "element_name"=>"error_description" if there are errors,
912 * or an empty array if everything is OK (true allowed for backwards compatibility too).
914 function validation($data, $files) {
915 return array();
919 * Method to add a repeating group of elements to a form.
921 * @param array $elementobjs Array of elements or groups of elements that are to be repeated
922 * @param integer $repeats no of times to repeat elements initially
923 * @param array $options Array of options to apply to elements. Array keys are element names.
924 * This is an array of arrays. The second sets of keys are the option types
925 * for the elements :
926 * 'default' - default value is value
927 * 'type' - PARAM_* constant is value
928 * 'helpbutton' - helpbutton params array is value
929 * 'disabledif' - last three moodleform::disabledIf()
930 * params are value as an array
931 * @param string $repeathiddenname name for hidden element storing no of repeats in this form
932 * @param string $addfieldsname name for button to add more fields
933 * @param int $addfieldsno how many fields to add at a time
934 * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
935 * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
936 * @return int no of repeats of element in this page
938 function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
939 $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
940 if ($addstring===null){
941 $addstring = get_string('addfields', 'form', $addfieldsno);
942 } else {
943 $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
945 $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
946 $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
947 if (!empty($addfields)){
948 $repeats += $addfieldsno;
950 $mform =& $this->_form;
951 $mform->registerNoSubmitButton($addfieldsname);
952 $mform->addElement('hidden', $repeathiddenname, $repeats);
953 $mform->setType($repeathiddenname, PARAM_INT);
954 //value not to be overridden by submitted value
955 $mform->setConstants(array($repeathiddenname=>$repeats));
956 $namecloned = array();
957 for ($i = 0; $i < $repeats; $i++) {
958 foreach ($elementobjs as $elementobj){
959 $elementclone = fullclone($elementobj);
960 $name = $elementclone->getName();
961 $namecloned[] = $name;
962 if (!empty($name)) {
963 $elementclone->setName($name."[$i]");
965 if (is_a($elementclone, 'HTML_QuickForm_header')) {
966 $value = $elementclone->_text;
967 $elementclone->setValue(str_replace('{no}', ($i+1), $value));
969 } else {
970 $value=$elementclone->getLabel();
971 $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
975 $mform->addElement($elementclone);
978 for ($i=0; $i<$repeats; $i++) {
979 foreach ($options as $elementname => $elementoptions){
980 $pos=strpos($elementname, '[');
981 if ($pos!==FALSE){
982 $realelementname = substr($elementname, 0, $pos)."[$i]";
983 $realelementname .= substr($elementname, $pos);
984 }else {
985 $realelementname = $elementname."[$i]";
987 foreach ($elementoptions as $option => $params){
989 switch ($option){
990 case 'default' :
991 $mform->setDefault($realelementname, $params);
992 break;
993 case 'helpbutton' :
994 $params = array_merge(array($realelementname), $params);
995 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
996 break;
997 case 'disabledif' :
998 foreach ($namecloned as $num => $name){
999 if ($params[0] == $name){
1000 $params[0] = $params[0]."[$i]";
1001 break;
1004 $params = array_merge(array($realelementname), $params);
1005 call_user_func_array(array(&$mform, 'disabledIf'), $params);
1006 break;
1007 case 'rule' :
1008 if (is_string($params)){
1009 $params = array(null, $params, null, 'client');
1011 $params = array_merge(array($realelementname), $params);
1012 call_user_func_array(array(&$mform, 'addRule'), $params);
1013 break;
1014 case 'type' :
1015 //Type should be set only once
1016 if (!isset($mform->_types[$elementname])) {
1017 $mform->setType($elementname, $params);
1019 break;
1024 $mform->addElement('submit', $addfieldsname, $addstring);
1026 if (!$addbuttoninside) {
1027 $mform->closeHeaderBefore($addfieldsname);
1030 return $repeats;
1034 * Adds a link/button that controls the checked state of a group of checkboxes.
1036 * @global object
1037 * @param int $groupid The id of the group of advcheckboxes this element controls
1038 * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1039 * @param array $attributes associative array of HTML attributes
1040 * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1042 function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1043 global $CFG, $PAGE;
1045 // Name of the controller button
1046 $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1047 $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1048 $checkboxgroupclass = 'checkboxgroup'.$groupid;
1050 // Set the default text if none was specified
1051 if (empty($text)) {
1052 $text = get_string('selectallornone', 'form');
1055 $mform = $this->_form;
1056 $select_value = optional_param($checkboxcontrollerparam, null, PARAM_INT);
1057 $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1059 $new_select_value = $select_value;
1060 if (is_null($select_value)) {
1061 $new_select_value = $originalValue;
1062 } else if (!is_null($contollerbutton)) {
1063 $new_select_value = (int) !$select_value;
1065 // set checkbox state depending on orignal/submitted value by controoler button
1066 if (!is_null($contollerbutton) || is_null($select_value)) {
1067 foreach ($mform->_elements as $element) {
1068 if (($element instanceof MoodleQuickForm_advcheckbox) &&
1069 $element->getAttribute('class') == $checkboxgroupclass &&
1070 !$element->isFrozen()) {
1071 $mform->setConstants(array($element->getName() => $new_select_value));
1076 $mform->addElement('hidden', $checkboxcontrollerparam, $new_select_value, array('id' => "id_".$checkboxcontrollerparam));
1077 $mform->setType($checkboxcontrollerparam, PARAM_INT);
1078 $mform->setConstants(array($checkboxcontrollerparam => $new_select_value));
1080 $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
1081 array(
1082 array('groupid' => $groupid,
1083 'checkboxclass' => $checkboxgroupclass,
1084 'checkboxcontroller' => $checkboxcontrollerparam,
1085 'controllerbutton' => $checkboxcontrollername)
1089 require_once("$CFG->libdir/form/submit.php");
1090 $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
1091 $mform->addElement($submitlink);
1092 $mform->registerNoSubmitButton($checkboxcontrollername);
1093 $mform->setDefault($checkboxcontrollername, $text);
1097 * Use this method to a cancel and submit button to the end of your form. Pass a param of false
1098 * if you don't want a cancel button in your form. If you have a cancel button make sure you
1099 * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
1100 * get data with get_data().
1102 * @param boolean $cancel whether to show cancel button, default true
1103 * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
1105 function add_action_buttons($cancel = true, $submitlabel=null){
1106 if (is_null($submitlabel)){
1107 $submitlabel = get_string('savechanges');
1109 $mform =& $this->_form;
1110 if ($cancel){
1111 //when two elements we need a group
1112 $buttonarray=array();
1113 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
1114 $buttonarray[] = &$mform->createElement('cancel');
1115 $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
1116 $mform->closeHeaderBefore('buttonar');
1117 } else {
1118 //no group needed
1119 $mform->addElement('submit', 'submitbutton', $submitlabel);
1120 $mform->closeHeaderBefore('submitbutton');
1125 * Adds an initialisation call for a standard JavaScript enhancement.
1127 * This function is designed to add an initialisation call for a JavaScript
1128 * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
1130 * Current options:
1131 * - Selectboxes
1132 * - smartselect: Turns a nbsp indented select box into a custom drop down
1133 * control that supports multilevel and category selection.
1134 * $enhancement = 'smartselect';
1135 * $options = array('selectablecategories' => true|false)
1137 * @since 2.0
1138 * @param string|element $element
1139 * @param string $enhancement
1140 * @param array $options
1141 * @param array $strings
1143 function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
1144 global $PAGE;
1145 if (is_string($element)) {
1146 $element = $this->_form->getElement($element);
1148 if (is_object($element)) {
1149 $element->_generateId();
1150 $elementid = $element->getAttribute('id');
1151 $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
1152 if (is_array($strings)) {
1153 foreach ($strings as $string) {
1154 if (is_array($string)) {
1155 call_user_method_array('string_for_js', $PAGE->requires, $string);
1156 } else {
1157 $PAGE->requires->string_for_js($string, 'moodle');
1165 * Returns a JS module definition for the mforms JS
1166 * @return array
1168 public static function get_js_module() {
1169 global $CFG;
1170 return array(
1171 'name' => 'mform',
1172 'fullpath' => '/lib/form/form.js',
1173 'requires' => array('base', 'node'),
1174 'strings' => array(
1175 array('showadvanced', 'form'),
1176 array('hideadvanced', 'form')
1183 * You never extend this class directly. The class methods of this class are available from
1184 * the private $this->_form property on moodleform and its children. You generally only
1185 * call methods on this class from within abstract methods that you override on moodleform such
1186 * as definition and definition_after_data
1188 * @package moodlecore
1189 * @copyright Jamie Pratt <me@jamiep.org>
1190 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1192 class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
1193 /** @var array */
1194 var $_types = array();
1195 var $_dependencies = array();
1197 * Array of buttons that if pressed do not result in the processing of the form.
1199 * @var array
1201 var $_noSubmitButtons=array();
1203 * Array of buttons that if pressed do not result in the processing of the form.
1205 * @var array
1207 var $_cancelButtons=array();
1210 * Array whose keys are element names. If the key exists this is a advanced element
1212 * @var array
1214 var $_advancedElements = array();
1217 * Whether to display advanced elements (on page load)
1219 * @var boolean
1221 var $_showAdvanced = null;
1224 * The form name is derived from the class name of the wrapper minus the trailing form
1225 * It is a name with words joined by underscores whereas the id attribute is words joined by
1226 * underscores.
1228 * @var unknown_type
1230 var $_formName = '';
1233 * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
1235 * @var string
1237 var $_pageparams = '';
1240 * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
1242 * @global object
1243 * @staticvar int $formcounter
1244 * @param string $formName Form's name.
1245 * @param string $method (optional)Form's method defaults to 'POST'
1246 * @param mixed $action (optional)Form's action - string or moodle_url
1247 * @param string $target (optional)Form's target defaults to none
1248 * @param mixed $attributes (optional)Extra attributes for <form> tag
1249 * @access public
1251 function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
1252 global $CFG, $OUTPUT;
1254 static $formcounter = 1;
1256 HTML_Common::HTML_Common($attributes);
1257 $target = empty($target) ? array() : array('target' => $target);
1258 $this->_formName = $formName;
1259 if (is_a($action, 'moodle_url')){
1260 $this->_pageparams = html_writer::input_hidden_params($action);
1261 $action = $action->out_omit_querystring();
1262 } else {
1263 $this->_pageparams = '';
1265 //no 'name' atttribute for form in xhtml strict :
1266 $attributes = array('action'=>$action, 'method'=>$method,
1267 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
1268 $formcounter++;
1269 $this->updateAttributes($attributes);
1271 //this is custom stuff for Moodle :
1272 $oldclass= $this->getAttribute('class');
1273 if (!empty($oldclass)){
1274 $this->updateAttributes(array('class'=>$oldclass.' mform'));
1275 }else {
1276 $this->updateAttributes(array('class'=>'mform'));
1278 $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
1279 $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
1280 $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
1284 * Use this method to indicate an element in a form is an advanced field. If items in a form
1285 * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
1286 * form so the user can decide whether to display advanced form controls.
1288 * If you set a header element to advanced then all elements it contains will also be set as advanced.
1290 * @param string $elementName group or element name (not the element name of something inside a group).
1291 * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
1293 function setAdvanced($elementName, $advanced=true){
1294 if ($advanced){
1295 $this->_advancedElements[$elementName]='';
1296 } elseif (isset($this->_advancedElements[$elementName])) {
1297 unset($this->_advancedElements[$elementName]);
1299 if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
1300 $this->setShowAdvanced();
1301 $this->registerNoSubmitButton('mform_showadvanced');
1303 $this->addElement('hidden', 'mform_showadvanced_last');
1304 $this->setType('mform_showadvanced_last', PARAM_INT);
1308 * Set whether to show advanced elements in the form on first displaying form. Default is not to
1309 * display advanced elements in the form until 'Show Advanced' is pressed.
1311 * You can get the last state of the form and possibly save it for this user by using
1312 * value 'mform_showadvanced_last' in submitted data.
1314 * @param boolean $showadvancedNow
1316 function setShowAdvanced($showadvancedNow = null){
1317 if ($showadvancedNow === null){
1318 if ($this->_showAdvanced !== null){
1319 return;
1320 } else { //if setShowAdvanced is called without any preference
1321 //make the default to not show advanced elements.
1322 $showadvancedNow = get_user_preferences(
1323 moodle_strtolower($this->_formName.'_showadvanced', 0));
1326 //value of hidden element
1327 $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
1328 //value of button
1329 $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
1330 //toggle if button pressed or else stay the same
1331 if ($hiddenLast == -1) {
1332 $next = $showadvancedNow;
1333 } elseif ($buttonPressed) { //toggle on button press
1334 $next = !$hiddenLast;
1335 } else {
1336 $next = $hiddenLast;
1338 $this->_showAdvanced = $next;
1339 if ($showadvancedNow != $next){
1340 set_user_preference($this->_formName.'_showadvanced', $next);
1342 $this->setConstants(array('mform_showadvanced_last'=>$next));
1344 function getShowAdvanced(){
1345 return $this->_showAdvanced;
1350 * Accepts a renderer
1352 * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
1353 * @access public
1354 * @return void
1356 function accept(&$renderer) {
1357 if (method_exists($renderer, 'setAdvancedElements')){
1358 //check for visible fieldsets where all elements are advanced
1359 //and mark these headers as advanced as well.
1360 //And mark all elements in a advanced header as advanced
1361 $stopFields = $renderer->getStopFieldSetElements();
1362 $lastHeader = null;
1363 $lastHeaderAdvanced = false;
1364 $anyAdvanced = false;
1365 foreach (array_keys($this->_elements) as $elementIndex){
1366 $element =& $this->_elements[$elementIndex];
1368 // if closing header and any contained element was advanced then mark it as advanced
1369 if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
1370 if ($anyAdvanced && !is_null($lastHeader)){
1371 $this->setAdvanced($lastHeader->getName());
1373 $lastHeaderAdvanced = false;
1374 unset($lastHeader);
1375 $lastHeader = null;
1376 } elseif ($lastHeaderAdvanced) {
1377 $this->setAdvanced($element->getName());
1380 if ($element->getType()=='header'){
1381 $lastHeader =& $element;
1382 $anyAdvanced = false;
1383 $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
1384 } elseif (isset($this->_advancedElements[$element->getName()])){
1385 $anyAdvanced = true;
1388 // the last header may not be closed yet...
1389 if ($anyAdvanced && !is_null($lastHeader)){
1390 $this->setAdvanced($lastHeader->getName());
1392 $renderer->setAdvancedElements($this->_advancedElements);
1395 parent::accept($renderer);
1399 * @param string $elementName
1401 function closeHeaderBefore($elementName){
1402 $renderer =& $this->defaultRenderer();
1403 $renderer->addStopFieldsetElements($elementName);
1407 * Should be used for all elements of a form except for select, radio and checkboxes which
1408 * clean their own data.
1410 * @param string $elementname
1411 * @param integer $paramtype use the constants PARAM_*.
1412 * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
1413 * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
1414 * It will strip all html tags. But will still let tags for multilang support
1415 * through.
1416 * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
1417 * html editor. Data from the editor is later cleaned before display using
1418 * format_text() function. PARAM_RAW can also be used for data that is validated
1419 * by some other way or printed by p() or s().
1420 * * PARAM_INT should be used for integers.
1421 * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
1422 * form actions.
1424 function setType($elementname, $paramtype) {
1425 $this->_types[$elementname] = $paramtype;
1429 * See description of setType above. This can be used to set several types at once.
1431 * @param array $paramtypes
1433 function setTypes($paramtypes) {
1434 $this->_types = $paramtypes + $this->_types;
1438 * @param array $submission
1439 * @param array $files
1441 function updateSubmission($submission, $files) {
1442 $this->_flagSubmitted = false;
1444 if (empty($submission)) {
1445 $this->_submitValues = array();
1446 } else {
1447 foreach ($submission as $key=>$s) {
1448 if (array_key_exists($key, $this->_types)) {
1449 $submission[$key] = clean_param($s, $this->_types[$key]);
1452 $this->_submitValues = $submission;
1453 $this->_flagSubmitted = true;
1456 if (empty($files)) {
1457 $this->_submitFiles = array();
1458 } else {
1459 $this->_submitFiles = $files;
1460 $this->_flagSubmitted = true;
1463 // need to tell all elements that they need to update their value attribute.
1464 foreach (array_keys($this->_elements) as $key) {
1465 $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1470 * @return string
1472 function getReqHTML(){
1473 return $this->_reqHTML;
1477 * @return string
1479 function getAdvancedHTML(){
1480 return $this->_advancedHTML;
1484 * Initializes a default form value. Used to specify the default for a new entry where
1485 * no data is loaded in using moodleform::set_data()
1487 * note: $slashed param removed
1489 * @param string $elementname element name
1490 * @param mixed $values values for that element name
1491 * @access public
1492 * @return void
1494 function setDefault($elementName, $defaultValue){
1495 $this->setDefaults(array($elementName=>$defaultValue));
1496 } // end func setDefault
1498 * Add an array of buttons to the form
1499 * @param array $buttons An associative array representing help button to attach to
1500 * to the form. keys of array correspond to names of elements in form.
1501 * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
1502 * @param bool $suppresscheck
1503 * @param string $function
1504 * @access public
1506 function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1508 debugging('function moodle_form::setHelpButtons() is deprecated');
1509 //foreach ($buttons as $elementname => $button){
1510 // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1514 * Add a single button.
1516 * @deprecated use addHelpButton() instead
1517 * @param string $elementname name of the element to add the item to
1518 * @param array $button arguments to pass to function $function
1519 * @param boolean $suppresscheck whether to throw an error if the element
1520 * doesn't exist.
1521 * @param string $function - function to generate html from the arguments in $button
1522 * @param string $function
1524 function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
1525 global $OUTPUT;
1527 debugging('function moodle_form::setHelpButton() is deprecated');
1528 if ($function !== 'helpbutton') {
1529 //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
1532 $buttonargs = (array)$buttonargs;
1534 if (array_key_exists($elementname, $this->_elementIndex)) {
1535 //_elements has a numeric index, this code accesses the elements by name
1536 $element = $this->_elements[$this->_elementIndex[$elementname]];
1538 $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
1539 $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
1540 $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
1541 $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
1543 $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
1545 } else if (!$suppresscheck) {
1546 print_error('nonexistentformelements', 'form', '', $elementname);
1551 * Add a help button to element, only one button per element is allowed.
1553 * This is new, simplified and preferable method of setting a help icon on form elements.
1554 * It uses the new $OUTPUT->help_icon().
1556 * Typically, you will provide the same identifier and the component as you have used for the
1557 * label of the element. The string identifier with the _help suffix added is then used
1558 * as the help string.
1560 * There has to be two strings defined:
1561 * 1/ get_string($identifier, $component) - the title of the help page
1562 * 2/ get_string($identifier.'_help', $component) - the actual help page text
1564 * @since 2.0
1565 * @param string $elementname name of the element to add the item to
1566 * @param string $identifier help string identifier without _help suffix
1567 * @param string $component component name to look the help string in
1568 * @param string $linktext optional text to display next to the icon
1569 * @param boolean $suppresscheck set to true if the element may not exist
1570 * @return void
1572 function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
1573 global $OUTPUT;
1574 if (array_key_exists($elementname, $this->_elementIndex)) {
1575 $element = $this->_elements[$this->_elementIndex[$elementname]];
1576 $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
1577 } else if (!$suppresscheck) {
1578 debugging(get_string('nonexistentformelements', 'form', $elementname));
1583 * Set constant value not overridden by _POST or _GET
1584 * note: this does not work for complex names with [] :-(
1586 * @param string $elname name of element
1587 * @param mixed $value
1588 * @return void
1590 function setConstant($elname, $value) {
1591 $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1592 $element =& $this->getElement($elname);
1593 $element->onQuickFormEvent('updateValue', null, $this);
1597 * @param string $elementList
1599 function exportValues($elementList = null){
1600 $unfiltered = array();
1601 if (null === $elementList) {
1602 // iterate over all elements, calling their exportValue() methods
1603 $emptyarray = array();
1604 foreach (array_keys($this->_elements) as $key) {
1605 if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1606 $value = $this->_elements[$key]->exportValue($emptyarray, true);
1607 } else {
1608 $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1611 if (is_array($value)) {
1612 // This shit throws a bogus warning in PHP 4.3.x
1613 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1616 } else {
1617 if (!is_array($elementList)) {
1618 $elementList = array_map('trim', explode(',', $elementList));
1620 foreach ($elementList as $elementName) {
1621 $value = $this->exportValue($elementName);
1622 if (PEAR::isError($value)) {
1623 return $value;
1625 //oh, stock QuickFOrm was returning array of arrays!
1626 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1630 if (is_array($this->_constantValues)) {
1631 $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
1634 return $unfiltered;
1637 * Adds a validation rule for the given field
1639 * If the element is in fact a group, it will be considered as a whole.
1640 * To validate grouped elements as separated entities,
1641 * use addGroupRule instead of addRule.
1643 * @param string $element Form element name
1644 * @param string $message Message to display for invalid data
1645 * @param string $type Rule type, use getRegisteredRules() to get types
1646 * @param string $format (optional)Required for extra rule data
1647 * @param string $validation (optional)Where to perform validation: "server", "client"
1648 * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
1649 * @param boolean $force Force the rule to be applied, even if the target form element does not exist
1650 * @access public
1652 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1654 parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1655 if ($validation == 'client') {
1656 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1659 } // end func addRule
1661 * Adds a validation rule for the given group of elements
1663 * Only groups with a name can be assigned a validation rule
1664 * Use addGroupRule when you need to validate elements inside the group.
1665 * Use addRule if you need to validate the group as a whole. In this case,
1666 * the same rule will be applied to all elements in the group.
1667 * Use addRule if you need to validate the group against a function.
1669 * @param string $group Form group name
1670 * @param mixed $arg1 Array for multiple elements or error message string for one element
1671 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1672 * @param string $format (optional)Required for extra rule data
1673 * @param int $howmany (optional)How many valid elements should be in the group
1674 * @param string $validation (optional)Where to perform validation: "server", "client"
1675 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1676 * @access public
1678 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1680 parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1681 if (is_array($arg1)) {
1682 foreach ($arg1 as $rules) {
1683 foreach ($rules as $rule) {
1684 $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1686 if ('client' == $validation) {
1687 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1691 } elseif (is_string($arg1)) {
1693 if ($validation == 'client') {
1694 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1697 } // end func addGroupRule
1699 // }}}
1701 * Returns the client side validation script
1703 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1704 * and slightly modified to run rules per-element
1705 * Needed to override this because of an error with client side validation of grouped elements.
1707 * @access public
1708 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1710 function getValidationScript()
1712 if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
1713 return '';
1716 include_once('HTML/QuickForm/RuleRegistry.php');
1717 $registry =& HTML_QuickForm_RuleRegistry::singleton();
1718 $test = array();
1719 $js_escape = array(
1720 "\r" => '\r',
1721 "\n" => '\n',
1722 "\t" => '\t',
1723 "'" => "\\'",
1724 '"' => '\"',
1725 '\\' => '\\\\'
1728 foreach ($this->_rules as $elementName => $rules) {
1729 foreach ($rules as $rule) {
1730 if ('client' == $rule['validation']) {
1731 unset($element); //TODO: find out how to properly initialize it
1733 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1734 $rule['message'] = strtr($rule['message'], $js_escape);
1736 if (isset($rule['group'])) {
1737 $group =& $this->getElement($rule['group']);
1738 // No JavaScript validation for frozen elements
1739 if ($group->isFrozen()) {
1740 continue 2;
1742 $elements =& $group->getElements();
1743 foreach (array_keys($elements) as $key) {
1744 if ($elementName == $group->getElementName($key)) {
1745 $element =& $elements[$key];
1746 break;
1749 } elseif ($dependent) {
1750 $element = array();
1751 $element[] =& $this->getElement($elementName);
1752 foreach ($rule['dependent'] as $elName) {
1753 $element[] =& $this->getElement($elName);
1755 } else {
1756 $element =& $this->getElement($elementName);
1758 // No JavaScript validation for frozen elements
1759 if (is_object($element) && $element->isFrozen()) {
1760 continue 2;
1761 } elseif (is_array($element)) {
1762 foreach (array_keys($element) as $key) {
1763 if ($element[$key]->isFrozen()) {
1764 continue 3;
1768 //for editor element, [text] is appended to the name.
1769 if ($element->getType() == 'editor') {
1770 $elementName .= '[text]';
1771 //Add format to rule as moodleform check which format is supported by browser
1772 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1773 if (is_null($rule['format'])) {
1774 $rule['format'] = $element->getFormat();
1777 // Fix for bug displaying errors for elements in a group
1778 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1779 $test[$elementName][1]=$element;
1780 //end of fix
1785 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1786 // the form, and then that form field gets corrupted by the code that follows.
1787 unset($element);
1789 $js = '
1790 <script type="text/javascript">
1791 //<![CDATA[
1793 var skipClientValidation = false;
1795 function qf_errorHandler(element, _qfMsg) {
1796 div = element.parentNode;
1798 if ((div == undefined) || (element.name == undefined)) {
1799 //no checking can be done for undefined elements so let server handle it.
1800 return true;
1803 if (_qfMsg != \'\') {
1804 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1805 if (!errorSpan) {
1806 errorSpan = document.createElement("span");
1807 errorSpan.id = \'id_error_\'+element.name;
1808 errorSpan.className = "error";
1809 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1812 while (errorSpan.firstChild) {
1813 errorSpan.removeChild(errorSpan.firstChild);
1816 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1817 errorSpan.appendChild(document.createElement("br"));
1819 if (div.className.substr(div.className.length - 6, 6) != " error"
1820 && div.className != "error") {
1821 div.className += " error";
1824 return false;
1825 } else {
1826 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1827 if (errorSpan) {
1828 errorSpan.parentNode.removeChild(errorSpan);
1831 if (div.className.substr(div.className.length - 6, 6) == " error") {
1832 div.className = div.className.substr(0, div.className.length - 6);
1833 } else if (div.className == "error") {
1834 div.className = "";
1837 return true;
1840 $validateJS = '';
1841 foreach ($test as $elementName => $jsandelement) {
1842 // Fix for bug displaying errors for elements in a group
1843 //unset($element);
1844 list($jsArr,$element)=$jsandelement;
1845 //end of fix
1846 $escapedElementName = preg_replace_callback(
1847 '/[_\[\]]/',
1848 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1849 $elementName);
1850 $js .= '
1851 function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
1852 if (undefined == element) {
1853 //required element was not found, then let form be submitted without client side validation
1854 return true;
1856 var value = \'\';
1857 var errFlag = new Array();
1858 var _qfGroups = {};
1859 var _qfMsg = \'\';
1860 var frm = element.parentNode;
1861 if ((undefined != element.name) && (frm != undefined)) {
1862 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1863 frm = frm.parentNode;
1865 ' . join("\n", $jsArr) . '
1866 return qf_errorHandler(element, _qfMsg);
1867 } else {
1868 //element name should be defined else error msg will not be displayed.
1869 return true;
1873 $validateJS .= '
1874 ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1875 if (!ret && !first_focus) {
1876 first_focus = true;
1877 frm.elements[\''.$elementName.'\'].focus();
1881 // Fix for bug displaying errors for elements in a group
1882 //unset($element);
1883 //$element =& $this->getElement($elementName);
1884 //end of fix
1885 $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
1886 $onBlur = $element->getAttribute('onBlur');
1887 $onChange = $element->getAttribute('onChange');
1888 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1889 'onChange' => $onChange . $valFunc));
1891 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1892 $js .= '
1893 function validate_' . $this->_formName . '(frm) {
1894 if (skipClientValidation) {
1895 return true;
1897 var ret = true;
1899 var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
1900 var first_focus = false;
1901 ' . $validateJS . ';
1902 return ret;
1904 //]]>
1905 </script>';
1906 return $js;
1907 } // end func getValidationScript
1908 function _setDefaultRuleMessages(){
1909 foreach ($this->_rules as $field => $rulesarr){
1910 foreach ($rulesarr as $key => $rule){
1911 if ($rule['message']===null){
1912 $a=new stdClass();
1913 $a->format=$rule['format'];
1914 $str=get_string('err_'.$rule['type'], 'form', $a);
1915 if (strpos($str, '[[')!==0){
1916 $this->_rules[$field][$key]['message']=$str;
1923 function getLockOptionObject(){
1924 $result = array();
1925 foreach ($this->_dependencies as $dependentOn => $conditions){
1926 $result[$dependentOn] = array();
1927 foreach ($conditions as $condition=>$values) {
1928 $result[$dependentOn][$condition] = array();
1929 foreach ($values as $value=>$dependents) {
1930 $result[$dependentOn][$condition][$value] = array();
1931 $i = 0;
1932 foreach ($dependents as $dependent) {
1933 $elements = $this->_getElNamesRecursive($dependent);
1934 if (empty($elements)) {
1935 // probably element inside of some group
1936 $elements = array($dependent);
1938 foreach($elements as $element) {
1939 if ($element == $dependentOn) {
1940 continue;
1942 $result[$dependentOn][$condition][$value][] = $element;
1948 return array($this->getAttribute('id'), $result);
1952 * @param mixed $element
1953 * @return array
1955 function _getElNamesRecursive($element) {
1956 if (is_string($element)) {
1957 if (!$this->elementExists($element)) {
1958 return array();
1960 $element = $this->getElement($element);
1963 if (is_a($element, 'HTML_QuickForm_group')) {
1964 $elsInGroup = $element->getElements();
1965 $elNames = array();
1966 foreach ($elsInGroup as $elInGroup){
1967 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
1968 // not sure if this would work - groups nested in groups
1969 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
1970 } else {
1971 $elNames[] = $element->getElementName($elInGroup->getName());
1975 } else if (is_a($element, 'HTML_QuickForm_header')) {
1976 return array();
1978 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
1979 return array();
1981 } else if (method_exists($element, 'getPrivateName') &&
1982 !($element instanceof HTML_QuickForm_advcheckbox)) {
1983 // The advcheckbox element implements a method called getPrivateName,
1984 // but in a way that is not compatible with the generic API, so we
1985 // have to explicitly exclude it.
1986 return array($element->getPrivateName());
1988 } else {
1989 $elNames = array($element->getName());
1992 return $elNames;
1996 * Adds a dependency for $elementName which will be disabled if $condition is met.
1997 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
1998 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
1999 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2000 * of the $dependentOn element is $condition (such as equal) to $value.
2002 * @param string $elementName the name of the element which will be disabled
2003 * @param string $dependentOn the name of the element whose state will be checked for
2004 * condition
2005 * @param string $condition the condition to check
2006 * @param mixed $value used in conjunction with condition.
2008 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
2009 if (!array_key_exists($dependentOn, $this->_dependencies)) {
2010 $this->_dependencies[$dependentOn] = array();
2012 if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
2013 $this->_dependencies[$dependentOn][$condition] = array();
2015 if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
2016 $this->_dependencies[$dependentOn][$condition][$value] = array();
2018 $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
2021 function registerNoSubmitButton($buttonname){
2022 $this->_noSubmitButtons[]=$buttonname;
2026 * @param string $buttonname
2027 * @return mixed
2029 function isNoSubmitButton($buttonname){
2030 return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
2034 * @param string $buttonname
2036 function _registerCancelButton($addfieldsname){
2037 $this->_cancelButtons[]=$addfieldsname;
2040 * Displays elements without HTML input tags.
2041 * This method is different to freeze() in that it makes sure no hidden
2042 * elements are included in the form.
2043 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2045 * This function also removes all previously defined rules.
2047 * @param mixed $elementList array or string of element(s) to be frozen
2048 * @access public
2050 function hardFreeze($elementList=null)
2052 if (!isset($elementList)) {
2053 $this->_freezeAll = true;
2054 $elementList = array();
2055 } else {
2056 if (!is_array($elementList)) {
2057 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2059 $elementList = array_flip($elementList);
2062 foreach (array_keys($this->_elements) as $key) {
2063 $name = $this->_elements[$key]->getName();
2064 if ($this->_freezeAll || isset($elementList[$name])) {
2065 $this->_elements[$key]->freeze();
2066 $this->_elements[$key]->setPersistantFreeze(false);
2067 unset($elementList[$name]);
2069 // remove all rules
2070 $this->_rules[$name] = array();
2071 // if field is required, remove the rule
2072 $unset = array_search($name, $this->_required);
2073 if ($unset !== false) {
2074 unset($this->_required[$unset]);
2079 if (!empty($elementList)) {
2080 return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
2082 return true;
2085 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2087 * This function also removes all previously defined rules of elements it freezes.
2089 * throws HTML_QuickForm_Error
2091 * @param array $elementList array or string of element(s) not to be frozen
2092 * @access public
2094 function hardFreezeAllVisibleExcept($elementList)
2096 $elementList = array_flip($elementList);
2097 foreach (array_keys($this->_elements) as $key) {
2098 $name = $this->_elements[$key]->getName();
2099 $type = $this->_elements[$key]->getType();
2101 if ($type == 'hidden'){
2102 // leave hidden types as they are
2103 } elseif (!isset($elementList[$name])) {
2104 $this->_elements[$key]->freeze();
2105 $this->_elements[$key]->setPersistantFreeze(false);
2107 // remove all rules
2108 $this->_rules[$name] = array();
2109 // if field is required, remove the rule
2110 $unset = array_search($name, $this->_required);
2111 if ($unset !== false) {
2112 unset($this->_required[$unset]);
2116 return true;
2119 * Tells whether the form was already submitted
2121 * This is useful since the _submitFiles and _submitValues arrays
2122 * may be completely empty after the trackSubmit value is removed.
2124 * @access public
2125 * @return bool
2127 function isSubmitted()
2129 return parent::isSubmitted() && (!$this->isFrozen());
2135 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2136 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2138 * Stylesheet is part of standard theme and should be automatically included.
2140 * @package moodlecore
2141 * @copyright Jamie Pratt <me@jamiep.org>
2142 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2144 class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
2147 * Element template array
2148 * @var array
2149 * @access private
2151 var $_elementTemplates;
2153 * Template used when opening a hidden fieldset
2154 * (i.e. a fieldset that is opened when there is no header element)
2155 * @var string
2156 * @access private
2158 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2160 * Header Template string
2161 * @var string
2162 * @access private
2164 var $_headerTemplate =
2165 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2168 * Template used when opening a fieldset
2169 * @var string
2170 * @access private
2172 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2175 * Template used when closing a fieldset
2176 * @var string
2177 * @access private
2179 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2182 * Required Note template string
2183 * @var string
2184 * @access private
2186 var $_requiredNoteTemplate =
2187 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2189 var $_advancedElements = array();
2192 * Whether to display advanced elements (on page load)
2194 * @var integer 1 means show 0 means hide
2196 var $_showAdvanced;
2198 function MoodleQuickForm_Renderer(){
2199 // switch next two lines for ol li containers for form items.
2200 // $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>');
2201 $this->_elementTemplates = array(
2202 '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>',
2204 '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>',
2206 '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>',
2208 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2210 'nodisplay'=>'');
2212 parent::HTML_QuickForm_Renderer_Tableless();
2216 * @param array $elements
2218 function setAdvancedElements($elements){
2219 $this->_advancedElements = $elements;
2223 * What to do when starting the form
2225 * @param object $form MoodleQuickForm
2227 function startForm(&$form){
2228 $this->_reqHTML = $form->getReqHTML();
2229 $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
2230 $this->_advancedHTML = $form->getAdvancedHTML();
2231 $this->_showAdvanced = $form->getShowAdvanced();
2232 parent::startForm($form);
2233 if ($form->isFrozen()){
2234 $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
2235 } else {
2236 $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2237 $this->_hiddenHtml .= $form->_pageparams;
2244 * @param object $group Passed by reference
2245 * @param mixed $required
2246 * @param mixed $error
2248 function startGroup(&$group, $required, $error){
2249 // Make sure the element has an id.
2250 $group->_generateId();
2252 if (method_exists($group, 'getElementTemplateType')){
2253 $html = $this->_elementTemplates[$group->getElementTemplateType()];
2254 }else{
2255 $html = $this->_elementTemplates['default'];
2258 if ($this->_showAdvanced){
2259 $advclass = ' advanced';
2260 } else {
2261 $advclass = ' advanced hide';
2263 if (isset($this->_advancedElements[$group->getName()])){
2264 $html =str_replace(' {advanced}', $advclass, $html);
2265 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2266 } else {
2267 $html =str_replace(' {advanced}', '', $html);
2268 $html =str_replace('{advancedimg}', '', $html);
2270 if (method_exists($group, 'getHelpButton')){
2271 $html =str_replace('{help}', $group->getHelpButton(), $html);
2272 }else{
2273 $html =str_replace('{help}', '', $html);
2275 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2276 $html =str_replace('{name}', $group->getName(), $html);
2277 $html =str_replace('{type}', 'fgroup', $html);
2279 $this->_templates[$group->getName()]=$html;
2280 // Fix for bug in tableless quickforms that didn't allow you to stop a
2281 // fieldset before a group of elements.
2282 // if the element name indicates the end of a fieldset, close the fieldset
2283 if ( in_array($group->getName(), $this->_stopFieldsetElements)
2284 && $this->_fieldsetsOpen > 0
2286 $this->_html .= $this->_closeFieldsetTemplate;
2287 $this->_fieldsetsOpen--;
2289 parent::startGroup($group, $required, $error);
2292 * @param object $element
2293 * @param mixed $required
2294 * @param mixed $error
2296 function renderElement(&$element, $required, $error){
2297 // Make sure the element has an id.
2298 $element->_generateId();
2300 //adding stuff to place holders in template
2301 //check if this is a group element first
2302 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2303 // so it gets substitutions for *each* element
2304 $html = $this->_groupElementTemplate;
2306 elseif (method_exists($element, 'getElementTemplateType')){
2307 $html = $this->_elementTemplates[$element->getElementTemplateType()];
2308 }else{
2309 $html = $this->_elementTemplates['default'];
2311 if ($this->_showAdvanced){
2312 $advclass = ' advanced';
2313 } else {
2314 $advclass = ' advanced hide';
2316 if (isset($this->_advancedElements[$element->getName()])){
2317 $html =str_replace(' {advanced}', $advclass, $html);
2318 } else {
2319 $html =str_replace(' {advanced}', '', $html);
2321 if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
2322 $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
2323 } else {
2324 $html =str_replace('{advancedimg}', '', $html);
2326 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2327 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2328 $html =str_replace('{name}', $element->getName(), $html);
2329 if (method_exists($element, 'getHelpButton')){
2330 $html = str_replace('{help}', $element->getHelpButton(), $html);
2331 }else{
2332 $html = str_replace('{help}', '', $html);
2335 if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
2336 $this->_groupElementTemplate = $html;
2338 elseif (!isset($this->_templates[$element->getName()])) {
2339 $this->_templates[$element->getName()] = $html;
2342 parent::renderElement($element, $required, $error);
2346 * @global moodle_page $PAGE
2347 * @param object $form Passed by reference
2349 function finishForm(&$form){
2350 global $PAGE;
2351 if ($form->isFrozen()){
2352 $this->_hiddenHtml = '';
2354 parent::finishForm($form);
2355 if (!$form->isFrozen()) {
2356 $args = $form->getLockOptionObject();
2357 if (count($args[1]) > 0) {
2358 $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
2363 * Called when visiting a header element
2365 * @param object $header An HTML_QuickForm_header element being visited
2366 * @access public
2367 * @return void
2368 * @global moodle_page $PAGE
2370 function renderHeader(&$header) {
2371 global $PAGE;
2373 $name = $header->getName();
2375 $id = empty($name) ? '' : ' id="' . $name . '"';
2376 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2377 if (is_null($header->_text)) {
2378 $header_html = '';
2379 } elseif (!empty($name) && isset($this->_templates[$name])) {
2380 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
2381 } else {
2382 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
2385 if (isset($this->_advancedElements[$name])){
2386 $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
2387 $elementName='mform_showadvanced';
2388 if ($this->_showAdvanced==0){
2389 $buttonlabel = get_string('showadvanced', 'form');
2390 } else {
2391 $buttonlabel = get_string('hideadvanced', 'form');
2393 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2394 $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
2395 $header_html = str_replace('{button}', $button, $header_html);
2396 } else {
2397 $header_html =str_replace('{advancedimg}', '', $header_html);
2398 $header_html = str_replace('{button}', '', $header_html);
2401 if ($this->_fieldsetsOpen > 0) {
2402 $this->_html .= $this->_closeFieldsetTemplate;
2403 $this->_fieldsetsOpen--;
2406 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
2407 if ($this->_showAdvanced){
2408 $advclass = ' class="advanced"';
2409 } else {
2410 $advclass = ' class="advanced hide"';
2412 if (isset($this->_advancedElements[$name])){
2413 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2414 } else {
2415 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2417 $this->_html .= $openFieldsetTemplate . $header_html;
2418 $this->_fieldsetsOpen++;
2419 } // end func renderHeader
2421 function getStopFieldsetElements(){
2422 return $this->_stopFieldsetElements;
2427 * Required elements validation
2428 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2430 class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
2432 * Checks if an element is not empty.
2433 * This is a server-side validation, it works for both text fields and editor fields
2435 * @param string $value Value to check
2436 * @param mixed $options Not used yet
2437 * @return boolean true if value is not empty
2439 function validate($value, $options = null) {
2440 global $CFG;
2441 if (is_array($value) && array_key_exists('text', $value)) {
2442 $value = $value['text'];
2444 if (is_array($value)) {
2445 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2446 $value = implode('', $value);
2448 $stripvalues = array(
2449 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2450 '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
2452 if (!empty($CFG->strictformsrequired)) {
2453 $value = preg_replace($stripvalues, '', (string)$value);
2455 if ((string)$value == '') {
2456 return false;
2458 return true;
2462 * This function returns Javascript code used to build client-side validation.
2463 * It checks if an element is not empty.
2465 * @param int $format
2466 * @return array
2468 function getValidationScript($format = null) {
2469 global $CFG;
2470 if (!empty($CFG->strictformsrequired)) {
2471 if (!empty($format) && $format == FORMAT_HTML) {
2472 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
2473 } else {
2474 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2476 } else {
2477 return array('', "{jsVar} == ''");
2483 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2484 * @name $_HTML_QuickForm_default_renderer
2486 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2488 /** Please keep this list in alphabetical order. */
2489 MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2490 MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2491 MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2492 MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2493 MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2494 MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2495 MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2496 MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2497 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2498 MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
2499 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2500 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2501 MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
2502 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2503 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2504 MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2505 MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2506 MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2507 MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2508 MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2509 MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2510 MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2511 MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2512 MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2513 MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2514 MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2515 MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2516 MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2517 MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2518 MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2519 MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2520 MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2521 MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2522 MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2523 MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2524 MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2526 MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");