/lib/formslib.php
PHP | 2372 lines | 1610 code | 159 blank | 603 comment | 194 complexity | 600f783e23775d39d3c5a448490d1d88 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause
Large files files are truncated, but you can click here to view the full file
- <?php
- // This file is part of Moodle - http://moodle.org/
- //
- // Moodle is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // Moodle is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
- /**
- * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
- *
- * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
- * and you want to name your class something like {modulename}_{purpose}_form. Your class will
- * extend moodleform overriding abstract classes definition and optionally defintion_after_data
- * and validation.
- *
- * See examples of use of this library in course/edit.php and course/edit_form.php
- *
- * A few notes :
- * form definition is used for both printing of form and processing and should be the same
- * for both or you may lose some submitted data which won't be let through.
- * you should be using setType for every form element except select, radio or checkbox
- * elements, these elements clean themselves.
- *
- *
- * @copyright Jamie Pratt <me@jamiep.org>
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- * @package core
- * @subpackage form
- */
- defined('MOODLE_INTERNAL') || die();
- /** setup.php includes our hacked pear libs first */
- require_once 'HTML/QuickForm.php';
- require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
- require_once 'HTML/QuickForm/Renderer/Tableless.php';
- require_once $CFG->libdir.'/filelib.php';
- define('EDITOR_UNLIMITED_FILES', -1);
- /**
- * Callback called when PEAR throws an error
- *
- * @param PEAR_Error $error
- */
- function pear_handle_error($error){
- echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
- echo '<br /> <strong>Backtrace </strong>:';
- print_object($error->backtrace);
- }
- if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
- PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
- }
- /**
- *
- * @staticvar bool $done
- * @global moodle_page $PAGE
- */
- function form_init_date_js() {
- global $PAGE;
- static $done = false;
- if (!$done) {
- $module = 'moodle-form-dateselector';
- $function = 'M.form.dateselector.init_date_selectors';
- $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
- $PAGE->requires->yui_module($module, $function, $config);
- $done = true;
- }
- }
- /**
- * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
- * use this class you should write a class definition which extends this class or a more specific
- * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
- *
- * You will write your own definition() method which performs the form set up.
- *
- * @package moodlecore
- * @copyright Jamie Pratt <me@jamiep.org>
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
- abstract class moodleform {
- /** @var string */
- protected $_formname; // form name
- /**
- * quickform object definition
- *
- * @var MoodleQuickForm MoodleQuickForm
- */
- protected $_form;
- /**
- * globals workaround
- *
- * @var array
- */
- protected $_customdata;
- /**
- * definition_after_data executed flag
- * @var object definition_finalized
- */
- protected $_definition_finalized = false;
- /**
- * The constructor function calls the abstract function definition() and it will then
- * process and clean and attempt to validate incoming data.
- *
- * It will call your custom validate method to validate data and will also check any rules
- * you have specified in definition using addRule
- *
- * The name of the form (id attribute of the form) is automatically generated depending on
- * the name you gave the class extending moodleform. You should call your class something
- * like
- *
- * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
- * current url. If a moodle_url object then outputs params as hidden variables.
- * @param array $customdata if your form defintion method needs access to data such as $course
- * $cm, etc. to construct the form definition then pass it in this array. You can
- * use globals for somethings.
- * @param string $method if you set this to anything other than 'post' then _GET and _POST will
- * be merged and used as incoming data to the form.
- * @param string $target target frame for form submission. You will rarely use this. Don't use
- * it if you don't need to as the target attribute is deprecated in xhtml
- * strict.
- * @param mixed $attributes you can pass a string of html attributes here or an array.
- * @param bool $editable
- * @return object moodleform
- */
- function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
- if (empty($action)){
- $action = strip_querystring(qualified_me());
- }
- $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
- $this->_customdata = $customdata;
- $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
- if (!$editable){
- $this->_form->hardFreeze();
- }
- $this->definition();
- $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
- $this->_form->setType('sesskey', PARAM_RAW);
- $this->_form->setDefault('sesskey', sesskey());
- $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
- $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
- $this->_form->setDefault('_qf__'.$this->_formname, 1);
- $this->_form->_setDefaultRuleMessages();
- // we have to know all input types before processing submission ;-)
- $this->_process_submission($method);
- }
- /**
- * To autofocus on first form element or first element with error.
- *
- * @param string $name if this is set then the focus is forced to a field with this name
- *
- * @return string javascript to select form element with first error or
- * first element if no errors. Use this as a parameter
- * when calling print_header
- */
- function focus($name=NULL) {
- $form =& $this->_form;
- $elkeys = array_keys($form->_elementIndex);
- $error = false;
- if (isset($form->_errors) && 0 != count($form->_errors)){
- $errorkeys = array_keys($form->_errors);
- $elkeys = array_intersect($elkeys, $errorkeys);
- $error = true;
- }
- if ($error or empty($name)) {
- $names = array();
- while (empty($names) and !empty($elkeys)) {
- $el = array_shift($elkeys);
- $names = $form->_getElNamesRecursive($el);
- }
- if (!empty($names)) {
- $name = array_shift($names);
- }
- }
- $focus = '';
- if (!empty($name)) {
- $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
- }
- return $focus;
- }
- /**
- * Internal method. Alters submitted data to be suitable for quickforms processing.
- * Must be called when the form is fully set up.
- *
- * @param string $method
- */
- function _process_submission($method) {
- $submission = array();
- if ($method == 'post') {
- if (!empty($_POST)) {
- $submission = $_POST;
- }
- } else {
- $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
- }
- // following trick is needed to enable proper sesskey checks when using GET forms
- // the _qf__.$this->_formname serves as a marker that form was actually submitted
- if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
- if (!confirm_sesskey()) {
- print_error('invalidsesskey');
- }
- $files = $_FILES;
- } else {
- $submission = array();
- $files = array();
- }
- $this->_form->updateSubmission($submission, $files);
- }
- /**
- * Internal method. Validates all old-style deprecated uploaded files.
- * The new way is to upload files via repository api.
- *
- * @global object
- * @global object
- * @param array $files
- * @return bool|array Success or an array of errors
- */
- function _validate_files(&$files) {
- global $CFG, $COURSE;
- $files = array();
- if (empty($_FILES)) {
- // we do not need to do any checks because no files were submitted
- // note: server side rules do not work for files - use custom verification in validate() instead
- return true;
- }
- $errors = array();
- $filenames = array();
- // now check that we really want each file
- foreach ($_FILES as $elname=>$file) {
- $required = $this->_form->isElementRequired($elname);
- if ($file['error'] == 4 and $file['size'] == 0) {
- if ($required) {
- $errors[$elname] = get_string('required');
- }
- unset($_FILES[$elname]);
- continue;
- }
- if (!empty($file['error'])) {
- $errors[$elname] = file_get_upload_error($file['error']);
- unset($_FILES[$elname]);
- continue;
- }
- if (!is_uploaded_file($file['tmp_name'])) {
- // TODO: improve error message
- $errors[$elname] = get_string('error');
- unset($_FILES[$elname]);
- continue;
- }
- if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
- // hmm, this file was not requested
- unset($_FILES[$elname]);
- continue;
- }
- /*
- // TODO: rethink the file scanning MDL-19380
- if ($CFG->runclamonupload) {
- if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
- $errors[$elname] = $_FILES[$elname]['uploadlog'];
- unset($_FILES[$elname]);
- continue;
- }
- }
- */
- $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
- if ($filename === '') {
- // TODO: improve error message - wrong chars
- $errors[$elname] = get_string('error');
- unset($_FILES[$elname]);
- continue;
- }
- if (in_array($filename, $filenames)) {
- // TODO: improve error message - duplicate name
- $errors[$elname] = get_string('error');
- unset($_FILES[$elname]);
- continue;
- }
- $filenames[] = $filename;
- $_FILES[$elname]['name'] = $filename;
- $files[$elname] = $_FILES[$elname]['tmp_name'];
- }
- // return errors if found
- if (count($errors) == 0){
- return true;
- } else {
- $files = array();
- return $errors;
- }
- }
- /**
- * Load in existing data as form defaults. Usually new entry defaults are stored directly in
- * form definition (new entry form); this function is used to load in data where values
- * already exist and data is being edited (edit entry form).
- *
- * note: $slashed param removed
- *
- * @param mixed $default_values object or array of default values
- */
- function set_data($default_values) {
- if (is_object($default_values)) {
- $default_values = (array)$default_values;
- }
- $this->_form->setDefaults($default_values);
- }
- /**
- * @deprecated
- */
- function set_upload_manager($um=false) {
- debugging('Old file uploads can not be used any more, please use new filepicker element');
- }
- /**
- * Check that form was submitted. Does not check validity of submitted data.
- *
- * @return bool true if form properly submitted
- */
- function is_submitted() {
- return $this->_form->isSubmitted();
- }
- /**
- * @staticvar bool $nosubmit
- */
- function no_submit_button_pressed(){
- static $nosubmit = null; // one check is enough
- if (!is_null($nosubmit)){
- return $nosubmit;
- }
- $mform =& $this->_form;
- $nosubmit = false;
- if (!$this->is_submitted()){
- return false;
- }
- foreach ($mform->_noSubmitButtons as $nosubmitbutton){
- if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
- $nosubmit = true;
- break;
- }
- }
- return $nosubmit;
- }
- /**
- * Check that form data is valid.
- * You should almost always use this, rather than {@see validate_defined_fields}
- *
- * @staticvar bool $validated
- * @return bool true if form data valid
- */
- function is_validated() {
- //finalize the form definition before any processing
- if (!$this->_definition_finalized) {
- $this->_definition_finalized = true;
- $this->definition_after_data();
- }
- return $this->validate_defined_fields();
- }
- /**
- * Validate the form.
- *
- * You almost always want to call {@see is_validated} instead of this
- * because it calls {@see definition_after_data} first, before validating the form,
- * which is what you want in 99% of cases.
- *
- * This is provided as a separate function for those special cases where
- * you want the form validated before definition_after_data is called
- * for example, to selectively add new elements depending on a no_submit_button press,
- * but only when the form is valid when the no_submit_button is pressed,
- *
- * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
- * is NOT to validate the form when a no submit button has been pressed.
- * pass true here to override this behaviour
- *
- * @return bool true if form data valid
- */
- function validate_defined_fields($validateonnosubmit=false) {
- static $validated = null; // one validation is enough
- $mform =& $this->_form;
- if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
- return false;
- } elseif ($validated === null) {
- $internal_val = $mform->validate();
- $files = array();
- $file_val = $this->_validate_files($files);
- if ($file_val !== true) {
- if (!empty($file_val)) {
- foreach ($file_val as $element=>$msg) {
- $mform->setElementError($element, $msg);
- }
- }
- $file_val = false;
- }
- $data = $mform->exportValues();
- $moodle_val = $this->validation($data, $files);
- if ((is_array($moodle_val) && count($moodle_val)!==0)) {
- // non-empty array means errors
- foreach ($moodle_val as $element=>$msg) {
- $mform->setElementError($element, $msg);
- }
- $moodle_val = false;
- } else {
- // anything else means validation ok
- $moodle_val = true;
- }
- $validated = ($internal_val and $moodle_val and $file_val);
- }
- return $validated;
- }
- /**
- * Return true if a cancel button has been pressed resulting in the form being submitted.
- *
- * @return boolean true if a cancel button has been pressed
- */
- function is_cancelled(){
- $mform =& $this->_form;
- if ($mform->isSubmitted()){
- foreach ($mform->_cancelButtons as $cancelbutton){
- if (optional_param($cancelbutton, 0, PARAM_RAW)){
- return true;
- }
- }
- }
- return false;
- }
- /**
- * Return submitted data if properly submitted or returns NULL if validation fails or
- * if there is no submitted data.
- *
- * note: $slashed param removed
- *
- * @return object submitted data; NULL if not valid or not submitted
- */
- function get_data() {
- $mform =& $this->_form;
- if ($this->is_submitted() and $this->is_validated()) {
- $data = $mform->exportValues();
- unset($data['sesskey']); // we do not need to return sesskey
- unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
- if (empty($data)) {
- return NULL;
- } else {
- return (object)$data;
- }
- } else {
- return NULL;
- }
- }
- /**
- * Return submitted data without validation or NULL if there is no submitted data.
- * note: $slashed param removed
- *
- * @return object submitted data; NULL if not submitted
- */
- function get_submitted_data() {
- $mform =& $this->_form;
- if ($this->is_submitted()) {
- $data = $mform->exportValues();
- unset($data['sesskey']); // we do not need to return sesskey
- unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
- if (empty($data)) {
- return NULL;
- } else {
- return (object)$data;
- }
- } else {
- return NULL;
- }
- }
- /**
- * Save verified uploaded files into directory. Upload process can be customised from definition()
- * NOTE: please use save_stored_file() or save_file()
- *
- * @return bool Always false
- */
- function save_files($destination) {
- debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
- return false;
- }
- /**
- * Returns name of uploaded file.
- *
- * @global object
- * @param string $elname, first element if null
- * @return mixed false in case of failure, string if ok
- */
- function get_new_filename($elname=null) {
- global $USER;
- if (!$this->is_submitted() or !$this->is_validated()) {
- return false;
- }
- if (is_null($elname)) {
- if (empty($_FILES)) {
- return false;
- }
- reset($_FILES);
- $elname = key($_FILES);
- }
- if (empty($elname)) {
- return false;
- }
- $element = $this->_form->getElement($elname);
- if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
- $values = $this->_form->exportValues($elname);
- if (empty($values[$elname])) {
- return false;
- }
- $draftid = $values[$elname];
- $fs = get_file_storage();
- $context = get_context_instance(CONTEXT_USER, $USER->id);
- if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
- return false;
- }
- $file = reset($files);
- return $file->get_filename();
- }
- if (!isset($_FILES[$elname])) {
- return false;
- }
- return $_FILES[$elname]['name'];
- }
- /**
- * Save file to standard filesystem
- *
- * @global object
- * @param string $elname name of element
- * @param string $pathname full path name of file
- * @param bool $override override file if exists
- * @return bool success
- */
- function save_file($elname, $pathname, $override=false) {
- global $USER;
- if (!$this->is_submitted() or !$this->is_validated()) {
- return false;
- }
- if (file_exists($pathname)) {
- if ($override) {
- if (!@unlink($pathname)) {
- return false;
- }
- } else {
- return false;
- }
- }
- $element = $this->_form->getElement($elname);
- if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
- $values = $this->_form->exportValues($elname);
- if (empty($values[$elname])) {
- return false;
- }
- $draftid = $values[$elname];
- $fs = get_file_storage();
- $context = get_context_instance(CONTEXT_USER, $USER->id);
- if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
- return false;
- }
- $file = reset($files);
- return $file->copy_content_to($pathname);
- } else if (isset($_FILES[$elname])) {
- return copy($_FILES[$elname]['tmp_name'], $pathname);
- }
- return false;
- }
- /**
- * Returns a temporary file, do not forget to delete after not needed any more.
- *
- * @param string $elname
- * @return string or false
- */
- function save_temp_file($elname) {
- if (!$this->get_new_filename($elname)) {
- return false;
- }
- if (!$dir = make_upload_directory('temp/forms')) {
- return false;
- }
- if (!$tempfile = tempnam($dir, 'tempup_')) {
- return false;
- }
- if (!$this->save_file($elname, $tempfile, true)) {
- // something went wrong
- @unlink($tempfile);
- return false;
- }
- return $tempfile;
- }
- /**
- * Get draft files of a form element
- * This is a protected method which will be used only inside moodleforms
- *
- * @global object $USER
- * @param string $elname name of element
- * @return array
- */
- protected function get_draft_files($elname) {
- global $USER;
- if (!$this->is_submitted()) {
- return false;
- }
- $element = $this->_form->getElement($elname);
- if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
- $values = $this->_form->exportValues($elname);
- if (empty($values[$elname])) {
- return false;
- }
- $draftid = $values[$elname];
- $fs = get_file_storage();
- $context = get_context_instance(CONTEXT_USER, $USER->id);
- if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
- return null;
- }
- return $files;
- }
- return null;
- }
- /**
- * Save file to local filesystem pool
- *
- * @global object
- * @param string $elname name of element
- * @param int $newcontextid
- * @param string $newfilearea
- * @param string $newfilepath
- * @param string $newfilename - use specified filename, if not specified name of uploaded file used
- * @param bool $overwrite - overwrite file if exists
- * @param int $newuserid - new userid if required
- * @return mixed stored_file object or false if error; may throw exception if duplicate found
- */
- function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
- $newfilename=null, $overwrite=false, $newuserid=null) {
- global $USER;
- if (!$this->is_submitted() or !$this->is_validated()) {
- return false;
- }
- if (empty($newuserid)) {
- $newuserid = $USER->id;
- }
- $element = $this->_form->getElement($elname);
- $fs = get_file_storage();
- if ($element instanceof MoodleQuickForm_filepicker) {
- $values = $this->_form->exportValues($elname);
- if (empty($values[$elname])) {
- return false;
- }
- $draftid = $values[$elname];
- $context = get_context_instance(CONTEXT_USER, $USER->id);
- if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
- return false;
- }
- $file = reset($files);
- if (is_null($newfilename)) {
- $newfilename = $file->get_filename();
- }
- if ($overwrite) {
- if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
- if (!$oldfile->delete()) {
- return false;
- }
- }
- }
- $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
- 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
- return $fs->create_file_from_storedfile($file_record, $file);
- } else if (isset($_FILES[$elname])) {
- $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
- if ($overwrite) {
- if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
- if (!$oldfile->delete()) {
- return false;
- }
- }
- }
- $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
- 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
- return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
- }
- return false;
- }
- /**
- * Get content of uploaded file.
- *
- * @global object
- * @param $element name of file upload element
- * @return mixed false in case of failure, string if ok
- */
- function get_file_content($elname) {
- global $USER;
- if (!$this->is_submitted() or !$this->is_validated()) {
- return false;
- }
- $element = $this->_form->getElement($elname);
- if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
- $values = $this->_form->exportValues($elname);
- if (empty($values[$elname])) {
- return false;
- }
- $draftid = $values[$elname];
- $fs = get_file_storage();
- $context = get_context_instance(CONTEXT_USER, $USER->id);
- if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
- return false;
- }
- $file = reset($files);
- return $file->get_content();
- } else if (isset($_FILES[$elname])) {
- return file_get_contents($_FILES[$elname]['tmp_name']);
- }
- return false;
- }
- /**
- * Print html form.
- */
- function display() {
- //finalize the form definition if not yet done
- if (!$this->_definition_finalized) {
- $this->_definition_finalized = true;
- $this->definition_after_data();
- }
- $this->_form->display();
- }
- /**
- * Abstract method - always override!
- */
- protected abstract function definition();
- /**
- * Dummy stub method - override if you need to setup the form depending on current
- * values. This method is called after definition(), data submission and set_data().
- * All form setup that is dependent on form values should go in here.
- */
- function definition_after_data(){
- }
- /**
- * Dummy stub method - override if you needed to perform some extra validation.
- * If there are errors return array of errors ("fieldname"=>"error message"),
- * otherwise true if ok.
- *
- * Server side rules do not work for uploaded files, implement serverside rules here if needed.
- *
- * @param array $data array of ("fieldname"=>value) of submitted data
- * @param array $files array of uploaded files "element_name"=>tmp_file_path
- * @return array of "element_name"=>"error_description" if there are errors,
- * or an empty array if everything is OK (true allowed for backwards compatibility too).
- */
- function validation($data, $files) {
- return array();
- }
- /**
- * Method to add a repeating group of elements to a form.
- *
- * @param array $elementobjs Array of elements or groups of elements that are to be repeated
- * @param integer $repeats no of times to repeat elements initially
- * @param array $options Array of options to apply to elements. Array keys are element names.
- * This is an array of arrays. The second sets of keys are the option types
- * for the elements :
- * 'default' - default value is value
- * 'type' - PARAM_* constant is value
- * 'helpbutton' - helpbutton params array is value
- * 'disabledif' - last three moodleform::disabledIf()
- * params are value as an array
- * @param string $repeathiddenname name for hidden element storing no of repeats in this form
- * @param string $addfieldsname name for button to add more fields
- * @param int $addfieldsno how many fields to add at a time
- * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
- * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
- * @return int no of repeats of element in this page
- */
- function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
- $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
- if ($addstring===null){
- $addstring = get_string('addfields', 'form', $addfieldsno);
- } else {
- $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
- }
- $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
- $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
- if (!empty($addfields)){
- $repeats += $addfieldsno;
- }
- $mform =& $this->_form;
- $mform->registerNoSubmitButton($addfieldsname);
- $mform->addElement('hidden', $repeathiddenname, $repeats);
- $mform->setType($repeathiddenname, PARAM_INT);
- //value not to be overridden by submitted value
- $mform->setConstants(array($repeathiddenname=>$repeats));
- $namecloned = array();
- for ($i = 0; $i < $repeats; $i++) {
- foreach ($elementobjs as $elementobj){
- $elementclone = fullclone($elementobj);
- $name = $elementclone->getName();
- $namecloned[] = $name;
- if (!empty($name)) {
- $elementclone->setName($name."[$i]");
- }
- if (is_a($elementclone, 'HTML_QuickForm_header')) {
- $value = $elementclone->_text;
- $elementclone->setValue(str_replace('{no}', ($i+1), $value));
- } else {
- $value=$elementclone->getLabel();
- $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
- }
- $mform->addElement($elementclone);
- }
- }
- for ($i=0; $i<$repeats; $i++) {
- foreach ($options as $elementname => $elementoptions){
- $pos=strpos($elementname, '[');
- if ($pos!==FALSE){
- $realelementname = substr($elementname, 0, $pos+1)."[$i]";
- $realelementname .= substr($elementname, $pos+1);
- }else {
- $realelementname = $elementname."[$i]";
- }
- foreach ($elementoptions as $option => $params){
- switch ($option){
- case 'default' :
- $mform->setDefault($realelementname, $params);
- break;
- case 'helpbutton' :
- $params = array_merge(array($realelementname), $params);
- call_user_func_array(array(&$mform, 'addHelpButton'), $params);
- break;
- case 'disabledif' :
- foreach ($namecloned as $num => $name){
- if ($params[0] == $name){
- $params[0] = $params[0]."[$i]";
- break;
- }
- }
- $params = array_merge(array($realelementname), $params);
- call_user_func_array(array(&$mform, 'disabledIf'), $params);
- break;
- case 'rule' :
- if (is_string($params)){
- $params = array(null, $params, null, 'client');
- }
- $params = array_merge(array($realelementname), $params);
- call_user_func_array(array(&$mform, 'addRule'), $params);
- break;
- }
- }
- }
- }
- $mform->addElement('submit', $addfieldsname, $addstring);
- if (!$addbuttoninside) {
- $mform->closeHeaderBefore($addfieldsname);
- }
- return $repeats;
- }
- /**
- * Adds a link/button that controls the checked state of a group of checkboxes.
- *
- * @global object
- * @param int $groupid The id of the group of advcheckboxes this element controls
- * @param string $buttontext The text of the link. Defaults to "select all/none"
- * @param array $attributes associative array of HTML attributes
- * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
- */
- function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
- global $CFG;
- if (empty($text)) {
- $text = get_string('selectallornone', 'form');
- }
- $mform = $this->_form;
- $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
- if ($select_value == 0 || is_null($select_value)) {
- $new_select_value = 1;
- } else {
- $new_select_value = 0;
- }
- $mform->addElement('hidden', "checkbox_controller$groupid");
- $mform->setType("checkbox_controller$groupid", PARAM_INT);
- $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
- // Locate all checkboxes for this group and set their value, IF the optional param was given
- if (!is_null($select_value)) {
- foreach ($this->_form->_elements as $element) {
- if ($element->getAttribute('class') == "checkboxgroup$groupid") {
- $mform->setConstants(array($element->getAttribute('name') => $select_value));
- }
- }
- }
- $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
- $mform->registerNoSubmitButton($checkbox_controller_name);
- // Prepare Javascript for submit element
- $js = "\n//<![CDATA[\n";
- if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
- $js .= <<<EOS
- function html_quickform_toggle_checkboxes(group) {
- var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
- var newvalue = false;
- var global = eval('html_quickform_checkboxgroup' + group + ';');
- if (global == 1) {
- eval('html_quickform_checkboxgroup' + group + ' = 0;');
- newvalue = '';
- } else {
- eval('html_quickform_checkboxgroup' + group + ' = 1;');
- newvalue = 'checked';
- }
- for (i = 0; i < checkboxes.length; i++) {
- checkboxes[i].checked = newvalue;
- }
- }
- EOS;
- define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
- }
- $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
- $js .= "//]]>\n";
- require_once("$CFG->libdir/form/submitlink.php");
- $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
- $submitlink->_js = $js;
- $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
- $mform->addElement($submitlink);
- $mform->setDefault($checkbox_controller_name, $text);
- }
- /**
- * Use this method to a cancel and submit button to the end of your form. Pass a param of false
- * if you don't want a cancel button in your form. If you have a cancel button make sure you
- * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
- * get data with get_data().
- *
- * @param boolean $cancel whether to show cancel button, default true
- * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
- */
- function add_action_buttons($cancel = true, $submitlabel=null){
- if (is_null($submitlabel)){
- $submitlabel = get_string('savechanges');
- }
- $mform =& $this->_form;
- if ($cancel){
- //when two elements we need a group
- $buttonarray=array();
- $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
- $buttonarray[] = &$mform->createElement('cancel');
- $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
- $mform->closeHeaderBefore('buttonar');
- } else {
- //no group needed
- $mform->addElement('submit', 'submitbutton', $submitlabel);
- $mform->closeHeaderBefore('submitbutton');
- }
- }
- /**
- * Adds an initialisation call for a standard JavaScript enhancement.
- *
- * This function is designed to add an initialisation call for a JavaScript
- * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
- *
- * Current options:
- * - Selectboxes
- * - smartselect: Turns a nbsp indented select box into a custom drop down
- * control that supports multilevel and category selection.
- * $enhancement = 'smartselect';
- * $options = array('selectablecategories' => true|false)
- *
- * @since 2.0
- * @param string|element $element
- * @param string $enhancement
- * @param array $options
- * @param array $strings
- */
- function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
- global $PAGE;
- if (is_string($element)) {
- $element = $this->_form->getElement($element);
- }
- if (is_object($element)) {
- $element->_generateId();
- $elementid = $element->getAttribute('id');
- $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
- if (is_array($strings)) {
- foreach ($strings as $string) {
- if (is_array($string)) {
- call_user_method_array('string_for_js', $PAGE->requires, $string);
- } else {
- $PAGE->requires->string_for_js($string, 'moodle');
- }
- }
- }
- }
- }
- /**
- * Returns a JS module definition for the mforms JS
- * @return array
- */
- public static function get_js_module() {
- global $CFG;
- return array(
- 'name' => 'mform',
- 'fullpath' => '/lib/form/form.js',
- 'requires' => array('base', 'node'),
- 'strings' => array(
- array('showadvanced', 'form'),
- array('hideadvanced', 'form')
- )
- );
- }
- }
- /**
- * You never extend this class directly. The class methods of this class are available from
- * the private $this->_form property on moodleform and its children. You generally only
- * call methods on this class from within abstract methods that you override on moodleform such
- * as definition and definition_after_data
- *
- * @package moodlecore
- * @copyright Jamie Pratt <me@jamiep.org>
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
- class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
- /** @var array */
- var $_types = array();
- var $_dependencies = array();
- /**
- * Array of buttons that if pressed do not result in the processing of the form.
- *
- * @var array
- */
- var $_noSubmitButtons=array();
- /**
- * Array of buttons that if pressed do not result in the processing of the form.
- *
- * @var array
- */
- var $_cancelButtons=array();
- /**
- * Array whose keys are element names. If the key exists this is a advanced element
- *
- * @var array
- */
- var $_advancedElements = array();
- /**
- * Whether to display advanced elements (on page load)
- *
- * @var boolean
- */
- var $_showAdvanced = null;
- /**
- * The form name is derived from the class name of the wrapper minus the trailing form
- * It is a name with words joined by underscores whereas the id attribute is words joined by
- * underscores.
- *
- * @var unknown_type
- */
- var $_formName = '';
- /**
- * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
- *
- * @var string
- */
- var $_pageparams = '';
- /**
- * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
- *
- * @global object
- * @staticvar int $formcounter
- * @param string $formName Form's name.
- * @param string $method (optional)Form's method defaults to 'POST'
- * @param mixed $action (optional)Form's action - string or moodle_url
- * @param string $target (optional)Form's target defaults to none
- * @param mixed $attributes (optional)Extra attributes for <form> tag
- * @access public
- */
- function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
- global $CFG, $OUTPUT;
- static $formcounter = 1;
- HTML_Common::HTML_Common($attributes);
- $target = empty($target) ? array() : array('target' => $target);
- $this->_formName = $formName;
- if (is_a($action, 'moodle_url')){
- $this->_pageparams = html_writer::input_hidden_params($action);
- $action = $action->out_omit_querystring();
- } else {
- $this->_pageparams = '';
- }
- //no 'name' atttribute for form in xhtml strict :
- $attributes = array('action'=>$action, 'method'=>$method,
- 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
- $formcounter++;
- $this->updateAttributes($attributes);
- //this is custom stuff for Moodle :
- $oldclass= $this->getAttribute('class');
- if (!empty($oldclass)){
- $this->updateAttributes(array('class'=>$oldclass.' mform'));
- }else {
- $this->updateAttributes(array('class'=>'mform'));
- }
- $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
- $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
- $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
- }
- /**
- * Use this method to indicate an element in a form is an advanced field. If items in a form
- * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
- * form so the user can decide whether to display advanced form controls.
- *
- * If you set a header element to advanced then all elements it contains will also be set as advanced.
- *
- * @param string $elementName group or element name (not the element name of something inside a group).
- * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
- */
- function setAdvanced($elementName, $advanced=true){
- if ($advanced){
- $this->_advancedElements[$elementName]='';
- } elseif (isset($this->_advancedElements[$elementName])) {
- unset($this->_advancedElements[$elementName]);
- }
- if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
- $this->setShowAdvanced();
- $this->registerNoSubmitButton('mform_showadvanced');
- $this->addElement('hidden', 'mform_showadvanced_last');
- $this->setType('mform_showadvanced_last', PARAM_INT);
- }
- }
- /**
- * Set whether to show advanced elements in the form on first displaying form. Default is not to
- * display advanced elements in the form until 'Show Advanced' is pressed.
- *
- * You can get the last state of the form and possibly save it for this user by using
- * value 'mform_showadvanced_last' in submitted data.
- *
- * @param boolean $showadvancedNow
- */
- function setShowAdvanced($showadvancedNow = null){
- if ($showadvancedNow === null){
- if ($this->_showAdvanced !== null){
- return;
- } else { //if setShowAdvanced is called without any preference
- //make the default to not show advanced elements.
- $showadvancedNow = get_user_preferences(
- moodle_strtolower($this->_formName.'_showadvanced', 0));
- }
- }
- //value of hidden element
- $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
- //value of button
- $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
- //toggle if button pressed or else stay the same
- if ($hiddenLast == -1) {
- $next = $showadvancedNow;
- } elseif ($buttonPressed) { //toggle on button press
- $next = !$hiddenLast;
- } else {
- $next = $hiddenLast;
- }
- $this->_showAdvanced = $next;
- if ($showadvancedNow != $next){
- set_user_preference($this->_formName.'_showadvanced', $next);
- }
- $this->setConstants(array('mform_showadvanced_last'=>$next));
- }
- function getShowAdvanced(){
- return $this->_showAdvanced;
- }
- /**
- * Accepts a renderer
- *
- * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
- * @access public
- * @return void
- */
- function accept(&$renderer) {
- if (method_exists($renderer, 'setAdvancedElements')){
- //check for visible fieldsets where all elements are advanced
- //and mark these headers as advanced as well.
- //And mark all elements in a advanced header as advanced
- $stopFields = $renderer->getStopFieldSetElements();
- $lastHeader = null;
- $lastHeaderAdvanced = false;
- $anyAdvanced = false;
- foreach (array_keys($this->_elements) as $elementIndex){
- $element =& $this->_elements[$elementIndex];
- // if closing header and any contained element was advanced then mark it as advanced
- if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
- if ($anyAdvanced && !is_null($lastHeader)){
- $this->setAdvanced($lastHeader->getName());
- }
- $lastHeaderAdvanced = false;
- unset($lastHeader);
- $lastHeader = null;
- } elseif ($lastHeaderAdvanced) {
- $this->setAdvanced($element->getName());
- }
- if ($element->getType()=='header'){
- $lastHeader =& $element;
- $anyAdvanced = false;
- $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
- } elseif (isset($this->_advancedElements[$element->getName()])){
- $anyAdvanced = true;
- }
- }
- // the last header may not be closed yet...
- if ($anyAdvanced && !is_nu…
Large files files are truncated, but you can click here to view the full file