PageRenderTime 67ms CodeModel.GetById 14ms app.highlight 38ms RepoModel.GetById 2ms app.codeStats 0ms

/lib/formslib.php

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

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