PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/formslib.php

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

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