PageRenderTime 269ms CodeModel.GetById 101ms app.highlight 71ms RepoModel.GetById 29ms app.codeStats 2ms

/lib/formslib.php

https://bitbucket.org/moodle/moodle
PHP | 3398 lines | 2339 code | 220 blank | 839 comment | 282 complexity | 3c6ec9b3f6cc1bf8788fdbb6afa4da8c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2// This file is part of Moodle - http://moodle.org/
   3//
   4// Moodle is free software: you can redistribute it and/or modify
   5// it under the terms of the GNU General Public License as published by
   6// the Free Software Foundation, either version 3 of the License, or
   7// (at your option) any later version.
   8//
   9// Moodle is distributed in the hope that it will be useful,
  10// but WITHOUT ANY WARRANTY; without even the implied warranty of
  11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12// GNU General Public License for more details.
  13//
  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/>.
  16
  17/**
  18 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
  19 *
  20 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
  21 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
  22 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
  23 * and validation.
  24 *
  25 * See examples of use of this library in course/edit.php and course/edit_form.php
  26 *
  27 * A few notes :
  28 *      form definition is used for both printing of form and processing and should be the same
  29 *              for both or you may lose some submitted data which won't be let through.
  30 *      you should be using setType for every form element except select, radio or checkbox
  31 *              elements, these elements clean themselves.
  32 *
  33 * @package   core_form
  34 * @copyright 2006 Jamie Pratt <me@jamiep.org>
  35 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36 */
  37
  38defined('MOODLE_INTERNAL') || die();
  39
  40/** setup.php includes our hacked pear libs first */
  41require_once 'HTML/QuickForm.php';
  42require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
  43require_once 'HTML/QuickForm/Renderer/Tableless.php';
  44require_once 'HTML/QuickForm/Rule.php';
  45
  46require_once $CFG->libdir.'/filelib.php';
  47
  48/**
  49 * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
  50 */
  51define('EDITOR_UNLIMITED_FILES', -1);
  52
  53/**
  54 * Callback called when PEAR throws an error
  55 *
  56 * @param PEAR_Error $error
  57 */
  58function pear_handle_error($error){
  59    echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
  60    echo '<br /> <strong>Backtrace </strong>:';
  61    print_object($error->backtrace);
  62}
  63
  64if ($CFG->debugdeveloper) {
  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';
  68}
  69
  70/**
  71 * Initalize javascript for date type form element
  72 *
  73 * @staticvar bool $done make sure it gets initalize once.
  74 * @global moodle_page $PAGE
  75 */
  76function form_init_date_js() {
  77    global $PAGE;
  78    static $done = false;
  79    if (!$done) {
  80        $done = true;
  81        $calendar = \core_calendar\type_factory::get_calendar_instance();
  82        if ($calendar->get_name() !== 'gregorian') {
  83            // The YUI2 calendar only supports the gregorian calendar type.
  84            return;
  85        }
  86        $module   = 'moodle-form-dateselector';
  87        $function = 'M.form.dateselector.init_date_selectors';
  88        $defaulttimezone = date_default_timezone_get();
  89
  90        $config = array(array(
  91            'firstdayofweek'    => $calendar->get_starting_weekday(),
  92            'mon'               => date_format_string(strtotime("Monday"), '%a', $defaulttimezone),
  93            'tue'               => date_format_string(strtotime("Tuesday"), '%a', $defaulttimezone),
  94            'wed'               => date_format_string(strtotime("Wednesday"), '%a', $defaulttimezone),
  95            'thu'               => date_format_string(strtotime("Thursday"), '%a', $defaulttimezone),
  96            'fri'               => date_format_string(strtotime("Friday"), '%a', $defaulttimezone),
  97            'sat'               => date_format_string(strtotime("Saturday"), '%a', $defaulttimezone),
  98            'sun'               => date_format_string(strtotime("Sunday"), '%a', $defaulttimezone),
  99            'january'           => date_format_string(strtotime("January 1"), '%B', $defaulttimezone),
 100            'february'          => date_format_string(strtotime("February 1"), '%B', $defaulttimezone),
 101            'march'             => date_format_string(strtotime("March 1"), '%B', $defaulttimezone),
 102            'april'             => date_format_string(strtotime("April 1"), '%B', $defaulttimezone),
 103            'may'               => date_format_string(strtotime("May 1"), '%B', $defaulttimezone),
 104            'june'              => date_format_string(strtotime("June 1"), '%B', $defaulttimezone),
 105            'july'              => date_format_string(strtotime("July 1"), '%B', $defaulttimezone),
 106            'august'            => date_format_string(strtotime("August 1"), '%B', $defaulttimezone),
 107            'september'         => date_format_string(strtotime("September 1"), '%B', $defaulttimezone),
 108            'october'           => date_format_string(strtotime("October 1"), '%B', $defaulttimezone),
 109            'november'          => date_format_string(strtotime("November 1"), '%B', $defaulttimezone),
 110            'december'          => date_format_string(strtotime("December 1"), '%B', $defaulttimezone)
 111        ));
 112        $PAGE->requires->yui_module($module, $function, $config);
 113    }
 114}
 115
 116/**
 117 * Wrapper that separates quickforms syntax from moodle code
 118 *
 119 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
 120 * use this class you should write a class definition which extends this class or a more specific
 121 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
 122 *
 123 * You will write your own definition() method which performs the form set up.
 124 *
 125 * @package   core_form
 126 * @copyright 2006 Jamie Pratt <me@jamiep.org>
 127 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 128 * @todo      MDL-19380 rethink the file scanning
 129 */
 130abstract class moodleform {
 131    /** @var string name of the form */
 132    protected $_formname;       // form name
 133
 134    /** @var MoodleQuickForm quickform object definition */
 135    protected $_form;
 136
 137    /** @var array globals workaround */
 138    protected $_customdata;
 139
 140    /** @var array submitted form data when using mforms with ajax */
 141    protected $_ajaxformdata;
 142
 143    /** @var object definition_after_data executed flag */
 144    protected $_definition_finalized = false;
 145
 146    /** @var bool|null stores the validation result of this form or null if not yet validated */
 147    protected $_validated = null;
 148
 149    /**
 150     * The constructor function calls the abstract function definition() and it will then
 151     * process and clean and attempt to validate incoming data.
 152     *
 153     * It will call your custom validate method to validate data and will also check any rules
 154     * you have specified in definition using addRule
 155     *
 156     * The name of the form (id attribute of the form) is automatically generated depending on
 157     * the name you gave the class extending moodleform. You should call your class something
 158     * like
 159     *
 160     * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
 161     *              current url. If a moodle_url object then outputs params as hidden variables.
 162     * @param mixed $customdata if your form defintion method needs access to data such as $course
 163     *              $cm, etc. to construct the form definition then pass it in this array. You can
 164     *              use globals for somethings.
 165     * @param string $method if you set this to anything other than 'post' then _GET and _POST will
 166     *               be merged and used as incoming data to the form.
 167     * @param string $target target frame for form submission. You will rarely use this. Don't use
 168     *               it if you don't need to as the target attribute is deprecated in xhtml strict.
 169     * @param mixed $attributes you can pass a string of html attributes here or an array.
 170     *               Special attribute 'data-random-ids' will randomise generated elements ids. This
 171     *               is necessary when there are several forms on the same page.
 172     *               Special attribute 'data-double-submit-protection' set to 'off' will turn off
 173     *               double-submit protection JavaScript - this may be necessary if your form sends
 174     *               downloadable files in response to a submit button, and can't call
 175     *               \core_form\util::form_download_complete();
 176     * @param bool $editable
 177     * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
 178     */
 179    public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true,
 180                                $ajaxformdata=null) {
 181        global $CFG, $FULLME;
 182        // no standard mform in moodle should allow autocomplete with the exception of user signup
 183        if (empty($attributes)) {
 184            $attributes = array('autocomplete'=>'off');
 185        } else if (is_array($attributes)) {
 186            $attributes['autocomplete'] = 'off';
 187        } else {
 188            if (strpos($attributes, 'autocomplete') === false) {
 189                $attributes .= ' autocomplete="off" ';
 190            }
 191        }
 192
 193
 194        if (empty($action)){
 195            // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
 196            $action = strip_querystring($FULLME);
 197            if (!empty($CFG->sslproxy)) {
 198                // return only https links when using SSL proxy
 199                $action = preg_replace('/^http:/', 'https:', $action, 1);
 200            }
 201            //TODO: use following instead of FULLME - see MDL-33015
 202            //$action = strip_querystring(qualified_me());
 203        }
 204        // Assign custom data first, so that get_form_identifier can use it.
 205        $this->_customdata = $customdata;
 206        $this->_formname = $this->get_form_identifier();
 207        $this->_ajaxformdata = $ajaxformdata;
 208
 209        $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes, $ajaxformdata);
 210        if (!$editable){
 211            $this->_form->hardFreeze();
 212        }
 213
 214        $this->definition();
 215
 216        $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
 217        $this->_form->setType('sesskey', PARAM_RAW);
 218        $this->_form->setDefault('sesskey', sesskey());
 219        $this->_form->addElement('hidden', '_qf__'.$this->_formname, null);   // form submission marker
 220        $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
 221        $this->_form->setDefault('_qf__'.$this->_formname, 1);
 222        $this->_form->_setDefaultRuleMessages();
 223
 224        // Hook to inject logic after the definition was provided.
 225        $this->after_definition();
 226
 227        // we have to know all input types before processing submission ;-)
 228        $this->_process_submission($method);
 229    }
 230
 231    /**
 232     * Old syntax of class constructor. Deprecated in PHP7.
 233     *
 234     * @deprecated since Moodle 3.1
 235     */
 236    public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
 237        debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
 238        self::__construct($action, $customdata, $method, $target, $attributes, $editable);
 239    }
 240
 241    /**
 242     * It should returns unique identifier for the form.
 243     * Currently it will return class name, but in case two same forms have to be
 244     * rendered on same page then override function to get unique form identifier.
 245     * e.g This is used on multiple self enrollments page.
 246     *
 247     * @return string form identifier.
 248     */
 249    protected function get_form_identifier() {
 250        $class = get_class($this);
 251
 252        return preg_replace('/[^a-z0-9_]/i', '_', $class);
 253    }
 254
 255    /**
 256     * To autofocus on first form element or first element with error.
 257     *
 258     * @param string $name if this is set then the focus is forced to a field with this name
 259     * @return string javascript to select form element with first error or
 260     *                first element if no errors. Use this as a parameter
 261     *                when calling print_header
 262     */
 263    function focus($name=NULL) {
 264        $form =& $this->_form;
 265        $elkeys = array_keys($form->_elementIndex);
 266        $error = false;
 267        if (isset($form->_errors) &&  0 != count($form->_errors)){
 268            $errorkeys = array_keys($form->_errors);
 269            $elkeys = array_intersect($elkeys, $errorkeys);
 270            $error = true;
 271        }
 272
 273        if ($error or empty($name)) {
 274            $names = array();
 275            while (empty($names) and !empty($elkeys)) {
 276                $el = array_shift($elkeys);
 277                $names = $form->_getElNamesRecursive($el);
 278            }
 279            if (!empty($names)) {
 280                $name = array_shift($names);
 281            }
 282        }
 283
 284        $focus = '';
 285        if (!empty($name)) {
 286            $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
 287        }
 288
 289        return $focus;
 290     }
 291
 292    /**
 293     * Internal method. Alters submitted data to be suitable for quickforms processing.
 294     * Must be called when the form is fully set up.
 295     *
 296     * @param string $method name of the method which alters submitted data
 297     */
 298    function _process_submission($method) {
 299        $submission = array();
 300        if (!empty($this->_ajaxformdata)) {
 301            $submission = $this->_ajaxformdata;
 302        } else if ($method == 'post') {
 303            if (!empty($_POST)) {
 304                $submission = $_POST;
 305            }
 306        } else {
 307            $submission = $_GET;
 308            merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
 309        }
 310
 311        // following trick is needed to enable proper sesskey checks when using GET forms
 312        // the _qf__.$this->_formname serves as a marker that form was actually submitted
 313        if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
 314            if (!confirm_sesskey()) {
 315                print_error('invalidsesskey');
 316            }
 317            $files = $_FILES;
 318        } else {
 319            $submission = array();
 320            $files = array();
 321        }
 322        $this->detectMissingSetType();
 323
 324        $this->_form->updateSubmission($submission, $files);
 325    }
 326
 327    /**
 328     * Internal method - should not be used anywhere.
 329     * @deprecated since 2.6
 330     * @return array $_POST.
 331     */
 332    protected function _get_post_params() {
 333        return $_POST;
 334    }
 335
 336    /**
 337     * Internal method. Validates all old-style deprecated uploaded files.
 338     * The new way is to upload files via repository api.
 339     *
 340     * @param array $files list of files to be validated
 341     * @return bool|array Success or an array of errors
 342     */
 343    function _validate_files(&$files) {
 344        global $CFG, $COURSE;
 345
 346        $files = array();
 347
 348        if (empty($_FILES)) {
 349            // we do not need to do any checks because no files were submitted
 350            // note: server side rules do not work for files - use custom verification in validate() instead
 351            return true;
 352        }
 353
 354        $errors = array();
 355        $filenames = array();
 356
 357        // now check that we really want each file
 358        foreach ($_FILES as $elname=>$file) {
 359            $required = $this->_form->isElementRequired($elname);
 360
 361            if ($file['error'] == 4 and $file['size'] == 0) {
 362                if ($required) {
 363                    $errors[$elname] = get_string('required');
 364                }
 365                unset($_FILES[$elname]);
 366                continue;
 367            }
 368
 369            if (!empty($file['error'])) {
 370                $errors[$elname] = file_get_upload_error($file['error']);
 371                unset($_FILES[$elname]);
 372                continue;
 373            }
 374
 375            if (!is_uploaded_file($file['tmp_name'])) {
 376                // TODO: improve error message
 377                $errors[$elname] = get_string('error');
 378                unset($_FILES[$elname]);
 379                continue;
 380            }
 381
 382            if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
 383                // hmm, this file was not requested
 384                unset($_FILES[$elname]);
 385                continue;
 386            }
 387
 388            // NOTE: the viruses are scanned in file picker, no need to deal with them here.
 389
 390            $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
 391            if ($filename === '') {
 392                // TODO: improve error message - wrong chars
 393                $errors[$elname] = get_string('error');
 394                unset($_FILES[$elname]);
 395                continue;
 396            }
 397            if (in_array($filename, $filenames)) {
 398                // TODO: improve error message - duplicate name
 399                $errors[$elname] = get_string('error');
 400                unset($_FILES[$elname]);
 401                continue;
 402            }
 403            $filenames[] = $filename;
 404            $_FILES[$elname]['name'] = $filename;
 405
 406            $files[$elname] = $_FILES[$elname]['tmp_name'];
 407        }
 408
 409        // return errors if found
 410        if (count($errors) == 0){
 411            return true;
 412
 413        } else {
 414            $files = array();
 415            return $errors;
 416        }
 417    }
 418
 419    /**
 420     * Internal method. Validates filepicker and filemanager files if they are
 421     * set as required fields. Also, sets the error message if encountered one.
 422     *
 423     * @return bool|array with errors
 424     */
 425    protected function validate_draft_files() {
 426        global $USER;
 427        $mform =& $this->_form;
 428
 429        $errors = array();
 430        //Go through all the required elements and make sure you hit filepicker or
 431        //filemanager element.
 432        foreach ($mform->_rules as $elementname => $rules) {
 433            $elementtype = $mform->getElementType($elementname);
 434            //If element is of type filepicker then do validation
 435            if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
 436                //Check if rule defined is required rule
 437                foreach ($rules as $rule) {
 438                    if ($rule['type'] == 'required') {
 439                        $draftid = (int)$mform->getSubmitValue($elementname);
 440                        $fs = get_file_storage();
 441                        $context = context_user::instance($USER->id);
 442                        if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
 443                            $errors[$elementname] = $rule['message'];
 444                        }
 445                    }
 446                }
 447            }
 448        }
 449        // Check all the filemanager elements to make sure they do not have too many
 450        // files in them.
 451        foreach ($mform->_elements as $element) {
 452            if ($element->_type == 'filemanager') {
 453                $maxfiles = $element->getMaxfiles();
 454                if ($maxfiles > 0) {
 455                    $draftid = (int)$element->getValue();
 456                    $fs = get_file_storage();
 457                    $context = context_user::instance($USER->id);
 458                    $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
 459                    if (count($files) > $maxfiles) {
 460                        $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
 461                    }
 462                }
 463            }
 464        }
 465        if (empty($errors)) {
 466            return true;
 467        } else {
 468            return $errors;
 469        }
 470    }
 471
 472    /**
 473     * Load in existing data as form defaults. Usually new entry defaults are stored directly in
 474     * form definition (new entry form); this function is used to load in data where values
 475     * already exist and data is being edited (edit entry form).
 476     *
 477     * note: $slashed param removed
 478     *
 479     * @param stdClass|array $default_values object or array of default values
 480     */
 481    function set_data($default_values) {
 482        if (is_object($default_values)) {
 483            $default_values = (array)$default_values;
 484        }
 485        $this->_form->setDefaults($default_values);
 486    }
 487
 488    /**
 489     * Check that form was submitted. Does not check validity of submitted data.
 490     *
 491     * @return bool true if form properly submitted
 492     */
 493    function is_submitted() {
 494        return $this->_form->isSubmitted();
 495    }
 496
 497    /**
 498     * Checks if button pressed is not for submitting the form
 499     *
 500     * @staticvar bool $nosubmit keeps track of no submit button
 501     * @return bool
 502     */
 503    function no_submit_button_pressed(){
 504        static $nosubmit = null; // one check is enough
 505        if (!is_null($nosubmit)){
 506            return $nosubmit;
 507        }
 508        $mform =& $this->_form;
 509        $nosubmit = false;
 510        if (!$this->is_submitted()){
 511            return false;
 512        }
 513        foreach ($mform->_noSubmitButtons as $nosubmitbutton){
 514            if ($this->optional_param($nosubmitbutton, 0, PARAM_RAW)) {
 515                $nosubmit = true;
 516                break;
 517            }
 518        }
 519        return $nosubmit;
 520    }
 521
 522    /**
 523     * Checks if a parameter was passed in the previous form submission
 524     *
 525     * @param string $name the name of the page parameter we want
 526     * @param mixed  $default the default value to return if nothing is found
 527     * @param string $type expected type of parameter
 528     * @return mixed
 529     */
 530    public function optional_param($name, $default, $type) {
 531        if (isset($this->_ajaxformdata[$name])) {
 532            return clean_param($this->_ajaxformdata[$name], $type);
 533        } else {
 534            return optional_param($name, $default, $type);
 535        }
 536    }
 537
 538    /**
 539     * Check that form data is valid.
 540     * You should almost always use this, rather than {@link validate_defined_fields}
 541     *
 542     * @return bool true if form data valid
 543     */
 544    function is_validated() {
 545        //finalize the form definition before any processing
 546        if (!$this->_definition_finalized) {
 547            $this->_definition_finalized = true;
 548            $this->definition_after_data();
 549        }
 550
 551        return $this->validate_defined_fields();
 552    }
 553
 554    /**
 555     * Validate the form.
 556     *
 557     * You almost always want to call {@link is_validated} instead of this
 558     * because it calls {@link definition_after_data} first, before validating the form,
 559     * which is what you want in 99% of cases.
 560     *
 561     * This is provided as a separate function for those special cases where
 562     * you want the form validated before definition_after_data is called
 563     * for example, to selectively add new elements depending on a no_submit_button press,
 564     * but only when the form is valid when the no_submit_button is pressed,
 565     *
 566     * @param bool $validateonnosubmit optional, defaults to false.  The default behaviour
 567     *             is NOT to validate the form when a no submit button has been pressed.
 568     *             pass true here to override this behaviour
 569     *
 570     * @return bool true if form data valid
 571     */
 572    function validate_defined_fields($validateonnosubmit=false) {
 573        $mform =& $this->_form;
 574        if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
 575            return false;
 576        } elseif ($this->_validated === null) {
 577            $internal_val = $mform->validate();
 578
 579            $files = array();
 580            $file_val = $this->_validate_files($files);
 581            //check draft files for validation and flag them if required files
 582            //are not in draft area.
 583            $draftfilevalue = $this->validate_draft_files();
 584
 585            if ($file_val !== true && $draftfilevalue !== true) {
 586                $file_val = array_merge($file_val, $draftfilevalue);
 587            } else if ($draftfilevalue !== true) {
 588                $file_val = $draftfilevalue;
 589            } //default is file_val, so no need to assign.
 590
 591            if ($file_val !== true) {
 592                if (!empty($file_val)) {
 593                    foreach ($file_val as $element=>$msg) {
 594                        $mform->setElementError($element, $msg);
 595                    }
 596                }
 597                $file_val = false;
 598            }
 599
 600            // Give the elements a chance to perform an implicit validation.
 601            $element_val = true;
 602            foreach ($mform->_elements as $element) {
 603                if (method_exists($element, 'validateSubmitValue')) {
 604                    $value = $mform->getSubmitValue($element->getName());
 605                    $result = $element->validateSubmitValue($value);
 606                    if (!empty($result) && is_string($result)) {
 607                        $element_val = false;
 608                        $mform->setElementError($element->getName(), $result);
 609                    }
 610                }
 611            }
 612
 613            // Let the form instance validate the submitted values.
 614            $data = $mform->exportValues();
 615            $moodle_val = $this->validation($data, $files);
 616            if ((is_array($moodle_val) && count($moodle_val)!==0)) {
 617                // non-empty array means errors
 618                foreach ($moodle_val as $element=>$msg) {
 619                    $mform->setElementError($element, $msg);
 620                }
 621                $moodle_val = false;
 622
 623            } else {
 624                // anything else means validation ok
 625                $moodle_val = true;
 626            }
 627
 628            $this->_validated = ($internal_val and $element_val and $moodle_val and $file_val);
 629        }
 630        return $this->_validated;
 631    }
 632
 633    /**
 634     * Return true if a cancel button has been pressed resulting in the form being submitted.
 635     *
 636     * @return bool true if a cancel button has been pressed
 637     */
 638    function is_cancelled(){
 639        $mform =& $this->_form;
 640        if ($mform->isSubmitted()){
 641            foreach ($mform->_cancelButtons as $cancelbutton){
 642                if ($this->optional_param($cancelbutton, 0, PARAM_RAW)) {
 643                    return true;
 644                }
 645            }
 646        }
 647        return false;
 648    }
 649
 650    /**
 651     * Return submitted data if properly submitted or returns NULL if validation fails or
 652     * if there is no submitted data.
 653     *
 654     * note: $slashed param removed
 655     *
 656     * @return object submitted data; NULL if not valid or not submitted or cancelled
 657     */
 658    function get_data() {
 659        $mform =& $this->_form;
 660
 661        if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
 662            $data = $mform->exportValues();
 663            unset($data['sesskey']); // we do not need to return sesskey
 664            unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
 665            if (empty($data)) {
 666                return NULL;
 667            } else {
 668                return (object)$data;
 669            }
 670        } else {
 671            return NULL;
 672        }
 673    }
 674
 675    /**
 676     * Return submitted data without validation or NULL if there is no submitted data.
 677     * note: $slashed param removed
 678     *
 679     * @return object submitted data; NULL if not submitted
 680     */
 681    function get_submitted_data() {
 682        $mform =& $this->_form;
 683
 684        if ($this->is_submitted()) {
 685            $data = $mform->exportValues();
 686            unset($data['sesskey']); // we do not need to return sesskey
 687            unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
 688            if (empty($data)) {
 689                return NULL;
 690            } else {
 691                return (object)$data;
 692            }
 693        } else {
 694            return NULL;
 695        }
 696    }
 697
 698    /**
 699     * Save verified uploaded files into directory. Upload process can be customised from definition()
 700     *
 701     * @deprecated since Moodle 2.0
 702     * @todo MDL-31294 remove this api
 703     * @see moodleform::save_stored_file()
 704     * @see moodleform::save_file()
 705     * @param string $destination path where file should be stored
 706     * @return bool Always false
 707     */
 708    function save_files($destination) {
 709        debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
 710        return false;
 711    }
 712
 713    /**
 714     * Returns name of uploaded file.
 715     *
 716     * @param string $elname first element if null
 717     * @return string|bool false in case of failure, string if ok
 718     */
 719    function get_new_filename($elname=null) {
 720        global $USER;
 721
 722        if (!$this->is_submitted() or !$this->is_validated()) {
 723            return false;
 724        }
 725
 726        if (is_null($elname)) {
 727            if (empty($_FILES)) {
 728                return false;
 729            }
 730            reset($_FILES);
 731            $elname = key($_FILES);
 732        }
 733
 734        if (empty($elname)) {
 735            return false;
 736        }
 737
 738        $element = $this->_form->getElement($elname);
 739
 740        if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
 741            $values = $this->_form->exportValues($elname);
 742            if (empty($values[$elname])) {
 743                return false;
 744            }
 745            $draftid = $values[$elname];
 746            $fs = get_file_storage();
 747            $context = context_user::instance($USER->id);
 748            if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
 749                return false;
 750            }
 751            $file = reset($files);
 752            return $file->get_filename();
 753        }
 754
 755        if (!isset($_FILES[$elname])) {
 756            return false;
 757        }
 758
 759        return $_FILES[$elname]['name'];
 760    }
 761
 762    /**
 763     * Save file to standard filesystem
 764     *
 765     * @param string $elname name of element
 766     * @param string $pathname full path name of file
 767     * @param bool $override override file if exists
 768     * @return bool success
 769     */
 770    function save_file($elname, $pathname, $override=false) {
 771        global $USER;
 772
 773        if (!$this->is_submitted() or !$this->is_validated()) {
 774            return false;
 775        }
 776        if (file_exists($pathname)) {
 777            if ($override) {
 778                if (!@unlink($pathname)) {
 779                    return false;
 780                }
 781            } else {
 782                return false;
 783            }
 784        }
 785
 786        $element = $this->_form->getElement($elname);
 787
 788        if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
 789            $values = $this->_form->exportValues($elname);
 790            if (empty($values[$elname])) {
 791                return false;
 792            }
 793            $draftid = $values[$elname];
 794            $fs = get_file_storage();
 795            $context = context_user::instance($USER->id);
 796            if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
 797                return false;
 798            }
 799            $file = reset($files);
 800
 801            return $file->copy_content_to($pathname);
 802
 803        } else if (isset($_FILES[$elname])) {
 804            return copy($_FILES[$elname]['tmp_name'], $pathname);
 805        }
 806
 807        return false;
 808    }
 809
 810    /**
 811     * Returns a temporary file, do not forget to delete after not needed any more.
 812     *
 813     * @param string $elname name of the elmenet
 814     * @return string|bool either string or false
 815     */
 816    function save_temp_file($elname) {
 817        if (!$this->get_new_filename($elname)) {
 818            return false;
 819        }
 820        if (!$dir = make_temp_directory('forms')) {
 821            return false;
 822        }
 823        if (!$tempfile = tempnam($dir, 'tempup_')) {
 824            return false;
 825        }
 826        if (!$this->save_file($elname, $tempfile, true)) {
 827            // something went wrong
 828            @unlink($tempfile);
 829            return false;
 830        }
 831
 832        return $tempfile;
 833    }
 834
 835    /**
 836     * Get draft files of a form element
 837     * This is a protected method which will be used only inside moodleforms
 838     *
 839     * @param string $elname name of element
 840     * @return array|bool|null
 841     */
 842    protected function get_draft_files($elname) {
 843        global $USER;
 844
 845        if (!$this->is_submitted()) {
 846            return false;
 847        }
 848
 849        $element = $this->_form->getElement($elname);
 850
 851        if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
 852            $values = $this->_form->exportValues($elname);
 853            if (empty($values[$elname])) {
 854                return false;
 855            }
 856            $draftid = $values[$elname];
 857            $fs = get_file_storage();
 858            $context = context_user::instance($USER->id);
 859            if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
 860                return null;
 861            }
 862            return $files;
 863        }
 864        return null;
 865    }
 866
 867    /**
 868     * Save file to local filesystem pool
 869     *
 870     * @param string $elname name of element
 871     * @param int $newcontextid id of context
 872     * @param string $newcomponent name of the component
 873     * @param string $newfilearea name of file area
 874     * @param int $newitemid item id
 875     * @param string $newfilepath path of file where it get stored
 876     * @param string $newfilename use specified filename, if not specified name of uploaded file used
 877     * @param bool $overwrite overwrite file if exists
 878     * @param int $newuserid new userid if required
 879     * @return mixed stored_file object or false if error; may throw exception if duplicate found
 880     */
 881    function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
 882                              $newfilename=null, $overwrite=false, $newuserid=null) {
 883        global $USER;
 884
 885        if (!$this->is_submitted() or !$this->is_validated()) {
 886            return false;
 887        }
 888
 889        if (empty($newuserid)) {
 890            $newuserid = $USER->id;
 891        }
 892
 893        $element = $this->_form->getElement($elname);
 894        $fs = get_file_storage();
 895
 896        if ($element instanceof MoodleQuickForm_filepicker) {
 897            $values = $this->_form->exportValues($elname);
 898            if (empty($values[$elname])) {
 899                return false;
 900            }
 901            $draftid = $values[$elname];
 902            $context = context_user::instance($USER->id);
 903            if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
 904                return false;
 905            }
 906            $file = reset($files);
 907            if (is_null($newfilename)) {
 908                $newfilename = $file->get_filename();
 909            }
 910
 911            if ($overwrite) {
 912                if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
 913                    if (!$oldfile->delete()) {
 914                        return false;
 915                    }
 916                }
 917            }
 918
 919            $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
 920                                 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
 921            return $fs->create_file_from_storedfile($file_record, $file);
 922
 923        } else if (isset($_FILES[$elname])) {
 924            $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
 925
 926            if ($overwrite) {
 927                if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
 928                    if (!$oldfile->delete()) {
 929                        return false;
 930                    }
 931                }
 932            }
 933
 934            $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
 935                                 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
 936            return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
 937        }
 938
 939        return false;
 940    }
 941
 942    /**
 943     * Get content of uploaded file.
 944     *
 945     * @param string $elname name of file upload element
 946     * @return string|bool false in case of failure, string if ok
 947     */
 948    function get_file_content($elname) {
 949        global $USER;
 950
 951        if (!$this->is_submitted() or !$this->is_validated()) {
 952            return false;
 953        }
 954
 955        $element = $this->_form->getElement($elname);
 956
 957        if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
 958            $values = $this->_form->exportValues($elname);
 959            if (empty($values[$elname])) {
 960                return false;
 961            }
 962            $draftid = $values[$elname];
 963            $fs = get_file_storage();
 964            $context = context_user::instance($USER->id);
 965            if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
 966                return false;
 967            }
 968            $file = reset($files);
 969
 970            return $file->get_content();
 971
 972        } else if (isset($_FILES[$elname])) {
 973            return file_get_contents($_FILES[$elname]['tmp_name']);
 974        }
 975
 976        return false;
 977    }
 978
 979    /**
 980     * Print html form.
 981     */
 982    function display() {
 983        //finalize the form definition if not yet done
 984        if (!$this->_definition_finalized) {
 985            $this->_definition_finalized = true;
 986            $this->definition_after_data();
 987        }
 988
 989        $this->_form->display();
 990    }
 991
 992    /**
 993     * Renders the html form (same as display, but returns the result).
 994     *
 995     * Note that you can only output this rendered result once per page, as
 996     * it contains IDs which must be unique.
 997     *
 998     * @return string HTML code for the form
 999     */
