PageRenderTime 74ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/formslib.php

https://github.com/lsuits/moodle
PHP | 2960 lines | 2040 code | 194 blank | 726 comment | 272 complexity | fe64ac86d31a7e9ab002384cea06bd8f MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, Apache-2.0

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

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