PageRenderTime 111ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/formslib.php

https://github.com/lsuits/moodle
PHP | 2960 lines | 2040 code | 194 blank | 726 comment | 272 complexity | fe64ac86d31a7e9ab002384cea06bd8f MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, Apache-2.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
  18. *
  19. * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
  20. * and you want to name your class something like {modulename}_{purpose}_form. Your class will
  21. * extend moodleform overriding abstract classes definition and optionally defintion_after_data
  22. * and validation.
  23. *
  24. * See examples of use of this library in course/edit.php and course/edit_form.php
  25. *
  26. * A few notes :
  27. * form definition is used for both printing of form and processing and should be the same
  28. * for both or you may lose some submitted data which won't be let through.
  29. * you should be using setType for every form element except select, radio or checkbox
  30. * elements, these elements clean themselves.
  31. *
  32. * @package core_form
  33. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  34. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35. */
  36. defined('MOODLE_INTERNAL') || die();
  37. /** setup.php includes our hacked pear libs first */
  38. require_once 'HTML/QuickForm.php';
  39. require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
  40. require_once 'HTML/QuickForm/Renderer/Tableless.php';
  41. require_once 'HTML/QuickForm/Rule.php';
  42. require_once $CFG->libdir.'/filelib.php';
  43. /**
  44. * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
  45. */
  46. define('EDITOR_UNLIMITED_FILES', -1);
  47. /**
  48. * Callback called when PEAR throws an error
  49. *
  50. * @param PEAR_Error $error
  51. */
  52. function pear_handle_error($error){
  53. echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
  54. echo '<br /> <strong>Backtrace </strong>:';
  55. print_object($error->backtrace);
  56. }
  57. if ($CFG->debugdeveloper) {
  58. //TODO: this is a wrong place to init PEAR!
  59. $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
  60. $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
  61. }
  62. /**
  63. * Initalize javascript for date type form element
  64. *
  65. * @staticvar bool $done make sure it gets initalize once.
  66. * @global moodle_page $PAGE
  67. */
  68. function form_init_date_js() {
  69. global $PAGE;
  70. static $done = false;
  71. if (!$done) {
  72. $module = 'moodle-form-dateselector';
  73. $function = 'M.form.dateselector.init_date_selectors';
  74. $config = array(array(
  75. 'firstdayofweek' => get_string('firstdayofweek', 'langconfig'),
  76. 'mon' => date_format_string(strtotime("Monday"), '%a', 99),
  77. 'tue' => date_format_string(strtotime("Tuesday"), '%a', 99),
  78. 'wed' => date_format_string(strtotime("Wednesday"), '%a', 99),
  79. 'thu' => date_format_string(strtotime("Thursday"), '%a', 99),
  80. 'fri' => date_format_string(strtotime("Friday"), '%a', 99),
  81. 'sat' => date_format_string(strtotime("Saturday"), '%a', 99),
  82. 'sun' => date_format_string(strtotime("Sunday"), '%a', 99),
  83. 'january' => date_format_string(strtotime("January 1"), '%B', 99),
  84. 'february' => date_format_string(strtotime("February 1"), '%B', 99),
  85. 'march' => date_format_string(strtotime("March 1"), '%B', 99),
  86. 'april' => date_format_string(strtotime("April 1"), '%B', 99),
  87. 'may' => date_format_string(strtotime("May 1"), '%B', 99),
  88. 'june' => date_format_string(strtotime("June 1"), '%B', 99),
  89. 'july' => date_format_string(strtotime("July 1"), '%B', 99),
  90. 'august' => date_format_string(strtotime("August 1"), '%B', 99),
  91. 'september' => date_format_string(strtotime("September 1"), '%B', 99),
  92. 'october' => date_format_string(strtotime("October 1"), '%B', 99),
  93. 'november' => date_format_string(strtotime("November 1"), '%B', 99),
  94. 'december' => date_format_string(strtotime("December 1"), '%B', 99)
  95. ));
  96. $PAGE->requires->yui_module($module, $function, $config);
  97. $done = true;
  98. }
  99. }
  100. /**
  101. * Wrapper that separates quickforms syntax from moodle code
  102. *
  103. * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
  104. * use this class you should write a class definition which extends this class or a more specific
  105. * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
  106. *
  107. * You will write your own definition() method which performs the form set up.
  108. *
  109. * @package core_form
  110. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  111. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  112. * @todo MDL-19380 rethink the file scanning
  113. */
  114. abstract class moodleform {
  115. /** @var string name of the form */
  116. protected $_formname; // form name
  117. /** @var MoodleQuickForm quickform object definition */
  118. protected $_form;
  119. /** @var array globals workaround */
  120. protected $_customdata;
  121. /** @var object definition_after_data executed flag */
  122. protected $_definition_finalized = false;
  123. /**
  124. * The constructor function calls the abstract function definition() and it will then
  125. * process and clean and attempt to validate incoming data.
  126. *
  127. * It will call your custom validate method to validate data and will also check any rules
  128. * you have specified in definition using addRule
  129. *
  130. * The name of the form (id attribute of the form) is automatically generated depending on
  131. * the name you gave the class extending moodleform. You should call your class something
  132. * like
  133. *
  134. * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
  135. * current url. If a moodle_url object then outputs params as hidden variables.
  136. * @param mixed $customdata if your form defintion method needs access to data such as $course
  137. * $cm, etc. to construct the form definition then pass it in this array. You can
  138. * use globals for somethings.
  139. * @param string $method if you set this to anything other than 'post' then _GET and _POST will
  140. * be merged and used as incoming data to the form.
  141. * @param string $target target frame for form submission. You will rarely use this. Don't use
  142. * it if you don't need to as the target attribute is deprecated in xhtml strict.
  143. * @param mixed $attributes you can pass a string of html attributes here or an array.
  144. * @param bool $editable
  145. */
  146. function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
  147. global $CFG, $FULLME;
  148. // no standard mform in moodle should allow autocomplete with the exception of user signup
  149. if (empty($attributes)) {
  150. $attributes = array('autocomplete'=>'off');
  151. } else if (is_array($attributes)) {
  152. $attributes['autocomplete'] = 'off';
  153. } else {
  154. if (strpos($attributes, 'autocomplete') === false) {
  155. $attributes .= ' autocomplete="off" ';
  156. }
  157. }
  158. if (empty($action)){
  159. // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
  160. $action = strip_querystring($FULLME);
  161. if (!empty($CFG->sslproxy)) {
  162. // return only https links when using SSL proxy
  163. $action = preg_replace('/^http:/', 'https:', $action, 1);
  164. }
  165. //TODO: use following instead of FULLME - see MDL-33015
  166. //$action = strip_querystring(qualified_me());
  167. }
  168. // Assign custom data first, so that get_form_identifier can use it.
  169. $this->_customdata = $customdata;
  170. $this->_formname = $this->get_form_identifier();
  171. $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
  172. if (!$editable){
  173. $this->_form->hardFreeze();
  174. }
  175. $this->definition();
  176. $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
  177. $this->_form->setType('sesskey', PARAM_RAW);
  178. $this->_form->setDefault('sesskey', sesskey());
  179. $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
  180. $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
  181. $this->_form->setDefault('_qf__'.$this->_formname, 1);
  182. $this->_form->_setDefaultRuleMessages();
  183. // we have to know all input types before processing submission ;-)
  184. $this->_process_submission($method);
  185. }
  186. /**
  187. * It should returns unique identifier for the form.
  188. * Currently it will return class name, but in case two same forms have to be
  189. * rendered on same page then override function to get unique form identifier.
  190. * e.g This is used on multiple self enrollments page.
  191. *
  192. * @return string form identifier.
  193. */
  194. protected function get_form_identifier() {
  195. return get_class($this);
  196. }
  197. /**
  198. * To autofocus on first form element or first element with error.
  199. *
  200. * @param string $name if this is set then the focus is forced to a field with this name
  201. * @return string javascript to select form element with first error or
  202. * first element if no errors. Use this as a parameter
  203. * when calling print_header
  204. */
  205. function focus($name=NULL) {
  206. $form =& $this->_form;
  207. $elkeys = array_keys($form->_elementIndex);
  208. $error = false;
  209. if (isset($form->_errors) && 0 != count($form->_errors)){
  210. $errorkeys = array_keys($form->_errors);
  211. $elkeys = array_intersect($elkeys, $errorkeys);
  212. $error = true;
  213. }
  214. if ($error or empty($name)) {
  215. $names = array();
  216. while (empty($names) and !empty($elkeys)) {
  217. $el = array_shift($elkeys);
  218. $names = $form->_getElNamesRecursive($el);
  219. }
  220. if (!empty($names)) {
  221. $name = array_shift($names);
  222. }
  223. }
  224. $focus = '';
  225. if (!empty($name)) {
  226. $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
  227. }
  228. return $focus;
  229. }
  230. /**
  231. * Internal method. Alters submitted data to be suitable for quickforms processing.
  232. * Must be called when the form is fully set up.
  233. *
  234. * @param string $method name of the method which alters submitted data
  235. */
  236. function _process_submission($method) {
  237. $submission = array();
  238. if ($method == 'post') {
  239. if (!empty($_POST)) {
  240. $submission = $_POST;
  241. }
  242. } else {
  243. $submission = $_GET;
  244. merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
  245. }
  246. // following trick is needed to enable proper sesskey checks when using GET forms
  247. // the _qf__.$this->_formname serves as a marker that form was actually submitted
  248. if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
  249. if (!confirm_sesskey()) {
  250. print_error('invalidsesskey');
  251. }
  252. $files = $_FILES;
  253. } else {
  254. $submission = array();
  255. $files = array();
  256. }
  257. $this->detectMissingSetType();
  258. $this->_form->updateSubmission($submission, $files);
  259. }
  260. /**
  261. * Internal method - should not be used anywhere.
  262. * @deprecated since 2.6
  263. * @return array $_POST.
  264. */
  265. protected function _get_post_params() {
  266. return $_POST;
  267. }
  268. /**
  269. * Internal method. Validates all old-style deprecated uploaded files.
  270. * The new way is to upload files via repository api.
  271. *
  272. * @param array $files list of files to be validated
  273. * @return bool|array Success or an array of errors
  274. */
  275. function _validate_files(&$files) {
  276. global $CFG, $COURSE;
  277. $files = array();
  278. if (empty($_FILES)) {
  279. // we do not need to do any checks because no files were submitted
  280. // note: server side rules do not work for files - use custom verification in validate() instead
  281. return true;
  282. }
  283. $errors = array();
  284. $filenames = array();
  285. // now check that we really want each file
  286. foreach ($_FILES as $elname=>$file) {
  287. $required = $this->_form->isElementRequired($elname);
  288. if ($file['error'] == 4 and $file['size'] == 0) {
  289. if ($required) {
  290. $errors[$elname] = get_string('required');
  291. }
  292. unset($_FILES[$elname]);
  293. continue;
  294. }
  295. if (!empty($file['error'])) {
  296. $errors[$elname] = file_get_upload_error($file['error']);
  297. unset($_FILES[$elname]);
  298. continue;
  299. }
  300. if (!is_uploaded_file($file['tmp_name'])) {
  301. // TODO: improve error message
  302. $errors[$elname] = get_string('error');
  303. unset($_FILES[$elname]);
  304. continue;
  305. }
  306. if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
  307. // hmm, this file was not requested
  308. unset($_FILES[$elname]);
  309. continue;
  310. }
  311. // NOTE: the viruses are scanned in file picker, no need to deal with them here.
  312. $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
  313. if ($filename === '') {
  314. // TODO: improve error message - wrong chars
  315. $errors[$elname] = get_string('error');
  316. unset($_FILES[$elname]);
  317. continue;
  318. }
  319. if (in_array($filename, $filenames)) {
  320. // TODO: improve error message - duplicate name
  321. $errors[$elname] = get_string('error');
  322. unset($_FILES[$elname]);
  323. continue;
  324. }
  325. $filenames[] = $filename;
  326. $_FILES[$elname]['name'] = $filename;
  327. $files[$elname] = $_FILES[$elname]['tmp_name'];
  328. }
  329. // return errors if found
  330. if (count($errors) == 0){
  331. return true;
  332. } else {
  333. $files = array();
  334. return $errors;
  335. }
  336. }
  337. /**
  338. * Internal method. Validates filepicker and filemanager files if they are
  339. * set as required fields. Also, sets the error message if encountered one.
  340. *
  341. * @return bool|array with errors
  342. */
  343. protected function validate_draft_files() {
  344. global $USER;
  345. $mform =& $this->_form;
  346. $errors = array();
  347. //Go through all the required elements and make sure you hit filepicker or
  348. //filemanager element.
  349. foreach ($mform->_rules as $elementname => $rules) {
  350. $elementtype = $mform->getElementType($elementname);
  351. //If element is of type filepicker then do validation
  352. if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
  353. //Check if rule defined is required rule
  354. foreach ($rules as $rule) {
  355. if ($rule['type'] == 'required') {
  356. $draftid = (int)$mform->getSubmitValue($elementname);
  357. $fs = get_file_storage();
  358. $context = context_user::instance($USER->id);
  359. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  360. $errors[$elementname] = $rule['message'];
  361. }
  362. }
  363. }
  364. }
  365. }
  366. // Check all the filemanager elements to make sure they do not have too many
  367. // files in them.
  368. foreach ($mform->_elements as $element) {
  369. if ($element->_type == 'filemanager') {
  370. $maxfiles = $element->getMaxfiles();
  371. if ($maxfiles > 0) {
  372. $draftid = (int)$element->getValue();
  373. $fs = get_file_storage();
  374. $context = context_user::instance($USER->id);
  375. $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
  376. if (count($files) > $maxfiles) {
  377. $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
  378. }
  379. }
  380. }
  381. }
  382. if (empty($errors)) {
  383. return true;
  384. } else {
  385. return $errors;
  386. }
  387. }
  388. /**
  389. * Load in existing data as form defaults. Usually new entry defaults are stored directly in
  390. * form definition (new entry form); this function is used to load in data where values
  391. * already exist and data is being edited (edit entry form).
  392. *
  393. * note: $slashed param removed
  394. *
  395. * @param stdClass|array $default_values object or array of default values
  396. */
  397. function set_data($default_values) {
  398. if (is_object($default_values)) {
  399. $default_values = (array)$default_values;
  400. }
  401. $this->_form->setDefaults($default_values);
  402. }
  403. /**
  404. * Check that form was submitted. Does not check validity of submitted data.
  405. *
  406. * @return bool true if form properly submitted
  407. */
  408. function is_submitted() {
  409. return $this->_form->isSubmitted();
  410. }
  411. /**
  412. * Checks if button pressed is not for submitting the form
  413. *
  414. * @staticvar bool $nosubmit keeps track of no submit button
  415. * @return bool
  416. */
  417. function no_submit_button_pressed(){
  418. static $nosubmit = null; // one check is enough
  419. if (!is_null($nosubmit)){
  420. return $nosubmit;
  421. }
  422. $mform =& $this->_form;
  423. $nosubmit = false;
  424. if (!$this->is_submitted()){
  425. return false;
  426. }
  427. foreach ($mform->_noSubmitButtons as $nosubmitbutton){
  428. if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
  429. $nosubmit = true;
  430. break;
  431. }
  432. }
  433. return $nosubmit;
  434. }
  435. /**
  436. * Check that form data is valid.
  437. * You should almost always use this, rather than {@link validate_defined_fields}
  438. *
  439. * @return bool true if form data valid
  440. */
  441. function is_validated() {
  442. //finalize the form definition before any processing
  443. if (!$this->_definition_finalized) {
  444. $this->_definition_finalized = true;
  445. $this->definition_after_data();
  446. }
  447. return $this->validate_defined_fields();
  448. }
  449. /**
  450. * Validate the form.
  451. *
  452. * You almost always want to call {@link is_validated} instead of this
  453. * because it calls {@link definition_after_data} first, before validating the form,
  454. * which is what you want in 99% of cases.
  455. *
  456. * This is provided as a separate function for those special cases where
  457. * you want the form validated before definition_after_data is called
  458. * for example, to selectively add new elements depending on a no_submit_button press,
  459. * but only when the form is valid when the no_submit_button is pressed,
  460. *
  461. * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
  462. * is NOT to validate the form when a no submit button has been pressed.
  463. * pass true here to override this behaviour
  464. *
  465. * @return bool true if form data valid
  466. */
  467. function validate_defined_fields($validateonnosubmit=false) {
  468. static $validated = null; // one validation is enough
  469. $mform =& $this->_form;
  470. if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
  471. return false;
  472. } elseif ($validated === null) {
  473. $internal_val = $mform->validate();
  474. $files = array();
  475. $file_val = $this->_validate_files($files);
  476. //check draft files for validation and flag them if required files
  477. //are not in draft area.
  478. $draftfilevalue = $this->validate_draft_files();
  479. if ($file_val !== true && $draftfilevalue !== true) {
  480. $file_val = array_merge($file_val, $draftfilevalue);
  481. } else if ($draftfilevalue !== true) {
  482. $file_val = $draftfilevalue;
  483. } //default is file_val, so no need to assign.
  484. if ($file_val !== true) {
  485. if (!empty($file_val)) {
  486. foreach ($file_val as $element=>$msg) {
  487. $mform->setElementError($element, $msg);
  488. }
  489. }
  490. $file_val = false;
  491. }
  492. $data = $mform->exportValues();
  493. $moodle_val = $this->validation($data, $files);
  494. if ((is_array($moodle_val) && count($moodle_val)!==0)) {
  495. // non-empty array means errors
  496. foreach ($moodle_val as $element=>$msg) {
  497. $mform->setElementError($element, $msg);
  498. }
  499. $moodle_val = false;
  500. } else {
  501. // anything else means validation ok
  502. $moodle_val = true;
  503. }
  504. $validated = ($internal_val and $moodle_val and $file_val);
  505. }
  506. return $validated;
  507. }
  508. /**
  509. * Return true if a cancel button has been pressed resulting in the form being submitted.
  510. *
  511. * @return bool true if a cancel button has been pressed
  512. */
  513. function is_cancelled(){
  514. $mform =& $this->_form;
  515. if ($mform->isSubmitted()){
  516. foreach ($mform->_cancelButtons as $cancelbutton){
  517. if (optional_param($cancelbutton, 0, PARAM_RAW)){
  518. return true;
  519. }
  520. }
  521. }
  522. return false;
  523. }
  524. /**
  525. * Return submitted data if properly submitted or returns NULL if validation fails or
  526. * if there is no submitted data.
  527. *
  528. * note: $slashed param removed
  529. *
  530. * @return object submitted data; NULL if not valid or not submitted or cancelled
  531. */
  532. function get_data() {
  533. $mform =& $this->_form;
  534. if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
  535. $data = $mform->exportValues();
  536. unset($data['sesskey']); // we do not need to return sesskey
  537. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  538. if (empty($data)) {
  539. return NULL;
  540. } else {
  541. return (object)$data;
  542. }
  543. } else {
  544. return NULL;
  545. }
  546. }
  547. /**
  548. * Return submitted data without validation or NULL if there is no submitted data.
  549. * note: $slashed param removed
  550. *
  551. * @return object submitted data; NULL if not submitted
  552. */
  553. function get_submitted_data() {
  554. $mform =& $this->_form;
  555. if ($this->is_submitted()) {
  556. $data = $mform->exportValues();
  557. unset($data['sesskey']); // we do not need to return sesskey
  558. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  559. if (empty($data)) {
  560. return NULL;
  561. } else {
  562. return (object)$data;
  563. }
  564. } else {
  565. return NULL;
  566. }
  567. }
  568. /**
  569. * Save verified uploaded files into directory. Upload process can be customised from definition()
  570. *
  571. * @deprecated since Moodle 2.0
  572. * @todo MDL-31294 remove this api
  573. * @see moodleform::save_stored_file()
  574. * @see moodleform::save_file()
  575. * @param string $destination path where file should be stored
  576. * @return bool Always false
  577. */
  578. function save_files($destination) {
  579. debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
  580. return false;
  581. }
  582. /**
  583. * Returns name of uploaded file.
  584. *
  585. * @param string $elname first element if null
  586. * @return string|bool false in case of failure, string if ok
  587. */
  588. function get_new_filename($elname=null) {
  589. global $USER;
  590. if (!$this->is_submitted() or !$this->is_validated()) {
  591. return false;
  592. }
  593. if (is_null($elname)) {
  594. if (empty($_FILES)) {
  595. return false;
  596. }
  597. reset($_FILES);
  598. $elname = key($_FILES);
  599. }
  600. if (empty($elname)) {
  601. return false;
  602. }
  603. $element = $this->_form->getElement($elname);
  604. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  605. $values = $this->_form->exportValues($elname);
  606. if (empty($values[$elname])) {
  607. return false;
  608. }
  609. $draftid = $values[$elname];
  610. $fs = get_file_storage();
  611. $context = context_user::instance($USER->id);
  612. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  613. return false;
  614. }
  615. $file = reset($files);
  616. return $file->get_filename();
  617. }
  618. if (!isset($_FILES[$elname])) {
  619. return false;
  620. }
  621. return $_FILES[$elname]['name'];
  622. }
  623. /**
  624. * Save file to standard filesystem
  625. *
  626. * @param string $elname name of element
  627. * @param string $pathname full path name of file
  628. * @param bool $override override file if exists
  629. * @return bool success
  630. */
  631. function save_file($elname, $pathname, $override=false) {
  632. global $USER;
  633. if (!$this->is_submitted() or !$this->is_validated()) {
  634. return false;
  635. }
  636. if (file_exists($pathname)) {
  637. if ($override) {
  638. if (!@unlink($pathname)) {
  639. return false;
  640. }
  641. } else {
  642. return false;
  643. }
  644. }
  645. $element = $this->_form->getElement($elname);
  646. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  647. $values = $this->_form->exportValues($elname);
  648. if (empty($values[$elname])) {
  649. return false;
  650. }
  651. $draftid = $values[$elname];
  652. $fs = get_file_storage();
  653. $context = context_user::instance($USER->id);
  654. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  655. return false;
  656. }
  657. $file = reset($files);
  658. return $file->copy_content_to($pathname);
  659. } else if (isset($_FILES[$elname])) {
  660. return copy($_FILES[$elname]['tmp_name'], $pathname);
  661. }
  662. return false;
  663. }
  664. /**
  665. * Returns a temporary file, do not forget to delete after not needed any more.
  666. *
  667. * @param string $elname name of the elmenet
  668. * @return string|bool either string or false
  669. */
  670. function save_temp_file($elname) {
  671. if (!$this->get_new_filename($elname)) {
  672. return false;
  673. }
  674. if (!$dir = make_temp_directory('forms')) {
  675. return false;
  676. }
  677. if (!$tempfile = tempnam($dir, 'tempup_')) {
  678. return false;
  679. }
  680. if (!$this->save_file($elname, $tempfile, true)) {
  681. // something went wrong
  682. @unlink($tempfile);
  683. return false;
  684. }
  685. return $tempfile;
  686. }
  687. /**
  688. * Get draft files of a form element
  689. * This is a protected method which will be used only inside moodleforms
  690. *
  691. * @param string $elname name of element
  692. * @return array|bool|null
  693. */
  694. protected function get_draft_files($elname) {
  695. global $USER;
  696. if (!$this->is_submitted()) {
  697. return false;
  698. }
  699. $element = $this->_form->getElement($elname);
  700. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  701. $values = $this->_form->exportValues($elname);
  702. if (empty($values[$elname])) {
  703. return false;
  704. }
  705. $draftid = $values[$elname];
  706. $fs = get_file_storage();
  707. $context = context_user::instance($USER->id);
  708. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  709. return null;
  710. }
  711. return $files;
  712. }
  713. return null;
  714. }
  715. /**
  716. * Save file to local filesystem pool
  717. *
  718. * @param string $elname name of element
  719. * @param int $newcontextid id of context
  720. * @param string $newcomponent name of the component
  721. * @param string $newfilearea name of file area
  722. * @param int $newitemid item id
  723. * @param string $newfilepath path of file where it get stored
  724. * @param string $newfilename use specified filename, if not specified name of uploaded file used
  725. * @param bool $overwrite overwrite file if exists
  726. * @param int $newuserid new userid if required
  727. * @return mixed stored_file object or false if error; may throw exception if duplicate found
  728. */
  729. function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
  730. $newfilename=null, $overwrite=false, $newuserid=null) {
  731. global $USER;
  732. if (!$this->is_submitted() or !$this->is_validated()) {
  733. return false;
  734. }
  735. if (empty($newuserid)) {
  736. $newuserid = $USER->id;
  737. }
  738. $element = $this->_form->getElement($elname);
  739. $fs = get_file_storage();
  740. if ($element instanceof MoodleQuickForm_filepicker) {
  741. $values = $this->_form->exportValues($elname);
  742. if (empty($values[$elname])) {
  743. return false;
  744. }
  745. $draftid = $values[$elname];
  746. $context = context_user::instance($USER->id);
  747. if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
  748. return false;
  749. }
  750. $file = reset($files);
  751. if (is_null($newfilename)) {
  752. $newfilename = $file->get_filename();
  753. }
  754. if ($overwrite) {
  755. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  756. if (!$oldfile->delete()) {
  757. return false;
  758. }
  759. }
  760. }
  761. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  762. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  763. return $fs->create_file_from_storedfile($file_record, $file);
  764. } else if (isset($_FILES[$elname])) {
  765. $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
  766. if ($overwrite) {
  767. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  768. if (!$oldfile->delete()) {
  769. return false;
  770. }
  771. }
  772. }
  773. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  774. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  775. return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
  776. }
  777. return false;
  778. }
  779. /**
  780. * Get content of uploaded file.
  781. *
  782. * @param string $elname name of file upload element
  783. * @return string|bool false in case of failure, string if ok
  784. */
  785. function get_file_content($elname) {
  786. global $USER;
  787. if (!$this->is_submitted() or !$this->is_validated()) {
  788. return false;
  789. }
  790. $element = $this->_form->getElement($elname);
  791. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  792. $values = $this->_form->exportValues($elname);
  793. if (empty($values[$elname])) {
  794. return false;
  795. }
  796. $draftid = $values[$elname];
  797. $fs = get_file_storage();
  798. $context = context_user::instance($USER->id);
  799. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  800. return false;
  801. }
  802. $file = reset($files);
  803. return $file->get_content();
  804. } else if (isset($_FILES[$elname])) {
  805. return file_get_contents($_FILES[$elname]['tmp_name']);
  806. }
  807. return false;
  808. }
  809. /**
  810. * Print html form.
  811. */
  812. function display() {
  813. //finalize the form definition if not yet done
  814. if (!$this->_definition_finalized) {
  815. $this->_definition_finalized = true;
  816. $this->definition_after_data();
  817. }
  818. $this->_form->display();
  819. }
  820. /**
  821. * Renders the html form (same as display, but returns the result).
  822. *
  823. * Note that you can only output this rendered result once per page, as
  824. * it contains IDs which must be unique.
  825. *
  826. * @return string HTML code for the form
  827. */
  828. public function render() {
  829. ob_start();
  830. $this->display();
  831. $out = ob_get_contents();
  832. ob_end_clean();
  833. return $out;
  834. }
  835. /**
  836. * Form definition. Abstract method - always override!
  837. */
  838. protected abstract function definition();
  839. /**
  840. * Dummy stub method - override if you need to setup the form depending on current
  841. * values. This method is called after definition(), data submission and set_data().
  842. * All form setup that is dependent on form values should go in here.
  843. */
  844. function definition_after_data(){
  845. }
  846. /**
  847. * Dummy stub method - override if you needed to perform some extra validation.
  848. * If there are errors return array of errors ("fieldname"=>"error message"),
  849. * otherwise true if ok.
  850. *
  851. * Server side rules do not work for uploaded files, implement serverside rules here if needed.
  852. *
  853. * @param array $data array of ("fieldname"=>value) of submitted data
  854. * @param array $files array of uploaded files "element_name"=>tmp_file_path
  855. * @return array of "element_name"=>"error_description" if there are errors,
  856. * or an empty array if everything is OK (true allowed for backwards compatibility too).
  857. */
  858. function validation($data, $files) {
  859. return array();
  860. }
  861. /**
  862. * Helper used by {@link repeat_elements()}.
  863. *
  864. * @param int $i the index of this element.
  865. * @param HTML_QuickForm_element $elementclone
  866. * @param array $namecloned array of names
  867. */
  868. function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
  869. $name = $elementclone->getName();
  870. $namecloned[] = $name;
  871. if (!empty($name)) {
  872. $elementclone->setName($name."[$i]");
  873. }
  874. if (is_a($elementclone, 'HTML_QuickForm_header')) {
  875. $value = $elementclone->_text;
  876. $elementclone->setValue(str_replace('{no}', ($i+1), $value));
  877. } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
  878. $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
  879. } else {
  880. $value=$elementclone->getLabel();
  881. $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
  882. }
  883. }
  884. /**
  885. * Method to add a repeating group of elements to a form.
  886. *
  887. * @param array $elementobjs Array of elements or groups of elements that are to be repeated
  888. * @param int $repeats no of times to repeat elements initially
  889. * @param array $options a nested array. The first array key is the element name.
  890. * the second array key is the type of option to set, and depend on that option,
  891. * the value takes different forms.
  892. * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
  893. * 'type' - PARAM_* type.
  894. * 'helpbutton' - array containing the helpbutton params.
  895. * 'disabledif' - array containing the disabledIf() arguments after the element name.
  896. * 'rule' - array containing the addRule arguments after the element name.
  897. * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
  898. * 'advanced' - whether this element is hidden by 'Show more ...'.
  899. * @param string $repeathiddenname name for hidden element storing no of repeats in this form
  900. * @param string $addfieldsname name for button to add more fields
  901. * @param int $addfieldsno how many fields to add at a time
  902. * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
  903. * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
  904. * @return int no of repeats of element in this page
  905. */
  906. function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
  907. $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
  908. if ($addstring===null){
  909. $addstring = get_string('addfields', 'form', $addfieldsno);
  910. } else {
  911. $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
  912. }
  913. $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
  914. $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
  915. if (!empty($addfields)){
  916. $repeats += $addfieldsno;
  917. }
  918. $mform =& $this->_form;
  919. $mform->registerNoSubmitButton($addfieldsname);
  920. $mform->addElement('hidden', $repeathiddenname, $repeats);
  921. $mform->setType($repeathiddenname, PARAM_INT);
  922. //value not to be overridden by submitted value
  923. $mform->setConstants(array($repeathiddenname=>$repeats));
  924. $namecloned = array();
  925. for ($i = 0; $i < $repeats; $i++) {
  926. foreach ($elementobjs as $elementobj){
  927. $elementclone = fullclone($elementobj);
  928. $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
  929. if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
  930. foreach ($elementclone->getElements() as $el) {
  931. $this->repeat_elements_fix_clone($i, $el, $namecloned);
  932. }
  933. $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
  934. }
  935. $mform->addElement($elementclone);
  936. }
  937. }
  938. for ($i=0; $i<$repeats; $i++) {
  939. foreach ($options as $elementname => $elementoptions){
  940. $pos=strpos($elementname, '[');
  941. if ($pos!==FALSE){
  942. $realelementname = substr($elementname, 0, $pos)."[$i]";
  943. $realelementname .= substr($elementname, $pos);
  944. }else {
  945. $realelementname = $elementname."[$i]";
  946. }
  947. foreach ($elementoptions as $option => $params){
  948. switch ($option){
  949. case 'default' :
  950. $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
  951. break;
  952. case 'helpbutton' :
  953. $params = array_merge(array($realelementname), $params);
  954. call_user_func_array(array(&$mform, 'addHelpButton'), $params);
  955. break;
  956. case 'disabledif' :
  957. foreach ($namecloned as $num => $name){
  958. if ($params[0] == $name){
  959. $params[0] = $params[0]."[$i]";
  960. break;
  961. }
  962. }
  963. $params = array_merge(array($realelementname), $params);
  964. call_user_func_array(array(&$mform, 'disabledIf'), $params);
  965. break;
  966. case 'rule' :
  967. if (is_string($params)){
  968. $params = array(null, $params, null, 'client');
  969. }
  970. $params = array_merge(array($realelementname), $params);
  971. call_user_func_array(array(&$mform, 'addRule'), $params);
  972. break;
  973. case 'type':
  974. $mform->setType($realelementname, $params);
  975. break;
  976. case 'expanded':
  977. $mform->setExpanded($realelementname, $params);
  978. break;
  979. case 'advanced' :
  980. $mform->setAdvanced($realelementname, $params);
  981. break;
  982. }
  983. }
  984. }
  985. }
  986. $mform->addElement('submit', $addfieldsname, $addstring);
  987. if (!$addbuttoninside) {
  988. $mform->closeHeaderBefore($addfieldsname);
  989. }
  990. return $repeats;
  991. }
  992. /**
  993. * Adds a link/button that controls the checked state of a group of checkboxes.
  994. *
  995. * @param int $groupid The id of the group of advcheckboxes this element controls
  996. * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
  997. * @param array $attributes associative array of HTML attributes
  998. * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
  999. */
  1000. function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
  1001. global $CFG, $PAGE;
  1002. // Name of the controller button
  1003. $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
  1004. $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
  1005. $checkboxgroupclass = 'checkboxgroup'.$groupid;
  1006. // Set the default text if none was specified
  1007. if (empty($text)) {
  1008. $text = get_string('selectallornone', 'form');
  1009. }
  1010. $mform = $this->_form;
  1011. $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
  1012. $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
  1013. $newselectvalue = $selectvalue;
  1014. if (is_null($selectvalue)) {
  1015. $newselectvalue = $originalValue;
  1016. } else if (!is_null($contollerbutton)) {
  1017. $newselectvalue = (int) !$selectvalue;
  1018. }
  1019. // set checkbox state depending on orignal/submitted value by controoler button
  1020. if (!is_null($contollerbutton) || is_null($selectvalue)) {
  1021. foreach ($mform->_elements as $element) {
  1022. if (($element instanceof MoodleQuickForm_advcheckbox) &&
  1023. $element->getAttribute('class') == $checkboxgroupclass &&
  1024. !$element->isFrozen()) {
  1025. $mform->setConstants(array($element->getName() => $newselectvalue));
  1026. }
  1027. }
  1028. }
  1029. $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
  1030. $mform->setType($checkboxcontrollerparam, PARAM_INT);
  1031. $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
  1032. $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
  1033. array(
  1034. array('groupid' => $groupid,
  1035. 'checkboxclass' => $checkboxgroupclass,
  1036. 'checkboxcontroller' => $checkboxcontrollerparam,
  1037. 'controllerbutton' => $checkboxcontrollername)
  1038. )
  1039. );
  1040. require_once("$CFG->libdir/form/submit.php");
  1041. $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
  1042. $mform->addElement($submitlink);
  1043. $mform->registerNoSubmitButton($checkboxcontrollername);
  1044. $mform->setDefault($checkboxcontrollername, $text);
  1045. }
  1046. /**
  1047. * Use this method to a cancel and submit button to the end of your form. Pass a param of false
  1048. * if you don't want a cancel button in your form. If you have a cancel button make sure you
  1049. * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
  1050. * get data with get_data().
  1051. *
  1052. * @param bool $cancel whether to show cancel button, default true
  1053. * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
  1054. */
  1055. function add_action_buttons($cancel = true, $submitlabel=null){
  1056. if (is_null($submitlabel)){
  1057. $submitlabel = get_string('savechanges');
  1058. }
  1059. $mform =& $this->_form;
  1060. if ($cancel){
  1061. //when two elements we need a group
  1062. $buttonarray=array();
  1063. $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
  1064. $buttonarray[] = &$mform->createElement('cancel');
  1065. $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
  1066. $mform->closeHeaderBefore('buttonar');
  1067. } else {
  1068. //no group needed
  1069. $mform->addElement('submit', 'submitbutton', $submitlabel);
  1070. $mform->closeHeaderBefore('submitbutton');
  1071. }
  1072. }
  1073. /**
  1074. * Adds an initialisation call for a standard JavaScript enhancement.
  1075. *
  1076. * This function is designed to add an initialisation call for a JavaScript
  1077. * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
  1078. *
  1079. * Current options:
  1080. * - Selectboxes
  1081. * - smartselect: Turns a nbsp indented select box into a custom drop down
  1082. * control that supports multilevel and category selection.
  1083. * $enhancement = 'smartselect';
  1084. * $options = array('selectablecategories' => true|false)
  1085. *
  1086. * @since Moodle 2.0
  1087. * @param string|element $element form element for which Javascript needs to be initalized
  1088. * @param string $enhancement which init function should be called
  1089. * @param array $options options passed to javascript
  1090. * @param array $strings strings for javascript
  1091. */
  1092. function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
  1093. global $PAGE;
  1094. if (is_string($element)) {
  1095. $element = $this->_form->getElement($element);
  1096. }
  1097. if (is_object($element)) {
  1098. $element->_generateId();
  1099. $elementid = $element->getAttribute('id');
  1100. $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
  1101. if (is_array($strings)) {
  1102. foreach ($strings as $string) {
  1103. if (is_array($string)) {
  1104. call_user_method_array('string_for_js', $PAGE->requires, $string);
  1105. } else {
  1106. $PAGE->requires->string_for_js($string, 'moodle');
  1107. }
  1108. }
  1109. }
  1110. }
  1111. }
  1112. /**
  1113. * Returns a JS module definition for the mforms JS
  1114. *
  1115. * @return array
  1116. */
  1117. public static function get_js_module() {
  1118. global $CFG;
  1119. return array(
  1120. 'name' => 'mform',
  1121. 'fullpath' => '/lib/form/form.js',
  1122. 'requires' => array('base', 'node')
  1123. );
  1124. }
  1125. /**
  1126. * Detects elements with missing setType() declerations.
  1127. *
  1128. * Finds elements in the form which should a PARAM_ type set and throws a
  1129. * developer debug warning for any elements without it. This is to reduce the
  1130. * risk of potential security issues by developers mistakenly forgetting to set
  1131. * the type.
  1132. *
  1133. * @return void
  1134. */
  1135. private function detectMissingSetType() {
  1136. global $CFG;
  1137. if (!$CFG->debugdeveloper) {
  1138. // Only for devs.
  1139. return;
  1140. }
  1141. $mform = $this->_form;
  1142. foreach ($mform->_elements as $element) {
  1143. $group = false;
  1144. $elements = array($element);
  1145. if ($element->getType() == 'group') {
  1146. $group = $element;
  1147. $elements = $element->getElements();
  1148. }
  1149. foreach ($elements as $index => $element) {
  1150. switch ($element->getType()) {
  1151. case 'hidden':
  1152. case 'text':
  1153. case 'url':
  1154. if ($group) {
  1155. $name = $group->getElementName($index);
  1156. } else {
  1157. $name = $element->getName();
  1158. }
  1159. $key = $name;
  1160. $found = array_key_exists($key, $mform->_types);
  1161. // For repeated elements we need to look for
  1162. // the "main" type, not for the one present
  1163. // on each repetition. All the stuff in formslib
  1164. // (repeat_elements(), updateSubmission()... seems
  1165. // to work that way.
  1166. while (!$found && strrpos($key, '[') !== false) {
  1167. $pos = strrpos($key, '[');
  1168. $key = substr($key, 0, $pos);
  1169. $found = array_key_exists($key, $mform->_types);
  1170. }
  1171. if (!$found) {
  1172. debugging("Did you remember to call setType() for '$name'? ".
  1173. 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
  1174. }
  1175. break;
  1176. }
  1177. }
  1178. }
  1179. }
  1180. /**
  1181. * Used by tests to simulate submitted form data submission from the user.
  1182. *
  1183. * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
  1184. * get_data.
  1185. *
  1186. * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
  1187. * global arrays after each test.
  1188. *
  1189. * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
  1190. * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
  1191. * @param string $method 'post' or 'get', defaults to 'post'.
  1192. * @param null $formidentifier the default is to use the class name for this class but you may need to provide
  1193. * a different value here for some forms that are used more than once on the
  1194. * same page.
  1195. */
  1196. public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
  1197. $formidentifier = null) {
  1198. $_FILES = $simulatedsubmittedfiles;
  1199. if ($formidentifier === null) {
  1200. $formidentifier = get_called_class();
  1201. }
  1202. $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
  1203. $simulatedsubmitteddata['sesskey'] = sesskey();
  1204. if (strtolower($method) === 'get') {
  1205. $_GET = $simulatedsubmitteddata;
  1206. } else {
  1207. $_POST = $simulatedsubmitteddata;
  1208. }
  1209. }
  1210. }
  1211. /**
  1212. * MoodleQuickForm implementation
  1213. *
  1214. * You never extend this class directly. The class methods of this class are available from
  1215. * the private $this->_form property on moodleform and its children. You generally only
  1216. * call methods on this class from within abstract methods that you override on moodleform such
  1217. * as definition and definition_after_data
  1218. *
  1219. * @package core_form
  1220. * @category form
  1221. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  1222. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1223. */
  1224. class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
  1225. /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
  1226. var $_types = array();
  1227. /** @var array dependent state for the element/'s */
  1228. var $_dependencies = array();
  1229. /** @var array Array of buttons that if pressed do not result in the processing of the form. */
  1230. var $_noSubmitButtons=array();
  1231. /** @var array Array of buttons that if pressed do not result in the processing of the form. */
  1232. var $_cancelButtons=array();
  1233. /** @var array Array whose keys are element names. If the key exists this is a advanced element */
  1234. var $_advancedElements = array();
  1235. /**
  1236. * Array whose keys are element names and values are the desired collapsible state.
  1237. * True for collapsed, False for expanded. If not present, set to default in
  1238. * {@link self::accept()}.
  1239. *
  1240. * @var array
  1241. */
  1242. var $_collapsibleElements = array();
  1243. /**
  1244. * Whether to enable shortforms for this form
  1245. *
  1246. * @var boolean
  1247. */
  1248. var $_disableShortforms = false;
  1249. /** @var bool whether to automatically initialise M.formchangechecker for this form. */
  1250. protected $_use_form_change_checker = true;
  1251. /**
  1252. * The form name is derived from the class name of the wrapper minus the trailing form
  1253. * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
  1254. * @var string
  1255. */
  1256. var $_formName = '';
  1257. /**
  1258. * String with the html for hidden params passed in as part of a moodle_url
  1259. * object for the action. Output in the form.
  1260. * @var string
  1261. */
  1262. var $_pageparams = '';
  1263. /**
  1264. * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
  1265. *
  1266. * @staticvar int $formcounter counts number of forms
  1267. * @param string $formName Form's name.
  1268. * @param string $method Form's method defaults to 'POST'
  1269. * @param string|moodle_url $action Form's action
  1270. * @param string $target (optional)Form's target defaults to none
  1271. * @param mixed $attributes (optional)Extra attributes for <form> tag
  1272. */
  1273. function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
  1274. global $CFG, $OUTPUT;
  1275. static $formcounter = 1;
  1276. HTML_Common::HTML_Common($attributes);
  1277. $target = empty($target) ? array() : array('target' => $target);
  1278. $this->_formName = $formName;
  1279. if (is_a($action, 'moodle_url')){
  1280. $this->_pageparams = html_writer::input_hidden_params($action);
  1281. $action = $action->out_omit_querystring();
  1282. } else {
  1283. $this->_pageparams = '';
  1284. }
  1285. // No 'name' atttribute for form in xhtml strict :
  1286. $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
  1287. if (is_null($this->getAttribute('id'))) {
  1288. $attributes['id'] = 'mform' . $formcounter;
  1289. }
  1290. $formcounter++;
  1291. $this->updateAttributes($attributes);
  1292. // This is custom stuff for Moodle :
  1293. $oldclass= $this->getAttribute('class');
  1294. if (!empty($oldclass)){
  1295. $this->updateAttributes(array('class'=>$oldclass.' mform'));
  1296. }else {
  1297. $this->updateAttributes(array('class'=>'mform'));
  1298. }
  1299. $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
  1300. $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
  1301. $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
  1302. }
  1303. /**
  1304. * Use this method to indicate an element in a form is an advanced field. If items in a form
  1305. * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
  1306. * form so the user can decide whether to display advanced form controls.
  1307. *
  1308. * If you set a header element to advanced then all elements it contains will also be set as advanced.
  1309. *
  1310. * @param string $elementName group or element name (not the element name of something inside a group).
  1311. * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
  1312. */
  1313. function setAdvanced($elementName, $advanced = true) {
  1314. if ($advanced){
  1315. $this->_advancedElements[$elementName]='';
  1316. } elseif (isset($this->_advancedElements[$elementName])) {
  1317. unset($this->_advancedElements[$elementName]);
  1318. }
  1319. }
  1320. /**
  1321. * Use this method to indicate that the fieldset should be shown as expanded.
  1322. * The method is applicable to header elements only.
  1323. *
  1324. * @param string $headername header element name
  1325. * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
  1326. * @param boolean $ignoreuserstate override the state regardless of the state it was on when
  1327. * the form was submitted.
  1328. * @return void
  1329. */
  1330. function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
  1331. if (empty($headername)) {
  1332. return;
  1333. }
  1334. $element = $this->getElement($headername);
  1335. if ($element->getType() != 'header') {
  1336. debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
  1337. return;
  1338. }
  1339. if (!$headerid = $element->getAttribute('id')) {
  1340. $element->_generateId();
  1341. $headerid = $element->getAttribute('id');
  1342. }
  1343. if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
  1344. // See if the form has been submitted already.
  1345. $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
  1346. if (!$ignoreuserstate && $formexpanded != -1) {
  1347. // Override expanded state with the form variable.
  1348. $expanded = $formexpanded;
  1349. }
  1350. // Create the form element for storing expanded state.
  1351. $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
  1352. $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
  1353. $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
  1354. }
  1355. $this->_collapsibleElements[$headername] = !$expanded;
  1356. }
  1357. /**
  1358. * Use this method to add show more/less status element required for passing
  1359. * over the advanced elements visibility status on the form submission.
  1360. *
  1361. * @param string $headerName header element name.
  1362. * @param boolean $showmore default false sets the advanced elements to be hidden.
  1363. */
  1364. function addAdvancedStatusElement($headerid, $showmore=false){
  1365. // Add extra hidden element to store advanced items state for each section.
  1366. if ($this->getElementType('mform_showmore_' . $headerid) === false) {
  1367. // See if we the form has been submitted already.
  1368. $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
  1369. if (!$showmore && $formshowmore != -1) {
  1370. // Override showmore state with the form variable.
  1371. $showmore = $formshowmore;
  1372. }
  1373. // Create the form element for storing advanced items state.
  1374. $this->addElement('hidden', 'mform_showmore_' . $headerid);
  1375. $this->setType('mform_showmore_' . $headerid, PARAM_INT);
  1376. $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
  1377. }
  1378. }
  1379. /**
  1380. * This function has been deprecated. Show advanced has been replaced by
  1381. * "Show more.../Show less..." in the shortforms javascript module.
  1382. *
  1383. * @deprecated since Moodle 2.5
  1384. * @param bool $showadvancedNow if true will show advanced elements.
  1385. */
  1386. function setShowAdvanced($showadvancedNow = null){
  1387. debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
  1388. }
  1389. /**
  1390. * This function has been deprecated. Show advanced has been replaced by
  1391. * "Show more.../Show less..." in the shortforms javascript module.
  1392. *
  1393. * @deprecated since Moodle 2.5
  1394. * @return bool (Always false)
  1395. */
  1396. function getShowAdvanced(){
  1397. debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
  1398. return false;
  1399. }
  1400. /**
  1401. * Use this method to indicate that the form will not be using shortforms.
  1402. *
  1403. * @param boolean $disable default true, controls if the shortforms are disabled.
  1404. */
  1405. function setDisableShortforms ($disable = true) {
  1406. $this->_disableShortforms = $disable;
  1407. }
  1408. /**
  1409. * Call this method if you don't want the formchangechecker JavaScript to be
  1410. * automatically initialised for this form.
  1411. */
  1412. public function disable_form_change_checker() {
  1413. $this->_use_form_change_checker = false;
  1414. }
  1415. /**
  1416. * If you have called {@link disable_form_change_checker()} then you can use
  1417. * this method to re-enable it. It is enabled by default, so normally you don't
  1418. * need to call this.
  1419. */
  1420. public function enable_form_change_checker() {
  1421. $this->_use_form_change_checker = true;
  1422. }
  1423. /**
  1424. * @return bool whether this form should automatically initialise
  1425. * formchangechecker for itself.
  1426. */
  1427. public function is_form_change_checker_enabled() {
  1428. return $this->_use_form_change_checker;
  1429. }
  1430. /**
  1431. * Accepts a renderer
  1432. *
  1433. * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
  1434. */
  1435. function accept(&$renderer) {
  1436. if (method_exists($renderer, 'setAdvancedElements')){
  1437. //Check for visible fieldsets where all elements are advanced
  1438. //and mark these headers as advanced as well.
  1439. //Also mark all elements in a advanced header as advanced.
  1440. $stopFields = $renderer->getStopFieldSetElements();
  1441. $lastHeader = null;
  1442. $lastHeaderAdvanced = false;
  1443. $anyAdvanced = false;
  1444. $anyError = false;
  1445. foreach (array_keys($this->_elements) as $elementIndex){
  1446. $element =& $this->_elements[$elementIndex];
  1447. // if closing header and any contained element was advanced then mark it as advanced
  1448. if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
  1449. if ($anyAdvanced && !is_null($lastHeader)) {
  1450. $lastHeader->_generateId();
  1451. $this->setAdvanced($lastHeader->getName());
  1452. $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
  1453. }
  1454. $lastHeaderAdvanced = false;
  1455. unset($lastHeader);
  1456. $lastHeader = null;
  1457. } elseif ($lastHeaderAdvanced) {
  1458. $this->setAdvanced($element->getName());
  1459. }
  1460. if ($element->getType()=='header'){
  1461. $lastHeader =& $element;
  1462. $anyAdvanced = false;
  1463. $anyError = false;
  1464. $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
  1465. } elseif (isset($this->_advancedElements[$element->getName()])){
  1466. $anyAdvanced = true;
  1467. if (isset($this->_errors[$element->getName()])) {
  1468. $anyError = true;
  1469. }
  1470. }
  1471. }
  1472. // the last header may not be closed yet...
  1473. if ($anyAdvanced && !is_null($lastHeader)){
  1474. $this->setAdvanced($lastHeader->getName());
  1475. $lastHeader->_generateId();
  1476. $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
  1477. }
  1478. $renderer->setAdvancedElements($this->_advancedElements);
  1479. }
  1480. if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
  1481. // Count the number of sections.
  1482. $headerscount = 0;
  1483. foreach (array_keys($this->_elements) as $elementIndex){
  1484. $element =& $this->_elements[$elementIndex];
  1485. if ($element->getType() == 'header') {
  1486. $headerscount++;
  1487. }
  1488. }
  1489. $anyrequiredorerror = false;
  1490. $headercounter = 0;
  1491. $headername = null;
  1492. foreach (array_keys($this->_elements) as $elementIndex){
  1493. $element =& $this->_elements[$elementIndex];
  1494. if ($element->getType() == 'header') {
  1495. $headercounter++;
  1496. $element->_generateId();
  1497. $headername = $element->getName();
  1498. $anyrequiredorerror = false;
  1499. } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
  1500. $anyrequiredorerror = true;
  1501. } else {
  1502. // Do not reset $anyrequiredorerror to false because we do not want any other element
  1503. // in this header (fieldset) to possibly revert the state given.
  1504. }
  1505. if ($element->getType() == 'header') {
  1506. if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
  1507. // By default the first section is always expanded, except if a state has already been set.
  1508. $this->setExpanded($headername, true);
  1509. } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
  1510. // The second section is always expanded if the form only contains 2 sections),
  1511. // except if a state has already been set.
  1512. $this->setExpanded($headername, true);
  1513. }
  1514. } else if ($anyrequiredorerror) {
  1515. // If any error or required field are present within the header, we need to expand it.
  1516. $this->setExpanded($headername, true, true);
  1517. } else if (!isset($this->_collapsibleElements[$headername])) {
  1518. // Define element as collapsed by default.
  1519. $this->setExpanded($headername, false);
  1520. }
  1521. }
  1522. // Pass the array to renderer object.
  1523. $renderer->setCollapsibleElements($this->_collapsibleElements);
  1524. }
  1525. parent::accept($renderer);
  1526. }
  1527. /**
  1528. * Adds one or more element names that indicate the end of a fieldset
  1529. *
  1530. * @param string $elementName name of the element
  1531. */
  1532. function closeHeaderBefore($elementName){
  1533. $renderer =& $this->defaultRenderer();
  1534. $renderer->addStopFieldsetElements($elementName);
  1535. }
  1536. /**
  1537. * Should be used for all elements of a form except for select, radio and checkboxes which
  1538. * clean their own data.
  1539. *
  1540. * @param string $elementname
  1541. * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
  1542. * {@link lib/moodlelib.php} for defined parameter types
  1543. */
  1544. function setType($elementname, $paramtype) {
  1545. $this->_types[$elementname] = $paramtype;
  1546. }
  1547. /**
  1548. * This can be used to set several types at once.
  1549. *
  1550. * @param array $paramtypes types of parameters.
  1551. * @see MoodleQuickForm::setType
  1552. */
  1553. function setTypes($paramtypes) {
  1554. $this->_types = $paramtypes + $this->_types;
  1555. }
  1556. /**
  1557. * Return the type(s) to use to clean an element.
  1558. *
  1559. * In the case where the element has an array as a value, we will try to obtain a
  1560. * type defined for that specific key, and recursively until done.
  1561. *
  1562. * This method does not work reverse, you cannot pass a nested element and hoping to
  1563. * fallback on the clean type of a parent. This method intends to be used with the
  1564. * main element, which will generate child types if needed, not the other way around.
  1565. *
  1566. * Example scenario:
  1567. *
  1568. * You have defined a new repeated element containing a text field called 'foo'.
  1569. * By default there will always be 2 occurence of 'foo' in the form. Even though
  1570. * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
  1571. * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
  1572. * $mform->setType('foo[0]', PARAM_FLOAT).
  1573. *
  1574. * Now if you call this method passing 'foo', along with the submitted values of 'foo':
  1575. * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
  1576. * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
  1577. * get the default clean type returned (param $default).
  1578. *
  1579. * @param string $elementname name of the element.
  1580. * @param mixed $value value that should be cleaned.
  1581. * @param int $default default constant value to be returned (PARAM_...)
  1582. * @return string|array constant value or array of constant values (PARAM_...)
  1583. */
  1584. public function getCleanType($elementname, $value, $default = PARAM_RAW) {
  1585. $type = $default;
  1586. if (array_key_exists($elementname, $this->_types)) {
  1587. $type = $this->_types[$elementname];
  1588. }
  1589. if (is_array($value)) {
  1590. $default = $type;
  1591. $type = array();
  1592. foreach ($value as $subkey => $subvalue) {
  1593. $typekey = "$elementname" . "[$subkey]";
  1594. if (array_key_exists($typekey, $this->_types)) {
  1595. $subtype = $this->_types[$typekey];
  1596. } else {
  1597. $subtype = $default;
  1598. }
  1599. if (is_array($subvalue)) {
  1600. $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
  1601. } else {
  1602. $type[$subkey] = $subtype;
  1603. }
  1604. }
  1605. }
  1606. return $type;
  1607. }
  1608. /**
  1609. * Return the cleaned value using the passed type(s).
  1610. *
  1611. * @param mixed $value value that has to be cleaned.
  1612. * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
  1613. * @return mixed cleaned up value.
  1614. */
  1615. public function getCleanedValue($value, $type) {
  1616. if (is_array($type) && is_array($value)) {
  1617. foreach ($type as $key => $param) {
  1618. $value[$key] = $this->getCleanedValue($value[$key], $param);
  1619. }
  1620. } else if (!is_array($type) && !is_array($value)) {
  1621. $value = clean_param($value, $type);
  1622. } else if (!is_array($type) && is_array($value)) {
  1623. $value = clean_param_array($value, $type, true);
  1624. } else {
  1625. throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
  1626. }
  1627. return $value;
  1628. }
  1629. /**
  1630. * Updates submitted values
  1631. *
  1632. * @param array $submission submitted values
  1633. * @param array $files list of files
  1634. */
  1635. function updateSubmission($submission, $files) {
  1636. $this->_flagSubmitted = false;
  1637. if (empty($submission)) {
  1638. $this->_submitValues = array();
  1639. } else {
  1640. foreach ($submission as $key => $s) {
  1641. $type = $this->getCleanType($key, $s);
  1642. $submission[$key] = $this->getCleanedValue($s, $type);
  1643. }
  1644. $this->_submitValues = $submission;
  1645. $this->_flagSubmitted = true;
  1646. }
  1647. if (empty($files)) {
  1648. $this->_submitFiles = array();
  1649. } else {
  1650. $this->_submitFiles = $files;
  1651. $this->_flagSubmitted = true;
  1652. }
  1653. // need to tell all elements that they need to update their value attribute.
  1654. foreach (array_keys($this->_elements) as $key) {
  1655. $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
  1656. }
  1657. }
  1658. /**
  1659. * Returns HTML for required elements
  1660. *
  1661. * @return string
  1662. */
  1663. function getReqHTML(){
  1664. return $this->_reqHTML;
  1665. }
  1666. /**
  1667. * Returns HTML for advanced elements
  1668. *
  1669. * @return string
  1670. */
  1671. function getAdvancedHTML(){
  1672. return $this->_advancedHTML;
  1673. }
  1674. /**
  1675. * Initializes a default form value. Used to specify the default for a new entry where
  1676. * no data is loaded in using moodleform::set_data()
  1677. *
  1678. * note: $slashed param removed
  1679. *
  1680. * @param string $elementName element name
  1681. * @param mixed $defaultValue values for that element name
  1682. */
  1683. function setDefault($elementName, $defaultValue){
  1684. $this->setDefaults(array($elementName=>$defaultValue));
  1685. }
  1686. /**
  1687. * Add a help button to element, only one button per element is allowed.
  1688. *
  1689. * This is new, simplified and preferable method of setting a help icon on form elements.
  1690. * It uses the new $OUTPUT->help_icon().
  1691. *
  1692. * Typically, you will provide the same identifier and the component as you have used for the
  1693. * label of the element. The string identifier with the _help suffix added is then used
  1694. * as the help string.
  1695. *
  1696. * There has to be two strings defined:
  1697. * 1/ get_string($identifier, $component) - the title of the help page
  1698. * 2/ get_string($identifier.'_help', $component) - the actual help page text
  1699. *
  1700. * @since Moodle 2.0
  1701. * @param string $elementname name of the element to add the item to
  1702. * @param string $identifier help string identifier without _help suffix
  1703. * @param string $component component name to look the help string in
  1704. * @param string $linktext optional text to display next to the icon
  1705. * @param bool $suppresscheck set to true if the element may not exist
  1706. */
  1707. function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
  1708. global $OUTPUT;
  1709. if (array_key_exists($elementname, $this->_elementIndex)) {
  1710. $element = $this->_elements[$this->_elementIndex[$elementname]];
  1711. $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
  1712. } else if (!$suppresscheck) {
  1713. debugging(get_string('nonexistentformelements', 'form', $elementname));
  1714. }
  1715. }
  1716. /**
  1717. * Set constant value not overridden by _POST or _GET
  1718. * note: this does not work for complex names with [] :-(
  1719. *
  1720. * @param string $elname name of element
  1721. * @param mixed $value
  1722. */
  1723. function setConstant($elname, $value) {
  1724. $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
  1725. $element =& $this->getElement($elname);
  1726. $element->onQuickFormEvent('updateValue', null, $this);
  1727. }
  1728. /**
  1729. * export submitted values
  1730. *
  1731. * @param string $elementList list of elements in form
  1732. * @return array
  1733. */
  1734. function exportValues($elementList = null){
  1735. $unfiltered = array();
  1736. if (null === $elementList) {
  1737. // iterate over all elements, calling their exportValue() methods
  1738. foreach (array_keys($this->_elements) as $key) {
  1739. if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
  1740. $varname = $this->_elements[$key]->_attributes['name'];
  1741. $value = '';
  1742. // If we have a default value then export it.
  1743. if (isset($this->_defaultValues[$varname])) {
  1744. $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
  1745. }
  1746. } else {
  1747. $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
  1748. }
  1749. if (is_array($value)) {
  1750. // This shit throws a bogus warning in PHP 4.3.x
  1751. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
  1752. }
  1753. }
  1754. } else {
  1755. if (!is_array($elementList)) {
  1756. $elementList = array_map('trim', explode(',', $elementList));
  1757. }
  1758. foreach ($elementList as $elementName) {
  1759. $value = $this->exportValue($elementName);
  1760. if (@PEAR::isError($value)) {
  1761. return $value;
  1762. }
  1763. //oh, stock QuickFOrm was returning array of arrays!
  1764. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
  1765. }
  1766. }
  1767. if (is_array($this->_constantValues)) {
  1768. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
  1769. }
  1770. return $unfiltered;
  1771. }
  1772. /**
  1773. * This is a bit of a hack, and it duplicates the code in
  1774. * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
  1775. * reliably calling that code. (Think about date selectors, for example.)
  1776. * @param string $name the element name.
  1777. * @param mixed $value the fixed value to set.
  1778. * @return mixed the appropriate array to add to the $unfiltered array.
  1779. */
  1780. protected function prepare_fixed_value($name, $value) {
  1781. if (null === $value) {
  1782. return null;
  1783. } else {
  1784. if (!strpos($name, '[')) {
  1785. return array($name => $value);
  1786. } else {
  1787. $valueAry = array();
  1788. $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
  1789. eval("\$valueAry$myIndex = \$value;");
  1790. return $valueAry;
  1791. }
  1792. }
  1793. }
  1794. /**
  1795. * Adds a validation rule for the given field
  1796. *
  1797. * If the element is in fact a group, it will be considered as a whole.
  1798. * To validate grouped elements as separated entities,
  1799. * use addGroupRule instead of addRule.
  1800. *
  1801. * @param string $element Form element name
  1802. * @param string $message Message to display for invalid data
  1803. * @param string $type Rule type, use getRegisteredRules() to get types
  1804. * @param string $format (optional)Required for extra rule data
  1805. * @param string $validation (optional)Where to perform validation: "server", "client"
  1806. * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
  1807. * @param bool $force Force the rule to be applied, even if the target form element does not exist
  1808. */
  1809. function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
  1810. {
  1811. parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
  1812. if ($validation == 'client') {
  1813. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1814. }
  1815. }
  1816. /**
  1817. * Adds a validation rule for the given group of elements
  1818. *
  1819. * Only groups with a name can be assigned a validation rule
  1820. * Use addGroupRule when you need to validate elements inside the group.
  1821. * Use addRule if you need to validate the group as a whole. In this case,
  1822. * the same rule will be applied to all elements in the group.
  1823. * Use addRule if you need to validate the group against a function.
  1824. *
  1825. * @param string $group Form group name
  1826. * @param array|string $arg1 Array for multiple elements or error message string for one element
  1827. * @param string $type (optional)Rule type use getRegisteredRules() to get types
  1828. * @param string $format (optional)Required for extra rule data
  1829. * @param int $howmany (optional)How many valid elements should be in the group
  1830. * @param string $validation (optional)Where to perform validation: "server", "client"
  1831. * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
  1832. */
  1833. function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
  1834. {
  1835. parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
  1836. if (is_array($arg1)) {
  1837. foreach ($arg1 as $rules) {
  1838. foreach ($rules as $rule) {
  1839. $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
  1840. if ('client' == $validation) {
  1841. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1842. }
  1843. }
  1844. }
  1845. } elseif (is_string($arg1)) {
  1846. if ($validation == 'client') {
  1847. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1848. }
  1849. }
  1850. }
  1851. /**
  1852. * Returns the client side validation script
  1853. *
  1854. * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
  1855. * and slightly modified to run rules per-element
  1856. * Needed to override this because of an error with client side validation of grouped elements.
  1857. *
  1858. * @return string Javascript to perform validation, empty string if no 'client' rules were added
  1859. */
  1860. function getValidationScript()
  1861. {
  1862. if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
  1863. return '';
  1864. }
  1865. include_once('HTML/QuickForm/RuleRegistry.php');
  1866. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1867. $test = array();
  1868. $js_escape = array(
  1869. "\r" => '\r',
  1870. "\n" => '\n',
  1871. "\t" => '\t',
  1872. "'" => "\\'",
  1873. '"' => '\"',
  1874. '\\' => '\\\\'
  1875. );
  1876. foreach ($this->_rules as $elementName => $rules) {
  1877. foreach ($rules as $rule) {
  1878. if ('client' == $rule['validation']) {
  1879. unset($element); //TODO: find out how to properly initialize it
  1880. $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
  1881. $rule['message'] = strtr($rule['message'], $js_escape);
  1882. if (isset($rule['group'])) {
  1883. $group =& $this->getElement($rule['group']);
  1884. // No JavaScript validation for frozen elements
  1885. if ($group->isFrozen()) {
  1886. continue 2;
  1887. }
  1888. $elements =& $group->getElements();
  1889. foreach (array_keys($elements) as $key) {
  1890. if ($elementName == $group->getElementName($key)) {
  1891. $element =& $elements[$key];
  1892. break;
  1893. }
  1894. }
  1895. } elseif ($dependent) {
  1896. $element = array();
  1897. $element[] =& $this->getElement($elementName);
  1898. foreach ($rule['dependent'] as $elName) {
  1899. $element[] =& $this->getElement($elName);
  1900. }
  1901. } else {
  1902. $element =& $this->getElement($elementName);
  1903. }
  1904. // No JavaScript validation for frozen elements
  1905. if (is_object($element) && $element->isFrozen()) {
  1906. continue 2;
  1907. } elseif (is_array($element)) {
  1908. foreach (array_keys($element) as $key) {
  1909. if ($element[$key]->isFrozen()) {
  1910. continue 3;
  1911. }
  1912. }
  1913. }
  1914. //for editor element, [text] is appended to the name.
  1915. $fullelementname = $elementName;
  1916. if ($element->getType() == 'editor') {
  1917. $fullelementname .= '[text]';
  1918. //Add format to rule as moodleform check which format is supported by browser
  1919. //it is not set anywhere... So small hack to make sure we pass it down to quickform
  1920. if (is_null($rule['format'])) {
  1921. $rule['format'] = $element->getFormat();
  1922. }
  1923. }
  1924. // Fix for bug displaying errors for elements in a group
  1925. $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
  1926. $test[$fullelementname][1]=$element;
  1927. //end of fix
  1928. }
  1929. }
  1930. }
  1931. // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
  1932. // the form, and then that form field gets corrupted by the code that follows.
  1933. unset($element);
  1934. $js = '
  1935. <script type="text/javascript">
  1936. //<![CDATA[
  1937. var skipClientValidation = false;
  1938. function qf_errorHandler(element, _qfMsg) {
  1939. div = element.parentNode;
  1940. if ((div == undefined) || (element.name == undefined)) {
  1941. //no checking can be done for undefined elements so let server handle it.
  1942. return true;
  1943. }
  1944. if (_qfMsg != \'\') {
  1945. var errorSpan = document.getElementById(\'id_error_\'+element.name);
  1946. if (!errorSpan) {
  1947. errorSpan = document.createElement("span");
  1948. errorSpan.id = \'id_error_\'+element.name;
  1949. errorSpan.className = "error";
  1950. element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
  1951. document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
  1952. document.getElementById(errorSpan.id).focus();
  1953. }
  1954. while (errorSpan.firstChild) {
  1955. errorSpan.removeChild(errorSpan.firstChild);
  1956. }
  1957. errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
  1958. if (div.className.substr(div.className.length - 6, 6) != " error"
  1959. && div.className != "error") {
  1960. div.className += " error";
  1961. linebreak = document.createElement("br");
  1962. linebreak.className = "error";
  1963. linebreak.id = \'id_error_break_\'+element.name;
  1964. errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
  1965. }
  1966. return false;
  1967. } else {
  1968. var errorSpan = document.getElementById(\'id_error_\'+element.name);
  1969. if (errorSpan) {
  1970. errorSpan.parentNode.removeChild(errorSpan);
  1971. }
  1972. var linebreak = document.getElementById(\'id_error_break_\'+element.name);
  1973. if (linebreak) {
  1974. linebreak.parentNode.removeChild(linebreak);
  1975. }
  1976. if (div.className.substr(div.className.length - 6, 6) == " error") {
  1977. div.className = div.className.substr(0, div.className.length - 6);
  1978. } else if (div.className == "error") {
  1979. div.className = "";
  1980. }
  1981. return true;
  1982. }
  1983. }';
  1984. $validateJS = '';
  1985. foreach ($test as $elementName => $jsandelement) {
  1986. // Fix for bug displaying errors for elements in a group
  1987. //unset($element);
  1988. list($jsArr,$element)=$jsandelement;
  1989. //end of fix
  1990. $escapedElementName = preg_replace_callback(
  1991. '/[_\[\]-]/',
  1992. create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
  1993. $elementName);
  1994. $js .= '
  1995. function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
  1996. if (undefined == element) {
  1997. //required element was not found, then let form be submitted without client side validation
  1998. return true;
  1999. }
  2000. var value = \'\';
  2001. var errFlag = new Array();
  2002. var _qfGroups = {};
  2003. var _qfMsg = \'\';
  2004. var frm = element.parentNode;
  2005. if ((undefined != element.name) && (frm != undefined)) {
  2006. while (frm && frm.nodeName.toUpperCase() != "FORM") {
  2007. frm = frm.parentNode;
  2008. }
  2009. ' . join("\n", $jsArr) . '
  2010. return qf_errorHandler(element, _qfMsg);
  2011. } else {
  2012. //element name should be defined else error msg will not be displayed.
  2013. return true;
  2014. }
  2015. }
  2016. ';
  2017. $validateJS .= '
  2018. ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
  2019. if (!ret && !first_focus) {
  2020. first_focus = true;
  2021. document.getElementById(\'id_error_'.$elementName.'\').focus();
  2022. }
  2023. ';
  2024. // Fix for bug displaying errors for elements in a group
  2025. //unset($element);
  2026. //$element =& $this->getElement($elementName);
  2027. //end of fix
  2028. $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
  2029. $onBlur = $element->getAttribute('onBlur');
  2030. $onChange = $element->getAttribute('onChange');
  2031. $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
  2032. 'onChange' => $onChange . $valFunc));
  2033. }
  2034. // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
  2035. $js .= '
  2036. function validate_' . $this->_formName . '(frm) {
  2037. if (skipClientValidation) {
  2038. return true;
  2039. }
  2040. var ret = true;
  2041. var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
  2042. var first_focus = false;
  2043. ' . $validateJS . ';
  2044. return ret;
  2045. }
  2046. //]]>
  2047. </script>';
  2048. return $js;
  2049. } // end func getValidationScript
  2050. /**
  2051. * Sets default error message
  2052. */
  2053. function _setDefaultRuleMessages(){
  2054. foreach ($this->_rules as $field => $rulesarr){
  2055. foreach ($rulesarr as $key => $rule){
  2056. if ($rule['message']===null){
  2057. $a=new stdClass();
  2058. $a->format=$rule['format'];
  2059. $str=get_string('err_'.$rule['type'], 'form', $a);
  2060. if (strpos($str, '[[')!==0){
  2061. $this->_rules[$field][$key]['message']=$str;
  2062. }
  2063. }
  2064. }
  2065. }
  2066. }
  2067. /**
  2068. * Get list of attributes which have dependencies
  2069. *
  2070. * @return array
  2071. */
  2072. function getLockOptionObject(){
  2073. $result = array();
  2074. foreach ($this->_dependencies as $dependentOn => $conditions){
  2075. $result[$dependentOn] = array();
  2076. foreach ($conditions as $condition=>$values) {
  2077. $result[$dependentOn][$condition] = array();
  2078. foreach ($values as $value=>$dependents) {
  2079. $result[$dependentOn][$condition][$value] = array();
  2080. $i = 0;
  2081. foreach ($dependents as $dependent) {
  2082. $elements = $this->_getElNamesRecursive($dependent);
  2083. if (empty($elements)) {
  2084. // probably element inside of some group
  2085. $elements = array($dependent);
  2086. }
  2087. foreach($elements as $element) {
  2088. if ($element == $dependentOn) {
  2089. continue;
  2090. }
  2091. $result[$dependentOn][$condition][$value][] = $element;
  2092. }
  2093. }
  2094. }
  2095. }
  2096. }
  2097. return array($this->getAttribute('id'), $result);
  2098. }
  2099. /**
  2100. * Get names of element or elements in a group.
  2101. *
  2102. * @param HTML_QuickForm_group|element $element element group or element object
  2103. * @return array
  2104. */
  2105. function _getElNamesRecursive($element) {
  2106. if (is_string($element)) {
  2107. if (!$this->elementExists($element)) {
  2108. return array();
  2109. }
  2110. $element = $this->getElement($element);
  2111. }
  2112. if (is_a($element, 'HTML_QuickForm_group')) {
  2113. $elsInGroup = $element->getElements();
  2114. $elNames = array();
  2115. foreach ($elsInGroup as $elInGroup){
  2116. if (is_a($elInGroup, 'HTML_QuickForm_group')) {
  2117. // not sure if this would work - groups nested in groups
  2118. $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
  2119. } else {
  2120. $elNames[] = $element->getElementName($elInGroup->getName());
  2121. }
  2122. }
  2123. } else if (is_a($element, 'HTML_QuickForm_header')) {
  2124. return array();
  2125. } else if (is_a($element, 'HTML_QuickForm_hidden')) {
  2126. return array();
  2127. } else if (method_exists($element, 'getPrivateName') &&
  2128. !($element instanceof HTML_QuickForm_advcheckbox)) {
  2129. // The advcheckbox element implements a method called getPrivateName,
  2130. // but in a way that is not compatible with the generic API, so we
  2131. // have to explicitly exclude it.
  2132. return array($element->getPrivateName());
  2133. } else {
  2134. $elNames = array($element->getName());
  2135. }
  2136. return $elNames;
  2137. }
  2138. /**
  2139. * Adds a dependency for $elementName which will be disabled if $condition is met.
  2140. * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
  2141. * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
  2142. * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
  2143. * of the $dependentOn element is $condition (such as equal) to $value.
  2144. *
  2145. * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
  2146. * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
  2147. * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
  2148. *
  2149. * @param string $elementName the name of the element which will be disabled
  2150. * @param string $dependentOn the name of the element whose state will be checked for condition
  2151. * @param string $condition the condition to check
  2152. * @param mixed $value used in conjunction with condition.
  2153. */
  2154. function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
  2155. // Multiple selects allow for a multiple selection, we transform the array to string here as
  2156. // an array cannot be used as a key in an associative array.
  2157. if (is_array($value)) {
  2158. $value = implode('|', $value);
  2159. }
  2160. if (!array_key_exists($dependentOn, $this->_dependencies)) {
  2161. $this->_dependencies[$dependentOn] = array();
  2162. }
  2163. if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
  2164. $this->_dependencies[$dependentOn][$condition] = array();
  2165. }
  2166. if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
  2167. $this->_dependencies[$dependentOn][$condition][$value] = array();
  2168. }
  2169. $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
  2170. }
  2171. /**
  2172. * Registers button as no submit button
  2173. *
  2174. * @param string $buttonname name of the button
  2175. */
  2176. function registerNoSubmitButton($buttonname){
  2177. $this->_noSubmitButtons[]=$buttonname;
  2178. }
  2179. /**
  2180. * Checks if button is a no submit button, i.e it doesn't submit form
  2181. *
  2182. * @param string $buttonname name of the button to check
  2183. * @return bool
  2184. */
  2185. function isNoSubmitButton($buttonname){
  2186. return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
  2187. }
  2188. /**
  2189. * Registers a button as cancel button
  2190. *
  2191. * @param string $addfieldsname name of the button
  2192. */
  2193. function _registerCancelButton($addfieldsname){
  2194. $this->_cancelButtons[]=$addfieldsname;
  2195. }
  2196. /**
  2197. * Displays elements without HTML input tags.
  2198. * This method is different to freeze() in that it makes sure no hidden
  2199. * elements are included in the form.
  2200. * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
  2201. *
  2202. * This function also removes all previously defined rules.
  2203. *
  2204. * @param string|array $elementList array or string of element(s) to be frozen
  2205. * @return object|bool if element list is not empty then return error object, else true
  2206. */
  2207. function hardFreeze($elementList=null)
  2208. {
  2209. if (!isset($elementList)) {
  2210. $this->_freezeAll = true;
  2211. $elementList = array();
  2212. } else {
  2213. if (!is_array($elementList)) {
  2214. $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
  2215. }
  2216. $elementList = array_flip($elementList);
  2217. }
  2218. foreach (array_keys($this->_elements) as $key) {
  2219. $name = $this->_elements[$key]->getName();
  2220. if ($this->_freezeAll || isset($elementList[$name])) {
  2221. $this->_elements[$key]->freeze();
  2222. $this->_elements[$key]->setPersistantFreeze(false);
  2223. unset($elementList[$name]);
  2224. // remove all rules
  2225. $this->_rules[$name] = array();
  2226. // if field is required, remove the rule
  2227. $unset = array_search($name, $this->_required);
  2228. if ($unset !== false) {
  2229. unset($this->_required[$unset]);
  2230. }
  2231. }
  2232. }
  2233. if (!empty($elementList)) {
  2234. return self::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
  2235. }
  2236. return true;
  2237. }
  2238. /**
  2239. * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
  2240. *
  2241. * This function also removes all previously defined rules of elements it freezes.
  2242. *
  2243. * @throws HTML_QuickForm_Error
  2244. * @param array $elementList array or string of element(s) not to be frozen
  2245. * @return bool returns true
  2246. */
  2247. function hardFreezeAllVisibleExcept($elementList)
  2248. {
  2249. $elementList = array_flip($elementList);
  2250. foreach (array_keys($this->_elements) as $key) {
  2251. $name = $this->_elements[$key]->getName();
  2252. $type = $this->_elements[$key]->getType();
  2253. if ($type == 'hidden'){
  2254. // leave hidden types as they are
  2255. } elseif (!isset($elementList[$name])) {
  2256. $this->_elements[$key]->freeze();
  2257. $this->_elements[$key]->setPersistantFreeze(false);
  2258. // remove all rules
  2259. $this->_rules[$name] = array();
  2260. // if field is required, remove the rule
  2261. $unset = array_search($name, $this->_required);
  2262. if ($unset !== false) {
  2263. unset($this->_required[$unset]);
  2264. }
  2265. }
  2266. }
  2267. return true;
  2268. }
  2269. /**
  2270. * Tells whether the form was already submitted
  2271. *
  2272. * This is useful since the _submitFiles and _submitValues arrays
  2273. * may be completely empty after the trackSubmit value is removed.
  2274. *
  2275. * @return bool
  2276. */
  2277. function isSubmitted()
  2278. {
  2279. return parent::isSubmitted() && (!$this->isFrozen());
  2280. }
  2281. }
  2282. /**
  2283. * MoodleQuickForm renderer
  2284. *
  2285. * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
  2286. * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
  2287. *
  2288. * Stylesheet is part of standard theme and should be automatically included.
  2289. *
  2290. * @package core_form
  2291. * @copyright 2007 Jamie Pratt <me@jamiep.org>
  2292. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2293. */
  2294. class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
  2295. /** @var array Element template array */
  2296. var $_elementTemplates;
  2297. /**
  2298. * Template used when opening a hidden fieldset
  2299. * (i.e. a fieldset that is opened when there is no header element)
  2300. * @var string
  2301. */
  2302. var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
  2303. /** @var string Header Template string */
  2304. var $_headerTemplate =
  2305. "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
  2306. /** @var string Template used when opening a fieldset */
  2307. var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
  2308. /** @var string Template used when closing a fieldset */
  2309. var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
  2310. /** @var string Required Note template string */
  2311. var $_requiredNoteTemplate =
  2312. "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
  2313. /**
  2314. * Collapsible buttons string template.
  2315. *
  2316. * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
  2317. * until the Javascript has been fully loaded.
  2318. *
  2319. * @var string
  2320. */
  2321. var $_collapseButtonsTemplate =
  2322. "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
  2323. /**
  2324. * Array whose keys are element names. If the key exists this is a advanced element
  2325. *
  2326. * @var array
  2327. */
  2328. var $_advancedElements = array();
  2329. /**
  2330. * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
  2331. *
  2332. * @var array
  2333. */
  2334. var $_collapsibleElements = array();
  2335. /**
  2336. * @var string Contains the collapsible buttons to add to the form.
  2337. */
  2338. var $_collapseButtons = '';
  2339. /**
  2340. * Constructor
  2341. */
  2342. function MoodleQuickForm_Renderer(){
  2343. // switch next two lines for ol li containers for form items.
  2344. // $this->_elementTemplates=array('default'=>"\n\t\t".'<li class="fitem"><label>{label}{help}<!-- BEGIN required -->{req}<!-- END required --></label><div class="qfelement<!-- BEGIN error --> error<!-- END error --> {type}"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></li>');
  2345. $this->_elementTemplates = array(
  2346. 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}" {aria-live}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
  2347. 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
  2348. 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
  2349. 'static'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
  2350. 'warning'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}">{element}</div>',
  2351. 'nodisplay'=>'');
  2352. parent::HTML_QuickForm_Renderer_Tableless();
  2353. }
  2354. /**
  2355. * Set element's as adavance element
  2356. *
  2357. * @param array $elements form elements which needs to be grouped as advance elements.
  2358. */
  2359. function setAdvancedElements($elements){
  2360. $this->_advancedElements = $elements;
  2361. }
  2362. /**
  2363. * Setting collapsible elements
  2364. *
  2365. * @param array $elements
  2366. */
  2367. function setCollapsibleElements($elements) {
  2368. $this->_collapsibleElements = $elements;
  2369. }
  2370. /**
  2371. * What to do when starting the form
  2372. *
  2373. * @param MoodleQuickForm $form reference of the form
  2374. */
  2375. function startForm(&$form){
  2376. global $PAGE;
  2377. $this->_reqHTML = $form->getReqHTML();
  2378. $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
  2379. $this->_advancedHTML = $form->getAdvancedHTML();
  2380. $this->_collapseButtons = '';
  2381. $formid = $form->getAttribute('id');
  2382. parent::startForm($form);
  2383. if ($form->isFrozen()){
  2384. $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
  2385. } else {
  2386. $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
  2387. $this->_hiddenHtml .= $form->_pageparams;
  2388. }
  2389. if ($form->is_form_change_checker_enabled()) {
  2390. $PAGE->requires->yui_module('moodle-core-formchangechecker',
  2391. 'M.core_formchangechecker.init',
  2392. array(array(
  2393. 'formid' => $formid
  2394. ))
  2395. );
  2396. $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
  2397. }
  2398. if (!empty($this->_collapsibleElements)) {
  2399. if (count($this->_collapsibleElements) > 1) {
  2400. $this->_collapseButtons = $this->_collapseButtonsTemplate;
  2401. $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
  2402. $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
  2403. }
  2404. $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
  2405. }
  2406. if (!empty($this->_advancedElements)){
  2407. $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
  2408. $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
  2409. }
  2410. }
  2411. /**
  2412. * Create advance group of elements
  2413. *
  2414. * @param object $group Passed by reference
  2415. * @param bool $required if input is required field
  2416. * @param string $error error message to display
  2417. */
  2418. function startGroup(&$group, $required, $error){
  2419. // Make sure the element has an id.
  2420. $group->_generateId();
  2421. if (method_exists($group, 'getElementTemplateType')){
  2422. $html = $this->_elementTemplates[$group->getElementTemplateType()];
  2423. }else{
  2424. $html = $this->_elementTemplates['default'];
  2425. }
  2426. if (isset($this->_advancedElements[$group->getName()])){
  2427. $html =str_replace(' {advanced}', ' advanced', $html);
  2428. $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
  2429. } else {
  2430. $html =str_replace(' {advanced}', '', $html);
  2431. $html =str_replace('{advancedimg}', '', $html);
  2432. }
  2433. if (method_exists($group, 'getHelpButton')){
  2434. $html =str_replace('{help}', $group->getHelpButton(), $html);
  2435. }else{
  2436. $html =str_replace('{help}', '', $html);
  2437. }
  2438. $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
  2439. $html =str_replace('{name}', $group->getName(), $html);
  2440. $html =str_replace('{type}', 'fgroup', $html);
  2441. $emptylabel = '';
  2442. if ($group->getLabel() == '') {
  2443. $emptylabel = 'femptylabel';
  2444. }
  2445. $html = str_replace('{emptylabel}', $emptylabel, $html);
  2446. $this->_templates[$group->getName()]=$html;
  2447. // Fix for bug in tableless quickforms that didn't allow you to stop a
  2448. // fieldset before a group of elements.
  2449. // if the element name indicates the end of a fieldset, close the fieldset
  2450. if ( in_array($group->getName(), $this->_stopFieldsetElements)
  2451. && $this->_fieldsetsOpen > 0
  2452. ) {
  2453. $this->_html .= $this->_closeFieldsetTemplate;
  2454. $this->_fieldsetsOpen--;
  2455. }
  2456. parent::startGroup($group, $required, $error);
  2457. }
  2458. /**
  2459. * Renders element
  2460. *
  2461. * @param HTML_QuickForm_element $element element
  2462. * @param bool $required if input is required field
  2463. * @param string $error error message to display
  2464. */
  2465. function renderElement(&$element, $required, $error){
  2466. // Make sure the element has an id.
  2467. $element->_generateId();
  2468. //adding stuff to place holders in template
  2469. //check if this is a group element first
  2470. if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
  2471. // so it gets substitutions for *each* element
  2472. $html = $this->_groupElementTemplate;
  2473. }
  2474. elseif (method_exists($element, 'getElementTemplateType')){
  2475. $html = $this->_elementTemplates[$element->getElementTemplateType()];
  2476. }else{
  2477. $html = $this->_elementTemplates['default'];
  2478. }
  2479. if (isset($this->_advancedElements[$element->getName()])){
  2480. $html = str_replace(' {advanced}', ' advanced', $html);
  2481. $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
  2482. } else {
  2483. $html = str_replace(' {advanced}', '', $html);
  2484. $html = str_replace(' {aria-live}', '', $html);
  2485. }
  2486. if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
  2487. $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
  2488. } else {
  2489. $html =str_replace('{advancedimg}', '', $html);
  2490. }
  2491. $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
  2492. $html =str_replace('{type}', 'f'.$element->getType(), $html);
  2493. $html =str_replace('{name}', $element->getName(), $html);
  2494. $emptylabel = '';
  2495. if ($element->getLabel() == '') {
  2496. $emptylabel = 'femptylabel';
  2497. }
  2498. $html = str_replace('{emptylabel}', $emptylabel, $html);
  2499. if (method_exists($element, 'getHelpButton')){
  2500. $html = str_replace('{help}', $element->getHelpButton(), $html);
  2501. }else{
  2502. $html = str_replace('{help}', '', $html);
  2503. }
  2504. if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
  2505. $this->_groupElementTemplate = $html;
  2506. }
  2507. elseif (!isset($this->_templates[$element->getName()])) {
  2508. $this->_templates[$element->getName()] = $html;
  2509. }
  2510. parent::renderElement($element, $required, $error);
  2511. }
  2512. /**
  2513. * Called when visiting a form, after processing all form elements
  2514. * Adds required note, form attributes, validation javascript and form content.
  2515. *
  2516. * @global moodle_page $PAGE
  2517. * @param moodleform $form Passed by reference
  2518. */
  2519. function finishForm(&$form){
  2520. global $PAGE;
  2521. if ($form->isFrozen()){
  2522. $this->_hiddenHtml = '';
  2523. }
  2524. parent::finishForm($form);
  2525. $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
  2526. if (!$form->isFrozen()) {
  2527. $args = $form->getLockOptionObject();
  2528. if (count($args[1]) > 0) {
  2529. $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
  2530. }
  2531. }
  2532. }
  2533. /**
  2534. * Called when visiting a header element
  2535. *
  2536. * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
  2537. * @global moodle_page $PAGE
  2538. */
  2539. function renderHeader(&$header) {
  2540. global $PAGE;
  2541. $header->_generateId();
  2542. $name = $header->getName();
  2543. $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
  2544. if (is_null($header->_text)) {
  2545. $header_html = '';
  2546. } elseif (!empty($name) && isset($this->_templates[$name])) {
  2547. $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
  2548. } else {
  2549. $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
  2550. }
  2551. if ($this->_fieldsetsOpen > 0) {
  2552. $this->_html .= $this->_closeFieldsetTemplate;
  2553. $this->_fieldsetsOpen--;
  2554. }
  2555. // Define collapsible classes for fieldsets.
  2556. $arialive = '';
  2557. $fieldsetclasses = array('clearfix');
  2558. if (isset($this->_collapsibleElements[$header->getName()])) {
  2559. $fieldsetclasses[] = 'collapsible';
  2560. if ($this->_collapsibleElements[$header->getName()]) {
  2561. $fieldsetclasses[] = 'collapsed';
  2562. }
  2563. }
  2564. if (isset($this->_advancedElements[$name])){
  2565. $fieldsetclasses[] = 'containsadvancedelements';
  2566. }
  2567. $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
  2568. $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
  2569. $this->_html .= $openFieldsetTemplate . $header_html;
  2570. $this->_fieldsetsOpen++;
  2571. }
  2572. /**
  2573. * Return Array of element names that indicate the end of a fieldset
  2574. *
  2575. * @return array
  2576. */
  2577. function getStopFieldsetElements(){
  2578. return $this->_stopFieldsetElements;
  2579. }
  2580. }
  2581. /**
  2582. * Required elements validation
  2583. *
  2584. * This class overrides QuickForm validation since it allowed space or empty tag as a value
  2585. *
  2586. * @package core_form
  2587. * @category form
  2588. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  2589. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2590. */
  2591. class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
  2592. /**
  2593. * Checks if an element is not empty.
  2594. * This is a server-side validation, it works for both text fields and editor fields
  2595. *
  2596. * @param string $value Value to check
  2597. * @param int|string|array $options Not used yet
  2598. * @return bool true if value is not empty
  2599. */
  2600. function validate($value, $options = null) {
  2601. global $CFG;
  2602. if (is_array($value) && array_key_exists('text', $value)) {
  2603. $value = $value['text'];
  2604. }
  2605. if (is_array($value)) {
  2606. // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
  2607. $value = implode('', $value);
  2608. }
  2609. $stripvalues = array(
  2610. '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
  2611. '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
  2612. );
  2613. if (!empty($CFG->strictformsrequired)) {
  2614. $value = preg_replace($stripvalues, '', (string)$value);
  2615. }
  2616. if ((string)$value == '') {
  2617. return false;
  2618. }
  2619. return true;
  2620. }
  2621. /**
  2622. * This function returns Javascript code used to build client-side validation.
  2623. * It checks if an element is not empty.
  2624. *
  2625. * @param int $format format of data which needs to be validated.
  2626. * @return array
  2627. */
  2628. function getValidationScript($format = null) {
  2629. global $CFG;
  2630. if (!empty($CFG->strictformsrequired)) {
  2631. if (!empty($format) && $format == FORMAT_HTML) {
  2632. return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
  2633. } else {
  2634. return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
  2635. }
  2636. } else {
  2637. return array('', "{jsVar} == ''");
  2638. }
  2639. }
  2640. }
  2641. /**
  2642. * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
  2643. * @name $_HTML_QuickForm_default_renderer
  2644. */
  2645. $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
  2646. /** Please keep this list in alphabetical order. */
  2647. MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
  2648. MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
  2649. MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
  2650. MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
  2651. MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
  2652. MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
  2653. MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
  2654. MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
  2655. MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
  2656. MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
  2657. MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
  2658. MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
  2659. MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
  2660. MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
  2661. MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
  2662. MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
  2663. MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
  2664. MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
  2665. MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
  2666. MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
  2667. MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
  2668. MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
  2669. MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
  2670. MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
  2671. MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
  2672. MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
  2673. MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
  2674. MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
  2675. MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
  2676. MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
  2677. MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
  2678. MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
  2679. MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
  2680. MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
  2681. MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
  2682. MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
  2683. MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");