PageRenderTime 73ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/formslib.php

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