PageRenderTime 56ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/formslib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 2968 lines | 2040 code | 193 blank | 735 comment | 272 complexity | cd085a7cfa6d349893248bb862b6e0a2 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.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. /*
  312. // TODO: rethink the file scanning MDL-19380
  313. if ($CFG->runclamonupload) {
  314. if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
  315. $errors[$elname] = $_FILES[$elname]['uploadlog'];
  316. unset($_FILES[$elname]);
  317. continue;
  318. }
  319. }
  320. */
  321. $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
  322. if ($filename === '') {
  323. // TODO: improve error message - wrong chars
  324. $errors[$elname] = get_string('error');
  325. unset($_FILES[$elname]);
  326. continue;
  327. }
  328. if (in_array($filename, $filenames)) {
  329. // TODO: improve error message - duplicate name
  330. $errors[$elname] = get_string('error');
  331. unset($_FILES[$elname]);
  332. continue;
  333. }
  334. $filenames[] = $filename;
  335. $_FILES[$elname]['name'] = $filename;
  336. $files[$elname] = $_FILES[$elname]['tmp_name'];
  337. }
  338. // return errors if found
  339. if (count($errors) == 0){
  340. return true;
  341. } else {
  342. $files = array();
  343. return $errors;
  344. }
  345. }
  346. /**
  347. * Internal method. Validates filepicker and filemanager files if they are
  348. * set as required fields. Also, sets the error message if encountered one.
  349. *
  350. * @return bool|array with errors
  351. */
  352. protected function validate_draft_files() {
  353. global $USER;
  354. $mform =& $this->_form;
  355. $errors = array();
  356. //Go through all the required elements and make sure you hit filepicker or
  357. //filemanager element.
  358. foreach ($mform->_rules as $elementname => $rules) {
  359. $elementtype = $mform->getElementType($elementname);
  360. //If element is of type filepicker then do validation
  361. if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
  362. //Check if rule defined is required rule
  363. foreach ($rules as $rule) {
  364. if ($rule['type'] == 'required') {
  365. $draftid = (int)$mform->getSubmitValue($elementname);
  366. $fs = get_file_storage();
  367. $context = context_user::instance($USER->id);
  368. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  369. $errors[$elementname] = $rule['message'];
  370. }
  371. }
  372. }
  373. }
  374. }
  375. // Check all the filemanager elements to make sure they do not have too many
  376. // files in them.
  377. foreach ($mform->_elements as $element) {
  378. if ($element->_type == 'filemanager') {
  379. $maxfiles = $element->getMaxfiles();
  380. if ($maxfiles > 0) {
  381. $draftid = (int)$element->getValue();
  382. $fs = get_file_storage();
  383. $context = context_user::instance($USER->id);
  384. $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
  385. if (count($files) > $maxfiles) {
  386. $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
  387. }
  388. }
  389. }
  390. }
  391. if (empty($errors)) {
  392. return true;
  393. } else {
  394. return $errors;
  395. }
  396. }
  397. /**
  398. * Load in existing data as form defaults. Usually new entry defaults are stored directly in
  399. * form definition (new entry form); this function is used to load in data where values
  400. * already exist and data is being edited (edit entry form).
  401. *
  402. * note: $slashed param removed
  403. *
  404. * @param stdClass|array $default_values object or array of default values
  405. */
  406. function set_data($default_values) {
  407. if (is_object($default_values)) {
  408. $default_values = (array)$default_values;
  409. }
  410. $this->_form->setDefaults($default_values);
  411. }
  412. /**
  413. * Check that form was submitted. Does not check validity of submitted data.
  414. *
  415. * @return bool true if form properly submitted
  416. */
  417. function is_submitted() {
  418. return $this->_form->isSubmitted();
  419. }
  420. /**
  421. * Checks if button pressed is not for submitting the form
  422. *
  423. * @staticvar bool $nosubmit keeps track of no submit button
  424. * @return bool
  425. */
  426. function no_submit_button_pressed(){
  427. static $nosubmit = null; // one check is enough
  428. if (!is_null($nosubmit)){
  429. return $nosubmit;
  430. }
  431. $mform =& $this->_form;
  432. $nosubmit = false;
  433. if (!$this->is_submitted()){
  434. return false;
  435. }
  436. foreach ($mform->_noSubmitButtons as $nosubmitbutton){
  437. if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
  438. $nosubmit = true;
  439. break;
  440. }
  441. }
  442. return $nosubmit;
  443. }
  444. /**
  445. * Check that form data is valid.
  446. * You should almost always use this, rather than {@link validate_defined_fields}
  447. *
  448. * @return bool true if form data valid
  449. */
  450. function is_validated() {
  451. //finalize the form definition before any processing
  452. if (!$this->_definition_finalized) {
  453. $this->_definition_finalized = true;
  454. $this->definition_after_data();
  455. }
  456. return $this->validate_defined_fields();
  457. }
  458. /**
  459. * Validate the form.
  460. *
  461. * You almost always want to call {@link is_validated} instead of this
  462. * because it calls {@link definition_after_data} first, before validating the form,
  463. * which is what you want in 99% of cases.
  464. *
  465. * This is provided as a separate function for those special cases where
  466. * you want the form validated before definition_after_data is called
  467. * for example, to selectively add new elements depending on a no_submit_button press,
  468. * but only when the form is valid when the no_submit_button is pressed,
  469. *
  470. * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
  471. * is NOT to validate the form when a no submit button has been pressed.
  472. * pass true here to override this behaviour
  473. *
  474. * @return bool true if form data valid
  475. */
  476. function validate_defined_fields($validateonnosubmit=false) {
  477. static $validated = null; // one validation is enough
  478. $mform =& $this->_form;
  479. if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
  480. return false;
  481. } elseif ($validated === null) {
  482. $internal_val = $mform->validate();
  483. $files = array();
  484. $file_val = $this->_validate_files($files);
  485. //check draft files for validation and flag them if required files
  486. //are not in draft area.
  487. $draftfilevalue = $this->validate_draft_files();
  488. if ($file_val !== true && $draftfilevalue !== true) {
  489. $file_val = array_merge($file_val, $draftfilevalue);
  490. } else if ($draftfilevalue !== true) {
  491. $file_val = $draftfilevalue;
  492. } //default is file_val, so no need to assign.
  493. if ($file_val !== true) {
  494. if (!empty($file_val)) {
  495. foreach ($file_val as $element=>$msg) {
  496. $mform->setElementError($element, $msg);
  497. }
  498. }
  499. $file_val = false;
  500. }
  501. $data = $mform->exportValues();
  502. $moodle_val = $this->validation($data, $files);
  503. if ((is_array($moodle_val) && count($moodle_val)!==0)) {
  504. // non-empty array means errors
  505. foreach ($moodle_val as $element=>$msg) {
  506. $mform->setElementError($element, $msg);
  507. }
  508. $moodle_val = false;
  509. } else {
  510. // anything else means validation ok
  511. $moodle_val = true;
  512. }
  513. $validated = ($internal_val and $moodle_val and $file_val);
  514. }
  515. return $validated;
  516. }
  517. /**
  518. * Return true if a cancel button has been pressed resulting in the form being submitted.
  519. *
  520. * @return bool true if a cancel button has been pressed
  521. */
  522. function is_cancelled(){
  523. $mform =& $this->_form;
  524. if ($mform->isSubmitted()){
  525. foreach ($mform->_cancelButtons as $cancelbutton){
  526. if (optional_param($cancelbutton, 0, PARAM_RAW)){
  527. return true;
  528. }
  529. }
  530. }
  531. return false;
  532. }
  533. /**
  534. * Return submitted data if properly submitted or returns NULL if validation fails or
  535. * if there is no submitted data.
  536. *
  537. * note: $slashed param removed
  538. *
  539. * @return object submitted data; NULL if not valid or not submitted or cancelled
  540. */
  541. function get_data() {
  542. $mform =& $this->_form;
  543. if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
  544. $data = $mform->exportValues();
  545. unset($data['sesskey']); // we do not need to return sesskey
  546. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  547. if (empty($data)) {
  548. return NULL;
  549. } else {
  550. return (object)$data;
  551. }
  552. } else {
  553. return NULL;
  554. }
  555. }
  556. /**
  557. * Return submitted data without validation or NULL if there is no submitted data.
  558. * note: $slashed param removed
  559. *
  560. * @return object submitted data; NULL if not submitted
  561. */
  562. function get_submitted_data() {
  563. $mform =& $this->_form;
  564. if ($this->is_submitted()) {
  565. $data = $mform->exportValues();
  566. unset($data['sesskey']); // we do not need to return sesskey
  567. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  568. if (empty($data)) {
  569. return NULL;
  570. } else {
  571. return (object)$data;
  572. }
  573. } else {
  574. return NULL;
  575. }
  576. }
  577. /**
  578. * Save verified uploaded files into directory. Upload process can be customised from definition()
  579. *
  580. * @deprecated since Moodle 2.0
  581. * @todo MDL-31294 remove this api
  582. * @see moodleform::save_stored_file()
  583. * @see moodleform::save_file()
  584. * @param string $destination path where file should be stored
  585. * @return bool Always false
  586. */
  587. function save_files($destination) {
  588. debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
  589. return false;
  590. }
  591. /**
  592. * Returns name of uploaded file.
  593. *
  594. * @param string $elname first element if null
  595. * @return string|bool false in case of failure, string if ok
  596. */
  597. function get_new_filename($elname=null) {
  598. global $USER;
  599. if (!$this->is_submitted() or !$this->is_validated()) {
  600. return false;
  601. }
  602. if (is_null($elname)) {
  603. if (empty($_FILES)) {
  604. return false;
  605. }
  606. reset($_FILES);
  607. $elname = key($_FILES);
  608. }
  609. if (empty($elname)) {
  610. return false;
  611. }
  612. $element = $this->_form->getElement($elname);
  613. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  614. $values = $this->_form->exportValues($elname);
  615. if (empty($values[$elname])) {
  616. return false;
  617. }
  618. $draftid = $values[$elname];
  619. $fs = get_file_storage();
  620. $context = context_user::instance($USER->id);
  621. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  622. return false;
  623. }
  624. $file = reset($files);
  625. return $file->get_filename();
  626. }
  627. if (!isset($_FILES[$elname])) {
  628. return false;
  629. }
  630. return $_FILES[$elname]['name'];
  631. }
  632. /**
  633. * Save file to standard filesystem
  634. *
  635. * @param string $elname name of element
  636. * @param string $pathname full path name of file
  637. * @param bool $override override file if exists
  638. * @return bool success
  639. */
  640. function save_file($elname, $pathname, $override=false) {
  641. global $USER;
  642. if (!$this->is_submitted() or !$this->is_validated()) {
  643. return false;
  644. }
  645. if (file_exists($pathname)) {
  646. if ($override) {
  647. if (!@unlink($pathname)) {
  648. return false;
  649. }
  650. } else {
  651. return false;
  652. }
  653. }
  654. $element = $this->_form->getElement($elname);
  655. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  656. $values = $this->_form->exportValues($elname);
  657. if (empty($values[$elname])) {
  658. return false;
  659. }
  660. $draftid = $values[$elname];
  661. $fs = get_file_storage();
  662. $context = context_user::instance($USER->id);
  663. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  664. return false;
  665. }
  666. $file = reset($files);
  667. return $file->copy_content_to($pathname);
  668. } else if (isset($_FILES[$elname])) {
  669. return copy($_FILES[$elname]['tmp_name'], $pathname);
  670. }
  671. return false;
  672. }
  673. /**
  674. * Returns a temporary file, do not forget to delete after not needed any more.
  675. *
  676. * @param string $elname name of the elmenet
  677. * @return string|bool either string or false
  678. */
  679. function save_temp_file($elname) {
  680. if (!$this->get_new_filename($elname)) {
  681. return false;
  682. }
  683. if (!$dir = make_temp_directory('forms')) {
  684. return false;
  685. }
  686. if (!$tempfile = tempnam($dir, 'tempup_')) {
  687. return false;
  688. }
  689. if (!$this->save_file($elname, $tempfile, true)) {
  690. // something went wrong
  691. @unlink($tempfile);
  692. return false;
  693. }
  694. return $tempfile;
  695. }
  696. /**
  697. * Get draft files of a form element
  698. * This is a protected method which will be used only inside moodleforms
  699. *
  700. * @param string $elname name of element
  701. * @return array|bool|null
  702. */
  703. protected function get_draft_files($elname) {
  704. global $USER;
  705. if (!$this->is_submitted()) {
  706. return false;
  707. }
  708. $element = $this->_form->getElement($elname);
  709. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  710. $values = $this->_form->exportValues($elname);
  711. if (empty($values[$elname])) {
  712. return false;
  713. }
  714. $draftid = $values[$elname];
  715. $fs = get_file_storage();
  716. $context = context_user::instance($USER->id);
  717. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  718. return null;
  719. }
  720. return $files;
  721. }
  722. return null;
  723. }
  724. /**
  725. * Save file to local filesystem pool
  726. *
  727. * @param string $elname name of element
  728. * @param int $newcontextid id of context
  729. * @param string $newcomponent name of the component
  730. * @param string $newfilearea name of file area
  731. * @param int $newitemid item id
  732. * @param string $newfilepath path of file where it get stored
  733. * @param string $newfilename use specified filename, if not specified name of uploaded file used
  734. * @param bool $overwrite overwrite file if exists
  735. * @param int $newuserid new userid if required
  736. * @return mixed stored_file object or false if error; may throw exception if duplicate found
  737. */
  738. function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
  739. $newfilename=null, $overwrite=false, $newuserid=null) {
  740. global $USER;
  741. if (!$this->is_submitted() or !$this->is_validated()) {
  742. return false;
  743. }
  744. if (empty($newuserid)) {
  745. $newuserid = $USER->id;
  746. }
  747. $element = $this->_form->getElement($elname);
  748. $fs = get_file_storage();
  749. if ($element instanceof MoodleQuickForm_filepicker) {
  750. $values = $this->_form->exportValues($elname);
  751. if (empty($values[$elname])) {
  752. return false;
  753. }
  754. $draftid = $values[$elname];
  755. $context = context_user::instance($USER->id);
  756. if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
  757. return false;
  758. }
  759. $file = reset($files);
  760. if (is_null($newfilename)) {
  761. $newfilename = $file->get_filename();
  762. }
  763. if ($overwrite) {
  764. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  765. if (!$oldfile->delete()) {
  766. return false;
  767. }
  768. }
  769. }
  770. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  771. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  772. return $fs->create_file_from_storedfile($file_record, $file);
  773. } else if (isset($_FILES[$elname])) {
  774. $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
  775. if ($overwrite) {
  776. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  777. if (!$oldfile->delete()) {
  778. return false;
  779. }
  780. }
  781. }
  782. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  783. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  784. return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
  785. }
  786. return false;
  787. }
  788. /**
  789. * Get content of uploaded file.
  790. *
  791. * @param string $elname name of file upload element
  792. * @return string|bool false in case of failure, string if ok
  793. */
  794. function get_file_content($elname) {
  795. global $USER;
  796. if (!$this->is_submitted() or !$this->is_validated()) {
  797. return false;
  798. }
  799. $element = $this->_form->getElement($elname);
  800. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  801. $values = $this->_form->exportValues($elname);
  802. if (empty($values[$elname])) {
  803. return false;
  804. }
  805. $draftid = $values[$elname];
  806. $fs = get_file_storage();
  807. $context = context_user::instance($USER->id);
  808. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  809. return false;
  810. }
  811. $file = reset($files);
  812. return $file->get_content();
  813. } else if (isset($_FILES[$elname])) {
  814. return file_get_contents($_FILES[$elname]['tmp_name']);
  815. }
  816. return false;
  817. }
  818. /**
  819. * Print html form.
  820. */
  821. function display() {
  822. //finalize the form definition if not yet done
  823. if (!$this->_definition_finalized) {
  824. $this->_definition_finalized = true;
  825. $this->definition_after_data();
  826. }
  827. $this->_form->display();
  828. }
  829. /**
  830. * Renders the html form (same as display, but returns the result).
  831. *
  832. * Note that you can only output this rendered result once per page, as
  833. * it contains IDs which must be unique.
  834. *
  835. * @return string HTML code for the form
  836. */
  837. public function render() {
  838. ob_start();
  839. $this->display();
  840. $out = ob_get_contents();
  841. ob_end_clean();
  842. return $out;
  843. }
  844. /**
  845. * Form definition. Abstract method - always override!
  846. */
  847. protected abstract function definition();
  848. /**
  849. * Dummy stub method - override if you need to setup the form depending on current
  850. * values. This method is called after definition(), data submission and set_data().
  851. * All form setup that is dependent on form values should go in here.
  852. */
  853. function definition_after_data(){
  854. }
  855. /**
  856. * Dummy stub method - override if you needed to perform some extra validation.
  857. * If there are errors return array of errors ("fieldname"=>"error message"),
  858. * otherwise true if ok.
  859. *
  860. * Server side rules do not work for uploaded files, implement serverside rules here if needed.
  861. *
  862. * @param array $data array of ("fieldname"=>value) of submitted data
  863. * @param array $files array of uploaded files "element_name"=>tmp_file_path
  864. * @return array of "element_name"=>"error_description" if there are errors,
  865. * or an empty array if everything is OK (true allowed for backwards compatibility too).
  866. */
  867. function validation($data, $files) {
  868. return array();
  869. }
  870. /**
  871. * Helper used by {@link repeat_elements()}.
  872. *
  873. * @param int $i the index of this element.
  874. * @param HTML_QuickForm_element $elementclone
  875. * @param array $namecloned array of names
  876. */
  877. function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
  878. $name = $elementclone->getName();
  879. $namecloned[] = $name;
  880. if (!empty($name)) {
  881. $elementclone->setName($name."[$i]");
  882. }
  883. if (is_a($elementclone, 'HTML_QuickForm_header')) {
  884. $value = $elementclone->_text;
  885. $elementclone->setValue(str_replace('{no}', ($i+1), $value));
  886. } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
  887. $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
  888. } else {
  889. $value=$elementclone->getLabel();
  890. $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
  891. }
  892. }
  893. /**
  894. * Method to add a repeating group of elements to a form.
  895. *
  896. * @param array $elementobjs Array of elements or groups of elements that are to be repeated
  897. * @param int $repeats no of times to repeat elements initially
  898. * @param array $options a nested array. The first array key is the element name.
  899. * the second array key is the type of option to set, and depend on that option,
  900. * the value takes different forms.
  901. * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
  902. * 'type' - PARAM_* type.
  903. * 'helpbutton' - array containing the helpbutton params.
  904. * 'disabledif' - array containing the disabledIf() arguments after the element name.
  905. * 'rule' - array containing the addRule arguments after the element name.
  906. * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
  907. * 'advanced' - whether this element is hidden by 'Show more ...'.
  908. * @param string $repeathiddenname name for hidden element storing no of repeats in this form
  909. * @param string $addfieldsname name for button to add more fields
  910. * @param int $addfieldsno how many fields to add at a time
  911. * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
  912. * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
  913. * @return int no of repeats of element in this page
  914. */
  915. function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
  916. $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
  917. if ($addstring===null){
  918. $addstring = get_string('addfields', 'form', $addfieldsno);
  919. } else {
  920. $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
  921. }
  922. $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
  923. $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
  924. if (!empty($addfields)){
  925. $repeats += $addfieldsno;
  926. }
  927. $mform =& $this->_form;
  928. $mform->registerNoSubmitButton($addfieldsname);
  929. $mform->addElement('hidden', $repeathiddenname, $repeats);
  930. $mform->setType($repeathiddenname, PARAM_INT);
  931. //value not to be overridden by submitted value
  932. $mform->setConstants(array($repeathiddenname=>$repeats));
  933. $namecloned = array();
  934. for ($i = 0; $i < $repeats; $i++) {
  935. foreach ($elementobjs as $elementobj){
  936. $elementclone = fullclone($elementobj);
  937. $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
  938. if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
  939. foreach ($elementclone->getElements() as $el) {
  940. $this->repeat_elements_fix_clone($i, $el, $namecloned);
  941. }
  942. $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
  943. }
  944. $mform->addElement($elementclone);
  945. }
  946. }
  947. for ($i=0; $i<$repeats; $i++) {
  948. foreach ($options as $elementname => $elementoptions){
  949. $pos=strpos($elementname, '[');
  950. if ($pos!==FALSE){
  951. $realelementname = substr($elementname, 0, $pos)."[$i]";
  952. $realelementname .= substr($elementname, $pos);
  953. }else {
  954. $realelementname = $elementname."[$i]";
  955. }
  956. foreach ($elementoptions as $option => $params){
  957. switch ($option){
  958. case 'default' :
  959. $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
  960. break;
  961. case 'helpbutton' :
  962. $params = array_merge(array($realelementname), $params);
  963. call_user_func_array(array(&$mform, 'addHelpButton'), $params);
  964. break;
  965. case 'disabledif' :
  966. foreach ($namecloned as $num => $name){
  967. if ($params[0] == $name){
  968. $params[0] = $params[0]."[$i]";
  969. break;
  970. }
  971. }
  972. $params = array_merge(array($realelementname), $params);
  973. call_user_func_array(array(&$mform, 'disabledIf'), $params);
  974. break;
  975. case 'rule' :
  976. if (is_string($params)){
  977. $params = array(null, $params, null, 'client');
  978. }
  979. $params = array_merge(array($realelementname), $params);
  980. call_user_func_array(array(&$mform, 'addRule'), $params);
  981. break;
  982. case 'type':
  983. $mform->setType($realelementname, $params);
  984. break;
  985. case 'expanded':
  986. $mform->setExpanded($realelementname, $params);
  987. break;
  988. case 'advanced' :
  989. $mform->setAdvanced($realelementname, $params);
  990. break;
  991. }
  992. }
  993. }
  994. }
  995. $mform->addElement('submit', $addfieldsname, $addstring);
  996. if (!$addbuttoninside) {
  997. $mform->closeHeaderBefore($addfieldsname);
  998. }
  999. return $repeats;
  1000. }
  1001. /**
  1002. * Adds a link/button that controls the checked state of a group of checkboxes.
  1003. *
  1004. * @param int $groupid The id of the group of advcheckboxes this element controls
  1005. * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
  1006. * @param array $attributes associative array of HTML attributes
  1007. * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
  1008. */
  1009. function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
  1010. global $CFG, $PAGE;
  1011. // Name of the controller button
  1012. $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
  1013. $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
  1014. $checkboxgroupclass = 'checkboxgroup'.$groupid;
  1015. // Set the default text if none was specified
  1016. if (empty($text)) {
  1017. $text = get_string('selectallornone', 'form');
  1018. }
  1019. $mform = $this->_form;
  1020. $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
  1021. $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
  1022. $newselectvalue = $selectvalue;
  1023. if (is_null($selectvalue)) {
  1024. $newselectvalue = $originalValue;
  1025. } else if (!is_null($contollerbutton)) {
  1026. $newselectvalue = (int) !$selectvalue;
  1027. }
  1028. // set checkbox state depending on orignal/submitted value by controoler button
  1029. if (!is_null($contollerbutton) || is_null($selectvalue)) {
  1030. foreach ($mform->_elements as $element) {
  1031. if (($element instanceof MoodleQuickForm_advcheckbox) &&
  1032. $element->getAttribute('class') == $checkboxgroupclass &&
  1033. !$element->isFrozen()) {
  1034. $mform->setConstants(array($element->getName() => $newselectvalue));
  1035. }
  1036. }
  1037. }
  1038. $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
  1039. $mform->setType($checkboxcontrollerparam, PARAM_INT);
  1040. $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
  1041. $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
  1042. array(
  1043. array('groupid' => $groupid,
  1044. 'checkboxclass' => $checkboxgroupclass,
  1045. 'checkboxcontroller' => $checkboxcontrollerparam,
  1046. 'controllerbutton' => $checkboxcontrollername)
  1047. )
  1048. );
  1049. require_once("$CFG->libdir/form/submit.php");
  1050. $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
  1051. $mform->addElement($submitlink);
  1052. $mform->registerNoSubmitButton($checkboxcontrollername);
  1053. $mform->setDefault($checkboxcontrollername, $text);
  1054. }
  1055. /**
  1056. * Use this method to a cancel and submit button to the end of your form. Pass a param of false
  1057. * if you don't want a cancel button in your form. If you have a cancel button make sure you
  1058. * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
  1059. * get data with get_data().
  1060. *
  1061. * @param bool $cancel whether to show cancel button, default true
  1062. * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
  1063. */
  1064. function add_action_buttons($cancel = true, $submitlabel=null){
  1065. if (is_null($submitlabel)){
  1066. $submitlabel = get_string('savechanges');
  1067. }
  1068. $mform =& $this->_form;
  1069. if ($cancel){
  1070. //when two elements we need a group
  1071. $buttonarray=array();
  1072. $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
  1073. $buttonarray[] = &$mform->createElement('cancel');
  1074. $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
  1075. $mform->closeHeaderBefore('buttonar');
  1076. } else {
  1077. //no group needed
  1078. $mform->addElement('submit', 'submitbutton', $submitlabel);
  1079. $mform->closeHeaderBefore('submitbutton');
  1080. }
  1081. }
  1082. /**
  1083. * Adds an initialisation call for a standard JavaScript enhancement.
  1084. *
  1085. * This function is designed to add an initialisation call for a JavaScript
  1086. * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
  1087. *
  1088. * Current options:
  1089. * - Selectboxes
  1090. * - smartselect: Turns a nbsp indented select box into a custom drop down
  1091. * control that supports multilevel and category selection.
  1092. * $enhancement = 'smartselect';
  1093. * $options = array('selectablecategories' => true|false)
  1094. *
  1095. * @since Moodle 2.0
  1096. * @param string|element $element form element for which Javascript needs to be initalized
  1097. * @param string $enhancement which init function should be called
  1098. * @param array $options options passed to javascript
  1099. * @param array $strings strings for javascript
  1100. */
  1101. function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
  1102. global $PAGE;
  1103. if (is_string($element)) {
  1104. $element = $this->_form->getElement($element);
  1105. }
  1106. if (is_object($element)) {
  1107. $element->_generateId();
  1108. $elementid = $element->getAttribute('id');
  1109. $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
  1110. if (is_array($strings)) {
  1111. foreach ($strings as $string) {
  1112. if (is_array($string)) {
  1113. call_user_method_array('string_for_js', $PAGE->requires, $string);
  1114. } else {
  1115. $PAGE->requires->string_for_js($string, 'moodle');
  1116. }
  1117. }
  1118. }
  1119. }
  1120. }
  1121. /**
  1122. * Returns a JS module definition for the mforms JS
  1123. *
  1124. * @return array
  1125. */
  1126. public static function get_js_module() {
  1127. global $CFG;
  1128. return array(
  1129. 'name' => 'mform',
  1130. 'fullpath' => '/lib/form/form.js',
  1131. 'requires' => array('base', 'node')
  1132. );
  1133. }
  1134. /**
  1135. * Detects elements with missing setType() declerations.
  1136. *
  1137. * Finds elements in the form which should a PARAM_ type set and throws a
  1138. * developer debug warning for any elements without it. This is to reduce the
  1139. * risk of potential security issues by developers mistakenly forgetting to set
  1140. * the type.
  1141. *
  1142. * @return void
  1143. */
  1144. private function det

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