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

/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

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. * 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', $chec

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