PageRenderTime 62ms CodeModel.GetById 18ms app.highlight 31ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/formslib.php

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

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