PageRenderTime 85ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/trunk/MoodleWebRole/lib/formslib.php

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

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