PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/formslib.php

https://bitbucket.org/andrewdavidson/sl-clone
PHP | 2586 lines | 1787 code | 178 blank | 621 comment | 220 complexity | 4889ff5bc19ce8f7e76061e8e140b55c MD5 | raw file
Possible License(s): AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, Apache-2.0, GPL-3.0, BSD-3-Clause, LGPL-2.1

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

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