PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 0ms 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
Possible License(s): GPL-2.0, LGPL-2.1, GPL-3.0, BSD-3-Clause, LGPL-2.0

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

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