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

/lib/formslib.php

https://bitbucket.org/moodle/moodle
PHP | 3488 lines | 2429 code | 220 blank | 839 comment | 295 complexity | 14810fb210be818ef79469824427e455 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
  18. *
  19. * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
  20. * and you want to name your class something like {modulename}_{purpose}_form. Your class will
  21. * extend moodleform overriding abstract classes definition and optionally defintion_after_data
  22. * and validation.
  23. *
  24. * See examples of use of this library in course/edit.php and course/edit_form.php
  25. *
  26. * A few notes :
  27. * form definition is used for both printing of form and processing and should be the same
  28. * for both or you may lose some submitted data which won't be let through.
  29. * you should be using setType for every form element except select, radio or checkbox
  30. * elements, these elements clean themselves.
  31. *
  32. * @package core_form
  33. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  34. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35. */
  36. defined('MOODLE_INTERNAL') || die();
  37. /** setup.php includes our hacked pear libs first */
  38. require_once 'HTML/QuickForm.php';
  39. require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
  40. require_once 'HTML/QuickForm/Renderer/Tableless.php';
  41. require_once 'HTML/QuickForm/Rule.php';
  42. require_once $CFG->libdir.'/filelib.php';
  43. /**
  44. * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
  45. */
  46. define('EDITOR_UNLIMITED_FILES', -1);
  47. /**
  48. * Callback called when PEAR throws an error
  49. *
  50. * @param PEAR_Error $error
  51. */
  52. function pear_handle_error($error){
  53. echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
  54. echo '<br /> <strong>Backtrace </strong>:';
  55. print_object($error->backtrace);
  56. }
  57. if ($CFG->debugdeveloper) {
  58. //TODO: this is a wrong place to init PEAR!
  59. $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
  60. $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
  61. }
  62. /**
  63. * Initalize javascript for date type form element
  64. *
  65. * @staticvar bool $done make sure it gets initalize once.
  66. * @global moodle_page $PAGE
  67. */
  68. function form_init_date_js() {
  69. global $PAGE;
  70. static $done = false;
  71. if (!$done) {
  72. $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. $varname = $this->_elements[$key]->_attributes['name'];
  2037. $value = '';
  2038. // If we have a default value then export it.
  2039. if (isset($this->_defaultValues[$varname])) {
  2040. $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
  2041. }
  2042. } else {
  2043. $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
  2044. }
  2045. if (is_array($value)) {
  2046. // This shit throws a bogus warning in PHP 4.3.x
  2047. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
  2048. }
  2049. }
  2050. } else {
  2051. if (!is_array($elementList)) {
  2052. $elementList = array_map('trim', explode(',', $elementList));
  2053. }
  2054. foreach ($elementList as $elementName) {
  2055. $value = $this->exportValue($elementName);
  2056. if ((new PEAR())->isError($value)) {
  2057. return $value;
  2058. }
  2059. //oh, stock QuickFOrm was returning array of arrays!
  2060. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
  2061. }
  2062. }
  2063. if (is_array($this->_constantValues)) {
  2064. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
  2065. }
  2066. return $unfiltered;
  2067. }
  2068. /**
  2069. * This is a bit of a hack, and it duplicates the code in
  2070. * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
  2071. * reliably calling that code. (Think about date selectors, for example.)
  2072. * @param string $name the element name.
  2073. * @param mixed $value the fixed value to set.
  2074. * @return mixed the appropriate array to add to the $unfiltered array.
  2075. */
  2076. protected function prepare_fixed_value($name, $value) {
  2077. if (null === $value) {
  2078. return null;
  2079. } else {
  2080. if (!strpos($name, '[')) {
  2081. return array($name => $value);
  2082. } else {
  2083. $valueAry = array();
  2084. $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
  2085. eval("\$valueAry$myIndex = \$value;");
  2086. return $valueAry;
  2087. }
  2088. }
  2089. }
  2090. /**
  2091. * Adds a validation rule for the given field
  2092. *
  2093. * If the element is in fact a group, it will be considered as a whole.
  2094. * To validate grouped elements as separated entities,
  2095. * use addGroupRule instead of addRule.
  2096. *
  2097. * @param string $element Form element name
  2098. * @param string $message Message to display for invalid data
  2099. * @param string $type Rule type, use getRegisteredRules() to get types
  2100. * @param string $format (optional)Required for extra rule data
  2101. * @param string $validation (optional)Where to perform validation: "server", "client"
  2102. * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
  2103. * @param bool $force Force the rule to be applied, even if the target form element does not exist
  2104. */
  2105. function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
  2106. {
  2107. parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
  2108. if ($validation == 'client') {
  2109. $this->clientvalidation = true;
  2110. }
  2111. }
  2112. /**
  2113. * Adds a validation rule for the given group of elements
  2114. *
  2115. * Only groups with a name can be assigned a validation rule
  2116. * Use addGroupRule when you need to validate elements inside the group.
  2117. * Use addRule if you need to validate the group as a whole. In this case,
  2118. * the same rule will be applied to all elements in the group.
  2119. * Use addRule if you need to validate the group against a function.
  2120. *
  2121. * @param string $group Form group name
  2122. * @param array|string $arg1 Array for multiple elements or error message string for one element
  2123. * @param string $type (optional)Rule type use getRegisteredRules() to get types
  2124. * @param string $format (optional)Required for extra rule data
  2125. * @param int $howmany (optional)How many valid elements should be in the group
  2126. * @param string $validation (optional)Where to perform validation: "server", "client"
  2127. * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
  2128. */
  2129. function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
  2130. {
  2131. parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
  2132. if (is_array($arg1)) {
  2133. foreach ($arg1 as $rules) {
  2134. foreach ($rules as $rule) {
  2135. $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
  2136. if ($validation == 'client') {
  2137. $this->clientvalidation = true;
  2138. }
  2139. }
  2140. }
  2141. } elseif (is_string($arg1)) {
  2142. if ($validation == 'client') {
  2143. $this->clientvalidation = true;
  2144. }
  2145. }
  2146. }
  2147. /**
  2148. * Returns the client side validation script
  2149. *
  2150. * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
  2151. * and slightly modified to run rules per-element
  2152. * Needed to override this because of an error with client side validation of grouped elements.
  2153. *
  2154. * @return string Javascript to perform validation, empty string if no 'client' rules were added
  2155. */
  2156. function getValidationScript()
  2157. {
  2158. global $PAGE;
  2159. if (empty($this->_rules) || $this->clientvalidation === false) {
  2160. return '';
  2161. }
  2162. include_once('HTML/QuickForm/RuleRegistry.php');
  2163. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  2164. $test = array();
  2165. $js_escape = array(
  2166. "\r" => '\r',
  2167. "\n" => '\n',
  2168. "\t" => '\t',
  2169. "'" => "\\'",
  2170. '"' => '\"',
  2171. '\\' => '\\\\'
  2172. );
  2173. foreach ($this->_rules as $elementName => $rules) {
  2174. foreach ($rules as $rule) {
  2175. if ('client' == $rule['validation']) {
  2176. unset($element); //TODO: find out how to properly initialize it
  2177. $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
  2178. $rule['message'] = strtr($rule['message'], $js_escape);
  2179. if (isset($rule['group'])) {
  2180. $group =& $this->getElement($rule['group']);
  2181. // No JavaScript validation for frozen elements
  2182. if ($group->isFrozen()) {
  2183. continue 2;
  2184. }
  2185. $elements =& $group->getElements();
  2186. foreach (array_keys($elements) as $key) {
  2187. if ($elementName == $group->getElementName($key)) {
  2188. $element =& $elements[$key];
  2189. break;
  2190. }
  2191. }
  2192. } elseif ($dependent) {
  2193. $element = array();
  2194. $element[] =& $this->getElement($elementName);
  2195. foreach ($rule['dependent'] as $elName) {
  2196. $element[] =& $this->getElement($elName);
  2197. }
  2198. } else {
  2199. $element =& $this->getElement($elementName);
  2200. }
  2201. // No JavaScript validation for frozen elements
  2202. if (is_object($element) && $element->isFrozen()) {
  2203. continue 2;
  2204. } elseif (is_array($element)) {
  2205. foreach (array_keys($element) as $key) {
  2206. if ($element[$key]->isFrozen()) {
  2207. continue 3;
  2208. }
  2209. }
  2210. }
  2211. //for editor element, [text] is appended to the name.
  2212. $fullelementname = $elementName;
  2213. if (is_object($element) && $element->getType() == 'editor') {
  2214. if ($element->getType() == 'editor') {
  2215. $fullelementname .= '[text]';
  2216. // Add format to rule as moodleform check which format is supported by browser
  2217. // it is not set anywhere... So small hack to make sure we pass it down to quickform.
  2218. if (is_null($rule['format'])) {
  2219. $rule['format'] = $element->getFormat();
  2220. }
  2221. }
  2222. }
  2223. // Fix for bug displaying errors for elements in a group
  2224. $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
  2225. $test[$fullelementname][1]=$element;
  2226. //end of fix
  2227. }
  2228. }
  2229. }
  2230. // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
  2231. // the form, and then that form field gets corrupted by the code that follows.
  2232. unset($element);
  2233. $js = '
  2234. require([
  2235. "core_form/events",
  2236. "jquery",
  2237. ], function(
  2238. FormEvents,
  2239. $
  2240. ) {
  2241. function qf_errorHandler(element, _qfMsg, escapedName) {
  2242. const event = FormEvents.notifyFieldValidationFailure(element, _qfMsg);
  2243. if (event.defaultPrevented) {
  2244. return _qfMsg == \'\';
  2245. } else {
  2246. // Legacy mforms.
  2247. var div = element.parentNode;
  2248. if ((div == undefined) || (element.name == undefined)) {
  2249. // No checking can be done for undefined elements so let server handle it.
  2250. return true;
  2251. }
  2252. if (_qfMsg != \'\') {
  2253. var errorSpan = document.getElementById(\'id_error_\' + escapedName);
  2254. if (!errorSpan) {
  2255. errorSpan = document.createElement("span");
  2256. errorSpan.id = \'id_error_\' + escapedName;
  2257. errorSpan.className = "error";
  2258. element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
  2259. document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
  2260. document.getElementById(errorSpan.id).focus();
  2261. }
  2262. while (errorSpan.firstChild) {
  2263. errorSpan.removeChild(errorSpan.firstChild);
  2264. }
  2265. errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
  2266. if (div.className.substr(div.className.length - 6, 6) != " error"
  2267. && div.className != "error") {
  2268. div.className += " error";
  2269. linebreak = document.createElement("br");
  2270. linebreak.className = "error";
  2271. linebreak.id = \'id_error_break_\' + escapedName;
  2272. errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
  2273. }
  2274. return false;
  2275. } else {
  2276. var errorSpan = document.getElementById(\'id_error_\' + escapedName);
  2277. if (errorSpan) {
  2278. errorSpan.parentNode.removeChild(errorSpan);
  2279. }
  2280. var linebreak = document.getElementById(\'id_error_break_\' + escapedName);
  2281. if (linebreak) {
  2282. linebreak.parentNode.removeChild(linebreak);
  2283. }
  2284. if (div.className.substr(div.className.length - 6, 6) == " error") {
  2285. div.className = div.className.substr(0, div.className.length - 6);
  2286. } else if (div.className == "error") {
  2287. div.className = "";
  2288. }
  2289. return true;
  2290. } // End if.
  2291. } // End if.
  2292. } // End function.
  2293. ';
  2294. $validateJS = '';
  2295. foreach ($test as $elementName => $jsandelement) {
  2296. // Fix for bug displaying errors for elements in a group
  2297. //unset($element);
  2298. list($jsArr,$element)=$jsandelement;
  2299. //end of fix
  2300. $escapedElementName = preg_replace_callback(
  2301. '/[_\[\]-]/',
  2302. function($matches) {
  2303. return sprintf("_%2x", ord($matches[0]));
  2304. },
  2305. $elementName);
  2306. $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(ev.target, \''.$escapedElementName.'\')';
  2307. if (!is_array($element)) {
  2308. $element = [$element];
  2309. }
  2310. foreach ($element as $elem) {
  2311. if (key_exists('id', $elem->_attributes)) {
  2312. $js .= '
  2313. function validate_' . $this->_formName . '_' . $escapedElementName . '(element, escapedName) {
  2314. if (undefined == element) {
  2315. //required element was not found, then let form be submitted without client side validation
  2316. return true;
  2317. }
  2318. var value = \'\';
  2319. var errFlag = new Array();
  2320. var _qfGroups = {};
  2321. var _qfMsg = \'\';
  2322. var frm = element.parentNode;
  2323. if ((undefined != element.name) && (frm != undefined)) {
  2324. while (frm && frm.nodeName.toUpperCase() != "FORM") {
  2325. frm = frm.parentNode;
  2326. }
  2327. ' . join("\n", $jsArr) . '
  2328. return qf_errorHandler(element, _qfMsg, escapedName);
  2329. } else {
  2330. //element name should be defined else error msg will not be displayed.
  2331. return true;
  2332. }
  2333. }
  2334. document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'blur\', function(ev) {
  2335. ' . $valFunc . '
  2336. });
  2337. document.getElementById(\'' . $elem->_attributes['id'] . '\').addEventListener(\'change\', function(ev) {
  2338. ' . $valFunc . '
  2339. });
  2340. ';
  2341. }
  2342. }
  2343. // This handles both randomised (MDL-65217) and non-randomised IDs.
  2344. $errorid = preg_replace('/^id_/', 'id_error_', $elem->_attributes['id']);
  2345. $validateJS .= '
  2346. ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\'], \''.$escapedElementName.'\') && ret;
  2347. if (!ret && !first_focus) {
  2348. first_focus = true;
  2349. const element = document.getElementById("' . $errorid . '");
  2350. if (element) {
  2351. FormEvents.notifyFormError(element);
  2352. element.focus();
  2353. }
  2354. }
  2355. ';
  2356. // Fix for bug displaying errors for elements in a group
  2357. //unset($element);
  2358. //$element =& $this->getElement($elementName);
  2359. //end of fix
  2360. //$onBlur = $element->getAttribute('onBlur');
  2361. //$onChange = $element->getAttribute('onChange');
  2362. //$element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
  2363. //'onChange' => $onChange . $valFunc));
  2364. }
  2365. // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
  2366. $js .= '
  2367. function validate_' . $this->_formName . '() {
  2368. if (skipClientValidation) {
  2369. return true;
  2370. }
  2371. var ret = true;
  2372. var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
  2373. var first_focus = false;
  2374. ' . $validateJS . ';
  2375. return ret;
  2376. }
  2377. var form = document.getElementById(\'' . $this->_attributes['id'] . '\').closest(\'form\');
  2378. form.addEventListener(FormEvents.eventTypes.formSubmittedByJavascript, () => {
  2379. try {
  2380. var myValidator = validate_' . $this->_formName . ';
  2381. } catch(e) {
  2382. return;
  2383. }
  2384. if (myValidator) {
  2385. myValidator();
  2386. }
  2387. });
  2388. document.getElementById(\'' . $this->_attributes['id'] . '\').addEventListener(\'submit\', function(ev) {
  2389. try {
  2390. var myValidator = validate_' . $this->_formName . ';
  2391. } catch(e) {
  2392. return true;
  2393. }
  2394. if (typeof window.tinyMCE !== \'undefined\') {
  2395. window.tinyMCE.triggerSave();
  2396. }
  2397. if (!myValidator()) {
  2398. ev.preventDefault();
  2399. }
  2400. });
  2401. });
  2402. ';
  2403. $PAGE->requires->js_amd_inline($js);
  2404. // Global variable used to skip the client validation.
  2405. return html_writer::tag('script', 'var skipClientValidation = false;');
  2406. } // end func getValidationScript
  2407. /**
  2408. * Sets default error message
  2409. */
  2410. function _setDefaultRuleMessages(){
  2411. foreach ($this->_rules as $field => $rulesarr){
  2412. foreach ($rulesarr as $key => $rule){
  2413. if ($rule['message']===null){
  2414. $a=new stdClass();
  2415. $a->format=$rule['format'];
  2416. $str=get_string('err_'.$rule['type'], 'form', $a);
  2417. if (strpos($str, '[[')!==0){
  2418. $this->_rules[$field][$key]['message']=$str;
  2419. }
  2420. }
  2421. }
  2422. }
  2423. }
  2424. /**
  2425. * Get list of attributes which have dependencies
  2426. *
  2427. * @return array
  2428. */
  2429. function getLockOptionObject(){
  2430. $result = array();
  2431. foreach ($this->_dependencies as $dependentOn => $conditions){
  2432. $result[$dependentOn] = array();
  2433. foreach ($conditions as $condition=>$values) {
  2434. $result[$dependentOn][$condition] = array();
  2435. foreach ($values as $value=>$dependents) {
  2436. $result[$dependentOn][$condition][$value][self::DEP_DISABLE] = array();
  2437. foreach ($dependents as $dependent) {
  2438. $elements = $this->_getElNamesRecursive($dependent);
  2439. if (empty($elements)) {
  2440. // probably element inside of some group
  2441. $elements = array($dependent);
  2442. }
  2443. foreach($elements as $element) {
  2444. if ($element == $dependentOn) {
  2445. continue;
  2446. }
  2447. $result[$dependentOn][$condition][$value][self::DEP_DISABLE][] = $element;
  2448. }
  2449. }
  2450. }
  2451. }
  2452. }
  2453. foreach ($this->_hideifs as $dependenton => $conditions) {
  2454. if (!isset($result[$dependenton])) {
  2455. $result[$dependenton] = array();
  2456. }
  2457. foreach ($conditions as $condition => $values) {
  2458. if (!isset($result[$dependenton][$condition])) {
  2459. $result[$dependenton][$condition] = array();
  2460. }
  2461. foreach ($values as $value => $dependents) {
  2462. $result[$dependenton][$condition][$value][self::DEP_HIDE] = array();
  2463. foreach ($dependents as $dependent) {
  2464. $elements = $this->_getElNamesRecursive($dependent);
  2465. if (!in_array($dependent, $elements)) {
  2466. // Always want to hide the main element, even if it contains sub-elements as well.
  2467. $elements[] = $dependent;
  2468. }
  2469. foreach ($elements as $element) {
  2470. if ($element == $dependenton) {
  2471. continue;
  2472. }
  2473. $result[$dependenton][$condition][$value][self::DEP_HIDE][] = $element;
  2474. }
  2475. }
  2476. }
  2477. }
  2478. }
  2479. return array($this->getAttribute('id'), $result);
  2480. }
  2481. /**
  2482. * Get names of element or elements in a group.
  2483. *
  2484. * @param HTML_QuickForm_group|element $element element group or element object
  2485. * @return array
  2486. */
  2487. function _getElNamesRecursive($element) {
  2488. if (is_string($element)) {
  2489. if (!$this->elementExists($element)) {
  2490. return array();
  2491. }
  2492. $element = $this->getElement($element);
  2493. }
  2494. if (is_a($element, 'HTML_QuickForm_group')) {
  2495. $elsInGroup = $element->getElements();
  2496. $elNames = array();
  2497. foreach ($elsInGroup as $elInGroup){
  2498. if (is_a($elInGroup, 'HTML_QuickForm_group')) {
  2499. // Groups nested in groups: append the group name to the element and then change it back.
  2500. // We will be appending group name again in MoodleQuickForm_group::export_for_template().
  2501. $oldname = $elInGroup->getName();
  2502. if ($element->_appendName) {
  2503. $elInGroup->setName($element->getName() . '[' . $oldname . ']');
  2504. }
  2505. $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
  2506. $elInGroup->setName($oldname);
  2507. } else {
  2508. $elNames[] = $element->getElementName($elInGroup->getName());
  2509. }
  2510. }
  2511. } else if (is_a($element, 'HTML_QuickForm_header')) {
  2512. return array();
  2513. } else if (is_a($element, 'HTML_QuickForm_hidden')) {
  2514. return array();
  2515. } else if (method_exists($element, 'getPrivateName') &&
  2516. !($element instanceof HTML_QuickForm_advcheckbox)) {
  2517. // The advcheckbox element implements a method called getPrivateName,
  2518. // but in a way that is not compatible with the generic API, so we
  2519. // have to explicitly exclude it.
  2520. return array($element->getPrivateName());
  2521. } else {
  2522. $elNames = array($element->getName());
  2523. }
  2524. return $elNames;
  2525. }
  2526. /**
  2527. * Adds a dependency for $elementName which will be disabled if $condition is met.
  2528. * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
  2529. * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
  2530. * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
  2531. * of the $dependentOn element is $condition (such as equal) to $value.
  2532. *
  2533. * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
  2534. * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
  2535. * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
  2536. *
  2537. * @param string $elementName the name of the element which will be disabled
  2538. * @param string $dependentOn the name of the element whose state will be checked for condition
  2539. * @param string $condition the condition to check
  2540. * @param mixed $value used in conjunction with condition.
  2541. */
  2542. function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
  2543. // Multiple selects allow for a multiple selection, we transform the array to string here as
  2544. // an array cannot be used as a key in an associative array.
  2545. if (is_array($value)) {
  2546. $value = implode('|', $value);
  2547. }
  2548. if (!array_key_exists($dependentOn, $this->_dependencies)) {
  2549. $this->_dependencies[$dependentOn] = array();
  2550. }
  2551. if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
  2552. $this->_dependencies[$dependentOn][$condition] = array();
  2553. }
  2554. if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
  2555. $this->_dependencies[$dependentOn][$condition][$value] = array();
  2556. }
  2557. $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
  2558. }
  2559. /**
  2560. * Adds a dependency for $elementName which will be hidden if $condition is met.
  2561. * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
  2562. * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
  2563. * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
  2564. * of the $dependentOn element is $condition (such as equal) to $value.
  2565. *
  2566. * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
  2567. * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
  2568. * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
  2569. *
  2570. * @param string $elementname the name of the element which will be hidden
  2571. * @param string $dependenton the name of the element whose state will be checked for condition
  2572. * @param string $condition the condition to check
  2573. * @param mixed $value used in conjunction with condition.
  2574. */
  2575. public function hideIf($elementname, $dependenton, $condition = 'notchecked', $value = '1') {
  2576. // Multiple selects allow for a multiple selection, we transform the array to string here as
  2577. // an array cannot be used as a key in an associative array.
  2578. if (is_array($value)) {
  2579. $value = implode('|', $value);
  2580. }
  2581. if (!array_key_exists($dependenton, $this->_hideifs)) {
  2582. $this->_hideifs[$dependenton] = array();
  2583. }
  2584. if (!array_key_exists($condition, $this->_hideifs[$dependenton])) {
  2585. $this->_hideifs[$dependenton][$condition] = array();
  2586. }
  2587. if (!array_key_exists($value, $this->_hideifs[$dependenton][$condition])) {
  2588. $this->_hideifs[$dependenton][$condition][$value] = array();
  2589. }
  2590. $this->_hideifs[$dependenton][$condition][$value][] = $elementname;
  2591. }
  2592. /**
  2593. * Registers button as no submit button
  2594. *
  2595. * @param string $buttonname name of the button
  2596. */
  2597. function registerNoSubmitButton($buttonname){
  2598. $this->_noSubmitButtons[]=$buttonname;
  2599. }
  2600. /**
  2601. * Checks if button is a no submit button, i.e it doesn't submit form
  2602. *
  2603. * @param string $buttonname name of the button to check
  2604. * @return bool
  2605. */
  2606. function isNoSubmitButton($buttonname){
  2607. return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
  2608. }
  2609. /**
  2610. * Registers a button as cancel button
  2611. *
  2612. * @param string $addfieldsname name of the button
  2613. */
  2614. function _registerCancelButton($addfieldsname){
  2615. $this->_cancelButtons[]=$addfieldsname;
  2616. }
  2617. /**
  2618. * Displays elements without HTML input tags.
  2619. * This method is different to freeze() in that it makes sure no hidden
  2620. * elements are included in the form.
  2621. * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
  2622. *
  2623. * This function also removes all previously defined rules.
  2624. *
  2625. * @param string|array $elementList array or string of element(s) to be frozen
  2626. * @return object|bool if element list is not empty then return error object, else true
  2627. */
  2628. function hardFreeze($elementList=null)
  2629. {
  2630. if (!isset($elementList)) {
  2631. $this->_freezeAll = true;
  2632. $elementList = array();
  2633. } else {
  2634. if (!is_array($elementList)) {
  2635. $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
  2636. }
  2637. $elementList = array_flip($elementList);
  2638. }
  2639. foreach (array_keys($this->_elements) as $key) {
  2640. $name = $this->_elements[$key]->getName();
  2641. if ($this->_freezeAll || isset($elementList[$name])) {
  2642. $this->_elements[$key]->freeze();
  2643. $this->_elements[$key]->setPersistantFreeze(false);
  2644. unset($elementList[$name]);
  2645. // remove all rules
  2646. $this->_rules[$name] = array();
  2647. // if field is required, remove the rule
  2648. $unset = array_search($name, $this->_required);
  2649. if ($unset !== false) {
  2650. unset($this->_required[$unset]);
  2651. }
  2652. }
  2653. }
  2654. if (!empty($elementList)) {
  2655. 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);
  2656. }
  2657. return true;
  2658. }
  2659. /**
  2660. * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
  2661. *
  2662. * This function also removes all previously defined rules of elements it freezes.
  2663. *
  2664. * @throws HTML_QuickForm_Error
  2665. * @param array $elementList array or string of element(s) not to be frozen
  2666. * @return bool returns true
  2667. */
  2668. function hardFreezeAllVisibleExcept($elementList)
  2669. {
  2670. $elementList = array_flip($elementList);
  2671. foreach (array_keys($this->_elements) as $key) {
  2672. $name = $this->_elements[$key]->getName();
  2673. $type = $this->_elements[$key]->getType();
  2674. if ($type == 'hidden'){
  2675. // leave hidden types as they are
  2676. } elseif (!isset($elementList[$name])) {
  2677. $this->_elements[$key]->freeze();
  2678. $this->_elements[$key]->setPersistantFreeze(false);
  2679. // remove all rules
  2680. $this->_rules[$name] = array();
  2681. // if field is required, remove the rule
  2682. $unset = array_search($name, $this->_required);
  2683. if ($unset !== false) {
  2684. unset($this->_required[$unset]);
  2685. }
  2686. }
  2687. }
  2688. return true;
  2689. }
  2690. /**
  2691. * Tells whether the form was already submitted
  2692. *
  2693. * This is useful since the _submitFiles and _submitValues arrays
  2694. * may be completely empty after the trackSubmit value is removed.
  2695. *
  2696. * @return bool
  2697. */
  2698. function isSubmitted()
  2699. {
  2700. return parent::isSubmitted() && (!$this->isFrozen());
  2701. }
  2702. /**
  2703. * Add the element name to the list of newly-created repeat elements
  2704. * (So that elements that interpret 'no data submitted' as a valid state
  2705. * can tell when they should get the default value instead).
  2706. *
  2707. * @param string $name the name of the new element
  2708. */
  2709. public function note_new_repeat($name) {
  2710. $this->_newrepeats[] = $name;
  2711. }
  2712. /**
  2713. * Check if the element with the given name has just been added by clicking
  2714. * on the 'Add repeating elements' button.
  2715. *
  2716. * @param string $name the name of the element being checked
  2717. * @return bool true if the element is newly added
  2718. */
  2719. public function is_new_repeat($name) {
  2720. return in_array($name, $this->_newrepeats);
  2721. }
  2722. }
  2723. /**
  2724. * MoodleQuickForm renderer
  2725. *
  2726. * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
  2727. * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
  2728. *
  2729. * Stylesheet is part of standard theme and should be automatically included.
  2730. *
  2731. * @package core_form
  2732. * @copyright 2007 Jamie Pratt <me@jamiep.org>
  2733. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2734. */
  2735. class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
  2736. /** @var array Element template array */
  2737. var $_elementTemplates;
  2738. /**
  2739. * Template used when opening a hidden fieldset
  2740. * (i.e. a fieldset that is opened when there is no header element)
  2741. * @var string
  2742. */
  2743. var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
  2744. /** @var string Header Template string */
  2745. var $_headerTemplate =
  2746. "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
  2747. /** @var string Template used when opening a fieldset */
  2748. var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
  2749. /** @var string Template used when closing a fieldset */
  2750. var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
  2751. /** @var string Required Note template string */
  2752. var $_requiredNoteTemplate =
  2753. "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
  2754. /**
  2755. * Collapsible buttons string template.
  2756. *
  2757. * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
  2758. * until the Javascript has been fully loaded.
  2759. *
  2760. * @var string
  2761. */
  2762. var $_collapseButtonsTemplate =
  2763. "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
  2764. /**
  2765. * Array whose keys are element names. If the key exists this is a advanced element
  2766. *
  2767. * @var array
  2768. */
  2769. var $_advancedElements = array();
  2770. /**
  2771. * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
  2772. *
  2773. * @var array
  2774. */
  2775. var $_collapsibleElements = array();
  2776. /**
  2777. * @var string Contains the collapsible buttons to add to the form.
  2778. */
  2779. var $_collapseButtons = '';
  2780. /**
  2781. * Constructor
  2782. */
  2783. public function __construct() {
  2784. // switch next two lines for ol li containers for form items.
  2785. // $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>');
  2786. $this->_elementTemplates = array(
  2787. '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>',
  2788. '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>',
  2789. '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>',
  2790. '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>',
  2791. 'warning' => "\n\t\t".'<div id="{id}" class="fitem {advanced} {emptylabel} {class}">{element}</div>',
  2792. 'nodisplay' => '');
  2793. parent::__construct();
  2794. }
  2795. /**
  2796. * Old syntax of class constructor. Deprecated in PHP7.
  2797. *
  2798. * @deprecated since Moodle 3.1
  2799. */
  2800. public function MoodleQuickForm_Renderer() {
  2801. debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
  2802. self::__construct();
  2803. }
  2804. /**
  2805. * Set element's as adavance element
  2806. *
  2807. * @param array $elements form elements which needs to be grouped as advance elements.
  2808. */
  2809. function setAdvancedElements($elements){
  2810. $this->_advancedElements = $elements;
  2811. }
  2812. /**
  2813. * Setting collapsible elements
  2814. *
  2815. * @param array $elements
  2816. */
  2817. function setCollapsibleElements($elements) {
  2818. $this->_collapsibleElements = $elements;
  2819. }
  2820. /**
  2821. * What to do when starting the form
  2822. *
  2823. * @param MoodleQuickForm $form reference of the form
  2824. */
  2825. function startForm(&$form){
  2826. global $PAGE;
  2827. $this->_reqHTML = $form->getReqHTML();
  2828. $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
  2829. $this->_advancedHTML = $form->getAdvancedHTML();
  2830. $this->_collapseButtons = '';
  2831. $formid = $form->getAttribute('id');
  2832. parent::startForm($form);
  2833. if ($form->isFrozen()){
  2834. $this->_formTemplate = "\n<div id=\"$formid\" class=\"mform frozen\">\n{collapsebtns}\n{content}\n</div>";
  2835. } else {
  2836. $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
  2837. $this->_hiddenHtml .= $form->_pageparams;
  2838. }
  2839. if ($form->is_form_change_checker_enabled()) {
  2840. $PAGE->requires->js_call_amd('core_form/changechecker', 'watchFormById', [$formid]);
  2841. if ($form->is_dirty()) {
  2842. $PAGE->requires->js_call_amd('core_form/changechecker', 'markFormAsDirtyById', [$formid]);
  2843. }
  2844. }
  2845. if (!empty($this->_collapsibleElements)) {
  2846. if (count($this->_collapsibleElements) > 1) {
  2847. $this->_collapseButtons = $this->_collapseButtonsTemplate;
  2848. $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
  2849. }
  2850. $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
  2851. }
  2852. if (!empty($this->_advancedElements)){
  2853. $PAGE->requires->js_call_amd('core_form/showadvanced', 'init', [$formid]);
  2854. }
  2855. }
  2856. /**
  2857. * Create advance group of elements
  2858. *
  2859. * @param MoodleQuickForm_group $group Passed by reference
  2860. * @param bool $required if input is required field
  2861. * @param string $error error message to display
  2862. */
  2863. function startGroup(&$group, $required, $error){
  2864. global $OUTPUT;
  2865. // Make sure the element has an id.
  2866. $group->_generateId();
  2867. // Prepend 'fgroup_' to the ID we generated.
  2868. $groupid = 'fgroup_' . $group->getAttribute('id');
  2869. // Update the ID.
  2870. $group->updateAttributes(array('id' => $groupid));
  2871. $advanced = isset($this->_advancedElements[$group->getName()]);
  2872. $html = $OUTPUT->mform_element($group, $required, $advanced, $error, false);
  2873. $fromtemplate = !empty($html);
  2874. if (!$fromtemplate) {
  2875. if (method_exists($group, 'getElementTemplateType')) {
  2876. $html = $this->_elementTemplates[$group->getElementTemplateType()];
  2877. } else {
  2878. $html = $this->_elementTemplates['default'];
  2879. }
  2880. if (isset($this->_advancedElements[$group->getName()])) {
  2881. $html = str_replace(' {advanced}', ' advanced', $html);
  2882. $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
  2883. } else {
  2884. $html = str_replace(' {advanced}', '', $html);
  2885. $html = str_replace('{advancedimg}', '', $html);
  2886. }
  2887. if (method_exists($group, 'getHelpButton')) {
  2888. $html = str_replace('{help}', $group->getHelpButton(), $html);
  2889. } else {
  2890. $html = str_replace('{help}', '', $html);
  2891. }
  2892. $html = str_replace('{id}', $group->getAttribute('id'), $html);
  2893. $html = str_replace('{name}', $group->getName(), $html);
  2894. $html = str_replace('{groupname}', 'data-groupname="'.$group->getName().'"', $html);
  2895. $html = str_replace('{typeclass}', 'fgroup', $html);
  2896. $html = str_replace('{type}', 'group', $html);
  2897. $html = str_replace('{class}', $group->getAttribute('class'), $html);
  2898. $emptylabel = '';
  2899. if ($group->getLabel() == '') {
  2900. $emptylabel = 'femptylabel';
  2901. }
  2902. $html = str_replace('{emptylabel}', $emptylabel, $html);
  2903. }
  2904. $this->_templates[$group->getName()] = $html;
  2905. // Fix for bug in tableless quickforms that didn't allow you to stop a
  2906. // fieldset before a group of elements.
  2907. // if the element name indicates the end of a fieldset, close the fieldset
  2908. if (in_array($group->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
  2909. $this->_html .= $this->_closeFieldsetTemplate;
  2910. $this->_fieldsetsOpen--;
  2911. }
  2912. if (!$fromtemplate) {
  2913. parent::startGroup($group, $required, $error);
  2914. } else {
  2915. $this->_html .= $html;
  2916. }
  2917. }
  2918. /**
  2919. * Renders element
  2920. *
  2921. * @param HTML_QuickForm_element $element element
  2922. * @param bool $required if input is required field
  2923. * @param string $error error message to display
  2924. */
  2925. function renderElement(&$element, $required, $error){
  2926. global $OUTPUT;
  2927. // Make sure the element has an id.
  2928. $element->_generateId();
  2929. $advanced = isset($this->_advancedElements[$element->getName()]);
  2930. $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
  2931. $fromtemplate = !empty($html);
  2932. if (!$fromtemplate) {
  2933. // Adding stuff to place holders in template
  2934. // check if this is a group element first.
  2935. if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
  2936. // So it gets substitutions for *each* element.
  2937. $html = $this->_groupElementTemplate;
  2938. } else if (method_exists($element, 'getElementTemplateType')) {
  2939. $html = $this->_elementTemplates[$element->getElementTemplateType()];
  2940. } else {
  2941. $html = $this->_elementTemplates['default'];
  2942. }
  2943. if (isset($this->_advancedElements[$element->getName()])) {
  2944. $html = str_replace(' {advanced}', ' advanced', $html);
  2945. $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
  2946. } else {
  2947. $html = str_replace(' {advanced}', '', $html);
  2948. $html = str_replace(' {aria-live}', '', $html);
  2949. }
  2950. if (isset($this->_advancedElements[$element->getName()]) || $element->getName() == 'mform_showadvanced') {
  2951. $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
  2952. } else {
  2953. $html = str_replace('{advancedimg}', '', $html);
  2954. }
  2955. $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
  2956. $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
  2957. $html = str_replace('{type}', $element->getType(), $html);
  2958. $html = str_replace('{name}', $element->getName(), $html);
  2959. $html = str_replace('{groupname}', '', $html);
  2960. $html = str_replace('{class}', $element->getAttribute('class'), $html);
  2961. $emptylabel = '';
  2962. if ($element->getLabel() == '') {
  2963. $emptylabel = 'femptylabel';
  2964. }
  2965. $html = str_replace('{emptylabel}', $emptylabel, $html);
  2966. if (method_exists($element, 'getHelpButton')) {
  2967. $html = str_replace('{help}', $element->getHelpButton(), $html);
  2968. } else {
  2969. $html = str_replace('{help}', '', $html);
  2970. }
  2971. } else {
  2972. if ($this->_inGroup) {
  2973. $this->_groupElementTemplate = $html;
  2974. }
  2975. }
  2976. if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
  2977. $this->_groupElementTemplate = $html;
  2978. } else if (!isset($this->_templates[$element->getName()])) {
  2979. $this->_templates[$element->getName()] = $html;
  2980. }
  2981. if (!$fromtemplate) {
  2982. parent::renderElement($element, $required, $error);
  2983. } else {
  2984. if (in_array($element->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
  2985. $this->_html .= $this->_closeFieldsetTemplate;
  2986. $this->_fieldsetsOpen--;
  2987. }
  2988. $this->_html .= $html;
  2989. }
  2990. }
  2991. /**
  2992. * Called when visiting a form, after processing all form elements
  2993. * Adds required note, form attributes, validation javascript and form content.
  2994. *
  2995. * @global moodle_page $PAGE
  2996. * @param moodleform $form Passed by reference
  2997. */
  2998. function finishForm(&$form){
  2999. global $PAGE;
  3000. if ($form->isFrozen()){
  3001. $this->_hiddenHtml = '';
  3002. }
  3003. parent::finishForm($form);
  3004. $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
  3005. if (!$form->isFrozen()) {
  3006. $args = $form->getLockOptionObject();
  3007. if (count($args[1]) > 0) {
  3008. $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
  3009. }
  3010. }
  3011. }
  3012. /**
  3013. * Called when visiting a header element
  3014. *
  3015. * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
  3016. * @global moodle_page $PAGE
  3017. */
  3018. function renderHeader(&$header) {
  3019. global $PAGE;
  3020. $header->_generateId();
  3021. $name = $header->getName();
  3022. $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
  3023. if (is_null($header->_text)) {
  3024. $header_html = '';
  3025. } elseif (!empty($name) && isset($this->_templates[$name])) {
  3026. $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
  3027. } else {
  3028. $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
  3029. }
  3030. if ($this->_fieldsetsOpen > 0) {
  3031. $this->_html .= $this->_closeFieldsetTemplate;
  3032. $this->_fieldsetsOpen--;
  3033. }
  3034. // Define collapsible classes for fieldsets.
  3035. $arialive = '';
  3036. $fieldsetclasses = array('clearfix');
  3037. if (isset($this->_collapsibleElements[$header->getName()])) {
  3038. $fieldsetclasses[] = 'collapsible';
  3039. if ($this->_collapsibleElements[$header->getName()]) {
  3040. $fieldsetclasses[] = 'collapsed';
  3041. }
  3042. }
  3043. if (isset($this->_advancedElements[$name])){
  3044. $fieldsetclasses[] = 'containsadvancedelements';
  3045. }
  3046. $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
  3047. $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
  3048. $this->_html .= $openFieldsetTemplate . $header_html;
  3049. $this->_fieldsetsOpen++;
  3050. }
  3051. /**
  3052. * Return Array of element names that indicate the end of a fieldset
  3053. *
  3054. * @return array
  3055. */
  3056. function getStopFieldsetElements(){
  3057. return $this->_stopFieldsetElements;
  3058. }
  3059. }
  3060. /**
  3061. * Required elements validation
  3062. *
  3063. * This class overrides QuickForm validation since it allowed space or empty tag as a value
  3064. *
  3065. * @package core_form
  3066. * @category form
  3067. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  3068. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3069. */
  3070. class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
  3071. /**
  3072. * Checks if an element is not empty.
  3073. * This is a server-side validation, it works for both text fields and editor fields
  3074. *
  3075. * @param string $value Value to check
  3076. * @param int|string|array $options Not used yet
  3077. * @return bool true if value is not empty
  3078. */
  3079. function validate($value, $options = null) {
  3080. global $CFG;
  3081. if (is_array($value) && array_key_exists('text', $value)) {
  3082. $value = $value['text'];
  3083. }
  3084. if (is_array($value)) {
  3085. // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
  3086. $value = implode('', $value);
  3087. }
  3088. $stripvalues = array(
  3089. '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
  3090. '#(\xc2\xa0|\s|&nbsp;)#', // Any whitespaces actually.
  3091. );
  3092. if (!empty($CFG->strictformsrequired)) {
  3093. $value = preg_replace($stripvalues, '', (string)$value);
  3094. }
  3095. if ((string)$value == '') {
  3096. return false;
  3097. }
  3098. return true;
  3099. }
  3100. /**
  3101. * This function returns Javascript code used to build client-side validation.
  3102. * It checks if an element is not empty.
  3103. *
  3104. * @param int $format format of data which needs to be validated.
  3105. * @return array
  3106. */
  3107. function getValidationScript($format = null) {
  3108. global $CFG;
  3109. if (!empty($CFG->strictformsrequired)) {
  3110. if (!empty($format) && $format == FORMAT_HTML) {
  3111. return array('', "{jsVar}.replace(/(<(?!img|hr|canvas)[^>]*>)|&nbsp;|\s+/ig, '') == ''");
  3112. } else {
  3113. return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
  3114. }
  3115. } else {
  3116. return array('', "{jsVar} == ''");
  3117. }
  3118. }
  3119. }
  3120. /**
  3121. * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
  3122. * @name $_HTML_QuickForm_default_renderer
  3123. */
  3124. $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
  3125. /** Please keep this list in alphabetical order. */
  3126. MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
  3127. MoodleQuickForm::registerElementType('autocomplete', "$CFG->libdir/form/autocomplete.php", 'MoodleQuickForm_autocomplete');
  3128. MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
  3129. MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
  3130. MoodleQuickForm::registerElementType('course', "$CFG->libdir/form/course.php", 'MoodleQuickForm_course');
  3131. MoodleQuickForm::registerElementType('cohort', "$CFG->libdir/form/cohort.php", 'MoodleQuickForm_cohort');
  3132. MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
  3133. MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
  3134. MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
  3135. MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
  3136. MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
  3137. MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
  3138. MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
  3139. MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
  3140. MoodleQuickForm::registerElementType('filetypes', "$CFG->libdir/form/filetypes.php", 'MoodleQuickForm_filetypes');
  3141. MoodleQuickForm::registerElementType('float', "$CFG->libdir/form/float.php", 'MoodleQuickForm_float');
  3142. MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
  3143. MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
  3144. MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
  3145. MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
  3146. MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
  3147. MoodleQuickForm::registerElementType('defaultcustom', "$CFG->libdir/form/defaultcustom.php", 'MoodleQuickForm_defaultcustom');
  3148. MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
  3149. MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
  3150. MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
  3151. MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
  3152. MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
  3153. MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
  3154. MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
  3155. MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
  3156. MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
  3157. MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
  3158. MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
  3159. MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
  3160. MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
  3161. MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
  3162. MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
  3163. MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
  3164. MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
  3165. MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
  3166. MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");