PageRenderTime 77ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/formslib.php

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