2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
25 * See examples of use of this library in course/edit.php and course/edit_form.php
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 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';
49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
51 define('EDITOR_UNLIMITED_FILES', -1);
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';
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() {
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);
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.
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 */
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
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';
167 if (strpos($attributes, 'autocomplete') === false) {
168 $attributes .= ' autocomplete="off" ';
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);
188 $this->_form
->hardFreeze();
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
);
229 if (isset($form->_errors
) && 0 != count($form->_errors
)){
230 $errorkeys = array_keys($form->_errors
);
231 $elkeys = array_intersect($elkeys, $errorkeys);
235 if ($error or empty($name)) {
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);
248 $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
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;
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');
278 $submission = 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;
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
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) {
312 $errors[$elname] = get_string('required');
314 unset($_FILES[$elname]);
318 if (!empty($file['error'])) {
319 $errors[$elname] = file_get_upload_error($file['error']);
320 unset($_FILES[$elname]);
324 if (!is_uploaded_file($file['tmp_name'])) {
325 // TODO: improve error message
326 $errors[$elname] = get_string('error');
327 unset($_FILES[$elname]);
331 if (!$this->_form
->elementExists($elname) or !$this->_form
->getElementType($elname)=='file') {
332 // hmm, this file was not requested
333 unset($_FILES[$elname]);
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]);
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]);
354 if (in_array($filename, $filenames)) {
355 // TODO: improve error message - duplicate name
356 $errors[$elname] = get_string('error');
357 unset($_FILES[$elname]);
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){
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() {
384 $mform =& $this->_form
;
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
408 foreach ($mform->_elements
as $element) {
409 if ($element->_type
== 'filemanager') {
410 $maxfiles = $element->getMaxfiles();
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)) {
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
460 function no_submit_button_pressed(){
461 static $nosubmit = null; // one check is enough
462 if (!is_null($nosubmit)){
465 $mform =& $this->_form
;
467 if (!$this->is_submitted()){
470 foreach ($mform->_noSubmitButtons
as $nosubmitbutton){
471 if (optional_param($nosubmitbutton, 0, PARAM_RAW
)){
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();
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)){
519 } elseif ($validated === null) {
520 $internal_val = $mform->validate();
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);
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);
553 // anything else means validation ok
557 $validated = ($internal_val and $moodle_val and $file_val);
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
)){
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
597 return (object)$data;
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
620 return (object)$data;
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');
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) {
651 if (!$this->is_submitted() or !$this->is_validated()) {
655 if (is_null($elname)) {
656 if (empty($_FILES)) {
660 $elname = key($_FILES);
663 if (empty($elname)) {
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])) {
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)) {
680 $file = reset($files);
681 return $file->get_filename();
684 if (!isset($_FILES[$elname])) {
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) {
702 if (!$this->is_submitted() or !$this->is_validated()) {
705 if (file_exists($pathname)) {
707 if (!@unlink
($pathname)) {
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])) {
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)) {
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);
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)) {
749 if (!$dir = make_temp_directory('forms')) {
752 if (!$tempfile = tempnam($dir, 'tempup_')) {
755 if (!$this->save_file($elname, $tempfile, true)) {
756 // something went wrong
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) {
774 if (!$this->is_submitted()) {
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])) {
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)) {
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) {
814 if (!$this->is_submitted() or !$this->is_validated()) {
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])) {
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)) {
835 $file = reset($files);
836 if (is_null($newfilename)) {
837 $newfilename = $file->get_filename();
841 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
842 if (!$oldfile->delete()) {
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;
856 if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
857 if (!$oldfile->delete()) {
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']);
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) {
880 if (!$this->is_submitted() or !$this->is_validated()) {
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])) {
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)) {
897 $file = reset($files);
899 return $file->get_content();
901 } else if (isset($_FILES[$elname])) {
902 return file_get_contents($_FILES[$elname]['tmp_name']);
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) {
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;
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()));
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);
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, '[');
1034 $realelementname = substr($elementname, 0, $pos)."[$i]";
1035 $realelementname .= substr($elementname, $pos);
1037 $realelementname = $elementname."[$i]";
1039 foreach ($elementoptions as $option => $params){
1043 $mform->setDefault($realelementname, str_replace('{no}', $i +
1, $params));
1046 $params = array_merge(array($realelementname), $params);
1047 call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1050 foreach ($namecloned as $num => $name){
1051 if ($params[0] == $name){
1052 $params[0] = $params[0]."[$i]";
1056 $params = array_merge(array($realelementname), $params);
1057 call_user_func_array(array(&$mform, 'disabledIf'), $params);
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);
1067 //Type should be set only once
1068 if (!isset($mform->_types
[$elementname])) {
1069 $mform->setType($elementname, $params);
1076 $mform->addElement('submit', $addfieldsname, $addstring);
1078 if (!$addbuttoninside) {
1079 $mform->closeHeaderBefore($addfieldsname);
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) {
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
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',
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
;
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');
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}.
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)
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) {
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);
1208 $PAGE->requires
->string_for_js($string, 'moodle');
1216 * Returns a JS module definition for the mforms JS
1220 public static function get_js_module() {
1224 'fullpath' => '/lib/form/form.js',
1225 'requires' => array('base', 'node'),
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
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.
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.
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();
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;
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'));
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){
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){
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
);
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;
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
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();
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;
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();
1514 foreach ($submission as $key=>$s) {
1515 if (array_key_exists($key, $this->_types
)) {
1516 $type = $this->_types
[$key];
1521 $submission[$key] = clean_param_array($s, $type, true);
1523 $submission[$key] = clean_param($s, $type);
1526 $this->_submitValues
= $submission;
1527 $this->_flagSubmitted
= true;
1530 if (empty($files)) {
1531 $this->_submitFiles
= array();
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
1548 function getReqHTML(){
1549 return $this->_reqHTML
;
1553 * Returns HTML for advanced elements
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
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) {
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
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'];
1632 // If we have a default value then export it.
1633 if (isset($this->_defaultValues
[$varname])) {
1634 $value = array($varname => $this->_defaultValues
[$varname]);
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);
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)) {
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
);
1666 * Adds a validation rule for the given field
1668 * If the element is in fact a group, it will be considered as a whole.
1669 * To validate grouped elements as separated entities,
1670 * use addGroupRule instead of addRule.
1672 * @param string $element Form element name
1673 * @param string $message Message to display for invalid data
1674 * @param string $type Rule type, use getRegisteredRules() to get types
1675 * @param string $format (optional)Required for extra rule data
1676 * @param string $validation (optional)Where to perform validation: "server", "client"
1677 * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
1678 * @param bool $force Force the rule to be applied, even if the target form element does not exist
1680 function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1682 parent
::addRule($element, $message, $type, $format, $validation, $reset, $force);
1683 if ($validation == 'client') {
1684 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1690 * Adds a validation rule for the given group of elements
1692 * Only groups with a name can be assigned a validation rule
1693 * Use addGroupRule when you need to validate elements inside the group.
1694 * Use addRule if you need to validate the group as a whole. In this case,
1695 * the same rule will be applied to all elements in the group.
1696 * Use addRule if you need to validate the group against a function.
1698 * @param string $group Form group name
1699 * @param array|string $arg1 Array for multiple elements or error message string for one element
1700 * @param string $type (optional)Rule type use getRegisteredRules() to get types
1701 * @param string $format (optional)Required for extra rule data
1702 * @param int $howmany (optional)How many valid elements should be in the group
1703 * @param string $validation (optional)Where to perform validation: "server", "client"
1704 * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
1706 function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1708 parent
::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1709 if (is_array($arg1)) {
1710 foreach ($arg1 as $rules) {
1711 foreach ($rules as $rule) {
1712 $validation = (isset($rule[3]) && 'client' == $rule[3])?
'client': 'server';
1714 if ('client' == $validation) {
1715 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1719 } elseif (is_string($arg1)) {
1721 if ($validation == 'client') {
1722 $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName
. '; } catch(e) { return true; } return myValidator(this);'));
1728 * Returns the client side validation script
1730 * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
1731 * and slightly modified to run rules per-element
1732 * Needed to override this because of an error with client side validation of grouped elements.
1734 * @return string Javascript to perform validation, empty string if no 'client' rules were added
1736 function getValidationScript()
1738 if (empty($this->_rules
) ||
empty($this->_attributes
['onsubmit'])) {
1742 include_once('HTML/QuickForm/RuleRegistry.php');
1743 $registry =& HTML_QuickForm_RuleRegistry
::singleton();
1754 foreach ($this->_rules
as $elementName => $rules) {
1755 foreach ($rules as $rule) {
1756 if ('client' == $rule['validation']) {
1757 unset($element); //TODO: find out how to properly initialize it
1759 $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
1760 $rule['message'] = strtr($rule['message'], $js_escape);
1762 if (isset($rule['group'])) {
1763 $group =& $this->getElement($rule['group']);
1764 // No JavaScript validation for frozen elements
1765 if ($group->isFrozen()) {
1768 $elements =& $group->getElements();
1769 foreach (array_keys($elements) as $key) {
1770 if ($elementName == $group->getElementName($key)) {
1771 $element =& $elements[$key];
1775 } elseif ($dependent) {
1777 $element[] =& $this->getElement($elementName);
1778 foreach ($rule['dependent'] as $elName) {
1779 $element[] =& $this->getElement($elName);
1782 $element =& $this->getElement($elementName);
1784 // No JavaScript validation for frozen elements
1785 if (is_object($element) && $element->isFrozen()) {
1787 } elseif (is_array($element)) {
1788 foreach (array_keys($element) as $key) {
1789 if ($element[$key]->isFrozen()) {
1794 //for editor element, [text] is appended to the name.
1795 if ($element->getType() == 'editor') {
1796 $elementName .= '[text]';
1797 //Add format to rule as moodleform check which format is supported by browser
1798 //it is not set anywhere... So small hack to make sure we pass it down to quickform
1799 if (is_null($rule['format'])) {
1800 $rule['format'] = $element->getFormat();
1803 // Fix for bug displaying errors for elements in a group
1804 $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
1805 $test[$elementName][1]=$element;
1811 // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
1812 // the form, and then that form field gets corrupted by the code that follows.
1816 <script type="text/javascript">
1819 var skipClientValidation = false;
1821 function qf_errorHandler(element, _qfMsg) {
1822 div = element.parentNode;
1824 if ((div == undefined) || (element.name == undefined)) {
1825 //no checking can be done for undefined elements so let server handle it.
1829 if (_qfMsg != \'\') {
1830 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1832 errorSpan = document.createElement("span");
1833 errorSpan.id = \'id_error_\'+element.name;
1834 errorSpan.className = "error";
1835 element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
1838 while (errorSpan.firstChild) {
1839 errorSpan.removeChild(errorSpan.firstChild);
1842 errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
1843 errorSpan.appendChild(document.createElement("br"));
1845 if (div.className.substr(div.className.length - 6, 6) != " error"
1846 && div.className != "error") {
1847 div.className += " error";
1852 var errorSpan = document.getElementById(\'id_error_\'+element.name);
1854 errorSpan.parentNode.removeChild(errorSpan);
1857 if (div.className.substr(div.className.length - 6, 6) == " error") {
1858 div.className = div.className.substr(0, div.className.length - 6);
1859 } else if (div.className == "error") {
1867 foreach ($test as $elementName => $jsandelement) {
1868 // Fix for bug displaying errors for elements in a group
1870 list($jsArr,$element)=$jsandelement;
1872 $escapedElementName = preg_replace_callback(
1874 create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
1877 function validate_' . $this->_formName
. '_' . $escapedElementName . '(element) {
1878 if (undefined == element) {
1879 //required element was not found, then let form be submitted without client side validation
1883 var errFlag = new Array();
1886 var frm = element.parentNode;
1887 if ((undefined != element.name) && (frm != undefined)) {
1888 while (frm && frm.nodeName.toUpperCase() != "FORM") {
1889 frm = frm.parentNode;
1891 ' . join("\n", $jsArr) . '
1892 return qf_errorHandler(element, _qfMsg);
1894 //element name should be defined else error msg will not be displayed.
1900 ret = validate_' . $this->_formName
. '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
1901 if (!ret && !first_focus) {
1903 frm.elements[\''.$elementName.'\'].focus();
1907 // Fix for bug displaying errors for elements in a group
1909 //$element =& $this->getElement($elementName);
1911 $valFunc = 'validate_' . $this->_formName
. '_' . $escapedElementName . '(this)';
1912 $onBlur = $element->getAttribute('onBlur');
1913 $onChange = $element->getAttribute('onChange');
1914 $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
1915 'onChange' => $onChange . $valFunc));
1917 // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
1919 function validate_' . $this->_formName
. '(frm) {
1920 if (skipClientValidation) {
1925 var frm = document.getElementById(\''. $this->_attributes
['id'] .'\')
1926 var first_focus = false;
1927 ' . $validateJS . ';
1933 } // end func getValidationScript
1936 * Sets default error message
1938 function _setDefaultRuleMessages(){
1939 foreach ($this->_rules
as $field => $rulesarr){
1940 foreach ($rulesarr as $key => $rule){
1941 if ($rule['message']===null){
1943 $a->format
=$rule['format'];
1944 $str=get_string('err_'.$rule['type'], 'form', $a);
1945 if (strpos($str, '[[')!==0){
1946 $this->_rules
[$field][$key]['message']=$str;
1954 * Get list of attributes which have dependencies
1958 function getLockOptionObject(){
1960 foreach ($this->_dependencies
as $dependentOn => $conditions){
1961 $result[$dependentOn] = array();
1962 foreach ($conditions as $condition=>$values) {
1963 $result[$dependentOn][$condition] = array();
1964 foreach ($values as $value=>$dependents) {
1965 $result[$dependentOn][$condition][$value] = array();
1967 foreach ($dependents as $dependent) {
1968 $elements = $this->_getElNamesRecursive($dependent);
1969 if (empty($elements)) {
1970 // probably element inside of some group
1971 $elements = array($dependent);
1973 foreach($elements as $element) {
1974 if ($element == $dependentOn) {
1977 $result[$dependentOn][$condition][$value][] = $element;
1983 return array($this->getAttribute('id'), $result);
1987 * Get names of element or elements in a group.
1989 * @param HTML_QuickForm_group|element $element element group or element object
1992 function _getElNamesRecursive($element) {
1993 if (is_string($element)) {
1994 if (!$this->elementExists($element)) {
1997 $element = $this->getElement($element);
2000 if (is_a($element, 'HTML_QuickForm_group')) {
2001 $elsInGroup = $element->getElements();
2003 foreach ($elsInGroup as $elInGroup){
2004 if (is_a($elInGroup, 'HTML_QuickForm_group')) {
2005 // not sure if this would work - groups nested in groups
2006 $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
2008 $elNames[] = $element->getElementName($elInGroup->getName());
2012 } else if (is_a($element, 'HTML_QuickForm_header')) {
2015 } else if (is_a($element, 'HTML_QuickForm_hidden')) {
2018 } else if (method_exists($element, 'getPrivateName') &&
2019 !($element instanceof HTML_QuickForm_advcheckbox
)) {
2020 // The advcheckbox element implements a method called getPrivateName,
2021 // but in a way that is not compatible with the generic API, so we
2022 // have to explicitly exclude it.
2023 return array($element->getPrivateName());
2026 $elNames = array($element->getName());
2033 * Adds a dependency for $elementName which will be disabled if $condition is met.
2034 * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
2035 * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
2036 * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
2037 * of the $dependentOn element is $condition (such as equal) to $value.
2039 * @param string $elementName the name of the element which will be disabled
2040 * @param string $dependentOn the name of the element whose state will be checked for condition
2041 * @param string $condition the condition to check
2042 * @param mixed $value used in conjunction with condition.
2044 function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
2045 if (!array_key_exists($dependentOn, $this->_dependencies
)) {
2046 $this->_dependencies
[$dependentOn] = array();
2048 if (!array_key_exists($condition, $this->_dependencies
[$dependentOn])) {
2049 $this->_dependencies
[$dependentOn][$condition] = array();
2051 if (!array_key_exists($value, $this->_dependencies
[$dependentOn][$condition])) {
2052 $this->_dependencies
[$dependentOn][$condition][$value] = array();
2054 $this->_dependencies
[$dependentOn][$condition][$value][] = $elementName;
2058 * Registers button as no submit button
2060 * @param string $buttonname name of the button
2062 function registerNoSubmitButton($buttonname){
2063 $this->_noSubmitButtons
[]=$buttonname;
2067 * Checks if button is a no submit button, i.e it doesn't submit form
2069 * @param string $buttonname name of the button to check
2072 function isNoSubmitButton($buttonname){
2073 return (array_search($buttonname, $this->_noSubmitButtons
)!==FALSE);
2077 * Registers a button as cancel button
2079 * @param string $addfieldsname name of the button
2081 function _registerCancelButton($addfieldsname){
2082 $this->_cancelButtons
[]=$addfieldsname;
2086 * Displays elements without HTML input tags.
2087 * This method is different to freeze() in that it makes sure no hidden
2088 * elements are included in the form.
2089 * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
2091 * This function also removes all previously defined rules.
2093 * @param string|array $elementList array or string of element(s) to be frozen
2094 * @return object|bool if element list is not empty then return error object, else true
2096 function hardFreeze($elementList=null)
2098 if (!isset($elementList)) {
2099 $this->_freezeAll
= true;
2100 $elementList = array();
2102 if (!is_array($elementList)) {
2103 $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
2105 $elementList = array_flip($elementList);
2108 foreach (array_keys($this->_elements
) as $key) {
2109 $name = $this->_elements
[$key]->getName();
2110 if ($this->_freezeAll ||
isset($elementList[$name])) {
2111 $this->_elements
[$key]->freeze();
2112 $this->_elements
[$key]->setPersistantFreeze(false);
2113 unset($elementList[$name]);
2116 $this->_rules
[$name] = array();
2117 // if field is required, remove the rule
2118 $unset = array_search($name, $this->_required
);
2119 if ($unset !== false) {
2120 unset($this->_required
[$unset]);
2125 if (!empty($elementList)) {
2126 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);
2132 * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
2134 * This function also removes all previously defined rules of elements it freezes.
2136 * @throws HTML_QuickForm_Error
2137 * @param array $elementList array or string of element(s) not to be frozen
2138 * @return bool returns true
2140 function hardFreezeAllVisibleExcept($elementList)
2142 $elementList = array_flip($elementList);
2143 foreach (array_keys($this->_elements
) as $key) {
2144 $name = $this->_elements
[$key]->getName();
2145 $type = $this->_elements
[$key]->getType();
2147 if ($type == 'hidden'){
2148 // leave hidden types as they are
2149 } elseif (!isset($elementList[$name])) {
2150 $this->_elements
[$key]->freeze();
2151 $this->_elements
[$key]->setPersistantFreeze(false);
2154 $this->_rules
[$name] = array();
2155 // if field is required, remove the rule
2156 $unset = array_search($name, $this->_required
);
2157 if ($unset !== false) {
2158 unset($this->_required
[$unset]);
2166 * Tells whether the form was already submitted
2168 * This is useful since the _submitFiles and _submitValues arrays
2169 * may be completely empty after the trackSubmit value is removed.
2173 function isSubmitted()
2175 return parent
::isSubmitted() && (!$this->isFrozen());
2180 * MoodleQuickForm renderer
2182 * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
2183 * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
2185 * Stylesheet is part of standard theme and should be automatically included.
2187 * @package core_form
2188 * @copyright 2007 Jamie Pratt <me@jamiep.org>
2189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2191 class MoodleQuickForm_Renderer
extends HTML_QuickForm_Renderer_Tableless
{
2193 /** @var array Element template array */
2194 var $_elementTemplates;
2197 * Template used when opening a hidden fieldset
2198 * (i.e. a fieldset that is opened when there is no header element)
2201 var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
2203 /** @var string Header Template string */
2204 var $_headerTemplate =
2205 "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
2207 /** @var string Template used when opening a fieldset */
2208 var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
2210 /** @var string Template used when closing a fieldset */
2211 var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
2213 /** @var string Required Note template string */
2214 var $_requiredNoteTemplate =
2215 "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
2217 /** @var array list of elements which are marked as advance and will be grouped together */
2218 var $_advancedElements = array();
2220 /** @var int Whether to display advanced elements (on page load) 1 => show, 0 => hide */
2226 function MoodleQuickForm_Renderer(){
2227 // switch next two lines for ol li containers for form items.
2228 // $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>');
2229 $this->_elementTemplates
= array(
2230 '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>',
2232 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
2234 '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>',
2236 '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} </div></div>',
2238 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
2242 parent
::HTML_QuickForm_Renderer_Tableless();
2246 * Set element's as adavance element
2248 * @param array $elements form elements which needs to be grouped as advance elements.
2250 function setAdvancedElements($elements){
2251 $this->_advancedElements
= $elements;
2255 * What to do when starting the form
2257 * @param MoodleQuickForm $form reference of the form
2259 function startForm(&$form){
2261 $this->_reqHTML
= $form->getReqHTML();
2262 $this->_elementTemplates
= str_replace('{req}', $this->_reqHTML
, $this->_elementTemplates
);
2263 $this->_advancedHTML
= $form->getAdvancedHTML();
2264 $this->_showAdvanced
= $form->getShowAdvanced();
2265 parent
::startForm($form);
2266 if ($form->isFrozen()){
2267 $this->_formTemplate
= "\n<div class=\"mform frozen\">\n{content}\n</div>";
2269 $this->_formTemplate
= "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
2270 $this->_hiddenHtml
.= $form->_pageparams
;
2273 if ($form->is_form_change_checker_enabled()) {
2274 $PAGE->requires
->yui_module('moodle-core-formchangechecker',
2275 'M.core_formchangechecker.init',
2277 'formid' => $form->getAttribute('id')
2280 $PAGE->requires
->string_for_js('changesmadereallygoaway', 'moodle');
2285 * Create advance group of elements
2287 * @param object $group Passed by reference
2288 * @param bool $required if input is required field
2289 * @param string $error error message to display
2291 function startGroup(&$group, $required, $error){
2292 // Make sure the element has an id.
2293 $group->_generateId();
2295 if (method_exists($group, 'getElementTemplateType')){
2296 $html = $this->_elementTemplates
[$group->getElementTemplateType()];
2298 $html = $this->_elementTemplates
['default'];
2301 if ($this->_showAdvanced
){
2302 $advclass = ' advanced';
2304 $advclass = ' advanced hide';
2306 if (isset($this->_advancedElements
[$group->getName()])){
2307 $html =str_replace(' {advanced}', $advclass, $html);
2308 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
2310 $html =str_replace(' {advanced}', '', $html);
2311 $html =str_replace('{advancedimg}', '', $html);
2313 if (method_exists($group, 'getHelpButton')){
2314 $html =str_replace('{help}', $group->getHelpButton(), $html);
2316 $html =str_replace('{help}', '', $html);
2318 $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
2319 $html =str_replace('{name}', $group->getName(), $html);
2320 $html =str_replace('{type}', 'fgroup', $html);
2322 $this->_templates
[$group->getName()]=$html;
2323 // Fix for bug in tableless quickforms that didn't allow you to stop a
2324 // fieldset before a group of elements.
2325 // if the element name indicates the end of a fieldset, close the fieldset
2326 if ( in_array($group->getName(), $this->_stopFieldsetElements
)
2327 && $this->_fieldsetsOpen
> 0
2329 $this->_html
.= $this->_closeFieldsetTemplate
;
2330 $this->_fieldsetsOpen
--;
2332 parent
::startGroup($group, $required, $error);
2337 * @param HTML_QuickForm_element $element element
2338 * @param bool $required if input is required field
2339 * @param string $error error message to display
2341 function renderElement(&$element, $required, $error){
2342 // Make sure the element has an id.
2343 $element->_generateId();
2345 //adding stuff to place holders in template
2346 //check if this is a group element first
2347 if (($this->_inGroup
) and !empty($this->_groupElementTemplate
)) {
2348 // so it gets substitutions for *each* element
2349 $html = $this->_groupElementTemplate
;
2351 elseif (method_exists($element, 'getElementTemplateType')){
2352 $html = $this->_elementTemplates
[$element->getElementTemplateType()];
2354 $html = $this->_elementTemplates
['default'];
2356 if ($this->_showAdvanced
){
2357 $advclass = ' advanced';
2359 $advclass = ' advanced hide';
2361 if (isset($this->_advancedElements
[$element->getName()])){
2362 $html =str_replace(' {advanced}', $advclass, $html);
2364 $html =str_replace(' {advanced}', '', $html);
2366 if (isset($this->_advancedElements
[$element->getName()])||
$element->getName() == 'mform_showadvanced'){
2367 $html =str_replace('{advancedimg}', $this->_advancedHTML
, $html);
2369 $html =str_replace('{advancedimg}', '', $html);
2371 $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
2372 $html =str_replace('{type}', 'f'.$element->getType(), $html);
2373 $html =str_replace('{name}', $element->getName(), $html);
2374 if (method_exists($element, 'getHelpButton')){
2375 $html = str_replace('{help}', $element->getHelpButton(), $html);
2377 $html = str_replace('{help}', '', $html);
2380 if (($this->_inGroup
) and !empty($this->_groupElementTemplate
)) {
2381 $this->_groupElementTemplate
= $html;
2383 elseif (!isset($this->_templates
[$element->getName()])) {
2384 $this->_templates
[$element->getName()] = $html;
2387 parent
::renderElement($element, $required, $error);
2391 * Called when visiting a form, after processing all form elements
2392 * Adds required note, form attributes, validation javascript and form content.
2394 * @global moodle_page $PAGE
2395 * @param moodleform $form Passed by reference
2397 function finishForm(&$form){
2399 if ($form->isFrozen()){
2400 $this->_hiddenHtml
= '';
2402 parent
::finishForm($form);
2403 if (!$form->isFrozen()) {
2404 $args = $form->getLockOptionObject();
2405 if (count($args[1]) > 0) {
2406 $PAGE->requires
->js_init_call('M.form.initFormDependencies', $args, true, moodleform
::get_js_module());
2411 * Called when visiting a header element
2413 * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
2414 * @global moodle_page $PAGE
2416 function renderHeader(&$header) {
2419 $name = $header->getName();
2421 $id = empty($name) ?
'' : ' id="' . $name . '"';
2422 $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
2423 if (is_null($header->_text
)) {
2425 } elseif (!empty($name) && isset($this->_templates
[$name])) {
2426 $header_html = str_replace('{header}', $header->toHtml(), $this->_templates
[$name]);
2428 $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate
);
2431 if (isset($this->_advancedElements
[$name])){
2432 $header_html =str_replace('{advancedimg}', $this->_advancedHTML
, $header_html);
2433 $elementName='mform_showadvanced';
2434 if ($this->_showAdvanced
==0){
2435 $buttonlabel = get_string('showadvanced', 'form');
2437 $buttonlabel = get_string('hideadvanced', 'form');
2439 $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
2440 $PAGE->requires
->js_init_call('M.form.initShowAdvanced', array(), false, moodleform
::get_js_module());
2441 $header_html = str_replace('{button}', $button, $header_html);
2443 $header_html =str_replace('{advancedimg}', '', $header_html);
2444 $header_html = str_replace('{button}', '', $header_html);
2447 if ($this->_fieldsetsOpen
> 0) {
2448 $this->_html
.= $this->_closeFieldsetTemplate
;
2449 $this->_fieldsetsOpen
--;
2452 $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate
);
2453 if ($this->_showAdvanced
){
2454 $advclass = ' class="advanced"';
2456 $advclass = ' class="advanced hide"';
2458 if (isset($this->_advancedElements
[$name])){
2459 $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
2461 $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
2463 $this->_html
.= $openFieldsetTemplate . $header_html;
2464 $this->_fieldsetsOpen++
;
2468 * Return Array of element names that indicate the end of a fieldset
2472 function getStopFieldsetElements(){
2473 return $this->_stopFieldsetElements
;
2478 * Required elements validation
2480 * This class overrides QuickForm validation since it allowed space or empty tag as a value
2482 * @package core_form
2484 * @copyright 2006 Jamie Pratt <me@jamiep.org>
2485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2487 class MoodleQuickForm_Rule_Required
extends HTML_QuickForm_Rule
{
2489 * Checks if an element is not empty.
2490 * This is a server-side validation, it works for both text fields and editor fields
2492 * @param string $value Value to check
2493 * @param int|string|array $options Not used yet
2494 * @return bool true if value is not empty
2496 function validate($value, $options = null) {
2498 if (is_array($value) && array_key_exists('text', $value)) {
2499 $value = $value['text'];
2501 if (is_array($value)) {
2502 // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
2503 $value = implode('', $value);
2505 $stripvalues = array(
2506 '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
2507 '#(\xc2|\xa0|\s| )#', //any whitespaces actually
2509 if (!empty($CFG->strictformsrequired
)) {
2510 $value = preg_replace($stripvalues, '', (string)$value);
2512 if ((string)$value == '') {
2519 * This function returns Javascript code used to build client-side validation.
2520 * It checks if an element is not empty.
2522 * @param int $format format of data which needs to be validated.
2525 function getValidationScript($format = null) {
2527 if (!empty($CFG->strictformsrequired
)) {
2528 if (!empty($format) && $format == FORMAT_HTML
) {
2529 return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)| |\s+/ig, '') == ''");
2531 return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
2534 return array('', "{jsVar} == ''");
2540 * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
2541 * @name $_HTML_QuickForm_default_renderer
2543 $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
2545 /** Please keep this list in alphabetical order. */
2546 MoodleQuickForm
::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
2547 MoodleQuickForm
::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
2548 MoodleQuickForm
::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
2549 MoodleQuickForm
::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
2550 MoodleQuickForm
::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
2551 MoodleQuickForm
::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
2552 MoodleQuickForm
::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
2553 MoodleQuickForm
::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
2554 MoodleQuickForm
::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
2555 MoodleQuickForm
::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
2556 MoodleQuickForm
::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
2557 MoodleQuickForm
::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
2558 MoodleQuickForm
::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
2559 MoodleQuickForm
::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
2560 MoodleQuickForm
::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
2561 MoodleQuickForm
::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
2562 MoodleQuickForm
::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
2563 MoodleQuickForm
::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
2564 MoodleQuickForm
::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
2565 MoodleQuickForm
::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
2566 MoodleQuickForm
::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
2567 MoodleQuickForm
::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
2568 MoodleQuickForm
::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
2569 MoodleQuickForm
::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
2570 MoodleQuickForm
::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
2571 MoodleQuickForm
::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
2572 MoodleQuickForm
::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
2573 MoodleQuickForm
::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
2574 MoodleQuickForm
::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
2575 MoodleQuickForm
::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
2576 MoodleQuickForm
::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
2577 MoodleQuickForm
::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
2578 MoodleQuickForm
::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
2579 MoodleQuickForm
::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
2580 MoodleQuickForm
::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
2582 MoodleQuickForm
::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");