PageRenderTime 81ms CodeModel.GetById 16ms app.highlight 45ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/formslib.php

https://bitbucket.org/systime/screening2
PHP | 1936 lines | 1376 code | 113 blank | 447 comment | 144 complexity | 00e230864f0c02951d1c6c6ad622b004 MD5 | raw file

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

   1<?php // $Id: formslib.php,v 1.129.2.25 2010/09/17 22:29:37 mudrd8mz Exp $
   2/**
   3 * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
   4 *
   5 * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
   6 * and you want to name your class something like {modulename}_{purpose}_form. Your class will
   7 * extend moodleform overriding abstract classes definition and optionally defintion_after_data
   8 * and validation.
   9 *
  10 * See examples of use of this library in course/edit.php and course/edit_form.php
  11 *
  12 * A few notes :
  13 *      form defintion is used for both printing of form and processing and should be the same
  14 *              for both or you may lose some submitted data which won't be let through.
  15 *      you should be using setType for every form element except select, radio or checkbox
  16 *              elements, these elements clean themselves.
  17 *
  18 *
  19 * @author  Jamie Pratt
  20 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  21 */
  22
  23if (!defined('MOODLE_INTERNAL')) {
  24    die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
  25}
  26
  27
  28//setup.php icludes our hacked pear libs first
  29require_once 'HTML/QuickForm.php';
  30require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
  31require_once 'HTML/QuickForm/Renderer/Tableless.php';
  32
  33require_once $CFG->libdir.'/uploadlib.php';
  34
  35/**
  36 * Callback called when PEAR throws an error
  37 *
  38 * @param PEAR_Error $error
  39 */
  40function pear_handle_error($error){
  41    echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
  42    echo '<br /> <strong>Backtrace </strong>:';
  43    print_object($error->backtrace);
  44}
  45
  46if ($CFG->debug >= DEBUG_ALL){
  47    PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
  48}
  49
  50
  51/**
  52 * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
  53 * use this class you should write a class definition which extends this class or a more specific
  54 * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
  55 *
  56 * You will write your own definition() method which performs the form set up.
  57 */
  58class moodleform {
  59    var $_formname;       // form name
  60    /**
  61     * quickform object definition
  62     *
  63     * @var MoodleQuickForm
  64     */
  65    var $_form;
  66    /**
  67     * globals workaround
  68     *
  69     * @var array
  70     */
  71    var $_customdata;
  72    /**
  73     * file upload manager
  74     *
  75     * @var upload_manager
  76     */
  77    var $_upload_manager; //
  78    /**
  79     * definition_after_data executed flag
  80     * @var definition_finalized
  81     */
  82    var $_definition_finalized = false;
  83
  84    /**
  85     * The constructor function calls the abstract function definition() and it will then
  86     * process and clean and attempt to validate incoming data.
  87     *
  88     * It will call your custom validate method to validate data and will also check any rules
  89     * you have specified in definition using addRule
  90     *
  91     * The name of the form (id attribute of the form) is automatically generated depending on
  92     * the name you gave the class extending moodleform. You should call your class something
  93     * like
  94     *
  95     * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
  96     *                  current url. If a moodle_url object then outputs params as hidden variables.
  97     * @param array $customdata if your form defintion method needs access to data such as $course
  98     *               $cm, etc. to construct the form definition then pass it in this array. You can
  99     *               use globals for somethings.
 100     * @param string $method if you set this to anything other than 'post' then _GET and _POST will
 101     *               be merged and used as incoming data to the form.
 102     * @param string $target target frame for form submission. You will rarely use this. Don't use
 103     *                  it if you don't need to as the target attribute is deprecated in xhtml
 104     *                  strict.
 105     * @param mixed $attributes you can pass a string of html attributes here or an array.
 106     * @return moodleform
 107     */
 108    function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
 109        if (empty($action)){
 110            $action = strip_querystring(qualified_me());
 111        }
 112
 113        $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
 114        $this->_customdata = $customdata;
 115        $this->_form =& new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
 116        if (!$editable){
 117            $this->_form->hardFreeze();
 118        }
 119        $this->set_upload_manager(new upload_manager());
 120
 121        $this->definition();
 122
 123        $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
 124        $this->_form->setType('sesskey', PARAM_RAW);
 125        $this->_form->setDefault('sesskey', sesskey());
 126        $this->_form->addElement('hidden', '_qf__'.$this->_formname, null);   // form submission marker
 127        $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
 128        $this->_form->setDefault('_qf__'.$this->_formname, 1);
 129        $this->_form->_setDefaultRuleMessages();
 130
 131        // we have to know all input types before processing submission ;-)
 132        $this->_process_submission($method);
 133    }
 134
 135    /**
 136     * To autofocus on first form element or first element with error.
 137     *
 138     * @param string $name if this is set then the focus is forced to a field with this name
 139     *
 140     * @return string  javascript to select form element with first error or
 141     *                  first element if no errors. Use this as a parameter
 142     *                  when calling print_header
 143     */
 144    function focus($name=NULL) {
 145        $form =& $this->_form;
 146        $elkeys = array_keys($form->_elementIndex);
 147        $error = false;
 148        if (isset($form->_errors) &&  0 != count($form->_errors)){
 149            $errorkeys = array_keys($form->_errors);
 150            $elkeys = array_intersect($elkeys, $errorkeys);
 151            $error = true;
 152        }
 153
 154        if ($error or empty($name)) {
 155            $names = array();
 156            while (empty($names) and !empty($elkeys)) {
 157                $el = array_shift($elkeys);
 158                $names = $form->_getElNamesRecursive($el);
 159            }
 160            if (!empty($names)) {
 161                $name = array_shift($names);
 162            }
 163        }
 164
 165        $focus = '';
 166        if (!empty($name)) {
 167            $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
 168        }
 169
 170        return $focus;
 171     }
 172
 173    /**
 174     * Internal method. Alters submitted data to be suitable for quickforms processing.
 175     * Must be called when the form is fully set up.
 176     */
 177    function _process_submission($method) {
 178        $submission = array();
 179        if ($method == 'post') {
 180            if (!empty($_POST)) {
 181                $submission = $_POST;
 182            }
 183        } else {
 184            $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
 185        }
 186
 187        // following trick is needed to enable proper sesskey checks when using GET forms
 188        // the _qf__.$this->_formname serves as a marker that form was actually submitted
 189        if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
 190            if (!confirm_sesskey()) {
 191                print_error('invalidsesskey');
 192            }
 193            $files = $_FILES;
 194        } else {
 195            $submission = array();
 196            $files = array();
 197        }
 198
 199        $this->_form->updateSubmission($submission, $files);
 200    }
 201
 202    /**
 203     * Internal method. Validates all uploaded files.
 204     */
 205    function _validate_files(&$files) {
 206        $files = array();
 207
 208        if (empty($_FILES)) {
 209            // we do not need to do any checks because no files were submitted
 210            // note: server side rules do not work for files - use custom verification in validate() instead
 211            return true;
 212        }
 213        $errors = array();
 214        $mform =& $this->_form;
 215
 216        // check the files
 217        $status = $this->_upload_manager->preprocess_files();
 218
 219        // now check that we really want each file
 220        foreach ($_FILES as $elname=>$file) {
 221            if ($mform->elementExists($elname) and $mform->getElementType($elname)=='file') {
 222                $required = $mform->isElementRequired($elname);
 223                if (!empty($this->_upload_manager->files[$elname]['uploadlog']) and empty($this->_upload_manager->files[$elname]['clear'])) {
 224                    if (!$required and $file['error'] == UPLOAD_ERR_NO_FILE) {
 225                        // file not uploaded and not required - ignore it
 226                        continue;
 227                    }
 228                    $errors[$elname] = $this->_upload_manager->files[$elname]['uploadlog'];
 229
 230                } else if (!empty($this->_upload_manager->files[$elname]['clear'])) {
 231                    $files[$elname] = $this->_upload_manager->files[$elname]['tmp_name'];
 232                }
 233            } else {
 234                error('Incorrect upload attempt!');
 235            }
 236        }
 237
 238        // return errors if found
 239        if ($status and 0 == count($errors)){
 240            return true;
 241
 242        } else {
 243            $files = array();
 244            return $errors;
 245        }
 246    }
 247
 248    /**
 249     * Load in existing data as form defaults. Usually new entry defaults are stored directly in
 250     * form definition (new entry form); this function is used to load in data where values
 251     * already exist and data is being edited (edit entry form).
 252     *
 253     * @param mixed $default_values object or array of default values
 254     * @param bool $slased true if magic quotes applied to data values
 255     */
 256    function set_data($default_values, $slashed=false) {
 257        if (is_object($default_values)) {
 258            $default_values = (array)$default_values;
 259        }
 260        $filter = $slashed ? 'stripslashes' : NULL;
 261        $this->_form->setDefaults($default_values, $filter);
 262    }
 263
 264    /**
 265     * Set custom upload manager.
 266     * Must be used BEFORE creating of file element!
 267     *
 268     * @param object $um - custom upload manager
 269     */
 270    function set_upload_manager($um=false) {
 271        if ($um === false) {
 272            $um = new upload_manager();
 273        }
 274        $this->_upload_manager = $um;
 275
 276        $this->_form->setMaxFileSize($um->config->maxbytes);
 277    }
 278
 279    /**
 280     * Check that form was submitted. Does not check validity of submitted data.
 281     *
 282     * @return bool true if form properly submitted
 283     */
 284    function is_submitted() {
 285        return $this->_form->isSubmitted();
 286    }
 287
 288    function no_submit_button_pressed(){
 289        static $nosubmit = null; // one check is enough
 290        if (!is_null($nosubmit)){
 291            return $nosubmit;
 292        }
 293        $mform =& $this->_form;
 294        $nosubmit = false;
 295        if (!$this->is_submitted()){
 296            return false;
 297        }
 298        foreach ($mform->_noSubmitButtons as $nosubmitbutton){
 299            if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
 300                $nosubmit = true;
 301                break;
 302            }
 303        }
 304        return $nosubmit;
 305    }
 306
 307
 308    /**
 309     * Check that form data is valid.
 310     * You should almost always use this, rather than {@see validate_defined_fields}
 311     *
 312     * @return bool true if form data valid
 313     */
 314    function is_validated() {
 315        //finalize the form definition before any processing
 316        if (!$this->_definition_finalized) {
 317            $this->_definition_finalized = true;
 318            $this->definition_after_data();
 319        }
 320        return $this->validate_defined_fields();
 321    }
 322
 323    /**
 324     * Validate the form.
 325     *
 326     * You almost always want to call {@see is_validated} instead of this
 327     * because it calls {@see definition_after_data} first, before validating the form,
 328     * which is what you want in 99% of cases.
 329     *
 330     * This is provided as a separate function for those special cases where
 331     * you want the form validated before definition_after_data is called
 332     * for example, to selectively add new elements depending on a no_submit_button press,
 333     * but only when the form is valid when the no_submit_button is pressed,
 334     *
 335     * @param boolean $validateonnosubmit optional, defaults to false.  The default behaviour
 336     *                is NOT to validate the form when a no submit button has been pressed.
 337     *                pass true here to override this behaviour
 338     *
 339     * @return bool true if form data valid
 340     */
 341    function validate_defined_fields($validateonnosubmit=false) {
 342        static $validated = null; // one validation is enough
 343        $mform =& $this->_form;
 344
 345        if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
 346            return false;
 347        } elseif ($validated === null) {
 348            $internal_val = $mform->validate();
 349
 350            $files = array();
 351            $file_val = $this->_validate_files($files);
 352            if ($file_val !== true) {
 353                if (!empty($file_val)) {
 354                    foreach ($file_val as $element=>$msg) {
 355                        $mform->setElementError($element, $msg);
 356                    }
 357                }
 358                $file_val = false;
 359            }
 360
 361            $data = $mform->exportValues(null, true);
 362            $moodle_val = $this->validation($data, $files);
 363            if ((is_array($moodle_val) && count($moodle_val)!==0)) {
 364                // non-empty array means errors
 365                foreach ($moodle_val as $element=>$msg) {
 366                    $mform->setElementError($element, $msg);
 367                }
 368                $moodle_val = false;
 369
 370            } else {
 371                // anything else means validation ok
 372                $moodle_val = true;
 373            }
 374
 375            $validated = ($internal_val and $moodle_val and $file_val);
 376        }
 377        return $validated;
 378    }
 379
 380    /**
 381     * Return true if a cancel button has been pressed resulting in the form being submitted.
 382     *
 383     * @return boolean true if a cancel button has been pressed
 384     */
 385    function is_cancelled(){
 386        $mform =& $this->_form;
 387        if ($mform->isSubmitted()){
 388            foreach ($mform->_cancelButtons as $cancelbutton){
 389                if (optional_param($cancelbutton, 0, PARAM_RAW)){
 390                    return true;
 391                }
 392            }
 393        }
 394        return false;
 395    }
 396
 397    /**
 398     * Return submitted data if properly submitted or returns NULL if validation fails or
 399     * if there is no submitted data.
 400     *
 401     * @param bool $slashed true means return data with addslashes applied
 402     * @return object submitted data; NULL if not valid or not submitted
 403     */
 404    function get_data($slashed=true) {
 405        $mform =& $this->_form;
 406
 407        if ($this->is_submitted() and $this->is_validated()) {
 408            $data = $mform->exportValues(null, $slashed);
 409            unset($data['sesskey']); // we do not need to return sesskey
 410            unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
 411            if (empty($data)) {
 412                return NULL;
 413            } else {
 414                return (object)$data;
 415            }
 416        } else {
 417            return NULL;
 418        }
 419    }
 420
 421    /**
 422     * Return submitted data without validation or NULL if there is no submitted data.
 423     *
 424     * @param bool $slashed true means return data with addslashes applied
 425     * @return object submitted data; NULL if not submitted
 426     */
 427    function get_submitted_data($slashed=true) {
 428        $mform =& $this->_form;
 429
 430        if ($this->is_submitted()) {
 431            $data = $mform->exportValues(null, $slashed);
 432            unset($data['sesskey']); // we do not need to return sesskey
 433            unset($data['_qf__'.$this->_formname]);   // we do not need the submission marker too
 434            if (empty($data)) {
 435                return NULL;
 436            } else {
 437                return (object)$data;
 438            }
 439        } else {
 440            return NULL;
 441        }
 442    }
 443
 444    /**
 445     * Save verified uploaded files into directory. Upload process can be customised from definition()
 446     * method by creating instance of upload manager and storing it in $this->_upload_form
 447     *
 448     * @param string $destination where to store uploaded files
 449     * @return bool success
 450     */
 451    function save_files($destination) {
 452        if ($this->is_submitted() and $this->is_validated()) {
 453            return $this->_upload_manager->save_files($destination);
 454        }
 455        return false;
 456    }
 457
 458    /**
 459     * If we're only handling one file (if inputname was given in the constructor)
 460     * this will return the (possibly changed) filename of the file.
 461     * @return mixed false in case of failure, string if ok
 462     */
 463    function get_new_filename() {
 464        return $this->_upload_manager->get_new_filename();
 465    }
 466
 467    /**
 468     * Get content of uploaded file.
 469     * @param $element name of file upload element
 470     * @return mixed false in case of failure, string if ok
 471     */
 472    function get_file_content($elname) {
 473        if (!$this->is_submitted() or !$this->is_validated()) {
 474            return false;
 475        }
 476
 477        if (!$this->_form->elementExists($elname)) {
 478            return false;
 479        }
 480
 481        if (empty($this->_upload_manager->files[$elname]['clear'])) {
 482            return false;
 483        }
 484
 485        if (empty($this->_upload_manager->files[$elname]['tmp_name'])) {
 486            return false;
 487        }
 488
 489        $data = "";
 490        $file = @fopen($this->_upload_manager->files[$elname]['tmp_name'], "rb");
 491        if ($file) {
 492            while (!feof($file)) {
 493                $data .= fread($file, 1024); // TODO: do we really have to do this?
 494            }
 495            fclose($file);
 496            return $data;
 497        } else {
 498            return false;
 499        }
 500    }
 501
 502    /**
 503     * Print html form.
 504     */
 505    function display() {
 506        //finalize the form definition if not yet done
 507        if (!$this->_definition_finalized) {
 508            $this->_definition_finalized = true;
 509            $this->definition_after_data();
 510        }
 511        $this->_form->display();
 512    }
 513
 514    /**
 515     * Abstract method - always override!
 516     *
 517     * If you need special handling of uploaded files, create instance of $this->_upload_manager here.
 518     */
 519    function definition() {
 520        error('Abstract form_definition() method in class '.get_class($this).' must be overriden, please fix the code.');
 521    }
 522
 523    /**
 524     * Dummy stub method - override if you need to setup the form depending on current
 525     * values. This method is called after definition(), data submission and set_data().
 526     * All form setup that is dependent on form values should go in here.
 527     */
 528    function definition_after_data(){
 529    }
 530
 531    /**
 532     * Dummy stub method - override if you needed to perform some extra validation.
 533     * If there are errors return array of errors ("fieldname"=>"error message"),
 534     * otherwise true if ok.
 535     *
 536     * Server side rules do not work for uploaded files, implement serverside rules here if needed.
 537     *
 538     * @param array $data array of ("fieldname"=>value) of submitted data
 539     * @param array $files array of uploaded files "element_name"=>tmp_file_path
 540     * @return array of "element_name"=>"error_description" if there are errors,
 541     *               or an empty array if everything is OK (true allowed for backwards compatibility too).
 542     */
 543    function validation($data, $files) {
 544        return array();
 545    }
 546
 547    /**
 548     * Method to add a repeating group of elements to a form.
 549     *
 550     * @param array $elementobjs Array of elements or groups of elements that are to be repeated
 551     * @param integer $repeats no of times to repeat elements initially
 552     * @param array $options Array of options to apply to elements. Array keys are element names.
 553     *                      This is an array of arrays. The second sets of keys are the option types
 554     *                      for the elements :
 555     *                          'default' - default value is value
 556     *                          'type' - PARAM_* constant is value
 557     *                          'helpbutton' - helpbutton params array is value
 558     *                          'disabledif' - last three moodleform::disabledIf()
 559     *                                           params are value as an array
 560     * @param string $repeathiddenname name for hidden element storing no of repeats in this form
 561     * @param string $addfieldsname name for button to add more fields
 562     * @param int $addfieldsno how many fields to add at a time
 563     * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
 564     * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
 565     * @return int no of repeats of element in this page
 566     */
 567    function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
 568            $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
 569        if ($addstring===null){
 570            $addstring = get_string('addfields', 'form', $addfieldsno);
 571        } else {
 572            $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
 573        }
 574        $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
 575        $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
 576        if (!empty($addfields)){
 577            $repeats += $addfieldsno;
 578        }
 579        $mform =& $this->_form;
 580        $mform->registerNoSubmitButton($addfieldsname);
 581        $mform->addElement('hidden', $repeathiddenname, $repeats);
 582        $mform->setType($repeathiddenname, PARAM_INT);
 583        //value not to be overridden by submitted value
 584        $mform->setConstants(array($repeathiddenname=>$repeats));
 585        $namecloned = array();
 586        for ($i = 0; $i < $repeats; $i++) {
 587            foreach ($elementobjs as $elementobj){
 588                $elementclone = fullclone($elementobj);
 589                $name = $elementclone->getName();
 590                $namecloned[] = $name;
 591                if (!empty($name)) {
 592                    $elementclone->setName($name."[$i]");
 593                }
 594                if (is_a($elementclone, 'HTML_QuickForm_header')) {
 595                    $value = $elementclone->_text;
 596                    $elementclone->setValue(str_replace('{no}', ($i+1), $value));
 597
 598                } else {
 599                    $value=$elementclone->getLabel();
 600                    $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
 601
 602                }
 603
 604                $mform->addElement($elementclone);
 605            }
 606        }
 607        for ($i=0; $i<$repeats; $i++) {
 608            foreach ($options as $elementname => $elementoptions){
 609                $pos=strpos($elementname, '[');
 610                if ($pos!==FALSE){
 611                    $realelementname = substr($elementname, 0, $pos+1)."[$i]";
 612                    $realelementname .= substr($elementname, $pos+1);
 613                }else {
 614                    $realelementname = $elementname."[$i]";
 615                }
 616                foreach ($elementoptions as  $option => $params){
 617
 618                    switch ($option){
 619                        case 'default' :
 620                            $mform->setDefault($realelementname, $params);
 621                            break;
 622                        case 'helpbutton' :
 623                            $mform->setHelpButton($realelementname, $params);
 624                            break;
 625                        case 'disabledif' :
 626                            foreach ($namecloned as $num => $name){
 627                                if ($params[0] == $name){
 628                                    $params[0] = $params[0]."[$i]";
 629                                    break;
 630                                }
 631                            }
 632                            $params = array_merge(array($realelementname), $params);
 633                            call_user_func_array(array(&$mform, 'disabledIf'), $params);
 634                            break;
 635                        case 'rule' :
 636                            if (is_string($params)){
 637                                $params = array(null, $params, null, 'client');
 638                            }
 639                            $params = array_merge(array($realelementname), $params);
 640                            call_user_func_array(array(&$mform, 'addRule'), $params);
 641                            break;
 642
 643                    }
 644                }
 645            }
 646        }
 647        $mform->addElement('submit', $addfieldsname, $addstring);
 648
 649        if (!$addbuttoninside) {
 650            $mform->closeHeaderBefore($addfieldsname);
 651        }
 652
 653        return $repeats;
 654    }
 655
 656    /**
 657     * Adds a link/button that controls the checked state of a group of checkboxes.
 658     * @param int    $groupid The id of the group of advcheckboxes this element controls
 659     * @param string $text The text of the link. Defaults to "select all/none"
 660     * @param array  $attributes associative array of HTML attributes
 661     * @param int    $originalValue The original general state of the checkboxes before the user first clicks this element
 662     */
 663    function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
 664        global $CFG;
 665        if (empty($text)) {
 666            $text = get_string('selectallornone', 'form');
 667        }
 668
 669        $mform = $this->_form;
 670        $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
 671
 672        if ($select_value == 0 || is_null($select_value)) {
 673            $new_select_value = 1;
 674        } else {
 675            $new_select_value = 0;
 676        }
 677
 678        $mform->addElement('hidden', "checkbox_controller$groupid");
 679        $mform->setType("checkbox_controller$groupid", PARAM_INT);
 680        $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
 681
 682        // Locate all checkboxes for this group and set their value, IF the optional param was given
 683        if (!is_null($select_value)) {
 684            foreach ($this->_form->_elements as $element) {
 685                if ($element->getAttribute('class') == "checkboxgroup$groupid") {
 686                    $mform->setConstants(array($element->getAttribute('name') => $select_value));
 687                }
 688            }
 689        }
 690
 691        $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
 692        $mform->registerNoSubmitButton($checkbox_controller_name);
 693
 694        // Prepare Javascript for submit element
 695        $js = "\n//<![CDATA[\n";
 696        if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
 697            $js .= <<<EOS
 698function html_quickform_toggle_checkboxes(group) {
 699    var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
 700    var newvalue = false;
 701    var global = eval('html_quickform_checkboxgroup' + group + ';');
 702    if (global == 1) {
 703        eval('html_quickform_checkboxgroup' + group + ' = 0;');
 704        newvalue = '';
 705    } else {
 706        eval('html_quickform_checkboxgroup' + group + ' = 1;');
 707        newvalue = 'checked';
 708    }
 709
 710    for (i = 0; i < checkboxes.length; i++) {
 711        checkboxes[i].checked = newvalue;
 712    }
 713}
 714EOS;
 715            define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
 716        }
 717        $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
 718
 719        $js .= "//]]>\n";
 720
 721        require_once("$CFG->libdir/form/submitlink.php");
 722        $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
 723        $submitlink->_js = $js;
 724        $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
 725        $mform->addElement($submitlink);
 726        $mform->setDefault($checkbox_controller_name, $text);
 727    }
 728
 729    /**
 730     * Use this method to a cancel and submit button to the end of your form. Pass a param of false
 731     * if you don't want a cancel button in your form. If you have a cancel button make sure you
 732     * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
 733     * get data with get_data().
 734     *
 735     * @param boolean $cancel whether to show cancel button, default true
 736     * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
 737     */
 738    function add_action_buttons($cancel = true, $submitlabel=null){
 739        if (is_null($submitlabel)){
 740            $submitlabel = get_string('savechanges');
 741        }
 742        $mform =& $this->_form;
 743        if ($cancel){
 744            //when two elements we need a group
 745            $buttonarray=array();
 746            $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
 747            $buttonarray[] = &$mform->createElement('cancel');
 748            $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
 749            $mform->closeHeaderBefore('buttonar');
 750        } else {
 751            //no group needed
 752            $mform->addElement('submit', 'submitbutton', $submitlabel);
 753            $mform->closeHeaderBefore('submitbutton');
 754        }
 755    }
 756}
 757
 758/**
 759 * You never extend this class directly. The class methods of this class are available from
 760 * the private $this->_form property on moodleform and its children. You generally only
 761 * call methods on this class from within abstract methods that you override on moodleform such
 762 * as definition and definition_after_data
 763 *
 764 */
 765class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
 766    var $_types = array();
 767    var $_dependencies = array();
 768    /**
 769     * Array of buttons that if pressed do not result in the processing of the form.
 770     *
 771     * @var array
 772     */
 773    var $_noSubmitButtons=array();
 774    /**
 775     * Array of buttons that if pressed do not result in the processing of the form.
 776     *
 777     * @var array
 778     */
 779    var $_cancelButtons=array();
 780
 781    /**
 782     * Array whose keys are element names. If the key exists this is a advanced element
 783     *
 784     * @var array
 785     */
 786    var $_advancedElements = array();
 787
 788    /**
 789     * Whether to display advanced elements (on page load)
 790     *
 791     * @var boolean
 792     */
 793    var $_showAdvanced = null;
 794
 795    /**
 796     * The form name is derrived from the class name of the wrapper minus the trailing form
 797     * It is a name with words joined by underscores whereas the id attribute is words joined by
 798     * underscores.
 799     *
 800     * @var unknown_type
 801     */
 802    var $_formName = '';
 803
 804    /**
 805     * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
 806     *
 807     * @var string
 808     */
 809    var $_pageparams = '';
 810
 811    /**
 812     * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
 813     * @param    string      $formName          Form's name.
 814     * @param    string      $method            (optional)Form's method defaults to 'POST'
 815     * @param    mixed      $action             (optional)Form's action - string or moodle_url
 816     * @param    string      $target            (optional)Form's target defaults to none
 817     * @param    mixed       $attributes        (optional)Extra attributes for <form> tag
 818     * @param    bool        $trackSubmit       (optional)Whether to track if the form was submitted by adding a special hidden field
 819     * @access   public
 820     */
 821    function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
 822        global $CFG;
 823
 824        static $formcounter = 1;
 825
 826        HTML_Common::HTML_Common($attributes);
 827        $target = empty($target) ? array() : array('target' => $target);
 828        $this->_formName = $formName;
 829        if (is_a($action, 'moodle_url')){
 830            $this->_pageparams = $action->hidden_params_out();
 831            $action = $action->out(true);
 832        } else {
 833            $this->_pageparams = '';
 834        }
 835        //no 'name' atttribute for form in xhtml strict :
 836        $attributes = array('action'=>$action, 'method'=>$method,
 837                'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
 838        $formcounter++;
 839        $this->updateAttributes($attributes);
 840
 841        //this is custom stuff for Moodle :
 842        $oldclass=   $this->getAttribute('class');
 843        if (!empty($oldclass)){
 844            $this->updateAttributes(array('class'=>$oldclass.' mform'));
 845        }else {
 846            $this->updateAttributes(array('class'=>'mform'));
 847        }
 848        $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />';
 849        $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$CFG->pixpath.'/adv.gif'.'" />';
 850        $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$CFG->pixpath.'/req.gif'.'" />'));
 851        //(Help file doesn't add anything) helpbutton('requiredelement', get_string('requiredelement', 'form'), 'moodle', true, false, '', true));
 852    }
 853
 854    /**
 855     * Use this method to indicate an element in a form is an advanced field. If items in a form
 856     * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
 857     * form so the user can decide whether to display advanced form controls.
 858     *
 859     * If you set a header element to advanced then all elements it contains will also be set as advanced.
 860     *
 861     * @param string $elementName group or element name (not the element name of something inside a group).
 862     * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
 863     */
 864    function setAdvanced($elementName, $advanced=true){
 865        if ($advanced){
 866            $this->_advancedElements[$elementName]='';
 867        } elseif (isset($this->_advancedElements[$elementName])) {
 868            unset($this->_advancedElements[$elementName]);
 869        }
 870        if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
 871            $this->setShowAdvanced();
 872            $this->registerNoSubmitButton('mform_showadvanced');
 873
 874            $this->addElement('hidden', 'mform_showadvanced_last');
 875            $this->setType('mform_showadvanced_last', PARAM_INT);
 876        }
 877    }
 878    /**
 879     * Set whether to show advanced elements in the form on first displaying form. Default is not to
 880     * display advanced elements in the form until 'Show Advanced' is pressed.
 881     *
 882     * You can get the last state of the form and possibly save it for this user by using
 883     * value 'mform_showadvanced_last' in submitted data.
 884     *
 885     * @param boolean $showadvancedNow
 886     */
 887    function setShowAdvanced($showadvancedNow = null){
 888        if ($showadvancedNow === null){
 889            if ($this->_showAdvanced !== null){
 890                return;
 891            } else { //if setShowAdvanced is called without any preference
 892                     //make the default to not show advanced elements.
 893                $showadvancedNow = get_user_preferences(
 894                                moodle_strtolower($this->_formName.'_showadvanced', 0));
 895            }
 896        }
 897        //value of hidden element
 898        $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
 899        //value of button
 900        $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
 901        //toggle if button pressed or else stay the same
 902        if ($hiddenLast == -1) {
 903            $next = $showadvancedNow;
 904        } elseif ($buttonPressed) { //toggle on button press
 905            $next = !$hiddenLast;
 906        } else {
 907            $next = $hiddenLast;
 908        }
 909        $this->_showAdvanced = $next;
 910        if ($showadvancedNow != $next){
 911            set_user_preference($this->_formName.'_showadvanced', $next);
 912        }
 913        $this->setConstants(array('mform_showadvanced_last'=>$next));
 914    }
 915    function getShowAdvanced(){
 916        return $this->_showAdvanced;
 917    }
 918
 919
 920   /**
 921    * Accepts a renderer
 922    *
 923    * @param HTML_QuickForm_Renderer  An HTML_QuickForm_Renderer object
 924    * @since 3.0
 925    * @access public
 926    * @return void
 927    */
 928    function accept(&$renderer) {
 929        if (method_exists($renderer, 'setAdvancedElements')){
 930            //check for visible fieldsets where all elements are advanced
 931            //and mark these headers as advanced as well.
 932            //And mark all elements in a advanced header as advanced
 933            $stopFields = $renderer->getStopFieldSetElements();
 934            $lastHeader = null;
 935            $lastHeaderAdvanced = false;
 936            $anyAdvanced = false;
 937            foreach (array_keys($this->_elements) as $elementIndex){
 938                $element =& $this->_elements[$elementIndex];
 939
 940                // if closing header and any contained element was advanced then mark it as advanced
 941                if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
 942                    if ($anyAdvanced && !is_null($lastHeader)){
 943                        $this->setAdvanced($lastHeader->getName());
 944                    }
 945                    $lastHeaderAdvanced = false;
 946                    unset($lastHeader);
 947                    $lastHeader = null;
 948                } elseif ($lastHeaderAdvanced) {
 949                    $this->setAdvanced($element->getName());
 950                }
 951
 952                if ($element->getType()=='header'){
 953                    $lastHeader =& $element;
 954                    $anyAdvanced = false;
 955                    $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
 956                } elseif (isset($this->_advancedElements[$element->getName()])){
 957                    $anyAdvanced = true;
 958                }
 959            }
 960            // the last header may not be closed yet...
 961            if ($anyAdvanced && !is_null($lastHeader)){
 962                $this->setAdvanced($lastHeader->getName());
 963            }
 964            $renderer->setAdvancedElements($this->_advancedElements);
 965
 966        }
 967        parent::accept($renderer);
 968    }
 969
 970
 971
 972    function closeHeaderBefore($elementName){
 973        $renderer =& $this->defaultRenderer();
 974        $renderer->addStopFieldsetElements($elementName);
 975    }
 976
 977    /**
 978     * Should be used for all elements of a form except for select, radio and checkboxes which
 979     * clean their own data.
 980     *
 981     * @param string $elementname
 982     * @param integer $paramtype use the constants PARAM_*.
 983     *     *  PARAM_CLEAN is deprecated and you should try to use a more specific type.
 984     *     *  PARAM_TEXT should be used for cleaning data that is expected to be plain text.
 985     *          It will strip all html tags. But will still let tags for multilang support
 986     *          through.
 987     *     *  PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
 988     *          html editor. Data from the editor is later cleaned before display using
 989     *          format_text() function. PARAM_RAW can also be used for data that is validated
 990     *          by some other way or printed by p() or s().
 991     *     *  PARAM_INT should be used for integers.
 992     *     *  PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
 993     *          form actions.
 994     */
 995    function setType($elementname, $paramtype) {
 996        $this->_types[$elementname] = $paramtype;
 997    }
 998
 999    /**
1000     * See description of setType above. This can be used to set several types at once.
1001     *
1002     * @param array $paramtypes
1003     */
1004    function setTypes($paramtypes) {
1005        $this->_types = $paramtypes + $this->_types;
1006    }
1007
1008    function updateSubmission($submission, $files) {
1009        $this->_flagSubmitted = false;
1010
1011        if (empty($submission)) {
1012            $this->_submitValues = array();
1013        } else {
1014            foreach ($submission as $key=>$s) {
1015                if (array_key_exists($key, $this->_types)) {
1016                    $submission[$key] = clean_param($s, $this->_types[$key]);
1017                }
1018            }
1019            $this->_submitValues = $this->_recursiveFilter('stripslashes', $submission);
1020            $this->_flagSubmitted = true;
1021        }
1022
1023        if (empty($files)) {
1024            $this->_submitFiles = array();
1025        } else {
1026            if (1 == get_magic_quotes_gpc()) {
1027                foreach (array_keys($files) as $elname) {
1028                    // dangerous characters in filenames are cleaned later in upload_manager
1029                    $files[$elname]['name'] = stripslashes($files[$elname]['name']);
1030                }
1031            }
1032            $this->_submitFiles = $files;
1033            $this->_flagSubmitted = true;
1034        }
1035
1036        // need to tell all elements that they need to update their value attribute.
1037         foreach (array_keys($this->_elements) as $key) {
1038             $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
1039         }
1040    }
1041
1042    function getReqHTML(){
1043        return $this->_reqHTML;
1044    }
1045
1046    function getAdvancedHTML(){
1047        return $this->_advancedHTML;
1048    }
1049
1050    /**
1051     * Initializes a default form value. Used to specify the default for a new entry where
1052     * no data is loaded in using moodleform::set_data()
1053     *
1054     * @param     string   $elementname        element name
1055     * @param     mixed    $values             values for that element name
1056     * @param     bool     $slashed            the default value is slashed
1057     * @access    public
1058     * @return    void
1059     */
1060    function setDefault($elementName, $defaultValue, $slashed=false){
1061        $filter = $slashed ? 'stripslashes' : NULL;
1062        $this->setDefaults(array($elementName=>$defaultValue), $filter);
1063    } // end func setDefault
1064    /**
1065     * Add an array of buttons to the form
1066     * @param    array       $buttons          An associative array representing help button to attach to
1067     *                                          to the form. keys of array correspond to names of elements in form.
1068     *
1069     * @access   public
1070    */
1071    function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
1072
1073        foreach ($buttons as $elementname => $button){
1074            $this->setHelpButton($elementname, $button, $suppresscheck, $function);
1075        }
1076    }
1077    /**
1078     * Add a single button.
1079     *
1080     * @param string $elementname name of the element to add the item to
1081     * @param array $button - arguments to pass to function $function
1082     * @param boolean $suppresscheck - whether to throw an error if the element
1083     *                                  doesn't exist.
1084     * @param string $function - function to generate html from the arguments in $button
1085     */
1086    function setHelpButton($elementname, $button, $suppresscheck=false, $function='helpbutton'){
1087        if (array_key_exists($elementname, $this->_elementIndex)){
1088            //_elements has a numeric index, this code accesses the elements by name
1089            $element=&$this->_elements[$this->_elementIndex[$elementname]];
1090            if (method_exists($element, 'setHelpButton')){
1091                $element->setHelpButton($button, $function);
1092            }else{
1093                $a=new object();
1094                $a->name=$element->getName();
1095                $a->classname=get_class($element);
1096                print_error('nomethodforaddinghelpbutton', 'form', '', $a);
1097            }
1098        }elseif (!$suppresscheck){
1099            print_error('nonexistentformelements', 'form', '', $elementname);
1100        }
1101    }
1102
1103    /**
1104     * Set constant value not overriden by _POST or _GET
1105     * note: this does not work for complex names with [] :-(
1106     * @param string $elname name of element
1107     * @param mixed $value
1108     * @return void
1109     */
1110    function setConstant($elname, $value) {
1111        $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
1112        $element =& $this->getElement($elname);
1113        $element->onQuickFormEvent('updateValue', null, $this);
1114    }
1115
1116    function exportValues($elementList= null, $addslashes=true){
1117        $unfiltered = array();
1118        if (null === $elementList) {
1119            // iterate over all elements, calling their exportValue() methods
1120            $emptyarray = array();
1121            foreach (array_keys($this->_elements) as $key) {
1122                if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
1123                    $value = $this->_elements[$key]->exportValue($emptyarray, true);
1124                } else {
1125                    $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
1126                }
1127
1128                if (is_array($value)) {
1129                    // This shit throws a bogus warning in PHP 4.3.x
1130                    $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
1131                }
1132            }
1133        } else {
1134            if (!is_array($elementList)) {
1135                $elementList = array_map('trim', explode(',', $elementList));
1136            }
1137            foreach ($elementList as $elementName) {
1138                $value = $this->exportValue($elementName);
1139                if (PEAR::isError($value)) {
1140                    return $value;
1141                }
1142                $unfiltered[$elementName] = $value;
1143            }
1144        }
1145
1146        if ($addslashes){
1147            return $this->_recursiveFilter('addslashes', $unfiltered);
1148        } else {
1149            return $unfiltered;
1150        }
1151    }
1152    /**
1153     * Adds a validation rule for the given field
1154     *
1155     * If the element is in fact a group, it will be considered as a whole.
1156     * To validate grouped elements as separated entities,
1157     * use addGroupRule instead of addRule.
1158     *
1159     * @param    string     $element       Form element name
1160     * @param    string     $message       Message to display for invalid data
1161     * @param    string     $type          Rule type, use getRegisteredRules() to get types
1162     * @param    string     $format        (optional)Required for extra rule data
1163     * @param    string     $validation    (optional)Where to perform validation: "server", "client"
1164     * @param    boolean    $reset         Client-side validation: reset the form element to its original value if there is an error?
1165     * @param    boolean    $force         Force the rule to be applied, even if the target form element does not exist
1166     * @since    1.0
1167     * @access   public
1168     * @throws   HTML_QuickForm_Error
1169     */
1170    function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
1171    {
1172        parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
1173        if ($validation == 'client') {
1174            $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1175        }
1176
1177    } // end func addRule
1178    /**
1179     * Adds a validation rule for the given group of elements
1180     *
1181     * Only groups with a name can be assigned a validation rule
1182     * Use addGroupRule when you need to validate elements inside the group.
1183     * Use addRule if you need to validate the group as a whole. In this case,
1184     * the same rule will be applied to all elements in the group.
1185     * Use addRule if you need to validate the group against a function.
1186     *
1187     * @param    string     $group         Form group name
1188     * @param    mixed      $arg1          Array for multiple elements or error message string for one element
1189     * @param    string     $type          (optional)Rule type use getRegisteredRules() to get types
1190     * @param    string     $format        (optional)Required for extra rule data
1191     * @param    int        $howmany       (optional)How many valid elements should be in the group
1192     * @param    string     $validation    (optional)Where to perform validation: "server", "client"
1193     * @param    bool       $reset         Client-side: whether to reset the element's value to its original state if validation failed.
1194     * @since    2.5
1195     * @access   public
1196     * @throws   HTML_QuickForm_Error
1197     */
1198    function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
1199    {
1200        parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
1201        if (is_array($arg1)) {
1202             foreach ($arg1 as $rules) {
1203                foreach ($rules as $rule) {
1204                    $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
1205
1206                    if ('client' == $validation) {
1207                        $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1208                    }
1209                }
1210            }
1211        } elseif (is_string($arg1)) {
1212
1213            if ($validation == 'client') {
1214                $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
1215            }
1216        }
1217    } // end func addGroupRule
1218
1219    // }}}
1220    /**
1221     * Returns the client side validation script
1222     *
1223     * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from  HTML_QuickForm
1224     * and slightly modified to run rules per-element
1225     * Needed to override this because of an error with client side validation of grouped elements.
1226     *
1227     * @access    public
1228     * @return    string    Javascript to perform validation, empty string…

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