PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/formslib.php

https://github.com/dongsheng/moodle
PHP | 3490 lines | 2431 code | 220 blank | 839 comment | 296 complexity | 2a4fa2108da35af6da02526955fcfaec MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1

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

  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
  18. *
  19. * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
  20. * and you want to name your class something like {modulename}_{purpose}_form. Your class will
  21. * extend moodleform overriding abstract classes definition and optionally defintion_after_data
  22. * and validation.
  23. *
  24. * See examples of use of this library in course/edit.php and course/edit_form.php
  25. *
  26. * A few notes :
  27. * form definition is used for both printing of form and processing and should be the same
  28. * for both or you may lose some submitted data which won't be let through.
  29. * you should be using setType for every form element except select, radio or checkbox
  30. * elements, these elements clean themselves.
  31. *
  32. * @package core_form
  33. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  34. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35. */
  36. defined('MOODLE_INTERNAL') || die();
  37. /** setup.php includes our hacked pear libs first */
  38. require_once 'HTML/QuickForm.php';
  39. require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
  40. require_once 'HTML/QuickForm/Renderer/Tableless.php';
  41. require_once 'HTML/QuickForm/Rule.php';
  42. require_once $CFG->libdir.'/filelib.php';
  43. /**
  44. * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
  45. */
  46. define('EDITOR_UNLIMITED_FILES', -1);
  47. /**
  48. * Callback called when PEAR throws an error
  49. *
  50. * @param PEAR_Error $error
  51. */
  52. function pear_handle_error($error){
  53. echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
  54. echo '<br /> <strong>Backtrace </strong>:';
  55. print_object($error->backtrace);
  56. }
  57. if ($CFG->debugdeveloper) {
  58. //TODO: this is a wrong place to init PEAR!
  59. $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
  60. $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
  61. }
  62. /**
  63. * Initalize javascript for date type form element
  64. *
  65. * @staticvar bool $done make sure it gets initalize once.
  66. * @global moodle_page $PAGE
  67. */
  68. function form_init_date_js() {
  69. global $PAGE;
  70. static $done = false;
  71. if (!$done) {
  72. $done = true;
  73. $calendar = \core_calendar\type_factory::get_calendar_instance();
  74. if ($calendar->get_name() !== 'gregorian') {
  75. // The YUI2 calendar only supports the gregorian calendar type.
  76. return;
  77. }
  78. $module = 'moodle-form-dateselector';
  79. $function = 'M.form.dateselector.init_date_selectors';
  80. $defaulttimezone = date_default_timezone_get();
  81. $config = array(array(
  82. 'firstdayofweek' => $calendar->get_starting_weekday(),
  83. 'mon' => date_format_string(strtotime("Monday"), '%a', $defaulttimezone),
  84. 'tue' => date_format_string(strtotime("Tuesday"), '%a', $defaulttimezone),
  85. 'wed' => date_format_string(strtotime("Wednesday"), '%a', $defaulttimezone),
  86. 'thu' => date_format_string(strtotime("Thursday"), '%a', $defaulttimezone),
  87. 'fri' => date_format_string(strtotime("Friday"), '%a', $defaulttimezone),
  88. 'sat' => date_format_string(strtotime("Saturday"), '%a', $defaulttimezone),
  89. 'sun' => date_format_string(strtotime("Sunday"), '%a', $defaulttimezone),
  90. 'january' => date_format_string(strtotime("January 1"), '%B', $defaulttimezone),
  91. 'february' => date_format_string(strtotime("February 1"), '%B', $defaulttimezone),
  92. 'march' => date_format_string(strtotime("March 1"), '%B', $defaulttimezone),
  93. 'april' => date_format_string(strtotime("April 1"), '%B', $defaulttimezone),
  94. 'may' => date_format_string(strtotime("May 1"), '%B', $defaulttimezone),
  95. 'june' => date_format_string(strtotime("June 1"), '%B', $defaulttimezone),
  96. 'july' => date_format_string(strtotime("July 1"), '%B', $defaulttimezone),
  97. 'august' => date_format_string(strtotime("August 1"), '%B', $defaulttimezone),
  98. 'september' => date_format_string(strtotime("September 1"), '%B', $defaulttimezone),
  99. 'october' => date_format_string(strtotime("October 1"), '%B', $defaulttimezone),
  100. 'november' => date_format_string(strtotime("November 1"), '%B', $defaulttimezone),
  101. 'december' => date_format_string(strtotime("December 1"), '%B', $defaulttimezone)
  102. ));
  103. $PAGE->requires->yui_module($module, $function, $config);
  104. }
  105. }
  106. /**
  107. * Wrapper that separates quickforms syntax from moodle code
  108. *
  109. * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
  110. * use this class you should write a class definition which extends this class or a more specific
  111. * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
  112. *
  113. * You will write your own definition() method which performs the form set up.
  114. *
  115. * @package core_form
  116. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  117. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  118. * @todo MDL-19380 rethink the file scanning
  119. */
  120. abstract class moodleform {
  121. /** @var string name of the form */
  122. protected $_formname; // form name
  123. /** @var MoodleQuickForm quickform object definition */
  124. protected $_form;
  125. /** @var array globals workaround */
  126. protected $_customdata;
  127. /** @var array submitted form data when using mforms with ajax */
  128. protected $_ajaxformdata;
  129. /** @var object definition_after_data executed flag */
  130. protected $_definition_finalized = false;
  131. /** @var bool|null stores the validation result of this form or null if not yet validated */
  132. protected $_validated = null;
  133. /**
  134. * The constructor function calls the abstract function definition() and it will then
  135. * process and clean and attempt to validate incoming data.
  136. *
  137. * It will call your custom validate method to validate data and will also check any rules
  138. * you have specified in definition using addRule
  139. *
  140. * The name of the form (id attribute of the form) is automatically generated depending on
  141. * the name you gave the class extending moodleform. You should call your class something
  142. * like
  143. *
  144. * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
  145. * current url. If a moodle_url object then outputs params as hidden variables.
  146. * @param mixed $customdata if your form defintion method needs access to data such as $course
  147. * $cm, etc. to construct the form definition then pass it in this array. You can
  148. * use globals for somethings.
  149. * @param string $method if you set this to anything other than 'post' then _GET and _POST will
  150. * be merged and used as incoming data to the form.
  151. * @param string $target target frame for form submission. You will rarely use this. Don't use
  152. * it if you don't need to as the target attribute is deprecated in xhtml strict.
  153. * @param mixed $attributes you can pass a string of html attributes here or an array.
  154. * Special attribute 'data-random-ids' will randomise generated elements ids. This
  155. * is necessary when there are several forms on the same page.
  156. * Special attribute 'data-double-submit-protection' set to 'off' will turn off
  157. * double-submit protection JavaScript - this may be necessary if your form sends
  158. * downloadable files in response to a submit button, and can't call
  159. * \core_form\util::form_download_complete();
  160. * @param bool $editable
  161. * @param array $ajaxformdata Forms submitted via ajax, must pass their data here, instead of relying on _GET and _POST.
  162. */
  163. public function __construct($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true,
  164. $ajaxformdata=null) {
  165. global $CFG, $FULLME;
  166. // no standard mform in moodle should allow autocomplete with the exception of user signup
  167. if (empty($attributes)) {
  168. $attributes = array('autocomplete'=>'off');
  169. } else if (is_array($attributes)) {
  170. $attributes['autocomplete'] = 'off';
  171. } else {
  172. if (strpos($attributes, 'autocomplete') === false) {
  173. $attributes .= ' autocomplete="off" ';
  174. }
  175. }
  176. if (empty($action)){
  177. // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
  178. $action = strip_querystring($FULLME);
  179. if (!empty($CFG->sslproxy)) {
  180. // return only https links when using SSL proxy
  181. $action = preg_replace('/^http:/', 'https:', $action, 1);
  182. }
  183. //TODO: use following instead of FULLME - see MDL-33015
  184. //$action = strip_querystring(qualified_me());
  185. }
  186. // Assign custom data first, so that get_form_identifier can use it.
  187. $this->_customdata = $customdata;
  188. $this->_formname = $this->get_form_identifier();
  189. $this->_ajaxformdata = $ajaxformdata;
  190. $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes, $ajaxformdata);
  191. if (!$editable){
  192. $this->_form->hardFreeze();
  193. }
  194. $this->definition();
  195. $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
  196. $this->_form->setType('sesskey', PARAM_RAW);
  197. $this->_form->setDefault('sesskey', sesskey());
  198. $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
  199. $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
  200. $this->_form->setDefault('_qf__'.$this->_formname, 1);
  201. $this->_form->_setDefaultRuleMessages();
  202. // Hook to inject logic after the definition was provided.
  203. $this->after_definition();
  204. // we have to know all input types before processing submission ;-)
  205. $this->_process_submission($method);
  206. }
  207. /**
  208. * Old syntax of class constructor. Deprecated in PHP7.
  209. *
  210. * @deprecated since Moodle 3.1
  211. */
  212. public function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
  213. debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
  214. self::__construct($action, $customdata, $method, $target, $attributes, $editable);
  215. }
  216. /**
  217. * It should returns unique identifier for the form.
  218. * Currently it will return class name, but in case two same forms have to be
  219. * rendered on same page then override function to get unique form identifier.
  220. * e.g This is used on multiple self enrollments page.
  221. *
  222. * @return string form identifier.
  223. */
  224. protected function get_form_identifier() {
  225. $class = get_class($this);
  226. return preg_replace('/[^a-z0-9_]/i', '_', $class);
  227. }
  228. /**
  229. * To autofocus on first form element or first element with error.
  230. *
  231. * @param string $name if this is set then the focus is forced to a field with this name
  232. * @return string javascript to select form element with first error or
  233. * first element if no errors. Use this as a parameter
  234. * when calling print_header
  235. */
  236. function focus($name=NULL) {
  237. $form =& $this->_form;
  238. $elkeys = array_keys($form->_elementIndex);
  239. $error = false;
  240. if (isset($form->_errors) && 0 != count($form->_errors)){
  241. $errorkeys = array_keys($form->_errors);
  242. $elkeys = array_intersect($elkeys, $errorkeys);
  243. $error = true;
  244. }
  245. if ($error or empty($name)) {
  246. $names = array();
  247. while (empty($names) and !empty($elkeys)) {
  248. $el = array_shift($elkeys);
  249. $names = $form->_getElNamesRecursive($el);
  250. }
  251. if (!empty($names)) {
  252. $name = array_shift($names);
  253. }
  254. }
  255. $focus = '';
  256. if (!empty($name)) {
  257. $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
  258. }
  259. return $focus;
  260. }
  261. /**
  262. * Internal method. Alters submitted data to be suitable for quickforms processing.
  263. * Must be called when the form is fully set up.
  264. *
  265. * @param string $method name of the method which alters submitted data
  266. */
  267. function _process_submission($method) {
  268. $submission = array();
  269. if (!empty($this->_ajaxformdata)) {
  270. $submission = $this->_ajaxformdata;
  271. } else if ($method == 'post') {
  272. if (!empty($_POST)) {
  273. $submission = $_POST;
  274. }
  275. } else {
  276. $submission = $_GET;
  277. merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
  278. }
  279. // following trick is needed to enable proper sesskey checks when using GET forms
  280. // the _qf__.$this->_formname serves as a marker that form was actually submitted
  281. if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
  282. if (!confirm_sesskey()) {
  283. print_error('invalidsesskey');
  284. }
  285. $files = $_FILES;
  286. } else {
  287. $submission = array();
  288. $files = array();
  289. }
  290. $this->detectMissingSetType();
  291. $this->_form->updateSubmission($submission, $files);
  292. }
  293. /**
  294. * Internal method - should not be used anywhere.
  295. * @deprecated since 2.6
  296. * @return array $_POST.
  297. */
  298. protected function _get_post_params() {
  299. return $_POST;
  300. }
  301. /**
  302. * Internal method. Validates all old-style deprecated uploaded files.
  303. * The new way is to upload files via repository api.
  304. *
  305. * @param array $files list of files to be validated
  306. * @return bool|array Success or an array of errors
  307. */
  308. function _validate_files(&$files) {
  309. global $CFG, $COURSE;
  310. $files = array();
  311. if (empty($_FILES)) {
  312. // we do not need to do any checks because no files were submitted
  313. // note: server side rules do not work for files - use custom verification in validate() instead
  314. return true;
  315. }
  316. $errors = array();
  317. $filenames = array();
  318. // now check that we really want each file
  319. foreach ($_FILES as $elname=>$file) {
  320. $required = $this->_form->isElementRequired($elname);
  321. if ($file['error'] == 4 and $file['size'] == 0) {
  322. if ($required) {
  323. $errors[$elname] = get_string('required');
  324. }
  325. unset($_FILES[$elname]);
  326. continue;
  327. }
  328. if (!empty($file['error'])) {
  329. $errors[$elname] = file_get_upload_error($file['error']);
  330. unset($_FILES[$elname]);
  331. continue;
  332. }
  333. if (!is_uploaded_file($file['tmp_name'])) {
  334. // TODO: improve error message
  335. $errors[$elname] = get_string('error');
  336. unset($_FILES[$elname]);
  337. continue;
  338. }
  339. if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
  340. // hmm, this file was not requested
  341. unset($_FILES[$elname]);
  342. continue;
  343. }
  344. // NOTE: the viruses are scanned in file picker, no need to deal with them here.
  345. $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
  346. if ($filename === '') {
  347. // TODO: improve error message - wrong chars
  348. $errors[$elname] = get_string('error');
  349. unset($_FILES[$elname]);
  350. continue;
  351. }
  352. if (in_array($filename, $filenames)) {
  353. // TODO: improve error message - duplicate name
  354. $errors[$elname] = get_string('error');
  355. unset($_FILES[$elname]);
  356. continue;
  357. }
  358. $filenames[] = $filename;
  359. $_FILES[$elname]['name'] = $filename;
  360. $files[$elname] = $_FILES[$elname]['tmp_name'];
  361. }
  362. // return errors if found
  363. if (count($errors) == 0){
  364. return true;
  365. } else {
  366. $files = array();
  367. return $errors;
  368. }
  369. }
  370. /**
  371. * Internal method. Validates filepicker and filemanager files if they are
  372. * set as required fields. Also, sets the error message if encountered one.
  373. *
  374. * @return bool|array with errors
  375. */
  376. protected function validate_draft_files() {
  377. global $USER;
  378. $mform =& $this->_form;
  379. $errors = array();
  380. //Go through all the required elements and make sure you hit filepicker or
  381. //filemanager element.
  382. foreach ($mform->_rules as $elementname => $rules) {
  383. $elementtype = $mform->getElementType($elementname);
  384. //If element is of type filepicker then do validation
  385. if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
  386. //Check if rule defined is required rule
  387. foreach ($rules as $rule) {
  388. if ($rule['type'] == 'required') {
  389. $draftid = (int)$mform->getSubmitValue($elementname);
  390. $fs = get_file_storage();
  391. $context = context_user::instance($USER->id);
  392. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  393. $errors[$elementname] = $rule['message'];
  394. }
  395. }
  396. }
  397. }
  398. }
  399. // Check all the filemanager elements to make sure they do not have too many
  400. // files in them.
  401. foreach ($mform->_elements as $element) {
  402. if ($element->_type == 'filemanager') {
  403. $maxfiles = $element->getMaxfiles();
  404. if ($maxfiles > 0) {
  405. $draftid = (int)$element->getValue();
  406. $fs = get_file_storage();
  407. $context = context_user::instance($USER->id);
  408. $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
  409. if (count($files) > $maxfiles) {
  410. $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
  411. }
  412. }
  413. }
  414. }
  415. if (empty($errors)) {
  416. return true;
  417. } else {
  418. return $errors;
  419. }
  420. }
  421. /**
  422. * Load in existing data as form defaults. Usually new entry defaults are stored directly in
  423. * form definition (new entry form); this function is used to load in data where values
  424. * already exist and data is being edited (edit entry form).
  425. *
  426. * note: $slashed param removed
  427. *
  428. * @param stdClass|array $default_values object or array of default values
  429. */
  430. function set_data($default_values) {
  431. if (is_object($default_values)) {
  432. $default_values = (array)$default_values;
  433. }
  434. $this->_form->setDefaults($default_values);
  435. }
  436. /**
  437. * Check that form was submitted. Does not check validity of submitted data.
  438. *
  439. * @return bool true if form properly submitted
  440. */
  441. function is_submitted() {
  442. return $this->_form->isSubmitted();
  443. }
  444. /**
  445. * Checks if button pressed is not for submitting the form
  446. *
  447. * @staticvar bool $nosubmit keeps track of no submit button
  448. * @return bool
  449. */
  450. function no_submit_button_pressed(){
  451. static $nosubmit = null; // one check is enough
  452. if (!is_null($nosubmit)){
  453. return $nosubmit;
  454. }
  455. $mform =& $this->_form;
  456. $nosubmit = false;
  457. if (!$this->is_submitted()){
  458. return false;
  459. }
  460. foreach ($mform->_noSubmitButtons as $nosubmitbutton){
  461. if ($this->optional_param($nosubmitbutton, 0, PARAM_RAW)) {
  462. $nosubmit = true;
  463. break;
  464. }
  465. }
  466. return $nosubmit;
  467. }
  468. /**
  469. * Returns an element of multi-dimensional array given the list of keys
  470. *
  471. * Example:
  472. * $array['a']['b']['c'] = 13;
  473. * $v = $this->get_array_value_by_keys($array, ['a', 'b', 'c']);
  474. *
  475. * Will result it $v==13
  476. *
  477. * @param array $array
  478. * @param array $keys
  479. * @return mixed returns null if keys not present
  480. */
  481. protected function get_array_value_by_keys(array $array, array $keys) {
  482. $value = $array;
  483. foreach ($keys as $key) {
  484. if (array_key_exists($key, $value)) {
  485. $value = $value[$key];
  486. } else {
  487. return null;
  488. }
  489. }
  490. return $value;
  491. }
  492. /**
  493. * Checks if a parameter was passed in the previous form submission
  494. *
  495. * @param string $name the name of the page parameter we want, for example 'id' or 'element[sub][13]'
  496. * @param mixed $default the default value to return if nothing is found
  497. * @param string $type expected type of parameter
  498. * @return mixed
  499. */
  500. public function optional_param($name, $default, $type) {
  501. $nameparsed = [];
  502. // Convert element name into a sequence of keys, for example 'element[sub][13]' -> ['element', 'sub', '13'].
  503. parse_str($name . '=1', $nameparsed);
  504. $keys = [];
  505. while (is_array($nameparsed)) {
  506. $key = key($nameparsed);
  507. $keys[] = $key;
  508. $nameparsed = $nameparsed[$key];
  509. }
  510. // Search for the element first in $this->_ajaxformdata, then in $_POST and then in $_GET.
  511. if (($value = $this->get_array_value_by_keys($this->_ajaxformdata ?? [], $keys)) !== null ||
  512. ($value = $this->get_array_value_by_keys($_POST, $keys)) !== null ||
  513. ($value = $this->get_array_value_by_keys($_GET, $keys)) !== null) {
  514. return $type == PARAM_RAW ? $value : clean_param($value, $type);
  515. }
  516. return $default;
  517. }
  518. /**
  519. * Check that form data is valid.
  520. * You should almost always use this, rather than {@link validate_defined_fields}
  521. *
  522. * @return bool true if form data valid
  523. */
  524. function is_validated() {
  525. //finalize the form definition before any processing
  526. if (!$this->_definition_finalized) {
  527. $this->_definition_finalized = true;
  528. $this->definition_after_data();
  529. }
  530. return $this->validate_defined_fields();
  531. }
  532. /**
  533. * Validate the form.
  534. *
  535. * You almost always want to call {@link is_validated} instead of this
  536. * because it calls {@link definition_after_data} first, before validating the form,
  537. * which is what you want in 99% of cases.
  538. *
  539. * This is provided as a separate function for those special cases where
  540. * you want the form validated before definition_after_data is called
  541. * for example, to selectively add new elements depending on a no_submit_button press,
  542. * but only when the form is valid when the no_submit_button is pressed,
  543. *
  544. * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
  545. * is NOT to validate the form when a no submit button has been pressed.
  546. * pass true here to override this behaviour
  547. *
  548. * @return bool true if form data valid
  549. */
  550. function validate_defined_fields($validateonnosubmit=false) {
  551. $mform =& $this->_form;
  552. if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
  553. return false;
  554. } elseif ($this->_validated === null) {
  555. $internal_val = $mform->validate();
  556. $files = array();
  557. $file_val = $this->_validate_files($files);
  558. //check draft files for validation and flag them if required files
  559. //are not in draft area.
  560. $draftfilevalue = $this->validate_draft_files();
  561. if ($file_val !== true && $draftfilevalue !== true) {
  562. $file_val = array_merge($file_val, $draftfilevalue);
  563. } else if ($draftfilevalue !== true) {
  564. $file_val = $draftfilevalue;
  565. } //default is file_val, so no need to assign.
  566. if ($file_val !== true) {
  567. if (!empty($file_val)) {
  568. foreach ($file_val as $element=>$msg) {
  569. $mform->setElementError($element, $msg);
  570. }
  571. }
  572. $file_val = false;
  573. }
  574. // Give the elements a chance to perform an implicit validation.
  575. $element_val = true;
  576. foreach ($mform->_elements as $element) {
  577. if (method_exists($element, 'validateSubmitValue')) {
  578. $value = $mform->getSubmitValue($element->getName());
  579. $result = $element->validateSubmitValue($value);
  580. if (!empty($result) && is_string($result)) {
  581. $element_val = false;
  582. $mform->setElementError($element->getName(), $result);
  583. }
  584. }
  585. }
  586. // Let the form instance validate the submitted values.
  587. $data = $mform->exportValues();
  588. $moodle_val = $this->validation($data, $files);
  589. if ((is_array($moodle_val) && count($moodle_val)!==0)) {
  590. // non-empty array means errors
  591. foreach ($moodle_val as $element=>$msg) {
  592. $mform->setElementError($element, $msg);
  593. }
  594. $moodle_val = false;
  595. } else {
  596. // anything else means validation ok
  597. $moodle_val = true;
  598. }
  599. $this->_validated = ($internal_val and $element_val and $moodle_val and $file_val);
  600. }
  601. return $this->_validated;
  602. }
  603. /**
  604. * Return true if a cancel button has been pressed resulting in the form being submitted.
  605. *
  606. * @return bool true if a cancel button has been pressed
  607. */
  608. function is_cancelled(){
  609. $mform =& $this->_form;
  610. if ($mform->isSubmitted()){
  611. foreach ($mform->_cancelButtons as $cancelbutton){
  612. if ($this->optional_param($cancelbutton, 0, PARAM_RAW)) {
  613. return true;
  614. }
  615. }
  616. }
  617. return false;
  618. }
  619. /**
  620. * Return submitted data if properly submitted or returns NULL if validation fails or
  621. * if there is no submitted data.
  622. *
  623. * note: $slashed param removed
  624. *
  625. * @return object submitted data; NULL if not valid or not submitted or cancelled
  626. */
  627. function get_data() {
  628. $mform =& $this->_form;
  629. if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
  630. $data = $mform->exportValues();
  631. unset($data['sesskey']); // we do not need to return sesskey
  632. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  633. if (empty($data)) {
  634. return NULL;
  635. } else {
  636. return (object)$data;
  637. }
  638. } else {
  639. return NULL;
  640. }
  641. }
  642. /**
  643. * Return submitted data without validation or NULL if there is no submitted data.
  644. * note: $slashed param removed
  645. *
  646. * @return object submitted data; NULL if not submitted
  647. */
  648. function get_submitted_data() {
  649. $mform =& $this->_form;
  650. if ($this->is_submitted()) {
  651. $data = $mform->exportValues();
  652. unset($data['sesskey']); // we do not need to return sesskey
  653. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  654. if (empty($data)) {
  655. return NULL;
  656. } else {
  657. return (object)$data;
  658. }
  659. } else {
  660. return NULL;
  661. }
  662. }
  663. /**
  664. * Save verified uploaded files into directory. Upload process can be customised from definition()
  665. *
  666. * @deprecated since Moodle 2.0
  667. * @todo MDL-31294 remove this api
  668. * @see moodleform::save_stored_file()
  669. * @see moodleform::save_file()
  670. * @param string $destination path where file should be stored
  671. * @return bool Always false
  672. */
  673. function save_files($destination) {
  674. debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
  675. return false;
  676. }
  677. /**
  678. * Returns name of uploaded file.
  679. *
  680. * @param string $elname first element if null
  681. * @return string|bool false in case of failure, string if ok
  682. */
  683. function get_new_filename($elname=null) {
  684. global $USER;
  685. if (!$this->is_submitted() or !$this->is_validated()) {
  686. return false;
  687. }
  688. if (is_null($elname)) {
  689. if (empty($_FILES)) {
  690. return false;
  691. }
  692. reset($_FILES);
  693. $elname = key($_FILES);
  694. }
  695. if (empty($elname)) {
  696. return false;
  697. }
  698. $element = $this->_form->getElement($elname);
  699. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  700. $values = $this->_form->exportValues($elname);
  701. if (empty($values[$elname])) {
  702. return false;
  703. }
  704. $draftid = $values[$elname];
  705. $fs = get_file_storage();
  706. $context = context_user::instance($USER->id);
  707. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  708. return false;
  709. }
  710. $file = reset($files);
  711. return $file->get_filename();
  712. }
  713. if (!isset($_FILES[$elname])) {
  714. return false;
  715. }
  716. return $_FILES[$elname]['name'];
  717. }
  718. /**
  719. * Save file to standard filesystem
  720. *
  721. * @param string $elname name of element
  722. * @param string $pathname full path name of file
  723. * @param bool $override override file if exists
  724. * @return bool success
  725. */
  726. function save_file($elname, $pathname, $override=false) {
  727. global $USER;
  728. if (!$this->is_submitted() or !$this->is_validated()) {
  729. return false;
  730. }
  731. if (file_exists($pathname)) {
  732. if ($override) {
  733. if (!@unlink($pathname)) {
  734. return false;
  735. }
  736. } else {
  737. return false;
  738. }
  739. }
  740. $element = $this->_form->getElement($elname);
  741. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  742. $values = $this->_form->exportValues($elname);
  743. if (empty($values[$elname])) {
  744. return false;
  745. }
  746. $draftid = $values[$elname];
  747. $fs = get_file_storage();
  748. $context = context_user::instance($USER->id);
  749. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  750. return false;
  751. }
  752. $file = reset($files);
  753. return $file->copy_content_to($pathname);
  754. } else if (isset($_FILES[$elname])) {
  755. return copy($_FILES[$elname]['tmp_name'], $pathname);
  756. }
  757. return false;
  758. }
  759. /**
  760. * Returns a temporary file, do not forget to delete after not needed any more.
  761. *
  762. * @param string $elname name of the elmenet
  763. * @return string|bool either string or false
  764. */
  765. function save_temp_file($elname) {
  766. if (!$this->get_new_filename($elname)) {
  767. return false;
  768. }
  769. if (!$dir = make_temp_directory('forms')) {
  770. return false;
  771. }
  772. if (!$tempfile = tempnam($dir, 'tempup_')) {
  773. return false;
  774. }
  775. if (!$this->save_file($elname, $tempfile, true)) {
  776. // something went wrong
  777. @unlink($tempfile);
  778. return false;
  779. }
  780. return $tempfile;
  781. }
  782. /**
  783. * Get draft files of a form element
  784. * This is a protected method which will be used only inside moodleforms
  785. *
  786. * @param string $elname name of element
  787. * @return array|bool|null
  788. */
  789. protected function get_draft_files($elname) {
  790. global $USER;
  791. if (!$this->is_submitted()) {
  792. return false;
  793. }
  794. $element = $this->_form->getElement($elname);
  795. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  796. $values = $this->_form->exportValues($elname);
  797. if (empty($values[$elname])) {
  798. return false;
  799. }
  800. $draftid = $values[$elname];
  801. $fs = get_file_storage();
  802. $context = context_user::instance($USER->id);
  803. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  804. return null;
  805. }
  806. return $files;
  807. }
  808. return null;
  809. }
  810. /**
  811. * Save file to local filesystem pool
  812. *
  813. * @param string $elname name of element
  814. * @param int $newcontextid id of context
  815. * @param string $newcomponent name of the component
  816. * @param string $newfilearea name of file area
  817. * @param int $newitemid item id
  818. * @param string $newfilepath path of file where it get stored
  819. * @param string $newfilename use specified filename, if not specified name of uploaded file used
  820. * @param bool $overwrite overwrite file if exists
  821. * @param int $newuserid new userid if required
  822. * @return mixed stored_file object or false if error; may throw exception if duplicate found
  823. */
  824. function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
  825. $newfilename=null, $overwrite=false, $newuserid=null) {
  826. global $USER;
  827. if (!$this->is_submitted() or !$this->is_validated()) {
  828. return false;
  829. }
  830. if (empty($newuserid)) {
  831. $newuserid = $USER->id;
  832. }
  833. $element = $this->_form->getElement($elname);
  834. $fs = get_file_storage();
  835. if ($element instanceof MoodleQuickForm_filepicker) {
  836. $values = $this->_form->exportValues($elname);
  837. if (empty($values[$elname])) {
  838. return false;
  839. }
  840. $draftid = $values[$elname];
  841. $context = context_user::instance($USER->id);
  842. if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
  843. return false;
  844. }
  845. $file = reset($files);
  846. if (is_null($newfilename)) {
  847. $newfilename = $file->get_filename();
  848. }
  849. if ($overwrite) {
  850. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  851. if (!$oldfile->delete()) {
  852. return false;
  853. }
  854. }
  855. }
  856. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  857. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  858. return $fs->create_file_from_storedfile($file_record, $file);
  859. } else if (isset($_FILES[$elname])) {
  860. $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
  861. if ($overwrite) {
  862. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  863. if (!$oldfile->delete()) {
  864. return false;
  865. }
  866. }
  867. }
  868. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  869. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  870. return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
  871. }
  872. return false;
  873. }
  874. /**
  875. * Get content of uploaded file.
  876. *
  877. * @param string $elname name of file upload element
  878. * @return string|bool false in case of failure, string if ok
  879. */
  880. function get_file_content($elname) {
  881. global $USER;
  882. if (!$this->is_submitted() or !$this->is_validated()) {
  883. return false;
  884. }
  885. $element = $this->_form->getElement($elname);
  886. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  887. $values = $this->_form->exportValues($elname);
  888. if (empty($values[$elname])) {
  889. return false;
  890. }
  891. $draftid = $values[$elname];
  892. $fs = get_file_storage();
  893. $context = context_user::instance($USER->id);
  894. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  895. return false;
  896. }
  897. $file = reset($files);
  898. return $file->get_content();
  899. } else if (isset($_FILES[$elname])) {
  900. return file_get_contents($_FILES[$elname]['tmp_name']);
  901. }
  902. return false;
  903. }
  904. /**
  905. * Print html form.
  906. */
  907. function display() {
  908. //finalize the form definition if not yet done
  909. if (!$this->_definition_finalized) {
  910. $this->_definition_finalized = true;
  911. $this->definition_after_data();
  912. }
  913. $this->_form->display();
  914. }
  915. /**
  916. * Renders the html form (same as display, but returns the result).
  917. *
  918. * Note that you can only output this rendered result once per page, as
  919. * it contains IDs which must be unique.
  920. *
  921. * @return string HTML code for the form
  922. */
  923. public function render() {
  924. ob_start();
  925. $this->display();
  926. $out = ob_get_contents();
  927. ob_end_clean();
  928. return $out;
  929. }
  930. /**
  931. * Form definition. Abstract method - always override!
  932. */
  933. protected abstract function definition();
  934. /**
  935. * After definition hook.
  936. *
  937. * This is useful for intermediate classes to inject logic after the definition was
  938. * provided without requiring developers to call the parent {{@link self::definition()}}
  939. * as it's not obvious by design. The 'intermediate' class is 'MyClass extends
  940. * IntermediateClass extends moodleform'.
  941. *
  942. * Classes overriding this method should always call the parent. We may not add
  943. * anything specifically in this instance of the method, but intermediate classes
  944. * are likely to do so, and so it is a good practice to always call the parent.
  945. *
  946. * @return void
  947. */
  948. protected function after_definition() {
  949. }
  950. /**
  951. * Dummy stub method - override if you need to setup the form depending on current
  952. * values. This method is called after definition(), data submission and set_data().
  953. * All form setup that is dependent on form values should go in here.
  954. */
  955. function definition_after_data(){
  956. }
  957. /**
  958. * Dummy stub method - override if you needed to perform some extra validation.
  959. * If there are errors return array of errors ("fieldname"=>"error message"),
  960. * otherwise true if ok.
  961. *
  962. * Server side rules do not work for uploaded files, implement serverside rules here if needed.
  963. *
  964. * @param array $data array of ("fieldname"=>value) of submitted data
  965. * @param array $files array of uploaded files "element_name"=>tmp_file_path
  966. * @return array of "element_name"=>"error_description" if there are errors,
  967. * or an empty array if everything is OK (true allowed for backwards compatibility too).
  968. */
  969. function validation($data, $files) {
  970. return array();
  971. }
  972. /**
  973. * Helper used by {@link repeat_elements()}.
  974. *
  975. * @param int $i the index of this element.
  976. * @param HTML_QuickForm_element $elementclone
  977. * @param array $namecloned array of names
  978. */
  979. function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
  980. $name = $elementclone->getName();
  981. $namecloned[] = $name;
  982. if (!empty($name)) {
  983. $elementclone->setName($name."[$i]");
  984. }
  985. if (is_a($elementclone, 'HTML_QuickForm_header')) {
  986. $value = $elementclone->_text;
  987. $elementclone->setValue(str_replace('{no}', ($i+1), $value));
  988. } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
  989. $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
  990. } else {
  991. $value=$elementclone->getLabel();
  992. $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
  993. }
  994. }
  995. /**
  996. * Method to add a repeating group of elements to a form.
  997. *
  998. * @param array $elementobjs Array of elements or groups of elements that are to be repeated
  999. * @param int $repeats no of times to repeat elements initially
  1000. * @param array $options a nested array. The first array key is the element name.
  1001. * the second array key is the type of option to set, and depend on that option,
  1002. * the value takes different forms.
  1003. * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
  1004. * 'type' - PARAM_* type.
  1005. * 'helpbutton' - array containing the helpbutton params.
  1006. * 'disabledif' - array containing the disabledIf() arguments after the element name.
  1007. * 'rule' - array containing the addRule arguments after the element name.
  1008. * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
  1009. * 'advanced' - whether this element is hidden by 'Show more ...'.
  1010. * @param string $repeathiddenname name for hidden element storing no of repeats in this form
  1011. * @param string $addfieldsname name for button to add more fields
  1012. * @param int $addfieldsno how many fields to add at a time
  1013. * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
  1014. * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
  1015. * @param string $deletebuttonname if specified, treats the no-submit button with this name as a "delete element" button
  1016. * in each of the elements
  1017. * @return int no of repeats of element in this page
  1018. */
  1019. public function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
  1020. $addfieldsname, $addfieldsno = 5, $addstring = null, $addbuttoninside = false,
  1021. $deletebuttonname = '') {
  1022. if ($addstring === null) {
  1023. $addstring = get_string('addfields', 'form', $addfieldsno);
  1024. } else {
  1025. $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
  1026. }
  1027. $repeats = $this->optional_param($repeathiddenname, $repeats, PARAM_INT);
  1028. $addfields = $this->optional_param($addfieldsname, '', PARAM_TEXT);
  1029. $oldrepeats = $repeats;
  1030. if (!empty($addfields)){
  1031. $repeats += $addfieldsno;
  1032. }
  1033. $mform =& $this->_form;
  1034. $mform->registerNoSubmitButton($addfieldsname);
  1035. $mform->addElement('hidden', $repeathiddenname, $repeats);
  1036. $mform->setType($repeathiddenname, PARAM_INT);
  1037. //value not to be overridden by submitted value
  1038. $mform->setConstants(array($repeathiddenname=>$repeats));
  1039. $namecloned = array();
  1040. $no = 1;
  1041. for ($i = 0; $i < $repeats; $i++) {
  1042. if ($deletebuttonname) {
  1043. $mform->registerNoSubmitButton($deletebuttonname . "[$i]");
  1044. $isdeleted = $this->optional_param($deletebuttonname . "[$i]", false, PARAM_RAW) ||
  1045. $this->optional_param($deletebuttonname . "-hidden[$i]", false, PARAM_RAW);
  1046. if ($isdeleted) {
  1047. $mform->addElement('hidden', $deletebuttonname . "-hidden[$i]", 1);
  1048. $mform->setType($deletebuttonname . "-hidden[$i]", PARAM_INT);
  1049. continue;
  1050. }
  1051. }
  1052. foreach ($elementobjs as $elementobj){
  1053. $elementclone = fullclone($elementobj);
  1054. $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
  1055. if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
  1056. foreach ($elementclone->getElements() as $el) {
  1057. $this->repeat_elements_fix_clone($i, $el, $namecloned);
  1058. }
  1059. $elementclone->setLabel(str_replace('{no}', $no, $elementclone->getLabel()));
  1060. } else if ($elementobj instanceof \HTML_QuickForm_submit && $elementobj->getName() == $deletebuttonname) {
  1061. // Mark the "Delete" button as no-submit.
  1062. $onclick = $elementclone->getAttribute('onclick');
  1063. $skip = 'skipClientValidation = true;';
  1064. $onclick = ($onclick !== null) ? $skip . ' ' . $onclick : $skip;
  1065. $elementclone->updateAttributes(['data-skip-validation' => 1, 'data-no-submit' => 1, 'onclick' => $onclick]);
  1066. }
  1067. // Mark newly created elements, so they know not to look for any submitted data.
  1068. if ($i >= $oldrepeats) {
  1069. $mform->note_new_repeat($elementclone->getName());
  1070. }
  1071. $mform->addElement($elementclone);
  1072. $no++;
  1073. }
  1074. }
  1075. for ($i=0; $i<$repeats; $i++) {
  1076. foreach ($options as $elementname => $elementoptions){
  1077. $pos=strpos($elementname, '[');
  1078. if ($pos!==FALSE){
  1079. $realelementname = substr($elementname, 0, $pos)."[$i]";
  1080. $realelementname .= substr($elementname, $pos);
  1081. }else {
  1082. $realelementname = $elementname."[$i]";
  1083. }
  1084. foreach ($elementoptions as $option => $params){
  1085. switch ($option){
  1086. case 'default' :
  1087. $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
  1088. break;
  1089. case 'helpbutton' :
  1090. $params = array_merge(array($realelementname), $params);
  1091. call_user_func_array(array(&$mform, 'addHelpButton'), $params);
  1092. break;
  1093. case 'disabledif' :
  1094. case 'hideif' :
  1095. $pos = strpos($params[0], '[');
  1096. $ending = '';
  1097. if ($pos !== false) {
  1098. $ending = substr($params[0], $pos);
  1099. $params[0] = substr($params[0], 0, $pos);
  1100. }
  1101. foreach ($namecloned as $num => $name){
  1102. if ($params[0] == $name){
  1103. $params[0] = $params[0] . "[$i]" . $ending;
  1104. break;
  1105. }
  1106. }
  1107. $params = array_merge(array($realelementname), $params);
  1108. $function = ($option === 'disabledif') ? 'disabledIf' : 'hideIf';
  1109. call_user_func_array(array(&$mform, $function), $params);
  1110. break;
  1111. case 'rule' :
  1112. if (is_string($params)){
  1113. $params = array(null, $params, null, 'client');
  1114. }
  1115. $params = array_merge(array($realelementname), $params);
  1116. call_user_func_array(array(&$mform, 'addRule'), $params);
  1117. break;
  1118. case 'type':

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