PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/formslib.php

https://github.com/mylescarrick/moodle
PHP | 2372 lines | 1610 code | 159 blank | 603 comment | 194 complexity | 600f783e23775d39d3c5a448490d1d88 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause

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

  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
  18. *
  19. * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
  20. * and you want to name your class something like {modulename}_{purpose}_form. Your class will
  21. * extend moodleform overriding abstract classes definition and optionally defintion_after_data
  22. * and validation.
  23. *
  24. * See examples of use of this library in course/edit.php and course/edit_form.php
  25. *
  26. * A few notes :
  27. * form definition is used for both printing of form and processing and should be the same
  28. * for both or you may lose some submitted data which won't be let through.
  29. * you should be using setType for every form element except select, radio or checkbox
  30. * elements, these elements clean themselves.
  31. *
  32. *
  33. * @copyright Jamie Pratt <me@jamiep.org>
  34. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35. * @package core
  36. * @subpackage form
  37. */
  38. defined('MOODLE_INTERNAL') || die();
  39. /** setup.php includes our hacked pear libs first */
  40. require_once 'HTML/QuickForm.php';
  41. require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
  42. require_once 'HTML/QuickForm/Renderer/Tableless.php';
  43. require_once $CFG->libdir.'/filelib.php';
  44. define('EDITOR_UNLIMITED_FILES', -1);
  45. /**
  46. * Callback called when PEAR throws an error
  47. *
  48. * @param PEAR_Error $error
  49. */
  50. function pear_handle_error($error){
  51. echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
  52. echo '<br /> <strong>Backtrace </strong>:';
  53. print_object($error->backtrace);
  54. }
  55. if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
  56. PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
  57. }
  58. /**
  59. *
  60. * @staticvar bool $done
  61. * @global moodle_page $PAGE
  62. */
  63. function form_init_date_js() {
  64. global $PAGE;
  65. static $done = false;
  66. if (!$done) {
  67. $module = 'moodle-form-dateselector';
  68. $function = 'M.form.dateselector.init_date_selectors';
  69. $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
  70. $PAGE->requires->yui_module($module, $function, $config);
  71. $done = true;
  72. }
  73. }
  74. /**
  75. * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
  76. * use this class you should write a class definition which extends this class or a more specific
  77. * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
  78. *
  79. * You will write your own definition() method which performs the form set up.
  80. *
  81. * @package moodlecore
  82. * @copyright Jamie Pratt <me@jamiep.org>
  83. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  84. */
  85. abstract class moodleform {
  86. /** @var string */
  87. protected $_formname; // form name
  88. /**
  89. * quickform object definition
  90. *
  91. * @var MoodleQuickForm MoodleQuickForm
  92. */
  93. protected $_form;
  94. /**
  95. * globals workaround
  96. *
  97. * @var array
  98. */
  99. protected $_customdata;
  100. /**
  101. * definition_after_data executed flag
  102. * @var object definition_finalized
  103. */
  104. protected $_definition_finalized = false;
  105. /**
  106. * The constructor function calls the abstract function definition() and it will then
  107. * process and clean and attempt to validate incoming data.
  108. *
  109. * It will call your custom validate method to validate data and will also check any rules
  110. * you have specified in definition using addRule
  111. *
  112. * The name of the form (id attribute of the form) is automatically generated depending on
  113. * the name you gave the class extending moodleform. You should call your class something
  114. * like
  115. *
  116. * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
  117. * current url. If a moodle_url object then outputs params as hidden variables.
  118. * @param array $customdata if your form defintion method needs access to data such as $course
  119. * $cm, etc. to construct the form definition then pass it in this array. You can
  120. * use globals for somethings.
  121. * @param string $method if you set this to anything other than 'post' then _GET and _POST will
  122. * be merged and used as incoming data to the form.
  123. * @param string $target target frame for form submission. You will rarely use this. Don't use
  124. * it if you don't need to as the target attribute is deprecated in xhtml
  125. * strict.
  126. * @param mixed $attributes you can pass a string of html attributes here or an array.
  127. * @param bool $editable
  128. * @return object moodleform
  129. */
  130. function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
  131. if (empty($action)){
  132. $action = strip_querystring(qualified_me());
  133. }
  134. $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
  135. $this->_customdata = $customdata;
  136. $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
  137. if (!$editable){
  138. $this->_form->hardFreeze();
  139. }
  140. $this->definition();
  141. $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
  142. $this->_form->setType('sesskey', PARAM_RAW);
  143. $this->_form->setDefault('sesskey', sesskey());
  144. $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
  145. $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
  146. $this->_form->setDefault('_qf__'.$this->_formname, 1);
  147. $this->_form->_setDefaultRuleMessages();
  148. // we have to know all input types before processing submission ;-)
  149. $this->_process_submission($method);
  150. }
  151. /**
  152. * To autofocus on first form element or first element with error.
  153. *
  154. * @param string $name if this is set then the focus is forced to a field with this name
  155. *
  156. * @return string javascript to select form element with first error or
  157. * first element if no errors. Use this as a parameter
  158. * when calling print_header
  159. */
  160. function focus($name=NULL) {
  161. $form =& $this->_form;
  162. $elkeys = array_keys($form->_elementIndex);
  163. $error = false;
  164. if (isset($form->_errors) && 0 != count($form->_errors)){
  165. $errorkeys = array_keys($form->_errors);
  166. $elkeys = array_intersect($elkeys, $errorkeys);
  167. $error = true;
  168. }
  169. if ($error or empty($name)) {
  170. $names = array();
  171. while (empty($names) and !empty($elkeys)) {
  172. $el = array_shift($elkeys);
  173. $names = $form->_getElNamesRecursive($el);
  174. }
  175. if (!empty($names)) {
  176. $name = array_shift($names);
  177. }
  178. }
  179. $focus = '';
  180. if (!empty($name)) {
  181. $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
  182. }
  183. return $focus;
  184. }
  185. /**
  186. * Internal method. Alters submitted data to be suitable for quickforms processing.
  187. * Must be called when the form is fully set up.
  188. *
  189. * @param string $method
  190. */
  191. function _process_submission($method) {
  192. $submission = array();
  193. if ($method == 'post') {
  194. if (!empty($_POST)) {
  195. $submission = $_POST;
  196. }
  197. } else {
  198. $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
  199. }
  200. // following trick is needed to enable proper sesskey checks when using GET forms
  201. // the _qf__.$this->_formname serves as a marker that form was actually submitted
  202. if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
  203. if (!confirm_sesskey()) {
  204. print_error('invalidsesskey');
  205. }
  206. $files = $_FILES;
  207. } else {
  208. $submission = array();
  209. $files = array();
  210. }
  211. $this->_form->updateSubmission($submission, $files);
  212. }
  213. /**
  214. * Internal method. Validates all old-style deprecated uploaded files.
  215. * The new way is to upload files via repository api.
  216. *
  217. * @global object
  218. * @global object
  219. * @param array $files
  220. * @return bool|array Success or an array of errors
  221. */
  222. function _validate_files(&$files) {
  223. global $CFG, $COURSE;
  224. $files = array();
  225. if (empty($_FILES)) {
  226. // we do not need to do any checks because no files were submitted
  227. // note: server side rules do not work for files - use custom verification in validate() instead
  228. return true;
  229. }
  230. $errors = array();
  231. $filenames = array();
  232. // now check that we really want each file
  233. foreach ($_FILES as $elname=>$file) {
  234. $required = $this->_form->isElementRequired($elname);
  235. if ($file['error'] == 4 and $file['size'] == 0) {
  236. if ($required) {
  237. $errors[$elname] = get_string('required');
  238. }
  239. unset($_FILES[$elname]);
  240. continue;
  241. }
  242. if (!empty($file['error'])) {
  243. $errors[$elname] = file_get_upload_error($file['error']);
  244. unset($_FILES[$elname]);
  245. continue;
  246. }
  247. if (!is_uploaded_file($file['tmp_name'])) {
  248. // TODO: improve error message
  249. $errors[$elname] = get_string('error');
  250. unset($_FILES[$elname]);
  251. continue;
  252. }
  253. if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
  254. // hmm, this file was not requested
  255. unset($_FILES[$elname]);
  256. continue;
  257. }
  258. /*
  259. // TODO: rethink the file scanning MDL-19380
  260. if ($CFG->runclamonupload) {
  261. if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
  262. $errors[$elname] = $_FILES[$elname]['uploadlog'];
  263. unset($_FILES[$elname]);
  264. continue;
  265. }
  266. }
  267. */
  268. $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
  269. if ($filename === '') {
  270. // TODO: improve error message - wrong chars
  271. $errors[$elname] = get_string('error');
  272. unset($_FILES[$elname]);
  273. continue;
  274. }
  275. if (in_array($filename, $filenames)) {
  276. // TODO: improve error message - duplicate name
  277. $errors[$elname] = get_string('error');
  278. unset($_FILES[$elname]);
  279. continue;
  280. }
  281. $filenames[] = $filename;
  282. $_FILES[$elname]['name'] = $filename;
  283. $files[$elname] = $_FILES[$elname]['tmp_name'];
  284. }
  285. // return errors if found
  286. if (count($errors) == 0){
  287. return true;
  288. } else {
  289. $files = array();
  290. return $errors;
  291. }
  292. }
  293. /**
  294. * Load in existing data as form defaults. Usually new entry defaults are stored directly in
  295. * form definition (new entry form); this function is used to load in data where values
  296. * already exist and data is being edited (edit entry form).
  297. *
  298. * note: $slashed param removed
  299. *
  300. * @param mixed $default_values object or array of default values
  301. */
  302. function set_data($default_values) {
  303. if (is_object($default_values)) {
  304. $default_values = (array)$default_values;
  305. }
  306. $this->_form->setDefaults($default_values);
  307. }
  308. /**
  309. * @deprecated
  310. */
  311. function set_upload_manager($um=false) {
  312. debugging('Old file uploads can not be used any more, please use new filepicker element');
  313. }
  314. /**
  315. * Check that form was submitted. Does not check validity of submitted data.
  316. *
  317. * @return bool true if form properly submitted
  318. */
  319. function is_submitted() {
  320. return $this->_form->isSubmitted();
  321. }
  322. /**
  323. * @staticvar bool $nosubmit
  324. */
  325. function no_submit_button_pressed(){
  326. static $nosubmit = null; // one check is enough
  327. if (!is_null($nosubmit)){
  328. return $nosubmit;
  329. }
  330. $mform =& $this->_form;
  331. $nosubmit = false;
  332. if (!$this->is_submitted()){
  333. return false;
  334. }
  335. foreach ($mform->_noSubmitButtons as $nosubmitbutton){
  336. if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
  337. $nosubmit = true;
  338. break;
  339. }
  340. }
  341. return $nosubmit;
  342. }
  343. /**
  344. * Check that form data is valid.
  345. * You should almost always use this, rather than {@see validate_defined_fields}
  346. *
  347. * @staticvar bool $validated
  348. * @return bool true if form data valid
  349. */
  350. function is_validated() {
  351. //finalize the form definition before any processing
  352. if (!$this->_definition_finalized) {
  353. $this->_definition_finalized = true;
  354. $this->definition_after_data();
  355. }
  356. return $this->validate_defined_fields();
  357. }
  358. /**
  359. * Validate the form.
  360. *
  361. * You almost always want to call {@see is_validated} instead of this
  362. * because it calls {@see definition_after_data} first, before validating the form,
  363. * which is what you want in 99% of cases.
  364. *
  365. * This is provided as a separate function for those special cases where
  366. * you want the form validated before definition_after_data is called
  367. * for example, to selectively add new elements depending on a no_submit_button press,
  368. * but only when the form is valid when the no_submit_button is pressed,
  369. *
  370. * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
  371. * is NOT to validate the form when a no submit button has been pressed.
  372. * pass true here to override this behaviour
  373. *
  374. * @return bool true if form data valid
  375. */
  376. function validate_defined_fields($validateonnosubmit=false) {
  377. static $validated = null; // one validation is enough
  378. $mform =& $this->_form;
  379. if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
  380. return false;
  381. } elseif ($validated === null) {
  382. $internal_val = $mform->validate();
  383. $files = array();
  384. $file_val = $this->_validate_files($files);
  385. if ($file_val !== true) {
  386. if (!empty($file_val)) {
  387. foreach ($file_val as $element=>$msg) {
  388. $mform->setElementError($element, $msg);
  389. }
  390. }
  391. $file_val = false;
  392. }
  393. $data = $mform->exportValues();
  394. $moodle_val = $this->validation($data, $files);
  395. if ((is_array($moodle_val) && count($moodle_val)!==0)) {
  396. // non-empty array means errors
  397. foreach ($moodle_val as $element=>$msg) {
  398. $mform->setElementError($element, $msg);
  399. }
  400. $moodle_val = false;
  401. } else {
  402. // anything else means validation ok
  403. $moodle_val = true;
  404. }
  405. $validated = ($internal_val and $moodle_val and $file_val);
  406. }
  407. return $validated;
  408. }
  409. /**
  410. * Return true if a cancel button has been pressed resulting in the form being submitted.
  411. *
  412. * @return boolean true if a cancel button has been pressed
  413. */
  414. function is_cancelled(){
  415. $mform =& $this->_form;
  416. if ($mform->isSubmitted()){
  417. foreach ($mform->_cancelButtons as $cancelbutton){
  418. if (optional_param($cancelbutton, 0, PARAM_RAW)){
  419. return true;
  420. }
  421. }
  422. }
  423. return false;
  424. }
  425. /**
  426. * Return submitted data if properly submitted or returns NULL if validation fails or
  427. * if there is no submitted data.
  428. *
  429. * note: $slashed param removed
  430. *
  431. * @return object submitted data; NULL if not valid or not submitted
  432. */
  433. function get_data() {
  434. $mform =& $this->_form;
  435. if ($this->is_submitted() and $this->is_validated()) {
  436. $data = $mform->exportValues();
  437. unset($data['sesskey']); // we do not need to return sesskey
  438. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  439. if (empty($data)) {
  440. return NULL;
  441. } else {
  442. return (object)$data;
  443. }
  444. } else {
  445. return NULL;
  446. }
  447. }
  448. /**
  449. * Return submitted data without validation or NULL if there is no submitted data.
  450. * note: $slashed param removed
  451. *
  452. * @return object submitted data; NULL if not submitted
  453. */
  454. function get_submitted_data() {
  455. $mform =& $this->_form;
  456. if ($this->is_submitted()) {
  457. $data = $mform->exportValues();
  458. unset($data['sesskey']); // we do not need to return sesskey
  459. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  460. if (empty($data)) {
  461. return NULL;
  462. } else {
  463. return (object)$data;
  464. }
  465. } else {
  466. return NULL;
  467. }
  468. }
  469. /**
  470. * Save verified uploaded files into directory. Upload process can be customised from definition()
  471. * NOTE: please use save_stored_file() or save_file()
  472. *
  473. * @return bool Always false
  474. */
  475. function save_files($destination) {
  476. debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
  477. return false;
  478. }
  479. /**
  480. * Returns name of uploaded file.
  481. *
  482. * @global object
  483. * @param string $elname, first element if null
  484. * @return mixed false in case of failure, string if ok
  485. */
  486. function get_new_filename($elname=null) {
  487. global $USER;
  488. if (!$this->is_submitted() or !$this->is_validated()) {
  489. return false;
  490. }
  491. if (is_null($elname)) {
  492. if (empty($_FILES)) {
  493. return false;
  494. }
  495. reset($_FILES);
  496. $elname = key($_FILES);
  497. }
  498. if (empty($elname)) {
  499. return false;
  500. }
  501. $element = $this->_form->getElement($elname);
  502. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  503. $values = $this->_form->exportValues($elname);
  504. if (empty($values[$elname])) {
  505. return false;
  506. }
  507. $draftid = $values[$elname];
  508. $fs = get_file_storage();
  509. $context = get_context_instance(CONTEXT_USER, $USER->id);
  510. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  511. return false;
  512. }
  513. $file = reset($files);
  514. return $file->get_filename();
  515. }
  516. if (!isset($_FILES[$elname])) {
  517. return false;
  518. }
  519. return $_FILES[$elname]['name'];
  520. }
  521. /**
  522. * Save file to standard filesystem
  523. *
  524. * @global object
  525. * @param string $elname name of element
  526. * @param string $pathname full path name of file
  527. * @param bool $override override file if exists
  528. * @return bool success
  529. */
  530. function save_file($elname, $pathname, $override=false) {
  531. global $USER;
  532. if (!$this->is_submitted() or !$this->is_validated()) {
  533. return false;
  534. }
  535. if (file_exists($pathname)) {
  536. if ($override) {
  537. if (!@unlink($pathname)) {
  538. return false;
  539. }
  540. } else {
  541. return false;
  542. }
  543. }
  544. $element = $this->_form->getElement($elname);
  545. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  546. $values = $this->_form->exportValues($elname);
  547. if (empty($values[$elname])) {
  548. return false;
  549. }
  550. $draftid = $values[$elname];
  551. $fs = get_file_storage();
  552. $context = get_context_instance(CONTEXT_USER, $USER->id);
  553. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  554. return false;
  555. }
  556. $file = reset($files);
  557. return $file->copy_content_to($pathname);
  558. } else if (isset($_FILES[$elname])) {
  559. return copy($_FILES[$elname]['tmp_name'], $pathname);
  560. }
  561. return false;
  562. }
  563. /**
  564. * Returns a temporary file, do not forget to delete after not needed any more.
  565. *
  566. * @param string $elname
  567. * @return string or false
  568. */
  569. function save_temp_file($elname) {
  570. if (!$this->get_new_filename($elname)) {
  571. return false;
  572. }
  573. if (!$dir = make_upload_directory('temp/forms')) {
  574. return false;
  575. }
  576. if (!$tempfile = tempnam($dir, 'tempup_')) {
  577. return false;
  578. }
  579. if (!$this->save_file($elname, $tempfile, true)) {
  580. // something went wrong
  581. @unlink($tempfile);
  582. return false;
  583. }
  584. return $tempfile;
  585. }
  586. /**
  587. * Get draft files of a form element
  588. * This is a protected method which will be used only inside moodleforms
  589. *
  590. * @global object $USER
  591. * @param string $elname name of element
  592. * @return array
  593. */
  594. protected function get_draft_files($elname) {
  595. global $USER;
  596. if (!$this->is_submitted()) {
  597. return false;
  598. }
  599. $element = $this->_form->getElement($elname);
  600. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  601. $values = $this->_form->exportValues($elname);
  602. if (empty($values[$elname])) {
  603. return false;
  604. }
  605. $draftid = $values[$elname];
  606. $fs = get_file_storage();
  607. $context = get_context_instance(CONTEXT_USER, $USER->id);
  608. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  609. return null;
  610. }
  611. return $files;
  612. }
  613. return null;
  614. }
  615. /**
  616. * Save file to local filesystem pool
  617. *
  618. * @global object
  619. * @param string $elname name of element
  620. * @param int $newcontextid
  621. * @param string $newfilearea
  622. * @param string $newfilepath
  623. * @param string $newfilename - use specified filename, if not specified name of uploaded file used
  624. * @param bool $overwrite - overwrite file if exists
  625. * @param int $newuserid - new userid if required
  626. * @return mixed stored_file object or false if error; may throw exception if duplicate found
  627. */
  628. function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
  629. $newfilename=null, $overwrite=false, $newuserid=null) {
  630. global $USER;
  631. if (!$this->is_submitted() or !$this->is_validated()) {
  632. return false;
  633. }
  634. if (empty($newuserid)) {
  635. $newuserid = $USER->id;
  636. }
  637. $element = $this->_form->getElement($elname);
  638. $fs = get_file_storage();
  639. if ($element instanceof MoodleQuickForm_filepicker) {
  640. $values = $this->_form->exportValues($elname);
  641. if (empty($values[$elname])) {
  642. return false;
  643. }
  644. $draftid = $values[$elname];
  645. $context = get_context_instance(CONTEXT_USER, $USER->id);
  646. if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
  647. return false;
  648. }
  649. $file = reset($files);
  650. if (is_null($newfilename)) {
  651. $newfilename = $file->get_filename();
  652. }
  653. if ($overwrite) {
  654. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  655. if (!$oldfile->delete()) {
  656. return false;
  657. }
  658. }
  659. }
  660. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  661. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  662. return $fs->create_file_from_storedfile($file_record, $file);
  663. } else if (isset($_FILES[$elname])) {
  664. $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
  665. if ($overwrite) {
  666. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  667. if (!$oldfile->delete()) {
  668. return false;
  669. }
  670. }
  671. }
  672. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  673. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  674. return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
  675. }
  676. return false;
  677. }
  678. /**
  679. * Get content of uploaded file.
  680. *
  681. * @global object
  682. * @param $element name of file upload element
  683. * @return mixed false in case of failure, string if ok
  684. */
  685. function get_file_content($elname) {
  686. global $USER;
  687. if (!$this->is_submitted() or !$this->is_validated()) {
  688. return false;
  689. }
  690. $element = $this->_form->getElement($elname);
  691. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  692. $values = $this->_form->exportValues($elname);
  693. if (empty($values[$elname])) {
  694. return false;
  695. }
  696. $draftid = $values[$elname];
  697. $fs = get_file_storage();
  698. $context = get_context_instance(CONTEXT_USER, $USER->id);
  699. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  700. return false;
  701. }
  702. $file = reset($files);
  703. return $file->get_content();
  704. } else if (isset($_FILES[$elname])) {
  705. return file_get_contents($_FILES[$elname]['tmp_name']);
  706. }
  707. return false;
  708. }
  709. /**
  710. * Print html form.
  711. */
  712. function display() {
  713. //finalize the form definition if not yet done
  714. if (!$this->_definition_finalized) {
  715. $this->_definition_finalized = true;
  716. $this->definition_after_data();
  717. }
  718. $this->_form->display();
  719. }
  720. /**
  721. * Abstract method - always override!
  722. */
  723. protected abstract function definition();
  724. /**
  725. * Dummy stub method - override if you need to setup the form depending on current
  726. * values. This method is called after definition(), data submission and set_data().
  727. * All form setup that is dependent on form values should go in here.
  728. */
  729. function definition_after_data(){
  730. }
  731. /**
  732. * Dummy stub method - override if you needed to perform some extra validation.
  733. * If there are errors return array of errors ("fieldname"=>"error message"),
  734. * otherwise true if ok.
  735. *
  736. * Server side rules do not work for uploaded files, implement serverside rules here if needed.
  737. *
  738. * @param array $data array of ("fieldname"=>value) of submitted data
  739. * @param array $files array of uploaded files "element_name"=>tmp_file_path
  740. * @return array of "element_name"=>"error_description" if there are errors,
  741. * or an empty array if everything is OK (true allowed for backwards compatibility too).
  742. */
  743. function validation($data, $files) {
  744. return array();
  745. }
  746. /**
  747. * Method to add a repeating group of elements to a form.
  748. *
  749. * @param array $elementobjs Array of elements or groups of elements that are to be repeated
  750. * @param integer $repeats no of times to repeat elements initially
  751. * @param array $options Array of options to apply to elements. Array keys are element names.
  752. * This is an array of arrays. The second sets of keys are the option types
  753. * for the elements :
  754. * 'default' - default value is value
  755. * 'type' - PARAM_* constant is value
  756. * 'helpbutton' - helpbutton params array is value
  757. * 'disabledif' - last three moodleform::disabledIf()
  758. * params are value as an array
  759. * @param string $repeathiddenname name for hidden element storing no of repeats in this form
  760. * @param string $addfieldsname name for button to add more fields
  761. * @param int $addfieldsno how many fields to add at a time
  762. * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
  763. * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
  764. * @return int no of repeats of element in this page
  765. */
  766. function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
  767. $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
  768. if ($addstring===null){
  769. $addstring = get_string('addfields', 'form', $addfieldsno);
  770. } else {
  771. $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
  772. }
  773. $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
  774. $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
  775. if (!empty($addfields)){
  776. $repeats += $addfieldsno;
  777. }
  778. $mform =& $this->_form;
  779. $mform->registerNoSubmitButton($addfieldsname);
  780. $mform->addElement('hidden', $repeathiddenname, $repeats);
  781. $mform->setType($repeathiddenname, PARAM_INT);
  782. //value not to be overridden by submitted value
  783. $mform->setConstants(array($repeathiddenname=>$repeats));
  784. $namecloned = array();
  785. for ($i = 0; $i < $repeats; $i++) {
  786. foreach ($elementobjs as $elementobj){
  787. $elementclone = fullclone($elementobj);
  788. $name = $elementclone->getName();
  789. $namecloned[] = $name;
  790. if (!empty($name)) {
  791. $elementclone->setName($name."[$i]");
  792. }
  793. if (is_a($elementclone, 'HTML_QuickForm_header')) {
  794. $value = $elementclone->_text;
  795. $elementclone->setValue(str_replace('{no}', ($i+1), $value));
  796. } else {
  797. $value=$elementclone->getLabel();
  798. $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
  799. }
  800. $mform->addElement($elementclone);
  801. }
  802. }
  803. for ($i=0; $i<$repeats; $i++) {
  804. foreach ($options as $elementname => $elementoptions){
  805. $pos=strpos($elementname, '[');
  806. if ($pos!==FALSE){
  807. $realelementname = substr($elementname, 0, $pos+1)."[$i]";
  808. $realelementname .= substr($elementname, $pos+1);
  809. }else {
  810. $realelementname = $elementname."[$i]";
  811. }
  812. foreach ($elementoptions as $option => $params){
  813. switch ($option){
  814. case 'default' :
  815. $mform->setDefault($realelementname, $params);
  816. break;
  817. case 'helpbutton' :
  818. $params = array_merge(array($realelementname), $params);
  819. call_user_func_array(array(&$mform, 'addHelpButton'), $params);
  820. break;
  821. case 'disabledif' :
  822. foreach ($namecloned as $num => $name){
  823. if ($params[0] == $name){
  824. $params[0] = $params[0]."[$i]";
  825. break;
  826. }
  827. }
  828. $params = array_merge(array($realelementname), $params);
  829. call_user_func_array(array(&$mform, 'disabledIf'), $params);
  830. break;
  831. case 'rule' :
  832. if (is_string($params)){
  833. $params = array(null, $params, null, 'client');
  834. }
  835. $params = array_merge(array($realelementname), $params);
  836. call_user_func_array(array(&$mform, 'addRule'), $params);
  837. break;
  838. }
  839. }
  840. }
  841. }
  842. $mform->addElement('submit', $addfieldsname, $addstring);
  843. if (!$addbuttoninside) {
  844. $mform->closeHeaderBefore($addfieldsname);
  845. }
  846. return $repeats;
  847. }
  848. /**
  849. * Adds a link/button that controls the checked state of a group of checkboxes.
  850. *
  851. * @global object
  852. * @param int $groupid The id of the group of advcheckboxes this element controls
  853. * @param string $buttontext The text of the link. Defaults to "select all/none"
  854. * @param array $attributes associative array of HTML attributes
  855. * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
  856. */
  857. function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
  858. global $CFG;
  859. if (empty($text)) {
  860. $text = get_string('selectallornone', 'form');
  861. }
  862. $mform = $this->_form;
  863. $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
  864. if ($select_value == 0 || is_null($select_value)) {
  865. $new_select_value = 1;
  866. } else {
  867. $new_select_value = 0;
  868. }
  869. $mform->addElement('hidden', "checkbox_controller$groupid");
  870. $mform->setType("checkbox_controller$groupid", PARAM_INT);
  871. $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
  872. // Locate all checkboxes for this group and set their value, IF the optional param was given
  873. if (!is_null($select_value)) {
  874. foreach ($this->_form->_elements as $element) {
  875. if ($element->getAttribute('class') == "checkboxgroup$groupid") {
  876. $mform->setConstants(array($element->getAttribute('name') => $select_value));
  877. }
  878. }
  879. }
  880. $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
  881. $mform->registerNoSubmitButton($checkbox_controller_name);
  882. // Prepare Javascript for submit element
  883. $js = "\n//<![CDATA[\n";
  884. if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
  885. $js .= <<<EOS
  886. function html_quickform_toggle_checkboxes(group) {
  887. var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
  888. var newvalue = false;
  889. var global = eval('html_quickform_checkboxgroup' + group + ';');
  890. if (global == 1) {
  891. eval('html_quickform_checkboxgroup' + group + ' = 0;');
  892. newvalue = '';
  893. } else {
  894. eval('html_quickform_checkboxgroup' + group + ' = 1;');
  895. newvalue = 'checked';
  896. }
  897. for (i = 0; i < checkboxes.length; i++) {
  898. checkboxes[i].checked = newvalue;
  899. }
  900. }
  901. EOS;
  902. define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
  903. }
  904. $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
  905. $js .= "//]]>\n";
  906. require_once("$CFG->libdir/form/submitlink.php");
  907. $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
  908. $submitlink->_js = $js;
  909. $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
  910. $mform->addElement($submitlink);
  911. $mform->setDefault($checkbox_controller_name, $text);
  912. }
  913. /**
  914. * Use this method to a cancel and submit button to the end of your form. Pass a param of false
  915. * if you don't want a cancel button in your form. If you have a cancel button make sure you
  916. * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
  917. * get data with get_data().
  918. *
  919. * @param boolean $cancel whether to show cancel button, default true
  920. * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
  921. */
  922. function add_action_buttons($cancel = true, $submitlabel=null){
  923. if (is_null($submitlabel)){
  924. $submitlabel = get_string('savechanges');
  925. }
  926. $mform =& $this->_form;
  927. if ($cancel){
  928. //when two elements we need a group
  929. $buttonarray=array();
  930. $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
  931. $buttonarray[] = &$mform->createElement('cancel');
  932. $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
  933. $mform->closeHeaderBefore('buttonar');
  934. } else {
  935. //no group needed
  936. $mform->addElement('submit', 'submitbutton', $submitlabel);
  937. $mform->closeHeaderBefore('submitbutton');
  938. }
  939. }
  940. /**
  941. * Adds an initialisation call for a standard JavaScript enhancement.
  942. *
  943. * This function is designed to add an initialisation call for a JavaScript
  944. * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
  945. *
  946. * Current options:
  947. * - Selectboxes
  948. * - smartselect: Turns a nbsp indented select box into a custom drop down
  949. * control that supports multilevel and category selection.
  950. * $enhancement = 'smartselect';
  951. * $options = array('selectablecategories' => true|false)
  952. *
  953. * @since 2.0
  954. * @param string|element $element
  955. * @param string $enhancement
  956. * @param array $options
  957. * @param array $strings
  958. */
  959. function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
  960. global $PAGE;
  961. if (is_string($element)) {
  962. $element = $this->_form->getElement($element);
  963. }
  964. if (is_object($element)) {
  965. $element->_generateId();
  966. $elementid = $element->getAttribute('id');
  967. $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
  968. if (is_array($strings)) {
  969. foreach ($strings as $string) {
  970. if (is_array($string)) {
  971. call_user_method_array('string_for_js', $PAGE->requires, $string);
  972. } else {
  973. $PAGE->requires->string_for_js($string, 'moodle');
  974. }
  975. }
  976. }
  977. }
  978. }
  979. /**
  980. * Returns a JS module definition for the mforms JS
  981. * @return array
  982. */
  983. public static function get_js_module() {
  984. global $CFG;
  985. return array(
  986. 'name' => 'mform',
  987. 'fullpath' => '/lib/form/form.js',
  988. 'requires' => array('base', 'node'),
  989. 'strings' => array(
  990. array('showadvanced', 'form'),
  991. array('hideadvanced', 'form')
  992. )
  993. );
  994. }
  995. }
  996. /**
  997. * You never extend this class directly. The class methods of this class are available from
  998. * the private $this->_form property on moodleform and its children. You generally only
  999. * call methods on this class from within abstract methods that you override on moodleform such
  1000. * as definition and definition_after_data
  1001. *
  1002. * @package moodlecore
  1003. * @copyright Jamie Pratt <me@jamiep.org>
  1004. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1005. */
  1006. class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
  1007. /** @var array */
  1008. var $_types = array();
  1009. var $_dependencies = array();
  1010. /**
  1011. * Array of buttons that if pressed do not result in the processing of the form.
  1012. *
  1013. * @var array
  1014. */
  1015. var $_noSubmitButtons=array();
  1016. /**
  1017. * Array of buttons that if pressed do not result in the processing of the form.
  1018. *
  1019. * @var array
  1020. */
  1021. var $_cancelButtons=array();
  1022. /**
  1023. * Array whose keys are element names. If the key exists this is a advanced element
  1024. *
  1025. * @var array
  1026. */
  1027. var $_advancedElements = array();
  1028. /**
  1029. * Whether to display advanced elements (on page load)
  1030. *
  1031. * @var boolean
  1032. */
  1033. var $_showAdvanced = null;
  1034. /**
  1035. * The form name is derived from the class name of the wrapper minus the trailing form
  1036. * It is a name with words joined by underscores whereas the id attribute is words joined by
  1037. * underscores.
  1038. *
  1039. * @var unknown_type
  1040. */
  1041. var $_formName = '';
  1042. /**
  1043. * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
  1044. *
  1045. * @var string
  1046. */
  1047. var $_pageparams = '';
  1048. /**
  1049. * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
  1050. *
  1051. * @global object
  1052. * @staticvar int $formcounter
  1053. * @param string $formName Form's name.
  1054. * @param string $method (optional)Form's method defaults to 'POST'
  1055. * @param mixed $action (optional)Form's action - string or moodle_url
  1056. * @param string $target (optional)Form's target defaults to none
  1057. * @param mixed $attributes (optional)Extra attributes for <form> tag
  1058. * @access public
  1059. */
  1060. function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
  1061. global $CFG, $OUTPUT;
  1062. static $formcounter = 1;
  1063. HTML_Common::HTML_Common($attributes);
  1064. $target = empty($target) ? array() : array('target' => $target);
  1065. $this->_formName = $formName;
  1066. if (is_a($action, 'moodle_url')){
  1067. $this->_pageparams = html_writer::input_hidden_params($action);
  1068. $action = $action->out_omit_querystring();
  1069. } else {
  1070. $this->_pageparams = '';
  1071. }
  1072. //no 'name' atttribute for form in xhtml strict :
  1073. $attributes = array('action'=>$action, 'method'=>$method,
  1074. 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
  1075. $formcounter++;
  1076. $this->updateAttributes($attributes);
  1077. //this is custom stuff for Moodle :
  1078. $oldclass= $this->getAttribute('class');
  1079. if (!empty($oldclass)){
  1080. $this->updateAttributes(array('class'=>$oldclass.' mform'));
  1081. }else {
  1082. $this->updateAttributes(array('class'=>'mform'));
  1083. }
  1084. $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
  1085. $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
  1086. $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
  1087. }
  1088. /**
  1089. * Use this method to indicate an element in a form is an advanced field. If items in a form
  1090. * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
  1091. * form so the user can decide whether to display advanced form controls.
  1092. *
  1093. * If you set a header element to advanced then all elements it contains will also be set as advanced.
  1094. *
  1095. * @param string $elementName group or element name (not the element name of something inside a group).
  1096. * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
  1097. */
  1098. function setAdvanced($elementName, $advanced=true){
  1099. if ($advanced){
  1100. $this->_advancedElements[$elementName]='';
  1101. } elseif (isset($this->_advancedElements[$elementName])) {
  1102. unset($this->_advancedElements[$elementName]);
  1103. }
  1104. if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
  1105. $this->setShowAdvanced();
  1106. $this->registerNoSubmitButton('mform_showadvanced');
  1107. $this->addElement('hidden', 'mform_showadvanced_last');
  1108. $this->setType('mform_showadvanced_last', PARAM_INT);
  1109. }
  1110. }
  1111. /**
  1112. * Set whether to show advanced elements in the form on first displaying form. Default is not to
  1113. * display advanced elements in the form until 'Show Advanced' is pressed.
  1114. *
  1115. * You can get the last state of the form and possibly save it for this user by using
  1116. * value 'mform_showadvanced_last' in submitted data.
  1117. *
  1118. * @param boolean $showadvancedNow
  1119. */
  1120. function setShowAdvanced($showadvancedNow = null){
  1121. if ($showadvancedNow === null){
  1122. if ($this->_showAdvanced !== null){
  1123. return;
  1124. } else { //if setShowAdvanced is called without any preference
  1125. //make the default to not show advanced elements.
  1126. $showadvancedNow = get_user_preferences(
  1127. moodle_strtolower($this->_formName.'_showadvanced', 0));
  1128. }
  1129. }
  1130. //value of hidden element
  1131. $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
  1132. //value of button
  1133. $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
  1134. //toggle if button pressed or else stay the same
  1135. if ($hiddenLast == -1) {
  1136. $next = $showadvancedNow;
  1137. } elseif ($buttonPressed) { //toggle on button press
  1138. $next = !$hiddenLast;
  1139. } else {
  1140. $next = $hiddenLast;
  1141. }
  1142. $this->_showAdvanced = $next;
  1143. if ($showadvancedNow != $next){
  1144. set_user_preference($this->_formName.'_showadvanced', $next);
  1145. }
  1146. $this->setConstants(array('mform_showadvanced_last'=>$next));
  1147. }
  1148. function getShowAdvanced(){
  1149. return $this->_showAdvanced;
  1150. }
  1151. /**
  1152. * Accepts a renderer
  1153. *
  1154. * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
  1155. * @access public
  1156. * @return void
  1157. */
  1158. function accept(&$renderer) {
  1159. if (method_exists($renderer, 'setAdvancedElements')){
  1160. //check for visible fieldsets where all elements are advanced
  1161. //and mark these headers as advanced as well.
  1162. //And mark all elements in a advanced header as advanced
  1163. $stopFields = $renderer->getStopFieldSetElements();
  1164. $lastHeader = null;
  1165. $lastHeaderAdvanced = false;
  1166. $anyAdvanced = false;
  1167. foreach (array_keys($this->_elements) as $elementIndex){
  1168. $element =& $this->_elements[$elementIndex];
  1169. // if closing header and any contained element was advanced then mark it as advanced
  1170. if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
  1171. if ($anyAdvanced && !is_null($lastHeader)){
  1172. $this->setAdvanced($lastHeader->getName());
  1173. }
  1174. $lastHeaderAdvanced = false;
  1175. unset($lastHeader);
  1176. $lastHeader = null;
  1177. } elseif ($lastHeaderAdvanced) {
  1178. $this->setAdvanced($element->getName());
  1179. }
  1180. if ($element->getType()=='header'){
  1181. $lastHeader =& $element;
  1182. $anyAdvanced = false;
  1183. $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
  1184. } elseif (isset($this->_advancedElements[$element->getName()])){
  1185. $anyAdvanced = true;
  1186. }
  1187. }
  1188. // the last header may not be closed yet...
  1189. if ($anyAdvanced && !is_nu

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