1000    public function render() {
1001        ob_start();
1002        $this->display();
1003        $out = ob_get_contents();
1004        ob_end_clean();
1005        return $out;
1006    }
1007
1008    /**
1009     * Form definition. Abstract method - always override!
1010     */
1011    protected abstract function definition();
1012
1013    /**
1014     * After definition hook.
1015     *
1016     * This is useful for intermediate classes to inject logic after the definition was
1017     * provided without requiring developers to call the parent {{@link self::definition()}}
1018     * as it's not obvious by design. The 'intermediate' class is 'MyClass extends
1019     * IntermediateClass extends moodleform'.
1020     *
1021     * Classes overriding this method should always call the parent. We may not add
1022     * anything specifically in this instance of the method, but intermediate classes
1023     * are likely to do so, and so it is a good practice to always call the parent.
1024     *
1025     * @return void
1026     */
1027    protected function after_definition() {
1028    }
1029
1030    /**
1031     * Dummy stub method - override if you need to setup the form depending on current
1032     * values. This method is called after definition(), data submission and set_data().
1033     * All form setup that is dependent on form values should go in here.
1034     */
1035    function definition_after_data(){
1036    }
1037
1038    /**
1039     * Dummy stub method - override if you needed to perform some extra validation.
1040     * If there are errors return array of errors ("fieldname"=>"error message"),
1041     * otherwise true if ok.
1042     *
1043     * Server side rules do not work for uploaded files, implement serverside rules here if needed.
1044     *
1045     * @param array $data array of ("fieldname"=>value) of submitted data
1046     * @param array $files array of uploaded files "element_name"=>tmp_file_path
1047     * @return array of "element_name"=>"error_description" if there are errors,
1048     *         or an empty array if everything is OK (true allowed for backwards compatibility too).
1049     */
1050    function validation($data, $files) {
1051        return array();
1052    }
1053
1054    /**
1055     * Helper used by {@link repeat_elements()}.
1056     *
1057     * @param int $i the index of this element.
1058     * @param HTML_QuickForm_element $elementclone
1059     * @param array $namecloned array of names
1060     */
1061    function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
1062        $name = $elementclone->getName();
1063        $namecloned[] = $name;
1064
1065        if (!empty($name)) {
1066            $elementclone->setName($name."[$i]");
1067        }
1068
1069        if (is_a($elementclone, 'HTML_QuickForm_header')) {
1070            $value = $elementclone->_text;
1071            $elementclone->setValue(str_replace('{no}', ($i+1), $value));
1072
1073        } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
1074            $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
1075
1076        } else {
1077            $value=$elementclone->getLabel();
1078            $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
1079        }
1080    }
1081
1082    /**
1083     * Method to add a repeating group of elements to a form.
1084     *
1085     * @param array $elementobjs Array of elements or groups of elements that are to be repeated
1086     * @param int $repeats no of times to repeat elements initially
1087     * @param array $options a nested array. The first array key is the element name.
1088     *    the second array key is the type of option to set, and depend on that option,
1089     *    the value takes different forms.
1090     *         'default'    - default value to set. Can include '{no}' which is replaced by the repeat number.
1091     *         'type'       - PARAM_* type.
1092     *         'helpbutton' - array containing the helpbutton params.
1093     *         'disabledif' - array containing the disabledIf() arguments after the element name.
1094     *         'rule'       - array containing the addRule arguments after the element name.
1095     *         'expanded'   - whether this section of the form should be expanded by default. (Name be a header element.)
1096     *         'advanced'   - whether this element is hidden by 'Show more ...'.
1097     * @param string $repeathiddenname name for hidden element storing no of repeats in this form
1098     * @param string $addfieldsname name for button to add more fields
1099     * @param int $addfieldsno how many fields to add at a time
1100     * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
1101     * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
1102     * @return int no of repeats of element in this page
1103     */
1104    function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
1105            $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
1106        if ($addstring===null){
1107            $addstring = get_string('addfields', 'form', $addfieldsno);
1108        } else {
1109            $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
1110        }
1111        $repeats = $this->optional_param($repeathiddenname, $repeats, PARAM_INT);
1112        $addfields = $this->optional_param($addfieldsname, '', PARAM_TEXT);
1113        $oldrepeats = $repeats;
1114        if (!empty($addfields)){
1115            $repeats += $addfieldsno;
1116        }
1117        $mform =& $this->_form;
1118        $mform->registerNoSubmitButton($addfieldsname);
1119        $mform->addElement('hidden', $repeathiddenname, $repeats);
1120        $mform->setType($repeathiddenname, PARAM_INT);
1121        //value not to be overridden by submitted value
1122        $mform->setConstants(array($repeathiddenname=>$repeats));
1123        $namecloned = array();
1124        for ($i = 0; $i < $repeats; $i++) {
1125            foreach ($elementobjs as $elementobj){
1126                $elementclone = fullclone($elementobj);
1127                $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
1128
1129                if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
1130                    foreach ($elementclone->getElements() as $el) {
1131                        $this->repeat_elements_fix_clone($i, $el, $namecloned);
1132                    }
1133                    $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
1134                }
1135
1136                // Mark newly created elements, so they know not to look for any submitted data.
1137                if ($i >= $oldrepeats) {
1138                    $mform->note_new_repeat($elementclone->getName());
1139                }
1140
1141                $mform->addElement($elementclone);
1142            }
1143        }
1144        for ($i=0; $i<$repeats; $i++) {
1145            foreach ($options as $elementname => $elementoptions){
1146                $pos=strpos($elementname, '[');
1147                if ($pos!==FALSE){
1148                    $realelementname = substr($elementname, 0, $pos)."[$i]";
1149                    $realelementname .= substr($elementname, $pos);
1150                }else {
1151                    $realelementname = $elementname."[$i]";
1152                }
1153                foreach ($elementoptions as  $option => $params){
1154
1155                    switch ($option){
1156                        case 'default' :
1157                            $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
1158                            break;
1159                        case 'helpbutton' :
1160                            $params = array_merge(array($realelementname), $params);
1161                            call_user_func_array(array(&$mform, 'addHelpButton'), $params);
1162                            break;
1163                        case 'disabledif' :
1164                            foreach ($namecloned as $num => $name){
1165                                if ($params[0] == $name){
1166                                    $params[0] = $params[0]."[$i]";
1167                                    break;
1168                                }
1169                            }
1170                            $params = array_merge(array($realelementname), $params);
1171                            call_user_func_array(array(&$mform, 'disabledIf'), $params);
1172                            break;
1173                        case 'hideif' :
1174                            foreach ($namecloned as $num => $name){
1175                                if ($params[0] == $name){
1176                                    $params[0] = $params[0]."[$i]";
1177                                    break;
1178                                }
1179                            }
1180                            $params = array_merge(array($realelementname), $params);
1181                            call_user_func_array(array(&$mform, 'hideIf'), $params);
1182                            break;
1183                        case 'rule' :
1184                            if (is_string($params)){
1185                                $params = array(null, $params, null, 'client');
1186                            }
1187                            $params = array_merge(array($realelementname), $params);
1188                            call_user_func_array(array(&$mform, 'addRule'), $params);
1189                            break;
1190
1191                        case 'type':
1192                            $mform->setType($realelementname, $params);
1193                            break;
1194
1195                        case 'expanded':
1196                            $mform->setExpanded($realelementname, $params);
1197                            break;
1198
1199                        case 'advanced' :
1200                            $mform->setAdvanced($realelementname, $params);
1201                            break;
1202                    }
1203                }
1204            }
1205        }
1206        $mform->addElement('submit', $addfieldsname, $addstring);
1207
1208        if (!$addbuttoninside) {
1209            $mform->closeHeaderBefore($addfieldsname);
1210        }
1211
1212        return $repeats;
1213    }
1214
1215    /**
1216     * Adds a link/button that controls the checked state of a group of checkboxes.
1217     *
1218     * @param int $groupid The id of the group of advcheckboxes this element controls
1219     * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
1220     * @param array $attributes associative array of HTML attributes
1221     * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
1222     */
1223    function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
1224        global $CFG, $PAGE;
1225
1226        // Name of the controller button
1227        $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
1228        $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
1229        $checkboxgroupclass = 'checkboxgroup'.$groupid;
1230
1231        // Set the default text if none was specified
1232        if (empty($text)) {
1233            $text = get_string('selectallornone', 'form');
1234        }
1235
1236        $mform = $this->_form;
1237        $selectvalue = $this->optional_param($checkboxcontrollerparam, null, PARAM_INT);
1238        $contollerbutton = $this->optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
1239
1240        $newselectvalue = $selectvalue;
1241        if (is_null($selectvalue)) {
1242            $newselectvalue = $originalValue;
1243        } else if (!is_null($contollerbutton)) {
1244            $newselectvalue = (int) !$selectvalue;
1245        }
1246        // set checkbox state depending on orignal/submitted value by controoler button
1247        if (!is_null($contollerbutton) || is_null($selectvalue)) {
1248            foreach ($mform->_elements as $element) {
1249                if (($element instanceof MoodleQuickForm_advcheckbox) &&
1250                        $element->getAttribute('class') == $checkboxgroupclass &&
1251                        !$element->isFrozen()) {
1252                    $mform->setConstants(array($element->getName() => $newselectvalue));
1253                }
1254            }
1255        }
1256
1257        $mform->addElement('hidden', $chec…

Large files files are truncated, but you can click here to view the full file