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

/lib/formslib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 2968 lines | 2040 code | 193 blank | 735 comment | 272 complexity | cd085a7cfa6d349893248bb862b6e0a2 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
  18. *
  19. * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
  20. * and you want to name your class something like {modulename}_{purpose}_form. Your class will
  21. * extend moodleform overriding abstract classes definition and optionally defintion_after_data
  22. * and validation.
  23. *
  24. * See examples of use of this library in course/edit.php and course/edit_form.php
  25. *
  26. * A few notes :
  27. * form definition is used for both printing of form and processing and should be the same
  28. * for both or you may lose some submitted data which won't be let through.
  29. * you should be using setType for every form element except select, radio or checkbox
  30. * elements, these elements clean themselves.
  31. *
  32. * @package core_form
  33. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  34. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35. */
  36. defined('MOODLE_INTERNAL') || die();
  37. /** setup.php includes our hacked pear libs first */
  38. require_once 'HTML/QuickForm.php';
  39. require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
  40. require_once 'HTML/QuickForm/Renderer/Tableless.php';
  41. require_once 'HTML/QuickForm/Rule.php';
  42. require_once $CFG->libdir.'/filelib.php';
  43. /**
  44. * EDITOR_UNLIMITED_FILES - hard-coded value for the 'maxfiles' option
  45. */
  46. define('EDITOR_UNLIMITED_FILES', -1);
  47. /**
  48. * Callback called when PEAR throws an error
  49. *
  50. * @param PEAR_Error $error
  51. */
  52. function pear_handle_error($error){
  53. echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
  54. echo '<br /> <strong>Backtrace </strong>:';
  55. print_object($error->backtrace);
  56. }
  57. if ($CFG->debugdeveloper) {
  58. //TODO: this is a wrong place to init PEAR!
  59. $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
  60. $GLOBALS['_PEAR_default_error_options'] = 'pear_handle_error';
  61. }
  62. /**
  63. * Initalize javascript for date type form element
  64. *
  65. * @staticvar bool $done make sure it gets initalize once.
  66. * @global moodle_page $PAGE
  67. */
  68. function form_init_date_js() {
  69. global $PAGE;
  70. static $done = false;
  71. if (!$done) {
  72. $module = 'moodle-form-dateselector';
  73. $function = 'M.form.dateselector.init_date_selectors';
  74. $config = array(array(
  75. 'firstdayofweek' => get_string('firstdayofweek', 'langconfig'),
  76. 'mon' => date_format_string(strtotime("Monday"), '%a', 99),
  77. 'tue' => date_format_string(strtotime("Tuesday"), '%a', 99),
  78. 'wed' => date_format_string(strtotime("Wednesday"), '%a', 99),
  79. 'thu' => date_format_string(strtotime("Thursday"), '%a', 99),
  80. 'fri' => date_format_string(strtotime("Friday"), '%a', 99),
  81. 'sat' => date_format_string(strtotime("Saturday"), '%a', 99),
  82. 'sun' => date_format_string(strtotime("Sunday"), '%a', 99),
  83. 'january' => date_format_string(strtotime("January 1"), '%B', 99),
  84. 'february' => date_format_string(strtotime("February 1"), '%B', 99),
  85. 'march' => date_format_string(strtotime("March 1"), '%B', 99),
  86. 'april' => date_format_string(strtotime("April 1"), '%B', 99),
  87. 'may' => date_format_string(strtotime("May 1"), '%B', 99),
  88. 'june' => date_format_string(strtotime("June 1"), '%B', 99),
  89. 'july' => date_format_string(strtotime("July 1"), '%B', 99),
  90. 'august' => date_format_string(strtotime("August 1"), '%B', 99),
  91. 'september' => date_format_string(strtotime("September 1"), '%B', 99),
  92. 'october' => date_format_string(strtotime("October 1"), '%B', 99),
  93. 'november' => date_format_string(strtotime("November 1"), '%B', 99),
  94. 'december' => date_format_string(strtotime("December 1"), '%B', 99)
  95. ));
  96. $PAGE->requires->yui_module($module, $function, $config);
  97. $done = true;
  98. }
  99. }
  100. /**
  101. * Wrapper that separates quickforms syntax from moodle code
  102. *
  103. * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
  104. * use this class you should write a class definition which extends this class or a more specific
  105. * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
  106. *
  107. * You will write your own definition() method which performs the form set up.
  108. *
  109. * @package core_form
  110. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  111. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  112. * @todo MDL-19380 rethink the file scanning
  113. */
  114. abstract class moodleform {
  115. /** @var string name of the form */
  116. protected $_formname; // form name
  117. /** @var MoodleQuickForm quickform object definition */
  118. protected $_form;
  119. /** @var array globals workaround */
  120. protected $_customdata;
  121. /** @var object definition_after_data executed flag */
  122. protected $_definition_finalized = false;
  123. /**
  124. * The constructor function calls the abstract function definition() and it will then
  125. * process and clean and attempt to validate incoming data.
  126. *
  127. * It will call your custom validate method to validate data and will also check any rules
  128. * you have specified in definition using addRule
  129. *
  130. * The name of the form (id attribute of the form) is automatically generated depending on
  131. * the name you gave the class extending moodleform. You should call your class something
  132. * like
  133. *
  134. * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
  135. * current url. If a moodle_url object then outputs params as hidden variables.
  136. * @param mixed $customdata if your form defintion method needs access to data such as $course
  137. * $cm, etc. to construct the form definition then pass it in this array. You can
  138. * use globals for somethings.
  139. * @param string $method if you set this to anything other than 'post' then _GET and _POST will
  140. * be merged and used as incoming data to the form.
  141. * @param string $target target frame for form submission. You will rarely use this. Don't use
  142. * it if you don't need to as the target attribute is deprecated in xhtml strict.
  143. * @param mixed $attributes you can pass a string of html attributes here or an array.
  144. * @param bool $editable
  145. */
  146. function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
  147. global $CFG, $FULLME;
  148. // no standard mform in moodle should allow autocomplete with the exception of user signup
  149. if (empty($attributes)) {
  150. $attributes = array('autocomplete'=>'off');
  151. } else if (is_array($attributes)) {
  152. $attributes['autocomplete'] = 'off';
  153. } else {
  154. if (strpos($attributes, 'autocomplete') === false) {
  155. $attributes .= ' autocomplete="off" ';
  156. }
  157. }
  158. if (empty($action)){
  159. // do not rely on PAGE->url here because dev often do not setup $actualurl properly in admin_externalpage_setup()
  160. $action = strip_querystring($FULLME);
  161. if (!empty($CFG->sslproxy)) {
  162. // return only https links when using SSL proxy
  163. $action = preg_replace('/^http:/', 'https:', $action, 1);
  164. }
  165. //TODO: use following instead of FULLME - see MDL-33015
  166. //$action = strip_querystring(qualified_me());
  167. }
  168. // Assign custom data first, so that get_form_identifier can use it.
  169. $this->_customdata = $customdata;
  170. $this->_formname = $this->get_form_identifier();
  171. $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
  172. if (!$editable){
  173. $this->_form->hardFreeze();
  174. }
  175. $this->definition();
  176. $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
  177. $this->_form->setType('sesskey', PARAM_RAW);
  178. $this->_form->setDefault('sesskey', sesskey());
  179. $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
  180. $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
  181. $this->_form->setDefault('_qf__'.$this->_formname, 1);
  182. $this->_form->_setDefaultRuleMessages();
  183. // we have to know all input types before processing submission ;-)
  184. $this->_process_submission($method);
  185. }
  186. /**
  187. * It should returns unique identifier for the form.
  188. * Currently it will return class name, but in case two same forms have to be
  189. * rendered on same page then override function to get unique form identifier.
  190. * e.g This is used on multiple self enrollments page.
  191. *
  192. * @return string form identifier.
  193. */
  194. protected function get_form_identifier() {
  195. return get_class($this);
  196. }
  197. /**
  198. * To autofocus on first form element or first element with error.
  199. *
  200. * @param string $name if this is set then the focus is forced to a field with this name
  201. * @return string javascript to select form element with first error or
  202. * first element if no errors. Use this as a parameter
  203. * when calling print_header
  204. */
  205. function focus($name=NULL) {
  206. $form =& $this->_form;
  207. $elkeys = array_keys($form->_elementIndex);
  208. $error = false;
  209. if (isset($form->_errors) && 0 != count($form->_errors)){
  210. $errorkeys = array_keys($form->_errors);
  211. $elkeys = array_intersect($elkeys, $errorkeys);
  212. $error = true;
  213. }
  214. if ($error or empty($name)) {
  215. $names = array();
  216. while (empty($names) and !empty($elkeys)) {
  217. $el = array_shift($elkeys);
  218. $names = $form->_getElNamesRecursive($el);
  219. }
  220. if (!empty($names)) {
  221. $name = array_shift($names);
  222. }
  223. }
  224. $focus = '';
  225. if (!empty($name)) {
  226. $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
  227. }
  228. return $focus;
  229. }
  230. /**
  231. * Internal method. Alters submitted data to be suitable for quickforms processing.
  232. * Must be called when the form is fully set up.
  233. *
  234. * @param string $method name of the method which alters submitted data
  235. */
  236. function _process_submission($method) {
  237. $submission = array();
  238. if ($method == 'post') {
  239. if (!empty($_POST)) {
  240. $submission = $_POST;
  241. }
  242. } else {
  243. $submission = $_GET;
  244. merge_query_params($submission, $_POST); // Emulate handling of parameters in xxxx_param().
  245. }
  246. // following trick is needed to enable proper sesskey checks when using GET forms
  247. // the _qf__.$this->_formname serves as a marker that form was actually submitted
  248. if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
  249. if (!confirm_sesskey()) {
  250. print_error('invalidsesskey');
  251. }
  252. $files = $_FILES;
  253. } else {
  254. $submission = array();
  255. $files = array();
  256. }
  257. $this->detectMissingSetType();
  258. $this->_form->updateSubmission($submission, $files);
  259. }
  260. /**
  261. * Internal method - should not be used anywhere.
  262. * @deprecated since 2.6
  263. * @return array $_POST.
  264. */
  265. protected function _get_post_params() {
  266. return $_POST;
  267. }
  268. /**
  269. * Internal method. Validates all old-style deprecated uploaded files.
  270. * The new way is to upload files via repository api.
  271. *
  272. * @param array $files list of files to be validated
  273. * @return bool|array Success or an array of errors
  274. */
  275. function _validate_files(&$files) {
  276. global $CFG, $COURSE;
  277. $files = array();
  278. if (empty($_FILES)) {
  279. // we do not need to do any checks because no files were submitted
  280. // note: server side rules do not work for files - use custom verification in validate() instead
  281. return true;
  282. }
  283. $errors = array();
  284. $filenames = array();
  285. // now check that we really want each file
  286. foreach ($_FILES as $elname=>$file) {
  287. $required = $this->_form->isElementRequired($elname);
  288. if ($file['error'] == 4 and $file['size'] == 0) {
  289. if ($required) {
  290. $errors[$elname] = get_string('required');
  291. }
  292. unset($_FILES[$elname]);
  293. continue;
  294. }
  295. if (!empty($file['error'])) {
  296. $errors[$elname] = file_get_upload_error($file['error']);
  297. unset($_FILES[$elname]);
  298. continue;
  299. }
  300. if (!is_uploaded_file($file['tmp_name'])) {
  301. // TODO: improve error message
  302. $errors[$elname] = get_string('error');
  303. unset($_FILES[$elname]);
  304. continue;
  305. }
  306. if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
  307. // hmm, this file was not requested
  308. unset($_FILES[$elname]);
  309. continue;
  310. }
  311. /*
  312. // TODO: rethink the file scanning MDL-19380
  313. if ($CFG->runclamonupload) {
  314. if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
  315. $errors[$elname] = $_FILES[$elname]['uploadlog'];
  316. unset($_FILES[$elname]);
  317. continue;
  318. }
  319. }
  320. */
  321. $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
  322. if ($filename === '') {
  323. // TODO: improve error message - wrong chars
  324. $errors[$elname] = get_string('error');
  325. unset($_FILES[$elname]);
  326. continue;
  327. }
  328. if (in_array($filename, $filenames)) {
  329. // TODO: improve error message - duplicate name
  330. $errors[$elname] = get_string('error');
  331. unset($_FILES[$elname]);
  332. continue;
  333. }
  334. $filenames[] = $filename;
  335. $_FILES[$elname]['name'] = $filename;
  336. $files[$elname] = $_FILES[$elname]['tmp_name'];
  337. }
  338. // return errors if found
  339. if (count($errors) == 0){
  340. return true;
  341. } else {
  342. $files = array();
  343. return $errors;
  344. }
  345. }
  346. /**
  347. * Internal method. Validates filepicker and filemanager files if they are
  348. * set as required fields. Also, sets the error message if encountered one.
  349. *
  350. * @return bool|array with errors
  351. */
  352. protected function validate_draft_files() {
  353. global $USER;
  354. $mform =& $this->_form;
  355. $errors = array();
  356. //Go through all the required elements and make sure you hit filepicker or
  357. //filemanager element.
  358. foreach ($mform->_rules as $elementname => $rules) {
  359. $elementtype = $mform->getElementType($elementname);
  360. //If element is of type filepicker then do validation
  361. if (($elementtype == 'filepicker') || ($elementtype == 'filemanager')){
  362. //Check if rule defined is required rule
  363. foreach ($rules as $rule) {
  364. if ($rule['type'] == 'required') {
  365. $draftid = (int)$mform->getSubmitValue($elementname);
  366. $fs = get_file_storage();
  367. $context = context_user::instance($USER->id);
  368. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  369. $errors[$elementname] = $rule['message'];
  370. }
  371. }
  372. }
  373. }
  374. }
  375. // Check all the filemanager elements to make sure they do not have too many
  376. // files in them.
  377. foreach ($mform->_elements as $element) {
  378. if ($element->_type == 'filemanager') {
  379. $maxfiles = $element->getMaxfiles();
  380. if ($maxfiles > 0) {
  381. $draftid = (int)$element->getValue();
  382. $fs = get_file_storage();
  383. $context = context_user::instance($USER->id);
  384. $files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, '', false);
  385. if (count($files) > $maxfiles) {
  386. $errors[$element->getName()] = get_string('err_maxfiles', 'form', $maxfiles);
  387. }
  388. }
  389. }
  390. }
  391. if (empty($errors)) {
  392. return true;
  393. } else {
  394. return $errors;
  395. }
  396. }
  397. /**
  398. * Load in existing data as form defaults. Usually new entry defaults are stored directly in
  399. * form definition (new entry form); this function is used to load in data where values
  400. * already exist and data is being edited (edit entry form).
  401. *
  402. * note: $slashed param removed
  403. *
  404. * @param stdClass|array $default_values object or array of default values
  405. */
  406. function set_data($default_values) {
  407. if (is_object($default_values)) {
  408. $default_values = (array)$default_values;
  409. }
  410. $this->_form->setDefaults($default_values);
  411. }
  412. /**
  413. * Check that form was submitted. Does not check validity of submitted data.
  414. *
  415. * @return bool true if form properly submitted
  416. */
  417. function is_submitted() {
  418. return $this->_form->isSubmitted();
  419. }
  420. /**
  421. * Checks if button pressed is not for submitting the form
  422. *
  423. * @staticvar bool $nosubmit keeps track of no submit button
  424. * @return bool
  425. */
  426. function no_submit_button_pressed(){
  427. static $nosubmit = null; // one check is enough
  428. if (!is_null($nosubmit)){
  429. return $nosubmit;
  430. }
  431. $mform =& $this->_form;
  432. $nosubmit = false;
  433. if (!$this->is_submitted()){
  434. return false;
  435. }
  436. foreach ($mform->_noSubmitButtons as $nosubmitbutton){
  437. if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
  438. $nosubmit = true;
  439. break;
  440. }
  441. }
  442. return $nosubmit;
  443. }
  444. /**
  445. * Check that form data is valid.
  446. * You should almost always use this, rather than {@link validate_defined_fields}
  447. *
  448. * @return bool true if form data valid
  449. */
  450. function is_validated() {
  451. //finalize the form definition before any processing
  452. if (!$this->_definition_finalized) {
  453. $this->_definition_finalized = true;
  454. $this->definition_after_data();
  455. }
  456. return $this->validate_defined_fields();
  457. }
  458. /**
  459. * Validate the form.
  460. *
  461. * You almost always want to call {@link is_validated} instead of this
  462. * because it calls {@link definition_after_data} first, before validating the form,
  463. * which is what you want in 99% of cases.
  464. *
  465. * This is provided as a separate function for those special cases where
  466. * you want the form validated before definition_after_data is called
  467. * for example, to selectively add new elements depending on a no_submit_button press,
  468. * but only when the form is valid when the no_submit_button is pressed,
  469. *
  470. * @param bool $validateonnosubmit optional, defaults to false. The default behaviour
  471. * is NOT to validate the form when a no submit button has been pressed.
  472. * pass true here to override this behaviour
  473. *
  474. * @return bool true if form data valid
  475. */
  476. function validate_defined_fields($validateonnosubmit=false) {
  477. static $validated = null; // one validation is enough
  478. $mform =& $this->_form;
  479. if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
  480. return false;
  481. } elseif ($validated === null) {
  482. $internal_val = $mform->validate();
  483. $files = array();
  484. $file_val = $this->_validate_files($files);
  485. //check draft files for validation and flag them if required files
  486. //are not in draft area.
  487. $draftfilevalue = $this->validate_draft_files();
  488. if ($file_val !== true && $draftfilevalue !== true) {
  489. $file_val = array_merge($file_val, $draftfilevalue);
  490. } else if ($draftfilevalue !== true) {
  491. $file_val = $draftfilevalue;
  492. } //default is file_val, so no need to assign.
  493. if ($file_val !== true) {
  494. if (!empty($file_val)) {
  495. foreach ($file_val as $element=>$msg) {
  496. $mform->setElementError($element, $msg);
  497. }
  498. }
  499. $file_val = false;
  500. }
  501. $data = $mform->exportValues();
  502. $moodle_val = $this->validation($data, $files);
  503. if ((is_array($moodle_val) && count($moodle_val)!==0)) {
  504. // non-empty array means errors
  505. foreach ($moodle_val as $element=>$msg) {
  506. $mform->setElementError($element, $msg);
  507. }
  508. $moodle_val = false;
  509. } else {
  510. // anything else means validation ok
  511. $moodle_val = true;
  512. }
  513. $validated = ($internal_val and $moodle_val and $file_val);
  514. }
  515. return $validated;
  516. }
  517. /**
  518. * Return true if a cancel button has been pressed resulting in the form being submitted.
  519. *
  520. * @return bool true if a cancel button has been pressed
  521. */
  522. function is_cancelled(){
  523. $mform =& $this->_form;
  524. if ($mform->isSubmitted()){
  525. foreach ($mform->_cancelButtons as $cancelbutton){
  526. if (optional_param($cancelbutton, 0, PARAM_RAW)){
  527. return true;
  528. }
  529. }
  530. }
  531. return false;
  532. }
  533. /**
  534. * Return submitted data if properly submitted or returns NULL if validation fails or
  535. * if there is no submitted data.
  536. *
  537. * note: $slashed param removed
  538. *
  539. * @return object submitted data; NULL if not valid or not submitted or cancelled
  540. */
  541. function get_data() {
  542. $mform =& $this->_form;
  543. if (!$this->is_cancelled() and $this->is_submitted() and $this->is_validated()) {
  544. $data = $mform->exportValues();
  545. unset($data['sesskey']); // we do not need to return sesskey
  546. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  547. if (empty($data)) {
  548. return NULL;
  549. } else {
  550. return (object)$data;
  551. }
  552. } else {
  553. return NULL;
  554. }
  555. }
  556. /**
  557. * Return submitted data without validation or NULL if there is no submitted data.
  558. * note: $slashed param removed
  559. *
  560. * @return object submitted data; NULL if not submitted
  561. */
  562. function get_submitted_data() {
  563. $mform =& $this->_form;
  564. if ($this->is_submitted()) {
  565. $data = $mform->exportValues();
  566. unset($data['sesskey']); // we do not need to return sesskey
  567. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  568. if (empty($data)) {
  569. return NULL;
  570. } else {
  571. return (object)$data;
  572. }
  573. } else {
  574. return NULL;
  575. }
  576. }
  577. /**
  578. * Save verified uploaded files into directory. Upload process can be customised from definition()
  579. *
  580. * @deprecated since Moodle 2.0
  581. * @todo MDL-31294 remove this api
  582. * @see moodleform::save_stored_file()
  583. * @see moodleform::save_file()
  584. * @param string $destination path where file should be stored
  585. * @return bool Always false
  586. */
  587. function save_files($destination) {
  588. debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
  589. return false;
  590. }
  591. /**
  592. * Returns name of uploaded file.
  593. *
  594. * @param string $elname first element if null
  595. * @return string|bool false in case of failure, string if ok
  596. */
  597. function get_new_filename($elname=null) {
  598. global $USER;
  599. if (!$this->is_submitted() or !$this->is_validated()) {
  600. return false;
  601. }
  602. if (is_null($elname)) {
  603. if (empty($_FILES)) {
  604. return false;
  605. }
  606. reset($_FILES);
  607. $elname = key($_FILES);
  608. }
  609. if (empty($elname)) {
  610. return false;
  611. }
  612. $element = $this->_form->getElement($elname);
  613. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  614. $values = $this->_form->exportValues($elname);
  615. if (empty($values[$elname])) {
  616. return false;
  617. }
  618. $draftid = $values[$elname];
  619. $fs = get_file_storage();
  620. $context = context_user::instance($USER->id);
  621. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  622. return false;
  623. }
  624. $file = reset($files);
  625. return $file->get_filename();
  626. }
  627. if (!isset($_FILES[$elname])) {
  628. return false;
  629. }
  630. return $_FILES[$elname]['name'];
  631. }
  632. /**
  633. * Save file to standard filesystem
  634. *
  635. * @param string $elname name of element
  636. * @param string $pathname full path name of file
  637. * @param bool $override override file if exists
  638. * @return bool success
  639. */
  640. function save_file($elname, $pathname, $override=false) {
  641. global $USER;
  642. if (!$this->is_submitted() or !$this->is_validated()) {
  643. return false;
  644. }
  645. if (file_exists($pathname)) {
  646. if ($override) {
  647. if (!@unlink($pathname)) {
  648. return false;
  649. }
  650. } else {
  651. return false;
  652. }
  653. }
  654. $element = $this->_form->getElement($elname);
  655. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  656. $values = $this->_form->exportValues($elname);
  657. if (empty($values[$elname])) {
  658. return false;
  659. }
  660. $draftid = $values[$elname];
  661. $fs = get_file_storage();
  662. $context = context_user::instance($USER->id);
  663. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  664. return false;
  665. }
  666. $file = reset($files);
  667. return $file->copy_content_to($pathname);
  668. } else if (isset($_FILES[$elname])) {
  669. return copy($_FILES[$elname]['tmp_name'], $pathname);
  670. }
  671. return false;
  672. }
  673. /**
  674. * Returns a temporary file, do not forget to delete after not needed any more.
  675. *
  676. * @param string $elname name of the elmenet
  677. * @return string|bool either string or false
  678. */
  679. function save_temp_file($elname) {
  680. if (!$this->get_new_filename($elname)) {
  681. return false;
  682. }
  683. if (!$dir = make_temp_directory('forms')) {
  684. return false;
  685. }
  686. if (!$tempfile = tempnam($dir, 'tempup_')) {
  687. return false;
  688. }
  689. if (!$this->save_file($elname, $tempfile, true)) {
  690. // something went wrong
  691. @unlink($tempfile);
  692. return false;
  693. }
  694. return $tempfile;
  695. }
  696. /**
  697. * Get draft files of a form element
  698. * This is a protected method which will be used only inside moodleforms
  699. *
  700. * @param string $elname name of element
  701. * @return array|bool|null
  702. */
  703. protected function get_draft_files($elname) {
  704. global $USER;
  705. if (!$this->is_submitted()) {
  706. return false;
  707. }
  708. $element = $this->_form->getElement($elname);
  709. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  710. $values = $this->_form->exportValues($elname);
  711. if (empty($values[$elname])) {
  712. return false;
  713. }
  714. $draftid = $values[$elname];
  715. $fs = get_file_storage();
  716. $context = context_user::instance($USER->id);
  717. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  718. return null;
  719. }
  720. return $files;
  721. }
  722. return null;
  723. }
  724. /**
  725. * Save file to local filesystem pool
  726. *
  727. * @param string $elname name of element
  728. * @param int $newcontextid id of context
  729. * @param string $newcomponent name of the component
  730. * @param string $newfilearea name of file area
  731. * @param int $newitemid item id
  732. * @param string $newfilepath path of file where it get stored
  733. * @param string $newfilename use specified filename, if not specified name of uploaded file used
  734. * @param bool $overwrite overwrite file if exists
  735. * @param int $newuserid new userid if required
  736. * @return mixed stored_file object or false if error; may throw exception if duplicate found
  737. */
  738. function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
  739. $newfilename=null, $overwrite=false, $newuserid=null) {
  740. global $USER;
  741. if (!$this->is_submitted() or !$this->is_validated()) {
  742. return false;
  743. }
  744. if (empty($newuserid)) {
  745. $newuserid = $USER->id;
  746. }
  747. $element = $this->_form->getElement($elname);
  748. $fs = get_file_storage();
  749. if ($element instanceof MoodleQuickForm_filepicker) {
  750. $values = $this->_form->exportValues($elname);
  751. if (empty($values[$elname])) {
  752. return false;
  753. }
  754. $draftid = $values[$elname];
  755. $context = context_user::instance($USER->id);
  756. if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
  757. return false;
  758. }
  759. $file = reset($files);
  760. if (is_null($newfilename)) {
  761. $newfilename = $file->get_filename();
  762. }
  763. if ($overwrite) {
  764. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  765. if (!$oldfile->delete()) {
  766. return false;
  767. }
  768. }
  769. }
  770. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  771. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  772. return $fs->create_file_from_storedfile($file_record, $file);
  773. } else if (isset($_FILES[$elname])) {
  774. $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
  775. if ($overwrite) {
  776. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  777. if (!$oldfile->delete()) {
  778. return false;
  779. }
  780. }
  781. }
  782. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  783. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  784. return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
  785. }
  786. return false;
  787. }
  788. /**
  789. * Get content of uploaded file.
  790. *
  791. * @param string $elname name of file upload element
  792. * @return string|bool false in case of failure, string if ok
  793. */
  794. function get_file_content($elname) {
  795. global $USER;
  796. if (!$this->is_submitted() or !$this->is_validated()) {
  797. return false;
  798. }
  799. $element = $this->_form->getElement($elname);
  800. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  801. $values = $this->_form->exportValues($elname);
  802. if (empty($values[$elname])) {
  803. return false;
  804. }
  805. $draftid = $values[$elname];
  806. $fs = get_file_storage();
  807. $context = context_user::instance($USER->id);
  808. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  809. return false;
  810. }
  811. $file = reset($files);
  812. return $file->get_content();
  813. } else if (isset($_FILES[$elname])) {
  814. return file_get_contents($_FILES[$elname]['tmp_name']);
  815. }
  816. return false;
  817. }
  818. /**
  819. * Print html form.
  820. */
  821. function display() {
  822. //finalize the form definition if not yet done
  823. if (!$this->_definition_finalized) {
  824. $this->_definition_finalized = true;
  825. $this->definition_after_data();
  826. }
  827. $this->_form->display();
  828. }
  829. /**
  830. * Renders the html form (same as display, but returns the result).
  831. *
  832. * Note that you can only output this rendered result once per page, as
  833. * it contains IDs which must be unique.
  834. *
  835. * @return string HTML code for the form
  836. */
  837. public function render() {
  838. ob_start();
  839. $this->display();
  840. $out = ob_get_contents();
  841. ob_end_clean();
  842. return $out;
  843. }
  844. /**
  845. * Form definition. Abstract method - always override!
  846. */
  847. protected abstract function definition();
  848. /**
  849. * Dummy stub method - override if you need to setup the form depending on current
  850. * values. This method is called after definition(), data submission and set_data().
  851. * All form setup that is dependent on form values should go in here.
  852. */
  853. function definition_after_data(){
  854. }
  855. /**
  856. * Dummy stub method - override if you needed to perform some extra validation.
  857. * If there are errors return array of errors ("fieldname"=>"error message"),
  858. * otherwise true if ok.
  859. *
  860. * Server side rules do not work for uploaded files, implement serverside rules here if needed.
  861. *
  862. * @param array $data array of ("fieldname"=>value) of submitted data
  863. * @param array $files array of uploaded files "element_name"=>tmp_file_path
  864. * @return array of "element_name"=>"error_description" if there are errors,
  865. * or an empty array if everything is OK (true allowed for backwards compatibility too).
  866. */
  867. function validation($data, $files) {
  868. return array();
  869. }
  870. /**
  871. * Helper used by {@link repeat_elements()}.
  872. *
  873. * @param int $i the index of this element.
  874. * @param HTML_QuickForm_element $elementclone
  875. * @param array $namecloned array of names
  876. */
  877. function repeat_elements_fix_clone($i, $elementclone, &$namecloned) {
  878. $name = $elementclone->getName();
  879. $namecloned[] = $name;
  880. if (!empty($name)) {
  881. $elementclone->setName($name."[$i]");
  882. }
  883. if (is_a($elementclone, 'HTML_QuickForm_header')) {
  884. $value = $elementclone->_text;
  885. $elementclone->setValue(str_replace('{no}', ($i+1), $value));
  886. } else if (is_a($elementclone, 'HTML_QuickForm_submit') || is_a($elementclone, 'HTML_QuickForm_button')) {
  887. $elementclone->setValue(str_replace('{no}', ($i+1), $elementclone->getValue()));
  888. } else {
  889. $value=$elementclone->getLabel();
  890. $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
  891. }
  892. }
  893. /**
  894. * Method to add a repeating group of elements to a form.
  895. *
  896. * @param array $elementobjs Array of elements or groups of elements that are to be repeated
  897. * @param int $repeats no of times to repeat elements initially
  898. * @param array $options a nested array. The first array key is the element name.
  899. * the second array key is the type of option to set, and depend on that option,
  900. * the value takes different forms.
  901. * 'default' - default value to set. Can include '{no}' which is replaced by the repeat number.
  902. * 'type' - PARAM_* type.
  903. * 'helpbutton' - array containing the helpbutton params.
  904. * 'disabledif' - array containing the disabledIf() arguments after the element name.
  905. * 'rule' - array containing the addRule arguments after the element name.
  906. * 'expanded' - whether this section of the form should be expanded by default. (Name be a header element.)
  907. * 'advanced' - whether this element is hidden by 'Show more ...'.
  908. * @param string $repeathiddenname name for hidden element storing no of repeats in this form
  909. * @param string $addfieldsname name for button to add more fields
  910. * @param int $addfieldsno how many fields to add at a time
  911. * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
  912. * @param bool $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
  913. * @return int no of repeats of element in this page
  914. */
  915. function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
  916. $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
  917. if ($addstring===null){
  918. $addstring = get_string('addfields', 'form', $addfieldsno);
  919. } else {
  920. $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
  921. }
  922. $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
  923. $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
  924. if (!empty($addfields)){
  925. $repeats += $addfieldsno;
  926. }
  927. $mform =& $this->_form;
  928. $mform->registerNoSubmitButton($addfieldsname);
  929. $mform->addElement('hidden', $repeathiddenname, $repeats);
  930. $mform->setType($repeathiddenname, PARAM_INT);
  931. //value not to be overridden by submitted value
  932. $mform->setConstants(array($repeathiddenname=>$repeats));
  933. $namecloned = array();
  934. for ($i = 0; $i < $repeats; $i++) {
  935. foreach ($elementobjs as $elementobj){
  936. $elementclone = fullclone($elementobj);
  937. $this->repeat_elements_fix_clone($i, $elementclone, $namecloned);
  938. if ($elementclone instanceof HTML_QuickForm_group && !$elementclone->_appendName) {
  939. foreach ($elementclone->getElements() as $el) {
  940. $this->repeat_elements_fix_clone($i, $el, $namecloned);
  941. }
  942. $elementclone->setLabel(str_replace('{no}', $i + 1, $elementclone->getLabel()));
  943. }
  944. $mform->addElement($elementclone);
  945. }
  946. }
  947. for ($i=0; $i<$repeats; $i++) {
  948. foreach ($options as $elementname => $elementoptions){
  949. $pos=strpos($elementname, '[');
  950. if ($pos!==FALSE){
  951. $realelementname = substr($elementname, 0, $pos)."[$i]";
  952. $realelementname .= substr($elementname, $pos);
  953. }else {
  954. $realelementname = $elementname."[$i]";
  955. }
  956. foreach ($elementoptions as $option => $params){
  957. switch ($option){
  958. case 'default' :
  959. $mform->setDefault($realelementname, str_replace('{no}', $i + 1, $params));
  960. break;
  961. case 'helpbutton' :
  962. $params = array_merge(array($realelementname), $params);
  963. call_user_func_array(array(&$mform, 'addHelpButton'), $params);
  964. break;
  965. case 'disabledif' :
  966. foreach ($namecloned as $num => $name){
  967. if ($params[0] == $name){
  968. $params[0] = $params[0]."[$i]";
  969. break;
  970. }
  971. }
  972. $params = array_merge(array($realelementname), $params);
  973. call_user_func_array(array(&$mform, 'disabledIf'), $params);
  974. break;
  975. case 'rule' :
  976. if (is_string($params)){
  977. $params = array(null, $params, null, 'client');
  978. }
  979. $params = array_merge(array($realelementname), $params);
  980. call_user_func_array(array(&$mform, 'addRule'), $params);
  981. break;
  982. case 'type':
  983. $mform->setType($realelementname, $params);
  984. break;
  985. case 'expanded':
  986. $mform->setExpanded($realelementname, $params);
  987. break;
  988. case 'advanced' :
  989. $mform->setAdvanced($realelementname, $params);
  990. break;
  991. }
  992. }
  993. }
  994. }
  995. $mform->addElement('submit', $addfieldsname, $addstring);
  996. if (!$addbuttoninside) {
  997. $mform->closeHeaderBefore($addfieldsname);
  998. }
  999. return $repeats;
  1000. }
  1001. /**
  1002. * Adds a link/button that controls the checked state of a group of checkboxes.
  1003. *
  1004. * @param int $groupid The id of the group of advcheckboxes this element controls
  1005. * @param string $text The text of the link. Defaults to selectallornone ("select all/none")
  1006. * @param array $attributes associative array of HTML attributes
  1007. * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
  1008. */
  1009. function add_checkbox_controller($groupid, $text = null, $attributes = null, $originalValue = 0) {
  1010. global $CFG, $PAGE;
  1011. // Name of the controller button
  1012. $checkboxcontrollername = 'nosubmit_checkbox_controller' . $groupid;
  1013. $checkboxcontrollerparam = 'checkbox_controller'. $groupid;
  1014. $checkboxgroupclass = 'checkboxgroup'.$groupid;
  1015. // Set the default text if none was specified
  1016. if (empty($text)) {
  1017. $text = get_string('selectallornone', 'form');
  1018. }
  1019. $mform = $this->_form;
  1020. $selectvalue = optional_param($checkboxcontrollerparam, null, PARAM_INT);
  1021. $contollerbutton = optional_param($checkboxcontrollername, null, PARAM_ALPHAEXT);
  1022. $newselectvalue = $selectvalue;
  1023. if (is_null($selectvalue)) {
  1024. $newselectvalue = $originalValue;
  1025. } else if (!is_null($contollerbutton)) {
  1026. $newselectvalue = (int) !$selectvalue;
  1027. }
  1028. // set checkbox state depending on orignal/submitted value by controoler button
  1029. if (!is_null($contollerbutton) || is_null($selectvalue)) {
  1030. foreach ($mform->_elements as $element) {
  1031. if (($element instanceof MoodleQuickForm_advcheckbox) &&
  1032. $element->getAttribute('class') == $checkboxgroupclass &&
  1033. !$element->isFrozen()) {
  1034. $mform->setConstants(array($element->getName() => $newselectvalue));
  1035. }
  1036. }
  1037. }
  1038. $mform->addElement('hidden', $checkboxcontrollerparam, $newselectvalue, array('id' => "id_".$checkboxcontrollerparam));
  1039. $mform->setType($checkboxcontrollerparam, PARAM_INT);
  1040. $mform->setConstants(array($checkboxcontrollerparam => $newselectvalue));
  1041. $PAGE->requires->yui_module('moodle-form-checkboxcontroller', 'M.form.checkboxcontroller',
  1042. array(
  1043. array('groupid' => $groupid,
  1044. 'checkboxclass' => $checkboxgroupclass,
  1045. 'checkboxcontroller' => $checkboxcontrollerparam,
  1046. 'controllerbutton' => $checkboxcontrollername)
  1047. )
  1048. );
  1049. require_once("$CFG->libdir/form/submit.php");
  1050. $submitlink = new MoodleQuickForm_submit($checkboxcontrollername, $attributes);
  1051. $mform->addElement($submitlink);
  1052. $mform->registerNoSubmitButton($checkboxcontrollername);
  1053. $mform->setDefault($checkboxcontrollername, $text);
  1054. }
  1055. /**
  1056. * Use this method to a cancel and submit button to the end of your form. Pass a param of false
  1057. * if you don't want a cancel button in your form. If you have a cancel button make sure you
  1058. * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
  1059. * get data with get_data().
  1060. *
  1061. * @param bool $cancel whether to show cancel button, default true
  1062. * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
  1063. */
  1064. function add_action_buttons($cancel = true, $submitlabel=null){
  1065. if (is_null($submitlabel)){
  1066. $submitlabel = get_string('savechanges');
  1067. }
  1068. $mform =& $this->_form;
  1069. if ($cancel){
  1070. //when two elements we need a group
  1071. $buttonarray=array();
  1072. $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
  1073. $buttonarray[] = &$mform->createElement('cancel');
  1074. $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
  1075. $mform->closeHeaderBefore('buttonar');
  1076. } else {
  1077. //no group needed
  1078. $mform->addElement('submit', 'submitbutton', $submitlabel);
  1079. $mform->closeHeaderBefore('submitbutton');
  1080. }
  1081. }
  1082. /**
  1083. * Adds an initialisation call for a standard JavaScript enhancement.
  1084. *
  1085. * This function is designed to add an initialisation call for a JavaScript
  1086. * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
  1087. *
  1088. * Current options:
  1089. * - Selectboxes
  1090. * - smartselect: Turns a nbsp indented select box into a custom drop down
  1091. * control that supports multilevel and category selection.
  1092. * $enhancement = 'smartselect';
  1093. * $options = array('selectablecategories' => true|false)
  1094. *
  1095. * @since Moodle 2.0
  1096. * @param string|element $element form element for which Javascript needs to be initalized
  1097. * @param string $enhancement which init function should be called
  1098. * @param array $options options passed to javascript
  1099. * @param array $strings strings for javascript
  1100. */
  1101. function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
  1102. global $PAGE;
  1103. if (is_string($element)) {
  1104. $element = $this->_form->getElement($element);
  1105. }
  1106. if (is_object($element)) {
  1107. $element->_generateId();
  1108. $elementid = $element->getAttribute('id');
  1109. $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
  1110. if (is_array($strings)) {
  1111. foreach ($strings as $string) {
  1112. if (is_array($string)) {
  1113. call_user_method_array('string_for_js', $PAGE->requires, $string);
  1114. } else {
  1115. $PAGE->requires->string_for_js($string, 'moodle');
  1116. }
  1117. }
  1118. }
  1119. }
  1120. }
  1121. /**
  1122. * Returns a JS module definition for the mforms JS
  1123. *
  1124. * @return array
  1125. */
  1126. public static function get_js_module() {
  1127. global $CFG;
  1128. return array(
  1129. 'name' => 'mform',
  1130. 'fullpath' => '/lib/form/form.js',
  1131. 'requires' => array('base', 'node')
  1132. );
  1133. }
  1134. /**
  1135. * Detects elements with missing setType() declerations.
  1136. *
  1137. * Finds elements in the form which should a PARAM_ type set and throws a
  1138. * developer debug warning for any elements without it. This is to reduce the
  1139. * risk of potential security issues by developers mistakenly forgetting to set
  1140. * the type.
  1141. *
  1142. * @return void
  1143. */
  1144. private function detectMissingSetType() {
  1145. global $CFG;
  1146. if (!$CFG->debugdeveloper) {
  1147. // Only for devs.
  1148. return;
  1149. }
  1150. $mform = $this->_form;
  1151. foreach ($mform->_elements as $element) {
  1152. $group = false;
  1153. $elements = array($element);
  1154. if ($element->getType() == 'group') {
  1155. $group = $element;
  1156. $elements = $element->getElements();
  1157. }
  1158. foreach ($elements as $index => $element) {
  1159. switch ($element->getType()) {
  1160. case 'hidden':
  1161. case 'text':
  1162. case 'url':
  1163. if ($group) {
  1164. $name = $group->getElementName($index);
  1165. } else {
  1166. $name = $element->getName();
  1167. }
  1168. $key = $name;
  1169. $found = array_key_exists($key, $mform->_types);
  1170. // For repeated elements we need to look for
  1171. // the "main" type, not for the one present
  1172. // on each repetition. All the stuff in formslib
  1173. // (repeat_elements(), updateSubmission()... seems
  1174. // to work that way.
  1175. while (!$found && strrpos($key, '[') !== false) {
  1176. $pos = strrpos($key, '[');
  1177. $key = substr($key, 0, $pos);
  1178. $found = array_key_exists($key, $mform->_types);
  1179. }
  1180. if (!$found) {
  1181. debugging("Did you remember to call setType() for '$name'? ".
  1182. 'Defaulting to PARAM_RAW cleaning.', DEBUG_DEVELOPER);
  1183. }
  1184. break;
  1185. }
  1186. }
  1187. }
  1188. }
  1189. /**
  1190. * Used by tests to simulate submitted form data submission from the user.
  1191. *
  1192. * For form fields where no data is submitted the default for that field as set by set_data or setDefault will be passed to
  1193. * get_data.
  1194. *
  1195. * This method sets $_POST or $_GET and $_FILES with the data supplied. Our unit test code empties all these
  1196. * global arrays after each test.
  1197. *
  1198. * @param array $simulatedsubmitteddata An associative array of form values (same format as $_POST).
  1199. * @param array $simulatedsubmittedfiles An associative array of files uploaded (same format as $_FILES). Can be omitted.
  1200. * @param string $method 'post' or 'get', defaults to 'post'.
  1201. * @param null $formidentifier the default is to use the class name for this class but you may need to provide
  1202. * a different value here for some forms that are used more than once on the
  1203. * same page.
  1204. */
  1205. public static function mock_submit($simulatedsubmitteddata, $simulatedsubmittedfiles = array(), $method = 'post',
  1206. $formidentifier = null) {
  1207. $_FILES = $simulatedsubmittedfiles;
  1208. if ($formidentifier === null) {
  1209. $formidentifier = get_called_class();
  1210. }
  1211. $simulatedsubmitteddata['_qf__'.$formidentifier] = 1;
  1212. $simulatedsubmitteddata['sesskey'] = sesskey();
  1213. if (strtolower($method) === 'get') {
  1214. $_GET = $simulatedsubmitteddata;
  1215. } else {
  1216. $_POST = $simulatedsubmitteddata;
  1217. }
  1218. }
  1219. }
  1220. /**
  1221. * MoodleQuickForm implementation
  1222. *
  1223. * You never extend this class directly. The class methods of this class are available from
  1224. * the private $this->_form property on moodleform and its children. You generally only
  1225. * call methods on this class from within abstract methods that you override on moodleform such
  1226. * as definition and definition_after_data
  1227. *
  1228. * @package core_form
  1229. * @category form
  1230. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  1231. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1232. */
  1233. class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
  1234. /** @var array type (PARAM_INT, PARAM_TEXT etc) of element value */
  1235. var $_types = array();
  1236. /** @var array dependent state for the element/'s */
  1237. var $_dependencies = array();
  1238. /** @var array Array of buttons that if pressed do not result in the processing of the form. */
  1239. var $_noSubmitButtons=array();
  1240. /** @var array Array of buttons that if pressed do not result in the processing of the form. */
  1241. var $_cancelButtons=array();
  1242. /** @var array Array whose keys are element names. If the key exists this is a advanced element */
  1243. var $_advancedElements = array();
  1244. /**
  1245. * Array whose keys are element names and values are the desired collapsible state.
  1246. * True for collapsed, False for expanded. If not present, set to default in
  1247. * {@link self::accept()}.
  1248. *
  1249. * @var array
  1250. */
  1251. var $_collapsibleElements = array();
  1252. /**
  1253. * Whether to enable shortforms for this form
  1254. *
  1255. * @var boolean
  1256. */
  1257. var $_disableShortforms = false;
  1258. /** @var bool whether to automatically initialise M.formchangechecker for this form. */
  1259. protected $_use_form_change_checker = true;
  1260. /**
  1261. * The form name is derived from the class name of the wrapper minus the trailing form
  1262. * It is a name with words joined by underscores whereas the id attribute is words joined by underscores.
  1263. * @var string
  1264. */
  1265. var $_formName = '';
  1266. /**
  1267. * String with the html for hidden params passed in as part of a moodle_url
  1268. * object for the action. Output in the form.
  1269. * @var string
  1270. */
  1271. var $_pageparams = '';
  1272. /**
  1273. * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
  1274. *
  1275. * @staticvar int $formcounter counts number of forms
  1276. * @param string $formName Form's name.
  1277. * @param string $method Form's method defaults to 'POST'
  1278. * @param string|moodle_url $action Form's action
  1279. * @param string $target (optional)Form's target defaults to none
  1280. * @param mixed $attributes (optional)Extra attributes for <form> tag
  1281. */
  1282. function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
  1283. global $CFG, $OUTPUT;
  1284. static $formcounter = 1;
  1285. HTML_Common::HTML_Common($attributes);
  1286. $target = empty($target) ? array() : array('target' => $target);
  1287. $this->_formName = $formName;
  1288. if (is_a($action, 'moodle_url')){
  1289. $this->_pageparams = html_writer::input_hidden_params($action);
  1290. $action = $action->out_omit_querystring();
  1291. } else {
  1292. $this->_pageparams = '';
  1293. }
  1294. // No 'name' atttribute for form in xhtml strict :
  1295. $attributes = array('action' => $action, 'method' => $method, 'accept-charset' => 'utf-8') + $target;
  1296. if (is_null($this->getAttribute('id'))) {
  1297. $attributes['id'] = 'mform' . $formcounter;
  1298. }
  1299. $formcounter++;
  1300. $this->updateAttributes($attributes);
  1301. // This is custom stuff for Moodle :
  1302. $oldclass= $this->getAttribute('class');
  1303. if (!empty($oldclass)){
  1304. $this->updateAttributes(array('class'=>$oldclass.' mform'));
  1305. }else {
  1306. $this->updateAttributes(array('class'=>'mform'));
  1307. }
  1308. $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
  1309. $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
  1310. $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
  1311. }
  1312. /**
  1313. * Use this method to indicate an element in a form is an advanced field. If items in a form
  1314. * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
  1315. * form so the user can decide whether to display advanced form controls.
  1316. *
  1317. * If you set a header element to advanced then all elements it contains will also be set as advanced.
  1318. *
  1319. * @param string $elementName group or element name (not the element name of something inside a group).
  1320. * @param bool $advanced default true sets the element to advanced. False removes advanced mark.
  1321. */
  1322. function setAdvanced($elementName, $advanced = true) {
  1323. if ($advanced){
  1324. $this->_advancedElements[$elementName]='';
  1325. } elseif (isset($this->_advancedElements[$elementName])) {
  1326. unset($this->_advancedElements[$elementName]);
  1327. }
  1328. }
  1329. /**
  1330. * Use this method to indicate that the fieldset should be shown as expanded.
  1331. * The method is applicable to header elements only.
  1332. *
  1333. * @param string $headername header element name
  1334. * @param boolean $expanded default true sets the element to expanded. False makes the element collapsed.
  1335. * @param boolean $ignoreuserstate override the state regardless of the state it was on when
  1336. * the form was submitted.
  1337. * @return void
  1338. */
  1339. function setExpanded($headername, $expanded = true, $ignoreuserstate = false) {
  1340. if (empty($headername)) {
  1341. return;
  1342. }
  1343. $element = $this->getElement($headername);
  1344. if ($element->getType() != 'header') {
  1345. debugging('Cannot use setExpanded on non-header elements', DEBUG_DEVELOPER);
  1346. return;
  1347. }
  1348. if (!$headerid = $element->getAttribute('id')) {
  1349. $element->_generateId();
  1350. $headerid = $element->getAttribute('id');
  1351. }
  1352. if ($this->getElementType('mform_isexpanded_' . $headerid) === false) {
  1353. // See if the form has been submitted already.
  1354. $formexpanded = optional_param('mform_isexpanded_' . $headerid, -1, PARAM_INT);
  1355. if (!$ignoreuserstate && $formexpanded != -1) {
  1356. // Override expanded state with the form variable.
  1357. $expanded = $formexpanded;
  1358. }
  1359. // Create the form element for storing expanded state.
  1360. $this->addElement('hidden', 'mform_isexpanded_' . $headerid);
  1361. $this->setType('mform_isexpanded_' . $headerid, PARAM_INT);
  1362. $this->setConstant('mform_isexpanded_' . $headerid, (int) $expanded);
  1363. }
  1364. $this->_collapsibleElements[$headername] = !$expanded;
  1365. }
  1366. /**
  1367. * Use this method to add show more/less status element required for passing
  1368. * over the advanced elements visibility status on the form submission.
  1369. *
  1370. * @param string $headerName header element name.
  1371. * @param boolean $showmore default false sets the advanced elements to be hidden.
  1372. */
  1373. function addAdvancedStatusElement($headerid, $showmore=false){
  1374. // Add extra hidden element to store advanced items state for each section.
  1375. if ($this->getElementType('mform_showmore_' . $headerid) === false) {
  1376. // See if we the form has been submitted already.
  1377. $formshowmore = optional_param('mform_showmore_' . $headerid, -1, PARAM_INT);
  1378. if (!$showmore && $formshowmore != -1) {
  1379. // Override showmore state with the form variable.
  1380. $showmore = $formshowmore;
  1381. }
  1382. // Create the form element for storing advanced items state.
  1383. $this->addElement('hidden', 'mform_showmore_' . $headerid);
  1384. $this->setType('mform_showmore_' . $headerid, PARAM_INT);
  1385. $this->setConstant('mform_showmore_' . $headerid, (int)$showmore);
  1386. }
  1387. }
  1388. /**
  1389. * This function has been deprecated. Show advanced has been replaced by
  1390. * "Show more.../Show less..." in the shortforms javascript module.
  1391. *
  1392. * @deprecated since Moodle 2.5
  1393. * @param bool $showadvancedNow if true will show advanced elements.
  1394. */
  1395. function setShowAdvanced($showadvancedNow = null){
  1396. debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
  1397. }
  1398. /**
  1399. * This function has been deprecated. Show advanced has been replaced by
  1400. * "Show more.../Show less..." in the shortforms javascript module.
  1401. *
  1402. * @deprecated since Moodle 2.5
  1403. * @return bool (Always false)
  1404. */
  1405. function getShowAdvanced(){
  1406. debugging('Call to deprecated function setShowAdvanced. See "Show more.../Show less..." in shortforms yui module.');
  1407. return false;
  1408. }
  1409. /**
  1410. * Use this method to indicate that the form will not be using shortforms.
  1411. *
  1412. * @param boolean $disable default true, controls if the shortforms are disabled.
  1413. */
  1414. function setDisableShortforms ($disable = true) {
  1415. $this->_disableShortforms = $disable;
  1416. }
  1417. /**
  1418. * Call this method if you don't want the formchangechecker JavaScript to be
  1419. * automatically initialised for this form.
  1420. */
  1421. public function disable_form_change_checker() {
  1422. $this->_use_form_change_checker = false;
  1423. }
  1424. /**
  1425. * If you have called {@link disable_form_change_checker()} then you can use
  1426. * this method to re-enable it. It is enabled by default, so normally you don't
  1427. * need to call this.
  1428. */
  1429. public function enable_form_change_checker() {
  1430. $this->_use_form_change_checker = true;
  1431. }
  1432. /**
  1433. * @return bool whether this form should automatically initialise
  1434. * formchangechecker for itself.
  1435. */
  1436. public function is_form_change_checker_enabled() {
  1437. return $this->_use_form_change_checker;
  1438. }
  1439. /**
  1440. * Accepts a renderer
  1441. *
  1442. * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
  1443. */
  1444. function accept(&$renderer) {
  1445. if (method_exists($renderer, 'setAdvancedElements')){
  1446. //Check for visible fieldsets where all elements are advanced
  1447. //and mark these headers as advanced as well.
  1448. //Also mark all elements in a advanced header as advanced.
  1449. $stopFields = $renderer->getStopFieldSetElements();
  1450. $lastHeader = null;
  1451. $lastHeaderAdvanced = false;
  1452. $anyAdvanced = false;
  1453. $anyError = false;
  1454. foreach (array_keys($this->_elements) as $elementIndex){
  1455. $element =& $this->_elements[$elementIndex];
  1456. // if closing header and any contained element was advanced then mark it as advanced
  1457. if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
  1458. if ($anyAdvanced && !is_null($lastHeader)) {
  1459. $lastHeader->_generateId();
  1460. $this->setAdvanced($lastHeader->getName());
  1461. $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
  1462. }
  1463. $lastHeaderAdvanced = false;
  1464. unset($lastHeader);
  1465. $lastHeader = null;
  1466. } elseif ($lastHeaderAdvanced) {
  1467. $this->setAdvanced($element->getName());
  1468. }
  1469. if ($element->getType()=='header'){
  1470. $lastHeader =& $element;
  1471. $anyAdvanced = false;
  1472. $anyError = false;
  1473. $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
  1474. } elseif (isset($this->_advancedElements[$element->getName()])){
  1475. $anyAdvanced = true;
  1476. if (isset($this->_errors[$element->getName()])) {
  1477. $anyError = true;
  1478. }
  1479. }
  1480. }
  1481. // the last header may not be closed yet...
  1482. if ($anyAdvanced && !is_null($lastHeader)){
  1483. $this->setAdvanced($lastHeader->getName());
  1484. $lastHeader->_generateId();
  1485. $this->addAdvancedStatusElement($lastHeader->getAttribute('id'), $anyError);
  1486. }
  1487. $renderer->setAdvancedElements($this->_advancedElements);
  1488. }
  1489. if (method_exists($renderer, 'setCollapsibleElements') && !$this->_disableShortforms) {
  1490. // Count the number of sections.
  1491. $headerscount = 0;
  1492. foreach (array_keys($this->_elements) as $elementIndex){
  1493. $element =& $this->_elements[$elementIndex];
  1494. if ($element->getType() == 'header') {
  1495. $headerscount++;
  1496. }
  1497. }
  1498. $anyrequiredorerror = false;
  1499. $headercounter = 0;
  1500. $headername = null;
  1501. foreach (array_keys($this->_elements) as $elementIndex){
  1502. $element =& $this->_elements[$elementIndex];
  1503. if ($element->getType() == 'header') {
  1504. $headercounter++;
  1505. $element->_generateId();
  1506. $headername = $element->getName();
  1507. $anyrequiredorerror = false;
  1508. } else if (in_array($element->getName(), $this->_required) || isset($this->_errors[$element->getName()])) {
  1509. $anyrequiredorerror = true;
  1510. } else {
  1511. // Do not reset $anyrequiredorerror to false because we do not want any other element
  1512. // in this header (fieldset) to possibly revert the state given.
  1513. }
  1514. if ($element->getType() == 'header') {
  1515. if ($headercounter === 1 && !isset($this->_collapsibleElements[$headername])) {
  1516. // By default the first section is always expanded, except if a state has already been set.
  1517. $this->setExpanded($headername, true);
  1518. } else if (($headercounter === 2 && $headerscount === 2) && !isset($this->_collapsibleElements[$headername])) {
  1519. // The second section is always expanded if the form only contains 2 sections),
  1520. // except if a state has already been set.
  1521. $this->setExpanded($headername, true);
  1522. }
  1523. } else if ($anyrequiredorerror) {
  1524. // If any error or required field are present within the header, we need to expand it.
  1525. $this->setExpanded($headername, true, true);
  1526. } else if (!isset($this->_collapsibleElements[$headername])) {
  1527. // Define element as collapsed by default.
  1528. $this->setExpanded($headername, false);
  1529. }
  1530. }
  1531. // Pass the array to renderer object.
  1532. $renderer->setCollapsibleElements($this->_collapsibleElements);
  1533. }
  1534. parent::accept($renderer);
  1535. }
  1536. /**
  1537. * Adds one or more element names that indicate the end of a fieldset
  1538. *
  1539. * @param string $elementName name of the element
  1540. */
  1541. function closeHeaderBefore($elementName){
  1542. $renderer =& $this->defaultRenderer();
  1543. $renderer->addStopFieldsetElements($elementName);
  1544. }
  1545. /**
  1546. * Should be used for all elements of a form except for select, radio and checkboxes which
  1547. * clean their own data.
  1548. *
  1549. * @param string $elementname
  1550. * @param int $paramtype defines type of data contained in element. Use the constants PARAM_*.
  1551. * {@link lib/moodlelib.php} for defined parameter types
  1552. */
  1553. function setType($elementname, $paramtype) {
  1554. $this->_types[$elementname] = $paramtype;
  1555. }
  1556. /**
  1557. * This can be used to set several types at once.
  1558. *
  1559. * @param array $paramtypes types of parameters.
  1560. * @see MoodleQuickForm::setType
  1561. */
  1562. function setTypes($paramtypes) {
  1563. $this->_types = $paramtypes + $this->_types;
  1564. }
  1565. /**
  1566. * Return the type(s) to use to clean an element.
  1567. *
  1568. * In the case where the element has an array as a value, we will try to obtain a
  1569. * type defined for that specific key, and recursively until done.
  1570. *
  1571. * This method does not work reverse, you cannot pass a nested element and hoping to
  1572. * fallback on the clean type of a parent. This method intends to be used with the
  1573. * main element, which will generate child types if needed, not the other way around.
  1574. *
  1575. * Example scenario:
  1576. *
  1577. * You have defined a new repeated element containing a text field called 'foo'.
  1578. * By default there will always be 2 occurence of 'foo' in the form. Even though
  1579. * you've set the type on 'foo' to be PARAM_INT, for some obscure reason, you want
  1580. * the first value of 'foo', to be PARAM_FLOAT, which you set using setType:
  1581. * $mform->setType('foo[0]', PARAM_FLOAT).
  1582. *
  1583. * Now if you call this method passing 'foo', along with the submitted values of 'foo':
  1584. * array(0 => '1.23', 1 => '10'), you will get an array telling you that the key 0 is a
  1585. * FLOAT and 1 is an INT. If you had passed 'foo[1]', along with its value '10', you would
  1586. * get the default clean type returned (param $default).
  1587. *
  1588. * @param string $elementname name of the element.
  1589. * @param mixed $value value that should be cleaned.
  1590. * @param int $default default constant value to be returned (PARAM_...)
  1591. * @return string|array constant value or array of constant values (PARAM_...)
  1592. */
  1593. public function getCleanType($elementname, $value, $default = PARAM_RAW) {
  1594. $type = $default;
  1595. if (array_key_exists($elementname, $this->_types)) {
  1596. $type = $this->_types[$elementname];
  1597. }
  1598. if (is_array($value)) {
  1599. $default = $type;
  1600. $type = array();
  1601. foreach ($value as $subkey => $subvalue) {
  1602. $typekey = "$elementname" . "[$subkey]";
  1603. if (array_key_exists($typekey, $this->_types)) {
  1604. $subtype = $this->_types[$typekey];
  1605. } else {
  1606. $subtype = $default;
  1607. }
  1608. if (is_array($subvalue)) {
  1609. $type[$subkey] = $this->getCleanType($typekey, $subvalue, $subtype);
  1610. } else {
  1611. $type[$subkey] = $subtype;
  1612. }
  1613. }
  1614. }
  1615. return $type;
  1616. }
  1617. /**
  1618. * Return the cleaned value using the passed type(s).
  1619. *
  1620. * @param mixed $value value that has to be cleaned.
  1621. * @param int|array $type constant value to use to clean (PARAM_...), typically returned by {@link self::getCleanType()}.
  1622. * @return mixed cleaned up value.
  1623. */
  1624. public function getCleanedValue($value, $type) {
  1625. if (is_array($type) && is_array($value)) {
  1626. foreach ($type as $key => $param) {
  1627. $value[$key] = $this->getCleanedValue($value[$key], $param);
  1628. }
  1629. } else if (!is_array($type) && !is_array($value)) {
  1630. $value = clean_param($value, $type);
  1631. } else if (!is_array($type) && is_array($value)) {
  1632. $value = clean_param_array($value, $type, true);
  1633. } else {
  1634. throw new coding_exception('Unexpected type or value received in MoodleQuickForm::getCleanedValue()');
  1635. }
  1636. return $value;
  1637. }
  1638. /**
  1639. * Updates submitted values
  1640. *
  1641. * @param array $submission submitted values
  1642. * @param array $files list of files
  1643. */
  1644. function updateSubmission($submission, $files) {
  1645. $this->_flagSubmitted = false;
  1646. if (empty($submission)) {
  1647. $this->_submitValues = array();
  1648. } else {
  1649. foreach ($submission as $key => $s) {
  1650. $type = $this->getCleanType($key, $s);
  1651. $submission[$key] = $this->getCleanedValue($s, $type);
  1652. }
  1653. $this->_submitValues = $submission;
  1654. $this->_flagSubmitted = true;
  1655. }
  1656. if (empty($files)) {
  1657. $this->_submitFiles = array();
  1658. } else {
  1659. $this->_submitFiles = $files;
  1660. $this->_flagSubmitted = true;
  1661. }
  1662. // need to tell all elements that they need to update their value attribute.
  1663. foreach (array_keys($this->_elements) as $key) {
  1664. $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
  1665. }
  1666. }
  1667. /**
  1668. * Returns HTML for required elements
  1669. *
  1670. * @return string
  1671. */
  1672. function getReqHTML(){
  1673. return $this->_reqHTML;
  1674. }
  1675. /**
  1676. * Returns HTML for advanced elements
  1677. *
  1678. * @return string
  1679. */
  1680. function getAdvancedHTML(){
  1681. return $this->_advancedHTML;
  1682. }
  1683. /**
  1684. * Initializes a default form value. Used to specify the default for a new entry where
  1685. * no data is loaded in using moodleform::set_data()
  1686. *
  1687. * note: $slashed param removed
  1688. *
  1689. * @param string $elementName element name
  1690. * @param mixed $defaultValue values for that element name
  1691. */
  1692. function setDefault($elementName, $defaultValue){
  1693. $this->setDefaults(array($elementName=>$defaultValue));
  1694. }
  1695. /**
  1696. * Add a help button to element, only one button per element is allowed.
  1697. *
  1698. * This is new, simplified and preferable method of setting a help icon on form elements.
  1699. * It uses the new $OUTPUT->help_icon().
  1700. *
  1701. * Typically, you will provide the same identifier and the component as you have used for the
  1702. * label of the element. The string identifier with the _help suffix added is then used
  1703. * as the help string.
  1704. *
  1705. * There has to be two strings defined:
  1706. * 1/ get_string($identifier, $component) - the title of the help page
  1707. * 2/ get_string($identifier.'_help', $component) - the actual help page text
  1708. *
  1709. * @since Moodle 2.0
  1710. * @param string $elementname name of the element to add the item to
  1711. * @param string $identifier help string identifier without _help suffix
  1712. * @param string $component component name to look the help string in
  1713. * @param string $linktext optional text to display next to the icon
  1714. * @param bool $suppresscheck set to true if the element may not exist
  1715. */
  1716. function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
  1717. global $OUTPUT;
  1718. if (array_key_exists($elementname, $this->_elementIndex)) {
  1719. $element = $this->_elements[$this->_elementIndex[$elementname]];
  1720. $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
  1721. } else if (!$suppresscheck) {
  1722. debugging(get_string('nonexistentformelements', 'form', $elementname));
  1723. }
  1724. }
  1725. /**
  1726. * Set constant value not overridden by _POST or _GET
  1727. * note: this does not work for complex names with [] :-(
  1728. *
  1729. * @param string $elname name of element
  1730. * @param mixed $value
  1731. */
  1732. function setConstant($elname, $value) {
  1733. $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
  1734. $element =& $this->getElement($elname);
  1735. $element->onQuickFormEvent('updateValue', null, $this);
  1736. }
  1737. /**
  1738. * export submitted values
  1739. *
  1740. * @param string $elementList list of elements in form
  1741. * @return array
  1742. */
  1743. function exportValues($elementList = null){
  1744. $unfiltered = array();
  1745. if (null === $elementList) {
  1746. // iterate over all elements, calling their exportValue() methods
  1747. foreach (array_keys($this->_elements) as $key) {
  1748. if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze) {
  1749. $varname = $this->_elements[$key]->_attributes['name'];
  1750. $value = '';
  1751. // If we have a default value then export it.
  1752. if (isset($this->_defaultValues[$varname])) {
  1753. $value = $this->prepare_fixed_value($varname, $this->_defaultValues[$varname]);
  1754. }
  1755. } else {
  1756. $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
  1757. }
  1758. if (is_array($value)) {
  1759. // This shit throws a bogus warning in PHP 4.3.x
  1760. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
  1761. }
  1762. }
  1763. } else {
  1764. if (!is_array($elementList)) {
  1765. $elementList = array_map('trim', explode(',', $elementList));
  1766. }
  1767. foreach ($elementList as $elementName) {
  1768. $value = $this->exportValue($elementName);
  1769. if (@PEAR::isError($value)) {
  1770. return $value;
  1771. }
  1772. //oh, stock QuickFOrm was returning array of arrays!
  1773. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
  1774. }
  1775. }
  1776. if (is_array($this->_constantValues)) {
  1777. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $this->_constantValues);
  1778. }
  1779. return $unfiltered;
  1780. }
  1781. /**
  1782. * This is a bit of a hack, and it duplicates the code in
  1783. * HTML_QuickForm_element::_prepareValue, but I could not think of a way or
  1784. * reliably calling that code. (Think about date selectors, for example.)
  1785. * @param string $name the element name.
  1786. * @param mixed $value the fixed value to set.
  1787. * @return mixed the appropriate array to add to the $unfiltered array.
  1788. */
  1789. protected function prepare_fixed_value($name, $value) {
  1790. if (null === $value) {
  1791. return null;
  1792. } else {
  1793. if (!strpos($name, '[')) {
  1794. return array($name => $value);
  1795. } else {
  1796. $valueAry = array();
  1797. $myIndex = "['" . str_replace(array(']', '['), array('', "']['"), $name) . "']";
  1798. eval("\$valueAry$myIndex = \$value;");
  1799. return $valueAry;
  1800. }
  1801. }
  1802. }
  1803. /**
  1804. * Adds a validation rule for the given field
  1805. *
  1806. * If the element is in fact a group, it will be considered as a whole.
  1807. * To validate grouped elements as separated entities,
  1808. * use addGroupRule instead of addRule.
  1809. *
  1810. * @param string $element Form element name
  1811. * @param string $message Message to display for invalid data
  1812. * @param string $type Rule type, use getRegisteredRules() to get types
  1813. * @param string $format (optional)Required for extra rule data
  1814. * @param string $validation (optional)Where to perform validation: "server", "client"
  1815. * @param bool $reset Client-side validation: reset the form element to its original value if there is an error?
  1816. * @param bool $force Force the rule to be applied, even if the target form element does not exist
  1817. */
  1818. function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
  1819. {
  1820. parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
  1821. if ($validation == 'client') {
  1822. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1823. }
  1824. }
  1825. /**
  1826. * Adds a validation rule for the given group of elements
  1827. *
  1828. * Only groups with a name can be assigned a validation rule
  1829. * Use addGroupRule when you need to validate elements inside the group.
  1830. * Use addRule if you need to validate the group as a whole. In this case,
  1831. * the same rule will be applied to all elements in the group.
  1832. * Use addRule if you need to validate the group against a function.
  1833. *
  1834. * @param string $group Form group name
  1835. * @param array|string $arg1 Array for multiple elements or error message string for one element
  1836. * @param string $type (optional)Rule type use getRegisteredRules() to get types
  1837. * @param string $format (optional)Required for extra rule data
  1838. * @param int $howmany (optional)How many valid elements should be in the group
  1839. * @param string $validation (optional)Where to perform validation: "server", "client"
  1840. * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
  1841. */
  1842. function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
  1843. {
  1844. parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
  1845. if (is_array($arg1)) {
  1846. foreach ($arg1 as $rules) {
  1847. foreach ($rules as $rule) {
  1848. $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
  1849. if ('client' == $validation) {
  1850. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1851. }
  1852. }
  1853. }
  1854. } elseif (is_string($arg1)) {
  1855. if ($validation == 'client') {
  1856. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1857. }
  1858. }
  1859. }
  1860. /**
  1861. * Returns the client side validation script
  1862. *
  1863. * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
  1864. * and slightly modified to run rules per-element
  1865. * Needed to override this because of an error with client side validation of grouped elements.
  1866. *
  1867. * @return string Javascript to perform validation, empty string if no 'client' rules were added
  1868. */
  1869. function getValidationScript()
  1870. {
  1871. if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
  1872. return '';
  1873. }
  1874. include_once('HTML/QuickForm/RuleRegistry.php');
  1875. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1876. $test = array();
  1877. $js_escape = array(
  1878. "\r" => '\r',
  1879. "\n" => '\n',
  1880. "\t" => '\t',
  1881. "'" => "\\'",
  1882. '"' => '\"',
  1883. '\\' => '\\\\'
  1884. );
  1885. foreach ($this->_rules as $elementName => $rules) {
  1886. foreach ($rules as $rule) {
  1887. if ('client' == $rule['validation']) {
  1888. unset($element); //TODO: find out how to properly initialize it
  1889. $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
  1890. $rule['message'] = strtr($rule['message'], $js_escape);
  1891. if (isset($rule['group'])) {
  1892. $group =& $this->getElement($rule['group']);
  1893. // No JavaScript validation for frozen elements
  1894. if ($group->isFrozen()) {
  1895. continue 2;
  1896. }
  1897. $elements =& $group->getElements();
  1898. foreach (array_keys($elements) as $key) {
  1899. if ($elementName == $group->getElementName($key)) {
  1900. $element =& $elements[$key];
  1901. break;
  1902. }
  1903. }
  1904. } elseif ($dependent) {
  1905. $element = array();
  1906. $element[] =& $this->getElement($elementName);
  1907. foreach ($rule['dependent'] as $elName) {
  1908. $element[] =& $this->getElement($elName);
  1909. }
  1910. } else {
  1911. $element =& $this->getElement($elementName);
  1912. }
  1913. // No JavaScript validation for frozen elements
  1914. if (is_object($element) && $element->isFrozen()) {
  1915. continue 2;
  1916. } elseif (is_array($element)) {
  1917. foreach (array_keys($element) as $key) {
  1918. if ($element[$key]->isFrozen()) {
  1919. continue 3;
  1920. }
  1921. }
  1922. }
  1923. //for editor element, [text] is appended to the name.
  1924. $fullelementname = $elementName;
  1925. if ($element->getType() == 'editor') {
  1926. $fullelementname .= '[text]';
  1927. //Add format to rule as moodleform check which format is supported by browser
  1928. //it is not set anywhere... So small hack to make sure we pass it down to quickform
  1929. if (is_null($rule['format'])) {
  1930. $rule['format'] = $element->getFormat();
  1931. }
  1932. }
  1933. // Fix for bug displaying errors for elements in a group
  1934. $test[$fullelementname][0][] = $registry->getValidationScript($element, $fullelementname, $rule);
  1935. $test[$fullelementname][1]=$element;
  1936. //end of fix
  1937. }
  1938. }
  1939. }
  1940. // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
  1941. // the form, and then that form field gets corrupted by the code that follows.
  1942. unset($element);
  1943. $js = '
  1944. <script type="text/javascript">
  1945. //<![CDATA[
  1946. var skipClientValidation = false;
  1947. function qf_errorHandler(element, _qfMsg) {
  1948. div = element.parentNode;
  1949. if ((div == undefined) || (element.name == undefined)) {
  1950. //no checking can be done for undefined elements so let server handle it.
  1951. return true;
  1952. }
  1953. if (_qfMsg != \'\') {
  1954. var errorSpan = document.getElementById(\'id_error_\'+element.name);
  1955. if (!errorSpan) {
  1956. errorSpan = document.createElement("span");
  1957. errorSpan.id = \'id_error_\'+element.name;
  1958. errorSpan.className = "error";
  1959. element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
  1960. document.getElementById(errorSpan.id).setAttribute(\'TabIndex\', \'0\');
  1961. document.getElementById(errorSpan.id).focus();
  1962. }
  1963. while (errorSpan.firstChild) {
  1964. errorSpan.removeChild(errorSpan.firstChild);
  1965. }
  1966. errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
  1967. if (div.className.substr(div.className.length - 6, 6) != " error"
  1968. && div.className != "error") {
  1969. div.className += " error";
  1970. linebreak = document.createElement("br");
  1971. linebreak.className = "error";
  1972. linebreak.id = \'id_error_break_\'+element.name;
  1973. errorSpan.parentNode.insertBefore(linebreak, errorSpan.nextSibling);
  1974. }
  1975. return false;
  1976. } else {
  1977. var errorSpan = document.getElementById(\'id_error_\'+element.name);
  1978. if (errorSpan) {
  1979. errorSpan.parentNode.removeChild(errorSpan);
  1980. }
  1981. var linebreak = document.getElementById(\'id_error_break_\'+element.name);
  1982. if (linebreak) {
  1983. linebreak.parentNode.removeChild(linebreak);
  1984. }
  1985. if (div.className.substr(div.className.length - 6, 6) == " error") {
  1986. div.className = div.className.substr(0, div.className.length - 6);
  1987. } else if (div.className == "error") {
  1988. div.className = "";
  1989. }
  1990. return true;
  1991. }
  1992. }';
  1993. $validateJS = '';
  1994. foreach ($test as $elementName => $jsandelement) {
  1995. // Fix for bug displaying errors for elements in a group
  1996. //unset($element);
  1997. list($jsArr,$element)=$jsandelement;
  1998. //end of fix
  1999. $escapedElementName = preg_replace_callback(
  2000. '/[_\[\]-]/',
  2001. create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
  2002. $elementName);
  2003. $js .= '
  2004. function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
  2005. if (undefined == element) {
  2006. //required element was not found, then let form be submitted without client side validation
  2007. return true;
  2008. }
  2009. var value = \'\';
  2010. var errFlag = new Array();
  2011. var _qfGroups = {};
  2012. var _qfMsg = \'\';
  2013. var frm = element.parentNode;
  2014. if ((undefined != element.name) && (frm != undefined)) {
  2015. while (frm && frm.nodeName.toUpperCase() != "FORM") {
  2016. frm = frm.parentNode;
  2017. }
  2018. ' . join("\n", $jsArr) . '
  2019. return qf_errorHandler(element, _qfMsg);
  2020. } else {
  2021. //element name should be defined else error msg will not be displayed.
  2022. return true;
  2023. }
  2024. }
  2025. ';
  2026. $validateJS .= '
  2027. ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
  2028. if (!ret && !first_focus) {
  2029. first_focus = true;
  2030. document.getElementById(\'id_error_'.$elementName.'\').focus();
  2031. }
  2032. ';
  2033. // Fix for bug displaying errors for elements in a group
  2034. //unset($element);
  2035. //$element =& $this->getElement($elementName);
  2036. //end of fix
  2037. $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
  2038. $onBlur = $element->getAttribute('onBlur');
  2039. $onChange = $element->getAttribute('onChange');
  2040. $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
  2041. 'onChange' => $onChange . $valFunc));
  2042. }
  2043. // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
  2044. $js .= '
  2045. function validate_' . $this->_formName . '(frm) {
  2046. if (skipClientValidation) {
  2047. return true;
  2048. }
  2049. var ret = true;
  2050. var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
  2051. var first_focus = false;
  2052. ' . $validateJS . ';
  2053. return ret;
  2054. }
  2055. //]]>
  2056. </script>';
  2057. return $js;
  2058. } // end func getValidationScript
  2059. /**
  2060. * Sets default error message
  2061. */
  2062. function _setDefaultRuleMessages(){
  2063. foreach ($this->_rules as $field => $rulesarr){
  2064. foreach ($rulesarr as $key => $rule){
  2065. if ($rule['message']===null){
  2066. $a=new stdClass();
  2067. $a->format=$rule['format'];
  2068. $str=get_string('err_'.$rule['type'], 'form', $a);
  2069. if (strpos($str, '[[')!==0){
  2070. $this->_rules[$field][$key]['message']=$str;
  2071. }
  2072. }
  2073. }
  2074. }
  2075. }
  2076. /**
  2077. * Get list of attributes which have dependencies
  2078. *
  2079. * @return array
  2080. */
  2081. function getLockOptionObject(){
  2082. $result = array();
  2083. foreach ($this->_dependencies as $dependentOn => $conditions){
  2084. $result[$dependentOn] = array();
  2085. foreach ($conditions as $condition=>$values) {
  2086. $result[$dependentOn][$condition] = array();
  2087. foreach ($values as $value=>$dependents) {
  2088. $result[$dependentOn][$condition][$value] = array();
  2089. $i = 0;
  2090. foreach ($dependents as $dependent) {
  2091. $elements = $this->_getElNamesRecursive($dependent);
  2092. if (empty($elements)) {
  2093. // probably element inside of some group
  2094. $elements = array($dependent);
  2095. }
  2096. foreach($elements as $element) {
  2097. if ($element == $dependentOn) {
  2098. continue;
  2099. }
  2100. $result[$dependentOn][$condition][$value][] = $element;
  2101. }
  2102. }
  2103. }
  2104. }
  2105. }
  2106. return array($this->getAttribute('id'), $result);
  2107. }
  2108. /**
  2109. * Get names of element or elements in a group.
  2110. *
  2111. * @param HTML_QuickForm_group|element $element element group or element object
  2112. * @return array
  2113. */
  2114. function _getElNamesRecursive($element) {
  2115. if (is_string($element)) {
  2116. if (!$this->elementExists($element)) {
  2117. return array();
  2118. }
  2119. $element = $this->getElement($element);
  2120. }
  2121. if (is_a($element, 'HTML_QuickForm_group')) {
  2122. $elsInGroup = $element->getElements();
  2123. $elNames = array();
  2124. foreach ($elsInGroup as $elInGroup){
  2125. if (is_a($elInGroup, 'HTML_QuickForm_group')) {
  2126. // not sure if this would work - groups nested in groups
  2127. $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
  2128. } else {
  2129. $elNames[] = $element->getElementName($elInGroup->getName());
  2130. }
  2131. }
  2132. } else if (is_a($element, 'HTML_QuickForm_header')) {
  2133. return array();
  2134. } else if (is_a($element, 'HTML_QuickForm_hidden')) {
  2135. return array();
  2136. } else if (method_exists($element, 'getPrivateName') &&
  2137. !($element instanceof HTML_QuickForm_advcheckbox)) {
  2138. // The advcheckbox element implements a method called getPrivateName,
  2139. // but in a way that is not compatible with the generic API, so we
  2140. // have to explicitly exclude it.
  2141. return array($element->getPrivateName());
  2142. } else {
  2143. $elNames = array($element->getName());
  2144. }
  2145. return $elNames;
  2146. }
  2147. /**
  2148. * Adds a dependency for $elementName which will be disabled if $condition is met.
  2149. * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
  2150. * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
  2151. * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
  2152. * of the $dependentOn element is $condition (such as equal) to $value.
  2153. *
  2154. * When working with multiple selects, the dependentOn has to be the real name of the select, meaning that
  2155. * it will most likely end up with '[]'. Also, the value should be an array of required values, or a string
  2156. * containing the values separated by pipes: array('red', 'blue') or 'red|blue'.
  2157. *
  2158. * @param string $elementName the name of the element which will be disabled
  2159. * @param string $dependentOn the name of the element whose state will be checked for condition
  2160. * @param string $condition the condition to check
  2161. * @param mixed $value used in conjunction with condition.
  2162. */
  2163. function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1') {
  2164. // Multiple selects allow for a multiple selection, we transform the array to string here as
  2165. // an array cannot be used as a key in an associative array.
  2166. if (is_array($value)) {
  2167. $value = implode('|', $value);
  2168. }
  2169. if (!array_key_exists($dependentOn, $this->_dependencies)) {
  2170. $this->_dependencies[$dependentOn] = array();
  2171. }
  2172. if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
  2173. $this->_dependencies[$dependentOn][$condition] = array();
  2174. }
  2175. if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
  2176. $this->_dependencies[$dependentOn][$condition][$value] = array();
  2177. }
  2178. $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
  2179. }
  2180. /**
  2181. * Registers button as no submit button
  2182. *
  2183. * @param string $buttonname name of the button
  2184. */
  2185. function registerNoSubmitButton($buttonname){
  2186. $this->_noSubmitButtons[]=$buttonname;
  2187. }
  2188. /**
  2189. * Checks if button is a no submit button, i.e it doesn't submit form
  2190. *
  2191. * @param string $buttonname name of the button to check
  2192. * @return bool
  2193. */
  2194. function isNoSubmitButton($buttonname){
  2195. return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
  2196. }
  2197. /**
  2198. * Registers a button as cancel button
  2199. *
  2200. * @param string $addfieldsname name of the button
  2201. */
  2202. function _registerCancelButton($addfieldsname){
  2203. $this->_cancelButtons[]=$addfieldsname;
  2204. }
  2205. /**
  2206. * Displays elements without HTML input tags.
  2207. * This method is different to freeze() in that it makes sure no hidden
  2208. * elements are included in the form.
  2209. * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
  2210. *
  2211. * This function also removes all previously defined rules.
  2212. *
  2213. * @param string|array $elementList array or string of element(s) to be frozen
  2214. * @return object|bool if element list is not empty then return error object, else true
  2215. */
  2216. function hardFreeze($elementList=null)
  2217. {
  2218. if (!isset($elementList)) {
  2219. $this->_freezeAll = true;
  2220. $elementList = array();
  2221. } else {
  2222. if (!is_array($elementList)) {
  2223. $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
  2224. }
  2225. $elementList = array_flip($elementList);
  2226. }
  2227. foreach (array_keys($this->_elements) as $key) {
  2228. $name = $this->_elements[$key]->getName();
  2229. if ($this->_freezeAll || isset($elementList[$name])) {
  2230. $this->_elements[$key]->freeze();
  2231. $this->_elements[$key]->setPersistantFreeze(false);
  2232. unset($elementList[$name]);
  2233. // remove all rules
  2234. $this->_rules[$name] = array();
  2235. // if field is required, remove the rule
  2236. $unset = array_search($name, $this->_required);
  2237. if ($unset !== false) {
  2238. unset($this->_required[$unset]);
  2239. }
  2240. }
  2241. }
  2242. if (!empty($elementList)) {
  2243. return self::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
  2244. }
  2245. return true;
  2246. }
  2247. /**
  2248. * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
  2249. *
  2250. * This function also removes all previously defined rules of elements it freezes.
  2251. *
  2252. * @throws HTML_QuickForm_Error
  2253. * @param array $elementList array or string of element(s) not to be frozen
  2254. * @return bool returns true
  2255. */
  2256. function hardFreezeAllVisibleExcept($elementList)
  2257. {
  2258. $elementList = array_flip($elementList);
  2259. foreach (array_keys($this->_elements) as $key) {
  2260. $name = $this->_elements[$key]->getName();
  2261. $type = $this->_elements[$key]->getType();
  2262. if ($type == 'hidden'){
  2263. // leave hidden types as they are
  2264. } elseif (!isset($elementList[$name])) {
  2265. $this->_elements[$key]->freeze();
  2266. $this->_elements[$key]->setPersistantFreeze(false);
  2267. // remove all rules
  2268. $this->_rules[$name] = array();
  2269. // if field is required, remove the rule
  2270. $unset = array_search($name, $this->_required);
  2271. if ($unset !== false) {
  2272. unset($this->_required[$unset]);
  2273. }
  2274. }
  2275. }
  2276. return true;
  2277. }
  2278. /**
  2279. * Tells whether the form was already submitted
  2280. *
  2281. * This is useful since the _submitFiles and _submitValues arrays
  2282. * may be completely empty after the trackSubmit value is removed.
  2283. *
  2284. * @return bool
  2285. */
  2286. function isSubmitted()
  2287. {
  2288. return parent::isSubmitted() && (!$this->isFrozen());
  2289. }
  2290. }
  2291. /**
  2292. * MoodleQuickForm renderer
  2293. *
  2294. * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
  2295. * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
  2296. *
  2297. * Stylesheet is part of standard theme and should be automatically included.
  2298. *
  2299. * @package core_form
  2300. * @copyright 2007 Jamie Pratt <me@jamiep.org>
  2301. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2302. */
  2303. class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
  2304. /** @var array Element template array */
  2305. var $_elementTemplates;
  2306. /**
  2307. * Template used when opening a hidden fieldset
  2308. * (i.e. a fieldset that is opened when there is no header element)
  2309. * @var string
  2310. */
  2311. var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
  2312. /** @var string Header Template string */
  2313. var $_headerTemplate =
  2314. "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"fcontainer clearfix\">\n\t\t";
  2315. /** @var string Template used when opening a fieldset */
  2316. var $_openFieldsetTemplate = "\n\t<fieldset class=\"{classes}\" {id}>";
  2317. /** @var string Template used when closing a fieldset */
  2318. var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
  2319. /** @var string Required Note template string */
  2320. var $_requiredNoteTemplate =
  2321. "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
  2322. /**
  2323. * Collapsible buttons string template.
  2324. *
  2325. * Note that the <span> will be converted as a link. This is done so that the link is not yet clickable
  2326. * until the Javascript has been fully loaded.
  2327. *
  2328. * @var string
  2329. */
  2330. var $_collapseButtonsTemplate =
  2331. "\n\t<div class=\"collapsible-actions\"><span class=\"collapseexpand\">{strexpandall}</span></div>";
  2332. /**
  2333. * Array whose keys are element names. If the key exists this is a advanced element
  2334. *
  2335. * @var array
  2336. */
  2337. var $_advancedElements = array();
  2338. /**
  2339. * Array whose keys are element names and the the boolean values reflect the current state. If the key exists this is a collapsible element.
  2340. *
  2341. * @var array
  2342. */
  2343. var $_collapsibleElements = array();
  2344. /**
  2345. * @var string Contains the collapsible buttons to add to the form.
  2346. */
  2347. var $_collapseButtons = '';
  2348. /**
  2349. * Constructor
  2350. */
  2351. function MoodleQuickForm_Renderer(){
  2352. // switch next two lines for ol li containers for form items.
  2353. // $this->_elementTemplates=array('default'=>"\n\t\t".'<li class="fitem"><label>{label}{help}<!-- BEGIN required -->{req}<!-- END required --></label><div class="qfelement<!-- BEGIN error --> error<!-- END error --> {type}"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></li>');
  2354. $this->_elementTemplates = array(
  2355. 'default'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}" {aria-live}><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
  2356. 'actionbuttons'=>"\n\t\t".'<div id="{id}" class="fitem fitem_actionbuttons fitem_{type}"><div class="felement {type}">{element}</div></div>',
  2357. 'fieldset'=>"\n\t\t".'<div id="{id}" class="fitem {advanced}<!-- BEGIN required --> required<!-- END required --> fitem_{type} {emptylabel}"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
  2358. 'static'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} </label>{help}</div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
  2359. 'warning'=>"\n\t\t".'<div class="fitem {advanced} {emptylabel}">{element}</div>',
  2360. 'nodisplay'=>'');
  2361. parent::HTML_QuickForm_Renderer_Tableless();
  2362. }
  2363. /**
  2364. * Set element's as adavance element
  2365. *
  2366. * @param array $elements form elements which needs to be grouped as advance elements.
  2367. */
  2368. function setAdvancedElements($elements){
  2369. $this->_advancedElements = $elements;
  2370. }
  2371. /**
  2372. * Setting collapsible elements
  2373. *
  2374. * @param array $elements
  2375. */
  2376. function setCollapsibleElements($elements) {
  2377. $this->_collapsibleElements = $elements;
  2378. }
  2379. /**
  2380. * What to do when starting the form
  2381. *
  2382. * @param MoodleQuickForm $form reference of the form
  2383. */
  2384. function startForm(&$form){
  2385. global $PAGE;
  2386. $this->_reqHTML = $form->getReqHTML();
  2387. $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
  2388. $this->_advancedHTML = $form->getAdvancedHTML();
  2389. $this->_collapseButtons = '';
  2390. $formid = $form->getAttribute('id');
  2391. parent::startForm($form);
  2392. if ($form->isFrozen()){
  2393. $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
  2394. } else {
  2395. $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{collapsebtns}\n{content}\n</form>";
  2396. $this->_hiddenHtml .= $form->_pageparams;
  2397. }
  2398. if ($form->is_form_change_checker_enabled()) {
  2399. $PAGE->requires->yui_module('moodle-core-formchangechecker',
  2400. 'M.core_formchangechecker.init',
  2401. array(array(
  2402. 'formid' => $formid
  2403. ))
  2404. );
  2405. $PAGE->requires->string_for_js('changesmadereallygoaway', 'moodle');
  2406. }
  2407. if (!empty($this->_collapsibleElements)) {
  2408. if (count($this->_collapsibleElements) > 1) {
  2409. $this->_collapseButtons = $this->_collapseButtonsTemplate;
  2410. $this->_collapseButtons = str_replace('{strexpandall}', get_string('expandall'), $this->_collapseButtons);
  2411. $PAGE->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
  2412. }
  2413. $PAGE->requires->yui_module('moodle-form-shortforms', 'M.form.shortforms', array(array('formid' => $formid)));
  2414. }
  2415. if (!empty($this->_advancedElements)){
  2416. $PAGE->requires->strings_for_js(array('showmore', 'showless'), 'form');
  2417. $PAGE->requires->yui_module('moodle-form-showadvanced', 'M.form.showadvanced', array(array('formid' => $formid)));
  2418. }
  2419. }
  2420. /**
  2421. * Create advance group of elements
  2422. *
  2423. * @param object $group Passed by reference
  2424. * @param bool $required if input is required field
  2425. * @param string $error error message to display
  2426. */
  2427. function startGroup(&$group, $required, $error){
  2428. // Make sure the element has an id.
  2429. $group->_generateId();
  2430. if (method_exists($group, 'getElementTemplateType')){
  2431. $html = $this->_elementTemplates[$group->getElementTemplateType()];
  2432. }else{
  2433. $html = $this->_elementTemplates['default'];
  2434. }
  2435. if (isset($this->_advancedElements[$group->getName()])){
  2436. $html =str_replace(' {advanced}', ' advanced', $html);
  2437. $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
  2438. } else {
  2439. $html =str_replace(' {advanced}', '', $html);
  2440. $html =str_replace('{advancedimg}', '', $html);
  2441. }
  2442. if (method_exists($group, 'getHelpButton')){
  2443. $html =str_replace('{help}', $group->getHelpButton(), $html);
  2444. }else{
  2445. $html =str_replace('{help}', '', $html);
  2446. }
  2447. $html =str_replace('{id}', 'fgroup_' . $group->getAttribute('id'), $html);
  2448. $html =str_replace('{name}', $group->getName(), $html);
  2449. $html =str_replace('{type}', 'fgroup', $html);
  2450. $emptylabel = '';
  2451. if ($group->getLabel() == '') {
  2452. $emptylabel = 'femptylabel';
  2453. }
  2454. $html = str_replace('{emptylabel}', $emptylabel, $html);
  2455. $this->_templates[$group->getName()]=$html;
  2456. // Fix for bug in tableless quickforms that didn't allow you to stop a
  2457. // fieldset before a group of elements.
  2458. // if the element name indicates the end of a fieldset, close the fieldset
  2459. if ( in_array($group->getName(), $this->_stopFieldsetElements)
  2460. && $this->_fieldsetsOpen > 0
  2461. ) {
  2462. $this->_html .= $this->_closeFieldsetTemplate;
  2463. $this->_fieldsetsOpen--;
  2464. }
  2465. parent::startGroup($group, $required, $error);
  2466. }
  2467. /**
  2468. * Renders element
  2469. *
  2470. * @param HTML_QuickForm_element $element element
  2471. * @param bool $required if input is required field
  2472. * @param string $error error message to display
  2473. */
  2474. function renderElement(&$element, $required, $error){
  2475. // Make sure the element has an id.
  2476. $element->_generateId();
  2477. //adding stuff to place holders in template
  2478. //check if this is a group element first
  2479. if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
  2480. // so it gets substitutions for *each* element
  2481. $html = $this->_groupElementTemplate;
  2482. }
  2483. elseif (method_exists($element, 'getElementTemplateType')){
  2484. $html = $this->_elementTemplates[$element->getElementTemplateType()];
  2485. }else{
  2486. $html = $this->_elementTemplates['default'];
  2487. }
  2488. if (isset($this->_advancedElements[$element->getName()])){
  2489. $html = str_replace(' {advanced}', ' advanced', $html);
  2490. $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
  2491. } else {
  2492. $html = str_replace(' {advanced}', '', $html);
  2493. $html = str_replace(' {aria-live}', '', $html);
  2494. }
  2495. if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
  2496. $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
  2497. } else {
  2498. $html =str_replace('{advancedimg}', '', $html);
  2499. }
  2500. $html =str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
  2501. $html =str_replace('{type}', 'f'.$element->getType(), $html);
  2502. $html =str_replace('{name}', $element->getName(), $html);
  2503. $emptylabel = '';
  2504. if ($element->getLabel() == '') {
  2505. $emptylabel = 'femptylabel';
  2506. }
  2507. $html = str_replace('{emptylabel}', $emptylabel, $html);
  2508. if (method_exists($element, 'getHelpButton')){
  2509. $html = str_replace('{help}', $element->getHelpButton(), $html);
  2510. }else{
  2511. $html = str_replace('{help}', '', $html);
  2512. }
  2513. if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
  2514. $this->_groupElementTemplate = $html;
  2515. }
  2516. elseif (!isset($this->_templates[$element->getName()])) {
  2517. $this->_templates[$element->getName()] = $html;
  2518. }
  2519. parent::renderElement($element, $required, $error);
  2520. }
  2521. /**
  2522. * Called when visiting a form, after processing all form elements
  2523. * Adds required note, form attributes, validation javascript and form content.
  2524. *
  2525. * @global moodle_page $PAGE
  2526. * @param moodleform $form Passed by reference
  2527. */
  2528. function finishForm(&$form){
  2529. global $PAGE;
  2530. if ($form->isFrozen()){
  2531. $this->_hiddenHtml = '';
  2532. }
  2533. parent::finishForm($form);
  2534. $this->_html = str_replace('{collapsebtns}', $this->_collapseButtons, $this->_html);
  2535. if (!$form->isFrozen()) {
  2536. $args = $form->getLockOptionObject();
  2537. if (count($args[1]) > 0) {
  2538. $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, true, moodleform::get_js_module());
  2539. }
  2540. }
  2541. }
  2542. /**
  2543. * Called when visiting a header element
  2544. *
  2545. * @param HTML_QuickForm_header $header An HTML_QuickForm_header element being visited
  2546. * @global moodle_page $PAGE
  2547. */
  2548. function renderHeader(&$header) {
  2549. global $PAGE;
  2550. $header->_generateId();
  2551. $name = $header->getName();
  2552. $id = empty($name) ? '' : ' id="' . $header->getAttribute('id') . '"';
  2553. if (is_null($header->_text)) {
  2554. $header_html = '';
  2555. } elseif (!empty($name) && isset($this->_templates[$name])) {
  2556. $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
  2557. } else {
  2558. $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
  2559. }
  2560. if ($this->_fieldsetsOpen > 0) {
  2561. $this->_html .= $this->_closeFieldsetTemplate;
  2562. $this->_fieldsetsOpen--;
  2563. }
  2564. // Define collapsible classes for fieldsets.
  2565. $arialive = '';
  2566. $fieldsetclasses = array('clearfix');
  2567. if (isset($this->_collapsibleElements[$header->getName()])) {
  2568. $fieldsetclasses[] = 'collapsible';
  2569. if ($this->_collapsibleElements[$header->getName()]) {
  2570. $fieldsetclasses[] = 'collapsed';
  2571. }
  2572. }
  2573. if (isset($this->_advancedElements[$name])){
  2574. $fieldsetclasses[] = 'containsadvancedelements';
  2575. }
  2576. $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
  2577. $openFieldsetTemplate = str_replace('{classes}', join(' ', $fieldsetclasses), $openFieldsetTemplate);
  2578. $this->_html .= $openFieldsetTemplate . $header_html;
  2579. $this->_fieldsetsOpen++;
  2580. }
  2581. /**
  2582. * Return Array of element names that indicate the end of a fieldset
  2583. *
  2584. * @return array
  2585. */
  2586. function getStopFieldsetElements(){
  2587. return $this->_stopFieldsetElements;
  2588. }
  2589. }
  2590. /**
  2591. * Required elements validation
  2592. *
  2593. * This class overrides QuickForm validation since it allowed space or empty tag as a value
  2594. *
  2595. * @package core_form
  2596. * @category form
  2597. * @copyright 2006 Jamie Pratt <me@jamiep.org>
  2598. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2599. */
  2600. class MoodleQuickForm_Rule_Required extends HTML_QuickForm_Rule {
  2601. /**
  2602. * Checks if an element is not empty.
  2603. * This is a server-side validation, it works for both text fields and editor fields
  2604. *
  2605. * @param string $value Value to check
  2606. * @param int|string|array $options Not used yet
  2607. * @return bool true if value is not empty
  2608. */
  2609. function validate($value, $options = null) {
  2610. global $CFG;
  2611. if (is_array($value) && array_key_exists('text', $value)) {
  2612. $value = $value['text'];
  2613. }
  2614. if (is_array($value)) {
  2615. // nasty guess - there has to be something in the array, hopefully nobody invents arrays in arrays
  2616. $value = implode('', $value);
  2617. }
  2618. $stripvalues = array(
  2619. '#</?(?!img|canvas|hr).*?>#im', // all tags except img, canvas and hr
  2620. '#(\xc2|\xa0|\s|&nbsp;)#', //any whitespaces actually
  2621. );
  2622. if (!empty($CFG->strictformsrequired)) {
  2623. $value = preg_replace($stripvalues, '', (string)$value);
  2624. }
  2625. if ((string)$value == '') {
  2626. return false;
  2627. }
  2628. return true;
  2629. }
  2630. /**
  2631. * This function returns Javascript code used to build client-side validation.
  2632. * It checks if an element is not empty.
  2633. *
  2634. * @param int $format format of data which needs to be validated.
  2635. * @return array
  2636. */
  2637. function getValidationScript($format = null) {
  2638. global $CFG;
  2639. if (!empty($CFG->strictformsrequired)) {
  2640. if (!empty($format) && $format == FORMAT_HTML) {
  2641. return array('', "{jsVar}.replace(/(<[^img|hr|canvas]+>)|&nbsp;|\s+/ig, '') == ''");
  2642. } else {
  2643. return array('', "{jsVar}.replace(/^\s+$/g, '') == ''");
  2644. }
  2645. } else {
  2646. return array('', "{jsVar} == ''");
  2647. }
  2648. }
  2649. }
  2650. /**
  2651. * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
  2652. * @name $_HTML_QuickForm_default_renderer
  2653. */
  2654. $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
  2655. /** Please keep this list in alphabetical order. */
  2656. MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
  2657. MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
  2658. MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
  2659. MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
  2660. MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
  2661. MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
  2662. MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
  2663. MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
  2664. MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
  2665. MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
  2666. MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
  2667. MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
  2668. MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
  2669. MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
  2670. MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
  2671. MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
  2672. MoodleQuickForm::registerElementType('listing', "$CFG->libdir/form/listing.php", 'MoodleQuickForm_listing');
  2673. MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
  2674. MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
  2675. MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
  2676. MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
  2677. MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
  2678. MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
  2679. MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
  2680. MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
  2681. MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
  2682. MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
  2683. MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
  2684. MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
  2685. MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
  2686. MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
  2687. MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
  2688. MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
  2689. MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
  2690. MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
  2691. MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
  2692. MoodleQuickForm::registerRule('required', null, 'MoodleQuickForm_Rule_Required', "$CFG->libdir/formslib.php");