PageRenderTime 45ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/formslib.php

https://bitbucket.org/ceu/moodle_demo
PHP | 1957 lines | 1391 code | 116 blank | 450 comment | 151 complexity | 70ebe4d1e7b4ae5d1232c9b1baffd1d5 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, LGPL-2.1

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

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

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