PageRenderTime 51ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/formslib.php

https://github.com/mylescarrick/moodle
PHP | 2372 lines | 1610 code | 159 blank | 603 comment | 194 complexity | 600f783e23775d39d3c5a448490d1d88 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * formslib.php - library of classes for creating forms in Moodle, based on PEAR QuickForms.
  18. *
  19. * To use formslib then you will want to create a new file purpose_form.php eg. edit_form.php
  20. * and you want to name your class something like {modulename}_{purpose}_form. Your class will
  21. * extend moodleform overriding abstract classes definition and optionally defintion_after_data
  22. * and validation.
  23. *
  24. * See examples of use of this library in course/edit.php and course/edit_form.php
  25. *
  26. * A few notes :
  27. * form definition is used for both printing of form and processing and should be the same
  28. * for both or you may lose some submitted data which won't be let through.
  29. * you should be using setType for every form element except select, radio or checkbox
  30. * elements, these elements clean themselves.
  31. *
  32. *
  33. * @copyright Jamie Pratt <me@jamiep.org>
  34. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35. * @package core
  36. * @subpackage form
  37. */
  38. defined('MOODLE_INTERNAL') || die();
  39. /** setup.php includes our hacked pear libs first */
  40. require_once 'HTML/QuickForm.php';
  41. require_once 'HTML/QuickForm/DHTMLRulesTableless.php';
  42. require_once 'HTML/QuickForm/Renderer/Tableless.php';
  43. require_once $CFG->libdir.'/filelib.php';
  44. define('EDITOR_UNLIMITED_FILES', -1);
  45. /**
  46. * Callback called when PEAR throws an error
  47. *
  48. * @param PEAR_Error $error
  49. */
  50. function pear_handle_error($error){
  51. echo '<strong>'.$error->GetMessage().'</strong> '.$error->getUserInfo();
  52. echo '<br /> <strong>Backtrace </strong>:';
  53. print_object($error->backtrace);
  54. }
  55. if (!empty($CFG->debug) and $CFG->debug >= DEBUG_ALL){
  56. PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'pear_handle_error');
  57. }
  58. /**
  59. *
  60. * @staticvar bool $done
  61. * @global moodle_page $PAGE
  62. */
  63. function form_init_date_js() {
  64. global $PAGE;
  65. static $done = false;
  66. if (!$done) {
  67. $module = 'moodle-form-dateselector';
  68. $function = 'M.form.dateselector.init_date_selectors';
  69. $config = array(array('firstdayofweek'=>get_string('firstdayofweek', 'langconfig')));
  70. $PAGE->requires->yui_module($module, $function, $config);
  71. $done = true;
  72. }
  73. }
  74. /**
  75. * Moodle specific wrapper that separates quickforms syntax from moodle code. You won't directly
  76. * use this class you should write a class definition which extends this class or a more specific
  77. * subclass such a moodleform_mod for each form you want to display and/or process with formslib.
  78. *
  79. * You will write your own definition() method which performs the form set up.
  80. *
  81. * @package moodlecore
  82. * @copyright Jamie Pratt <me@jamiep.org>
  83. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  84. */
  85. abstract class moodleform {
  86. /** @var string */
  87. protected $_formname; // form name
  88. /**
  89. * quickform object definition
  90. *
  91. * @var MoodleQuickForm MoodleQuickForm
  92. */
  93. protected $_form;
  94. /**
  95. * globals workaround
  96. *
  97. * @var array
  98. */
  99. protected $_customdata;
  100. /**
  101. * definition_after_data executed flag
  102. * @var object definition_finalized
  103. */
  104. protected $_definition_finalized = false;
  105. /**
  106. * The constructor function calls the abstract function definition() and it will then
  107. * process and clean and attempt to validate incoming data.
  108. *
  109. * It will call your custom validate method to validate data and will also check any rules
  110. * you have specified in definition using addRule
  111. *
  112. * The name of the form (id attribute of the form) is automatically generated depending on
  113. * the name you gave the class extending moodleform. You should call your class something
  114. * like
  115. *
  116. * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
  117. * current url. If a moodle_url object then outputs params as hidden variables.
  118. * @param array $customdata if your form defintion method needs access to data such as $course
  119. * $cm, etc. to construct the form definition then pass it in this array. You can
  120. * use globals for somethings.
  121. * @param string $method if you set this to anything other than 'post' then _GET and _POST will
  122. * be merged and used as incoming data to the form.
  123. * @param string $target target frame for form submission. You will rarely use this. Don't use
  124. * it if you don't need to as the target attribute is deprecated in xhtml
  125. * strict.
  126. * @param mixed $attributes you can pass a string of html attributes here or an array.
  127. * @param bool $editable
  128. * @return object moodleform
  129. */
  130. function moodleform($action=null, $customdata=null, $method='post', $target='', $attributes=null, $editable=true) {
  131. if (empty($action)){
  132. $action = strip_querystring(qualified_me());
  133. }
  134. $this->_formname = get_class($this); // '_form' suffix kept in order to prevent collisions of form id and other element
  135. $this->_customdata = $customdata;
  136. $this->_form = new MoodleQuickForm($this->_formname, $method, $action, $target, $attributes);
  137. if (!$editable){
  138. $this->_form->hardFreeze();
  139. }
  140. $this->definition();
  141. $this->_form->addElement('hidden', 'sesskey', null); // automatic sesskey protection
  142. $this->_form->setType('sesskey', PARAM_RAW);
  143. $this->_form->setDefault('sesskey', sesskey());
  144. $this->_form->addElement('hidden', '_qf__'.$this->_formname, null); // form submission marker
  145. $this->_form->setType('_qf__'.$this->_formname, PARAM_RAW);
  146. $this->_form->setDefault('_qf__'.$this->_formname, 1);
  147. $this->_form->_setDefaultRuleMessages();
  148. // we have to know all input types before processing submission ;-)
  149. $this->_process_submission($method);
  150. }
  151. /**
  152. * To autofocus on first form element or first element with error.
  153. *
  154. * @param string $name if this is set then the focus is forced to a field with this name
  155. *
  156. * @return string javascript to select form element with first error or
  157. * first element if no errors. Use this as a parameter
  158. * when calling print_header
  159. */
  160. function focus($name=NULL) {
  161. $form =& $this->_form;
  162. $elkeys = array_keys($form->_elementIndex);
  163. $error = false;
  164. if (isset($form->_errors) && 0 != count($form->_errors)){
  165. $errorkeys = array_keys($form->_errors);
  166. $elkeys = array_intersect($elkeys, $errorkeys);
  167. $error = true;
  168. }
  169. if ($error or empty($name)) {
  170. $names = array();
  171. while (empty($names) and !empty($elkeys)) {
  172. $el = array_shift($elkeys);
  173. $names = $form->_getElNamesRecursive($el);
  174. }
  175. if (!empty($names)) {
  176. $name = array_shift($names);
  177. }
  178. }
  179. $focus = '';
  180. if (!empty($name)) {
  181. $focus = 'forms[\''.$form->getAttribute('id').'\'].elements[\''.$name.'\']';
  182. }
  183. return $focus;
  184. }
  185. /**
  186. * Internal method. Alters submitted data to be suitable for quickforms processing.
  187. * Must be called when the form is fully set up.
  188. *
  189. * @param string $method
  190. */
  191. function _process_submission($method) {
  192. $submission = array();
  193. if ($method == 'post') {
  194. if (!empty($_POST)) {
  195. $submission = $_POST;
  196. }
  197. } else {
  198. $submission = array_merge_recursive($_GET, $_POST); // emulate handling of parameters in xxxx_param()
  199. }
  200. // following trick is needed to enable proper sesskey checks when using GET forms
  201. // the _qf__.$this->_formname serves as a marker that form was actually submitted
  202. if (array_key_exists('_qf__'.$this->_formname, $submission) and $submission['_qf__'.$this->_formname] == 1) {
  203. if (!confirm_sesskey()) {
  204. print_error('invalidsesskey');
  205. }
  206. $files = $_FILES;
  207. } else {
  208. $submission = array();
  209. $files = array();
  210. }
  211. $this->_form->updateSubmission($submission, $files);
  212. }
  213. /**
  214. * Internal method. Validates all old-style deprecated uploaded files.
  215. * The new way is to upload files via repository api.
  216. *
  217. * @global object
  218. * @global object
  219. * @param array $files
  220. * @return bool|array Success or an array of errors
  221. */
  222. function _validate_files(&$files) {
  223. global $CFG, $COURSE;
  224. $files = array();
  225. if (empty($_FILES)) {
  226. // we do not need to do any checks because no files were submitted
  227. // note: server side rules do not work for files - use custom verification in validate() instead
  228. return true;
  229. }
  230. $errors = array();
  231. $filenames = array();
  232. // now check that we really want each file
  233. foreach ($_FILES as $elname=>$file) {
  234. $required = $this->_form->isElementRequired($elname);
  235. if ($file['error'] == 4 and $file['size'] == 0) {
  236. if ($required) {
  237. $errors[$elname] = get_string('required');
  238. }
  239. unset($_FILES[$elname]);
  240. continue;
  241. }
  242. if (!empty($file['error'])) {
  243. $errors[$elname] = file_get_upload_error($file['error']);
  244. unset($_FILES[$elname]);
  245. continue;
  246. }
  247. if (!is_uploaded_file($file['tmp_name'])) {
  248. // TODO: improve error message
  249. $errors[$elname] = get_string('error');
  250. unset($_FILES[$elname]);
  251. continue;
  252. }
  253. if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
  254. // hmm, this file was not requested
  255. unset($_FILES[$elname]);
  256. continue;
  257. }
  258. /*
  259. // TODO: rethink the file scanning MDL-19380
  260. if ($CFG->runclamonupload) {
  261. if (!clam_scan_moodle_file($_FILES[$elname], $COURSE)) {
  262. $errors[$elname] = $_FILES[$elname]['uploadlog'];
  263. unset($_FILES[$elname]);
  264. continue;
  265. }
  266. }
  267. */
  268. $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
  269. if ($filename === '') {
  270. // TODO: improve error message - wrong chars
  271. $errors[$elname] = get_string('error');
  272. unset($_FILES[$elname]);
  273. continue;
  274. }
  275. if (in_array($filename, $filenames)) {
  276. // TODO: improve error message - duplicate name
  277. $errors[$elname] = get_string('error');
  278. unset($_FILES[$elname]);
  279. continue;
  280. }
  281. $filenames[] = $filename;
  282. $_FILES[$elname]['name'] = $filename;
  283. $files[$elname] = $_FILES[$elname]['tmp_name'];
  284. }
  285. // return errors if found
  286. if (count($errors) == 0){
  287. return true;
  288. } else {
  289. $files = array();
  290. return $errors;
  291. }
  292. }
  293. /**
  294. * Load in existing data as form defaults. Usually new entry defaults are stored directly in
  295. * form definition (new entry form); this function is used to load in data where values
  296. * already exist and data is being edited (edit entry form).
  297. *
  298. * note: $slashed param removed
  299. *
  300. * @param mixed $default_values object or array of default values
  301. */
  302. function set_data($default_values) {
  303. if (is_object($default_values)) {
  304. $default_values = (array)$default_values;
  305. }
  306. $this->_form->setDefaults($default_values);
  307. }
  308. /**
  309. * @deprecated
  310. */
  311. function set_upload_manager($um=false) {
  312. debugging('Old file uploads can not be used any more, please use new filepicker element');
  313. }
  314. /**
  315. * Check that form was submitted. Does not check validity of submitted data.
  316. *
  317. * @return bool true if form properly submitted
  318. */
  319. function is_submitted() {
  320. return $this->_form->isSubmitted();
  321. }
  322. /**
  323. * @staticvar bool $nosubmit
  324. */
  325. function no_submit_button_pressed(){
  326. static $nosubmit = null; // one check is enough
  327. if (!is_null($nosubmit)){
  328. return $nosubmit;
  329. }
  330. $mform =& $this->_form;
  331. $nosubmit = false;
  332. if (!$this->is_submitted()){
  333. return false;
  334. }
  335. foreach ($mform->_noSubmitButtons as $nosubmitbutton){
  336. if (optional_param($nosubmitbutton, 0, PARAM_RAW)){
  337. $nosubmit = true;
  338. break;
  339. }
  340. }
  341. return $nosubmit;
  342. }
  343. /**
  344. * Check that form data is valid.
  345. * You should almost always use this, rather than {@see validate_defined_fields}
  346. *
  347. * @staticvar bool $validated
  348. * @return bool true if form data valid
  349. */
  350. function is_validated() {
  351. //finalize the form definition before any processing
  352. if (!$this->_definition_finalized) {
  353. $this->_definition_finalized = true;
  354. $this->definition_after_data();
  355. }
  356. return $this->validate_defined_fields();
  357. }
  358. /**
  359. * Validate the form.
  360. *
  361. * You almost always want to call {@see is_validated} instead of this
  362. * because it calls {@see definition_after_data} first, before validating the form,
  363. * which is what you want in 99% of cases.
  364. *
  365. * This is provided as a separate function for those special cases where
  366. * you want the form validated before definition_after_data is called
  367. * for example, to selectively add new elements depending on a no_submit_button press,
  368. * but only when the form is valid when the no_submit_button is pressed,
  369. *
  370. * @param boolean $validateonnosubmit optional, defaults to false. The default behaviour
  371. * is NOT to validate the form when a no submit button has been pressed.
  372. * pass true here to override this behaviour
  373. *
  374. * @return bool true if form data valid
  375. */
  376. function validate_defined_fields($validateonnosubmit=false) {
  377. static $validated = null; // one validation is enough
  378. $mform =& $this->_form;
  379. if ($this->no_submit_button_pressed() && empty($validateonnosubmit)){
  380. return false;
  381. } elseif ($validated === null) {
  382. $internal_val = $mform->validate();
  383. $files = array();
  384. $file_val = $this->_validate_files($files);
  385. if ($file_val !== true) {
  386. if (!empty($file_val)) {
  387. foreach ($file_val as $element=>$msg) {
  388. $mform->setElementError($element, $msg);
  389. }
  390. }
  391. $file_val = false;
  392. }
  393. $data = $mform->exportValues();
  394. $moodle_val = $this->validation($data, $files);
  395. if ((is_array($moodle_val) && count($moodle_val)!==0)) {
  396. // non-empty array means errors
  397. foreach ($moodle_val as $element=>$msg) {
  398. $mform->setElementError($element, $msg);
  399. }
  400. $moodle_val = false;
  401. } else {
  402. // anything else means validation ok
  403. $moodle_val = true;
  404. }
  405. $validated = ($internal_val and $moodle_val and $file_val);
  406. }
  407. return $validated;
  408. }
  409. /**
  410. * Return true if a cancel button has been pressed resulting in the form being submitted.
  411. *
  412. * @return boolean true if a cancel button has been pressed
  413. */
  414. function is_cancelled(){
  415. $mform =& $this->_form;
  416. if ($mform->isSubmitted()){
  417. foreach ($mform->_cancelButtons as $cancelbutton){
  418. if (optional_param($cancelbutton, 0, PARAM_RAW)){
  419. return true;
  420. }
  421. }
  422. }
  423. return false;
  424. }
  425. /**
  426. * Return submitted data if properly submitted or returns NULL if validation fails or
  427. * if there is no submitted data.
  428. *
  429. * note: $slashed param removed
  430. *
  431. * @return object submitted data; NULL if not valid or not submitted
  432. */
  433. function get_data() {
  434. $mform =& $this->_form;
  435. if ($this->is_submitted() and $this->is_validated()) {
  436. $data = $mform->exportValues();
  437. unset($data['sesskey']); // we do not need to return sesskey
  438. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  439. if (empty($data)) {
  440. return NULL;
  441. } else {
  442. return (object)$data;
  443. }
  444. } else {
  445. return NULL;
  446. }
  447. }
  448. /**
  449. * Return submitted data without validation or NULL if there is no submitted data.
  450. * note: $slashed param removed
  451. *
  452. * @return object submitted data; NULL if not submitted
  453. */
  454. function get_submitted_data() {
  455. $mform =& $this->_form;
  456. if ($this->is_submitted()) {
  457. $data = $mform->exportValues();
  458. unset($data['sesskey']); // we do not need to return sesskey
  459. unset($data['_qf__'.$this->_formname]); // we do not need the submission marker too
  460. if (empty($data)) {
  461. return NULL;
  462. } else {
  463. return (object)$data;
  464. }
  465. } else {
  466. return NULL;
  467. }
  468. }
  469. /**
  470. * Save verified uploaded files into directory. Upload process can be customised from definition()
  471. * NOTE: please use save_stored_file() or save_file()
  472. *
  473. * @return bool Always false
  474. */
  475. function save_files($destination) {
  476. debugging('Not used anymore, please fix code! Use save_stored_file() or save_file() instead');
  477. return false;
  478. }
  479. /**
  480. * Returns name of uploaded file.
  481. *
  482. * @global object
  483. * @param string $elname, first element if null
  484. * @return mixed false in case of failure, string if ok
  485. */
  486. function get_new_filename($elname=null) {
  487. global $USER;
  488. if (!$this->is_submitted() or !$this->is_validated()) {
  489. return false;
  490. }
  491. if (is_null($elname)) {
  492. if (empty($_FILES)) {
  493. return false;
  494. }
  495. reset($_FILES);
  496. $elname = key($_FILES);
  497. }
  498. if (empty($elname)) {
  499. return false;
  500. }
  501. $element = $this->_form->getElement($elname);
  502. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  503. $values = $this->_form->exportValues($elname);
  504. if (empty($values[$elname])) {
  505. return false;
  506. }
  507. $draftid = $values[$elname];
  508. $fs = get_file_storage();
  509. $context = get_context_instance(CONTEXT_USER, $USER->id);
  510. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  511. return false;
  512. }
  513. $file = reset($files);
  514. return $file->get_filename();
  515. }
  516. if (!isset($_FILES[$elname])) {
  517. return false;
  518. }
  519. return $_FILES[$elname]['name'];
  520. }
  521. /**
  522. * Save file to standard filesystem
  523. *
  524. * @global object
  525. * @param string $elname name of element
  526. * @param string $pathname full path name of file
  527. * @param bool $override override file if exists
  528. * @return bool success
  529. */
  530. function save_file($elname, $pathname, $override=false) {
  531. global $USER;
  532. if (!$this->is_submitted() or !$this->is_validated()) {
  533. return false;
  534. }
  535. if (file_exists($pathname)) {
  536. if ($override) {
  537. if (!@unlink($pathname)) {
  538. return false;
  539. }
  540. } else {
  541. return false;
  542. }
  543. }
  544. $element = $this->_form->getElement($elname);
  545. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  546. $values = $this->_form->exportValues($elname);
  547. if (empty($values[$elname])) {
  548. return false;
  549. }
  550. $draftid = $values[$elname];
  551. $fs = get_file_storage();
  552. $context = get_context_instance(CONTEXT_USER, $USER->id);
  553. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  554. return false;
  555. }
  556. $file = reset($files);
  557. return $file->copy_content_to($pathname);
  558. } else if (isset($_FILES[$elname])) {
  559. return copy($_FILES[$elname]['tmp_name'], $pathname);
  560. }
  561. return false;
  562. }
  563. /**
  564. * Returns a temporary file, do not forget to delete after not needed any more.
  565. *
  566. * @param string $elname
  567. * @return string or false
  568. */
  569. function save_temp_file($elname) {
  570. if (!$this->get_new_filename($elname)) {
  571. return false;
  572. }
  573. if (!$dir = make_upload_directory('temp/forms')) {
  574. return false;
  575. }
  576. if (!$tempfile = tempnam($dir, 'tempup_')) {
  577. return false;
  578. }
  579. if (!$this->save_file($elname, $tempfile, true)) {
  580. // something went wrong
  581. @unlink($tempfile);
  582. return false;
  583. }
  584. return $tempfile;
  585. }
  586. /**
  587. * Get draft files of a form element
  588. * This is a protected method which will be used only inside moodleforms
  589. *
  590. * @global object $USER
  591. * @param string $elname name of element
  592. * @return array
  593. */
  594. protected function get_draft_files($elname) {
  595. global $USER;
  596. if (!$this->is_submitted()) {
  597. return false;
  598. }
  599. $element = $this->_form->getElement($elname);
  600. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  601. $values = $this->_form->exportValues($elname);
  602. if (empty($values[$elname])) {
  603. return false;
  604. }
  605. $draftid = $values[$elname];
  606. $fs = get_file_storage();
  607. $context = get_context_instance(CONTEXT_USER, $USER->id);
  608. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  609. return null;
  610. }
  611. return $files;
  612. }
  613. return null;
  614. }
  615. /**
  616. * Save file to local filesystem pool
  617. *
  618. * @global object
  619. * @param string $elname name of element
  620. * @param int $newcontextid
  621. * @param string $newfilearea
  622. * @param string $newfilepath
  623. * @param string $newfilename - use specified filename, if not specified name of uploaded file used
  624. * @param bool $overwrite - overwrite file if exists
  625. * @param int $newuserid - new userid if required
  626. * @return mixed stored_file object or false if error; may throw exception if duplicate found
  627. */
  628. function save_stored_file($elname, $newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath='/',
  629. $newfilename=null, $overwrite=false, $newuserid=null) {
  630. global $USER;
  631. if (!$this->is_submitted() or !$this->is_validated()) {
  632. return false;
  633. }
  634. if (empty($newuserid)) {
  635. $newuserid = $USER->id;
  636. }
  637. $element = $this->_form->getElement($elname);
  638. $fs = get_file_storage();
  639. if ($element instanceof MoodleQuickForm_filepicker) {
  640. $values = $this->_form->exportValues($elname);
  641. if (empty($values[$elname])) {
  642. return false;
  643. }
  644. $draftid = $values[$elname];
  645. $context = get_context_instance(CONTEXT_USER, $USER->id);
  646. if (!$files = $fs->get_area_files($context->id, 'user' ,'draft', $draftid, 'id DESC', false)) {
  647. return false;
  648. }
  649. $file = reset($files);
  650. if (is_null($newfilename)) {
  651. $newfilename = $file->get_filename();
  652. }
  653. if ($overwrite) {
  654. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  655. if (!$oldfile->delete()) {
  656. return false;
  657. }
  658. }
  659. }
  660. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  661. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  662. return $fs->create_file_from_storedfile($file_record, $file);
  663. } else if (isset($_FILES[$elname])) {
  664. $filename = is_null($newfilename) ? $_FILES[$elname]['name'] : $newfilename;
  665. if ($overwrite) {
  666. if ($oldfile = $fs->get_file($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  667. if (!$oldfile->delete()) {
  668. return false;
  669. }
  670. }
  671. }
  672. $file_record = array('contextid'=>$newcontextid, 'component'=>$newcomponent, 'filearea'=>$newfilearea, 'itemid'=>$newitemid,
  673. 'filepath'=>$newfilepath, 'filename'=>$newfilename, 'userid'=>$newuserid);
  674. return $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
  675. }
  676. return false;
  677. }
  678. /**
  679. * Get content of uploaded file.
  680. *
  681. * @global object
  682. * @param $element name of file upload element
  683. * @return mixed false in case of failure, string if ok
  684. */
  685. function get_file_content($elname) {
  686. global $USER;
  687. if (!$this->is_submitted() or !$this->is_validated()) {
  688. return false;
  689. }
  690. $element = $this->_form->getElement($elname);
  691. if ($element instanceof MoodleQuickForm_filepicker || $element instanceof MoodleQuickForm_filemanager) {
  692. $values = $this->_form->exportValues($elname);
  693. if (empty($values[$elname])) {
  694. return false;
  695. }
  696. $draftid = $values[$elname];
  697. $fs = get_file_storage();
  698. $context = get_context_instance(CONTEXT_USER, $USER->id);
  699. if (!$files = $fs->get_area_files($context->id, 'user', 'draft', $draftid, 'id DESC', false)) {
  700. return false;
  701. }
  702. $file = reset($files);
  703. return $file->get_content();
  704. } else if (isset($_FILES[$elname])) {
  705. return file_get_contents($_FILES[$elname]['tmp_name']);
  706. }
  707. return false;
  708. }
  709. /**
  710. * Print html form.
  711. */
  712. function display() {
  713. //finalize the form definition if not yet done
  714. if (!$this->_definition_finalized) {
  715. $this->_definition_finalized = true;
  716. $this->definition_after_data();
  717. }
  718. $this->_form->display();
  719. }
  720. /**
  721. * Abstract method - always override!
  722. */
  723. protected abstract function definition();
  724. /**
  725. * Dummy stub method - override if you need to setup the form depending on current
  726. * values. This method is called after definition(), data submission and set_data().
  727. * All form setup that is dependent on form values should go in here.
  728. */
  729. function definition_after_data(){
  730. }
  731. /**
  732. * Dummy stub method - override if you needed to perform some extra validation.
  733. * If there are errors return array of errors ("fieldname"=>"error message"),
  734. * otherwise true if ok.
  735. *
  736. * Server side rules do not work for uploaded files, implement serverside rules here if needed.
  737. *
  738. * @param array $data array of ("fieldname"=>value) of submitted data
  739. * @param array $files array of uploaded files "element_name"=>tmp_file_path
  740. * @return array of "element_name"=>"error_description" if there are errors,
  741. * or an empty array if everything is OK (true allowed for backwards compatibility too).
  742. */
  743. function validation($data, $files) {
  744. return array();
  745. }
  746. /**
  747. * Method to add a repeating group of elements to a form.
  748. *
  749. * @param array $elementobjs Array of elements or groups of elements that are to be repeated
  750. * @param integer $repeats no of times to repeat elements initially
  751. * @param array $options Array of options to apply to elements. Array keys are element names.
  752. * This is an array of arrays. The second sets of keys are the option types
  753. * for the elements :
  754. * 'default' - default value is value
  755. * 'type' - PARAM_* constant is value
  756. * 'helpbutton' - helpbutton params array is value
  757. * 'disabledif' - last three moodleform::disabledIf()
  758. * params are value as an array
  759. * @param string $repeathiddenname name for hidden element storing no of repeats in this form
  760. * @param string $addfieldsname name for button to add more fields
  761. * @param int $addfieldsno how many fields to add at a time
  762. * @param string $addstring name of button, {no} is replaced by no of blanks that will be added.
  763. * @param boolean $addbuttoninside if true, don't call closeHeaderBefore($addfieldsname). Default false.
  764. * @return int no of repeats of element in this page
  765. */
  766. function repeat_elements($elementobjs, $repeats, $options, $repeathiddenname,
  767. $addfieldsname, $addfieldsno=5, $addstring=null, $addbuttoninside=false){
  768. if ($addstring===null){
  769. $addstring = get_string('addfields', 'form', $addfieldsno);
  770. } else {
  771. $addstring = str_ireplace('{no}', $addfieldsno, $addstring);
  772. }
  773. $repeats = optional_param($repeathiddenname, $repeats, PARAM_INT);
  774. $addfields = optional_param($addfieldsname, '', PARAM_TEXT);
  775. if (!empty($addfields)){
  776. $repeats += $addfieldsno;
  777. }
  778. $mform =& $this->_form;
  779. $mform->registerNoSubmitButton($addfieldsname);
  780. $mform->addElement('hidden', $repeathiddenname, $repeats);
  781. $mform->setType($repeathiddenname, PARAM_INT);
  782. //value not to be overridden by submitted value
  783. $mform->setConstants(array($repeathiddenname=>$repeats));
  784. $namecloned = array();
  785. for ($i = 0; $i < $repeats; $i++) {
  786. foreach ($elementobjs as $elementobj){
  787. $elementclone = fullclone($elementobj);
  788. $name = $elementclone->getName();
  789. $namecloned[] = $name;
  790. if (!empty($name)) {
  791. $elementclone->setName($name."[$i]");
  792. }
  793. if (is_a($elementclone, 'HTML_QuickForm_header')) {
  794. $value = $elementclone->_text;
  795. $elementclone->setValue(str_replace('{no}', ($i+1), $value));
  796. } else {
  797. $value=$elementclone->getLabel();
  798. $elementclone->setLabel(str_replace('{no}', ($i+1), $value));
  799. }
  800. $mform->addElement($elementclone);
  801. }
  802. }
  803. for ($i=0; $i<$repeats; $i++) {
  804. foreach ($options as $elementname => $elementoptions){
  805. $pos=strpos($elementname, '[');
  806. if ($pos!==FALSE){
  807. $realelementname = substr($elementname, 0, $pos+1)."[$i]";
  808. $realelementname .= substr($elementname, $pos+1);
  809. }else {
  810. $realelementname = $elementname."[$i]";
  811. }
  812. foreach ($elementoptions as $option => $params){
  813. switch ($option){
  814. case 'default' :
  815. $mform->setDefault($realelementname, $params);
  816. break;
  817. case 'helpbutton' :
  818. $params = array_merge(array($realelementname), $params);
  819. call_user_func_array(array(&$mform, 'addHelpButton'), $params);
  820. break;
  821. case 'disabledif' :
  822. foreach ($namecloned as $num => $name){
  823. if ($params[0] == $name){
  824. $params[0] = $params[0]."[$i]";
  825. break;
  826. }
  827. }
  828. $params = array_merge(array($realelementname), $params);
  829. call_user_func_array(array(&$mform, 'disabledIf'), $params);
  830. break;
  831. case 'rule' :
  832. if (is_string($params)){
  833. $params = array(null, $params, null, 'client');
  834. }
  835. $params = array_merge(array($realelementname), $params);
  836. call_user_func_array(array(&$mform, 'addRule'), $params);
  837. break;
  838. }
  839. }
  840. }
  841. }
  842. $mform->addElement('submit', $addfieldsname, $addstring);
  843. if (!$addbuttoninside) {
  844. $mform->closeHeaderBefore($addfieldsname);
  845. }
  846. return $repeats;
  847. }
  848. /**
  849. * Adds a link/button that controls the checked state of a group of checkboxes.
  850. *
  851. * @global object
  852. * @param int $groupid The id of the group of advcheckboxes this element controls
  853. * @param string $buttontext The text of the link. Defaults to "select all/none"
  854. * @param array $attributes associative array of HTML attributes
  855. * @param int $originalValue The original general state of the checkboxes before the user first clicks this element
  856. */
  857. function add_checkbox_controller($groupid, $buttontext, $attributes, $originalValue = 0) {
  858. global $CFG;
  859. if (empty($text)) {
  860. $text = get_string('selectallornone', 'form');
  861. }
  862. $mform = $this->_form;
  863. $select_value = optional_param('checkbox_controller'. $groupid, null, PARAM_INT);
  864. if ($select_value == 0 || is_null($select_value)) {
  865. $new_select_value = 1;
  866. } else {
  867. $new_select_value = 0;
  868. }
  869. $mform->addElement('hidden', "checkbox_controller$groupid");
  870. $mform->setType("checkbox_controller$groupid", PARAM_INT);
  871. $mform->setConstants(array("checkbox_controller$groupid" => $new_select_value));
  872. // Locate all checkboxes for this group and set their value, IF the optional param was given
  873. if (!is_null($select_value)) {
  874. foreach ($this->_form->_elements as $element) {
  875. if ($element->getAttribute('class') == "checkboxgroup$groupid") {
  876. $mform->setConstants(array($element->getAttribute('name') => $select_value));
  877. }
  878. }
  879. }
  880. $checkbox_controller_name = 'nosubmit_checkbox_controller' . $groupid;
  881. $mform->registerNoSubmitButton($checkbox_controller_name);
  882. // Prepare Javascript for submit element
  883. $js = "\n//<![CDATA[\n";
  884. if (!defined('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS')) {
  885. $js .= <<<EOS
  886. function html_quickform_toggle_checkboxes(group) {
  887. var checkboxes = getElementsByClassName(document, 'input', 'checkboxgroup' + group);
  888. var newvalue = false;
  889. var global = eval('html_quickform_checkboxgroup' + group + ';');
  890. if (global == 1) {
  891. eval('html_quickform_checkboxgroup' + group + ' = 0;');
  892. newvalue = '';
  893. } else {
  894. eval('html_quickform_checkboxgroup' + group + ' = 1;');
  895. newvalue = 'checked';
  896. }
  897. for (i = 0; i < checkboxes.length; i++) {
  898. checkboxes[i].checked = newvalue;
  899. }
  900. }
  901. EOS;
  902. define('HTML_QUICKFORM_CHECKBOXCONTROLLER_EXISTS', true);
  903. }
  904. $js .= "\nvar html_quickform_checkboxgroup$groupid=$originalValue;\n";
  905. $js .= "//]]>\n";
  906. require_once("$CFG->libdir/form/submitlink.php");
  907. $submitlink = new MoodleQuickForm_submitlink($checkbox_controller_name, $attributes);
  908. $submitlink->_js = $js;
  909. $submitlink->_onclick = "html_quickform_toggle_checkboxes($groupid); return false;";
  910. $mform->addElement($submitlink);
  911. $mform->setDefault($checkbox_controller_name, $text);
  912. }
  913. /**
  914. * Use this method to a cancel and submit button to the end of your form. Pass a param of false
  915. * if you don't want a cancel button in your form. If you have a cancel button make sure you
  916. * check for it being pressed using is_cancelled() and redirecting if it is true before trying to
  917. * get data with get_data().
  918. *
  919. * @param boolean $cancel whether to show cancel button, default true
  920. * @param string $submitlabel label for submit button, defaults to get_string('savechanges')
  921. */
  922. function add_action_buttons($cancel = true, $submitlabel=null){
  923. if (is_null($submitlabel)){
  924. $submitlabel = get_string('savechanges');
  925. }
  926. $mform =& $this->_form;
  927. if ($cancel){
  928. //when two elements we need a group
  929. $buttonarray=array();
  930. $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
  931. $buttonarray[] = &$mform->createElement('cancel');
  932. $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
  933. $mform->closeHeaderBefore('buttonar');
  934. } else {
  935. //no group needed
  936. $mform->addElement('submit', 'submitbutton', $submitlabel);
  937. $mform->closeHeaderBefore('submitbutton');
  938. }
  939. }
  940. /**
  941. * Adds an initialisation call for a standard JavaScript enhancement.
  942. *
  943. * This function is designed to add an initialisation call for a JavaScript
  944. * enhancement that should exist within javascript-static M.form.init_{enhancementname}.
  945. *
  946. * Current options:
  947. * - Selectboxes
  948. * - smartselect: Turns a nbsp indented select box into a custom drop down
  949. * control that supports multilevel and category selection.
  950. * $enhancement = 'smartselect';
  951. * $options = array('selectablecategories' => true|false)
  952. *
  953. * @since 2.0
  954. * @param string|element $element
  955. * @param string $enhancement
  956. * @param array $options
  957. * @param array $strings
  958. */
  959. function init_javascript_enhancement($element, $enhancement, array $options=array(), array $strings=null) {
  960. global $PAGE;
  961. if (is_string($element)) {
  962. $element = $this->_form->getElement($element);
  963. }
  964. if (is_object($element)) {
  965. $element->_generateId();
  966. $elementid = $element->getAttribute('id');
  967. $PAGE->requires->js_init_call('M.form.init_'.$enhancement, array($elementid, $options));
  968. if (is_array($strings)) {
  969. foreach ($strings as $string) {
  970. if (is_array($string)) {
  971. call_user_method_array('string_for_js', $PAGE->requires, $string);
  972. } else {
  973. $PAGE->requires->string_for_js($string, 'moodle');
  974. }
  975. }
  976. }
  977. }
  978. }
  979. /**
  980. * Returns a JS module definition for the mforms JS
  981. * @return array
  982. */
  983. public static function get_js_module() {
  984. global $CFG;
  985. return array(
  986. 'name' => 'mform',
  987. 'fullpath' => '/lib/form/form.js',
  988. 'requires' => array('base', 'node'),
  989. 'strings' => array(
  990. array('showadvanced', 'form'),
  991. array('hideadvanced', 'form')
  992. )
  993. );
  994. }
  995. }
  996. /**
  997. * You never extend this class directly. The class methods of this class are available from
  998. * the private $this->_form property on moodleform and its children. You generally only
  999. * call methods on this class from within abstract methods that you override on moodleform such
  1000. * as definition and definition_after_data
  1001. *
  1002. * @package moodlecore
  1003. * @copyright Jamie Pratt <me@jamiep.org>
  1004. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1005. */
  1006. class MoodleQuickForm extends HTML_QuickForm_DHTMLRulesTableless {
  1007. /** @var array */
  1008. var $_types = array();
  1009. var $_dependencies = array();
  1010. /**
  1011. * Array of buttons that if pressed do not result in the processing of the form.
  1012. *
  1013. * @var array
  1014. */
  1015. var $_noSubmitButtons=array();
  1016. /**
  1017. * Array of buttons that if pressed do not result in the processing of the form.
  1018. *
  1019. * @var array
  1020. */
  1021. var $_cancelButtons=array();
  1022. /**
  1023. * Array whose keys are element names. If the key exists this is a advanced element
  1024. *
  1025. * @var array
  1026. */
  1027. var $_advancedElements = array();
  1028. /**
  1029. * Whether to display advanced elements (on page load)
  1030. *
  1031. * @var boolean
  1032. */
  1033. var $_showAdvanced = null;
  1034. /**
  1035. * The form name is derived from the class name of the wrapper minus the trailing form
  1036. * It is a name with words joined by underscores whereas the id attribute is words joined by
  1037. * underscores.
  1038. *
  1039. * @var unknown_type
  1040. */
  1041. var $_formName = '';
  1042. /**
  1043. * String with the html for hidden params passed in as part of a moodle_url object for the action. Output in the form.
  1044. *
  1045. * @var string
  1046. */
  1047. var $_pageparams = '';
  1048. /**
  1049. * Class constructor - same parameters as HTML_QuickForm_DHTMLRulesTableless
  1050. *
  1051. * @global object
  1052. * @staticvar int $formcounter
  1053. * @param string $formName Form's name.
  1054. * @param string $method (optional)Form's method defaults to 'POST'
  1055. * @param mixed $action (optional)Form's action - string or moodle_url
  1056. * @param string $target (optional)Form's target defaults to none
  1057. * @param mixed $attributes (optional)Extra attributes for <form> tag
  1058. * @access public
  1059. */
  1060. function MoodleQuickForm($formName, $method, $action, $target='', $attributes=null){
  1061. global $CFG, $OUTPUT;
  1062. static $formcounter = 1;
  1063. HTML_Common::HTML_Common($attributes);
  1064. $target = empty($target) ? array() : array('target' => $target);
  1065. $this->_formName = $formName;
  1066. if (is_a($action, 'moodle_url')){
  1067. $this->_pageparams = html_writer::input_hidden_params($action);
  1068. $action = $action->out_omit_querystring();
  1069. } else {
  1070. $this->_pageparams = '';
  1071. }
  1072. //no 'name' atttribute for form in xhtml strict :
  1073. $attributes = array('action'=>$action, 'method'=>$method,
  1074. 'accept-charset'=>'utf-8', 'id'=>'mform'.$formcounter) + $target;
  1075. $formcounter++;
  1076. $this->updateAttributes($attributes);
  1077. //this is custom stuff for Moodle :
  1078. $oldclass= $this->getAttribute('class');
  1079. if (!empty($oldclass)){
  1080. $this->updateAttributes(array('class'=>$oldclass.' mform'));
  1081. }else {
  1082. $this->updateAttributes(array('class'=>'mform'));
  1083. }
  1084. $this->_reqHTML = '<img class="req" title="'.get_string('requiredelement', 'form').'" alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />';
  1085. $this->_advancedHTML = '<img class="adv" title="'.get_string('advancedelement', 'form').'" alt="'.get_string('advancedelement', 'form').'" src="'.$OUTPUT->pix_url('adv') .'" />';
  1086. $this->setRequiredNote(get_string('somefieldsrequired', 'form', '<img alt="'.get_string('requiredelement', 'form').'" src="'.$OUTPUT->pix_url('req') .'" />'));
  1087. }
  1088. /**
  1089. * Use this method to indicate an element in a form is an advanced field. If items in a form
  1090. * are marked as advanced then 'Hide/Show Advanced' buttons will automatically be displayed in the
  1091. * form so the user can decide whether to display advanced form controls.
  1092. *
  1093. * If you set a header element to advanced then all elements it contains will also be set as advanced.
  1094. *
  1095. * @param string $elementName group or element name (not the element name of something inside a group).
  1096. * @param boolean $advanced default true sets the element to advanced. False removes advanced mark.
  1097. */
  1098. function setAdvanced($elementName, $advanced=true){
  1099. if ($advanced){
  1100. $this->_advancedElements[$elementName]='';
  1101. } elseif (isset($this->_advancedElements[$elementName])) {
  1102. unset($this->_advancedElements[$elementName]);
  1103. }
  1104. if ($advanced && $this->getElementType('mform_showadvanced_last')===false){
  1105. $this->setShowAdvanced();
  1106. $this->registerNoSubmitButton('mform_showadvanced');
  1107. $this->addElement('hidden', 'mform_showadvanced_last');
  1108. $this->setType('mform_showadvanced_last', PARAM_INT);
  1109. }
  1110. }
  1111. /**
  1112. * Set whether to show advanced elements in the form on first displaying form. Default is not to
  1113. * display advanced elements in the form until 'Show Advanced' is pressed.
  1114. *
  1115. * You can get the last state of the form and possibly save it for this user by using
  1116. * value 'mform_showadvanced_last' in submitted data.
  1117. *
  1118. * @param boolean $showadvancedNow
  1119. */
  1120. function setShowAdvanced($showadvancedNow = null){
  1121. if ($showadvancedNow === null){
  1122. if ($this->_showAdvanced !== null){
  1123. return;
  1124. } else { //if setShowAdvanced is called without any preference
  1125. //make the default to not show advanced elements.
  1126. $showadvancedNow = get_user_preferences(
  1127. moodle_strtolower($this->_formName.'_showadvanced', 0));
  1128. }
  1129. }
  1130. //value of hidden element
  1131. $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT);
  1132. //value of button
  1133. $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW);
  1134. //toggle if button pressed or else stay the same
  1135. if ($hiddenLast == -1) {
  1136. $next = $showadvancedNow;
  1137. } elseif ($buttonPressed) { //toggle on button press
  1138. $next = !$hiddenLast;
  1139. } else {
  1140. $next = $hiddenLast;
  1141. }
  1142. $this->_showAdvanced = $next;
  1143. if ($showadvancedNow != $next){
  1144. set_user_preference($this->_formName.'_showadvanced', $next);
  1145. }
  1146. $this->setConstants(array('mform_showadvanced_last'=>$next));
  1147. }
  1148. function getShowAdvanced(){
  1149. return $this->_showAdvanced;
  1150. }
  1151. /**
  1152. * Accepts a renderer
  1153. *
  1154. * @param object $renderer HTML_QuickForm_Renderer An HTML_QuickForm_Renderer object
  1155. * @access public
  1156. * @return void
  1157. */
  1158. function accept(&$renderer) {
  1159. if (method_exists($renderer, 'setAdvancedElements')){
  1160. //check for visible fieldsets where all elements are advanced
  1161. //and mark these headers as advanced as well.
  1162. //And mark all elements in a advanced header as advanced
  1163. $stopFields = $renderer->getStopFieldSetElements();
  1164. $lastHeader = null;
  1165. $lastHeaderAdvanced = false;
  1166. $anyAdvanced = false;
  1167. foreach (array_keys($this->_elements) as $elementIndex){
  1168. $element =& $this->_elements[$elementIndex];
  1169. // if closing header and any contained element was advanced then mark it as advanced
  1170. if ($element->getType()=='header' || in_array($element->getName(), $stopFields)){
  1171. if ($anyAdvanced && !is_null($lastHeader)){
  1172. $this->setAdvanced($lastHeader->getName());
  1173. }
  1174. $lastHeaderAdvanced = false;
  1175. unset($lastHeader);
  1176. $lastHeader = null;
  1177. } elseif ($lastHeaderAdvanced) {
  1178. $this->setAdvanced($element->getName());
  1179. }
  1180. if ($element->getType()=='header'){
  1181. $lastHeader =& $element;
  1182. $anyAdvanced = false;
  1183. $lastHeaderAdvanced = isset($this->_advancedElements[$element->getName()]);
  1184. } elseif (isset($this->_advancedElements[$element->getName()])){
  1185. $anyAdvanced = true;
  1186. }
  1187. }
  1188. // the last header may not be closed yet...
  1189. if ($anyAdvanced && !is_null($lastHeader)){
  1190. $this->setAdvanced($lastHeader->getName());
  1191. }
  1192. $renderer->setAdvancedElements($this->_advancedElements);
  1193. }
  1194. parent::accept($renderer);
  1195. }
  1196. /**
  1197. * @param string $elementName
  1198. */
  1199. function closeHeaderBefore($elementName){
  1200. $renderer =& $this->defaultRenderer();
  1201. $renderer->addStopFieldsetElements($elementName);
  1202. }
  1203. /**
  1204. * Should be used for all elements of a form except for select, radio and checkboxes which
  1205. * clean their own data.
  1206. *
  1207. * @param string $elementname
  1208. * @param integer $paramtype use the constants PARAM_*.
  1209. * * PARAM_CLEAN is deprecated and you should try to use a more specific type.
  1210. * * PARAM_TEXT should be used for cleaning data that is expected to be plain text.
  1211. * It will strip all html tags. But will still let tags for multilang support
  1212. * through.
  1213. * * PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the
  1214. * html editor. Data from the editor is later cleaned before display using
  1215. * format_text() function. PARAM_RAW can also be used for data that is validated
  1216. * by some other way or printed by p() or s().
  1217. * * PARAM_INT should be used for integers.
  1218. * * PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying
  1219. * form actions.
  1220. */
  1221. function setType($elementname, $paramtype) {
  1222. $this->_types[$elementname] = $paramtype;
  1223. }
  1224. /**
  1225. * See description of setType above. This can be used to set several types at once.
  1226. *
  1227. * @param array $paramtypes
  1228. */
  1229. function setTypes($paramtypes) {
  1230. $this->_types = $paramtypes + $this->_types;
  1231. }
  1232. /**
  1233. * @param array $submission
  1234. * @param array $files
  1235. */
  1236. function updateSubmission($submission, $files) {
  1237. $this->_flagSubmitted = false;
  1238. if (empty($submission)) {
  1239. $this->_submitValues = array();
  1240. } else {
  1241. foreach ($submission as $key=>$s) {
  1242. if (array_key_exists($key, $this->_types)) {
  1243. $submission[$key] = clean_param($s, $this->_types[$key]);
  1244. }
  1245. }
  1246. $this->_submitValues = $submission;
  1247. $this->_flagSubmitted = true;
  1248. }
  1249. if (empty($files)) {
  1250. $this->_submitFiles = array();
  1251. } else {
  1252. $this->_submitFiles = $files;
  1253. $this->_flagSubmitted = true;
  1254. }
  1255. // need to tell all elements that they need to update their value attribute.
  1256. foreach (array_keys($this->_elements) as $key) {
  1257. $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
  1258. }
  1259. }
  1260. /**
  1261. * @return string
  1262. */
  1263. function getReqHTML(){
  1264. return $this->_reqHTML;
  1265. }
  1266. /**
  1267. * @return string
  1268. */
  1269. function getAdvancedHTML(){
  1270. return $this->_advancedHTML;
  1271. }
  1272. /**
  1273. * Initializes a default form value. Used to specify the default for a new entry where
  1274. * no data is loaded in using moodleform::set_data()
  1275. *
  1276. * note: $slashed param removed
  1277. *
  1278. * @param string $elementname element name
  1279. * @param mixed $values values for that element name
  1280. * @access public
  1281. * @return void
  1282. */
  1283. function setDefault($elementName, $defaultValue){
  1284. $this->setDefaults(array($elementName=>$defaultValue));
  1285. } // end func setDefault
  1286. /**
  1287. * Add an array of buttons to the form
  1288. * @param array $buttons An associative array representing help button to attach to
  1289. * to the form. keys of array correspond to names of elements in form.
  1290. * @deprecated since Moodle 2.0 - use addHelpButton() call on each element manually
  1291. * @param bool $suppresscheck
  1292. * @param string $function
  1293. * @access public
  1294. */
  1295. function setHelpButtons($buttons, $suppresscheck=false, $function='helpbutton'){
  1296. debugging('function moodle_form::setHelpButtons() is deprecated');
  1297. //foreach ($buttons as $elementname => $button){
  1298. // $this->setHelpButton($elementname, $button, $suppresscheck, $function);
  1299. //}
  1300. }
  1301. /**
  1302. * Add a single button.
  1303. *
  1304. * @deprecated use addHelpButton() instead
  1305. * @param string $elementname name of the element to add the item to
  1306. * @param array $button arguments to pass to function $function
  1307. * @param boolean $suppresscheck whether to throw an error if the element
  1308. * doesn't exist.
  1309. * @param string $function - function to generate html from the arguments in $button
  1310. * @param string $function
  1311. */
  1312. function setHelpButton($elementname, $buttonargs, $suppresscheck=false, $function='helpbutton'){
  1313. global $OUTPUT;
  1314. debugging('function moodle_form::setHelpButton() is deprecated');
  1315. if ($function !== 'helpbutton') {
  1316. //debugging('parameter $function in moodle_form::setHelpButton() is not supported any more');
  1317. }
  1318. $buttonargs = (array)$buttonargs;
  1319. if (array_key_exists($elementname, $this->_elementIndex)) {
  1320. //_elements has a numeric index, this code accesses the elements by name
  1321. $element = $this->_elements[$this->_elementIndex[$elementname]];
  1322. $page = isset($buttonargs[0]) ? $buttonargs[0] : null;
  1323. $text = isset($buttonargs[1]) ? $buttonargs[1] : null;
  1324. $module = isset($buttonargs[2]) ? $buttonargs[2] : 'moodle';
  1325. $linktext = isset($buttonargs[3]) ? $buttonargs[3] : false;
  1326. $element->_helpbutton = $OUTPUT->old_help_icon($page, $text, $module, $linktext);
  1327. } else if (!$suppresscheck) {
  1328. print_error('nonexistentformelements', 'form', '', $elementname);
  1329. }
  1330. }
  1331. /**
  1332. * Add a help button to element, only one button per element is allowed.
  1333. *
  1334. * This is new, simplified and preferable method of setting a help icon on form elements.
  1335. * It uses the new $OUTPUT->help_icon().
  1336. *
  1337. * Typically, you will provide the same identifier and the component as you have used for the
  1338. * label of the element. The string identifier with the _help suffix added is then used
  1339. * as the help string.
  1340. *
  1341. * There has to be two strings defined:
  1342. * 1/ get_string($identifier, $component) - the title of the help page
  1343. * 2/ get_string($identifier.'_help', $component) - the actual help page text
  1344. *
  1345. * @since 2.0
  1346. * @param string $elementname name of the element to add the item to
  1347. * @param string $identifier help string identifier without _help suffix
  1348. * @param string $component component name to look the help string in
  1349. * @param string $linktext optional text to display next to the icon
  1350. * @param boolean $suppresscheck set to true if the element may not exist
  1351. * @return void
  1352. */
  1353. function addHelpButton($elementname, $identifier, $component = 'moodle', $linktext = '', $suppresscheck = false) {
  1354. global $OUTPUT;
  1355. if (array_key_exists($elementname, $this->_elementIndex)) {
  1356. $element = $this->_elements[$this->_elementIndex[$elementname]];
  1357. $element->_helpbutton = $OUTPUT->help_icon($identifier, $component, $linktext);
  1358. } else if (!$suppresscheck) {
  1359. debugging(get_string('nonexistentformelements', 'form', $elementname));
  1360. }
  1361. }
  1362. /**
  1363. * Set constant value not overridden by _POST or _GET
  1364. * note: this does not work for complex names with [] :-(
  1365. *
  1366. * @param string $elname name of element
  1367. * @param mixed $value
  1368. * @return void
  1369. */
  1370. function setConstant($elname, $value) {
  1371. $this->_constantValues = HTML_QuickForm::arrayMerge($this->_constantValues, array($elname=>$value));
  1372. $element =& $this->getElement($elname);
  1373. $element->onQuickFormEvent('updateValue', null, $this);
  1374. }
  1375. /**
  1376. * @param string $elementList
  1377. */
  1378. function exportValues($elementList = null){
  1379. $unfiltered = array();
  1380. if (null === $elementList) {
  1381. // iterate over all elements, calling their exportValue() methods
  1382. $emptyarray = array();
  1383. foreach (array_keys($this->_elements) as $key) {
  1384. if ($this->_elements[$key]->isFrozen() && !$this->_elements[$key]->_persistantFreeze){
  1385. $value = $this->_elements[$key]->exportValue($emptyarray, true);
  1386. } else {
  1387. $value = $this->_elements[$key]->exportValue($this->_submitValues, true);
  1388. }
  1389. if (is_array($value)) {
  1390. // This shit throws a bogus warning in PHP 4.3.x
  1391. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
  1392. }
  1393. }
  1394. } else {
  1395. if (!is_array($elementList)) {
  1396. $elementList = array_map('trim', explode(',', $elementList));
  1397. }
  1398. foreach ($elementList as $elementName) {
  1399. $value = $this->exportValue($elementName);
  1400. if (PEAR::isError($value)) {
  1401. return $value;
  1402. }
  1403. //oh, stock QuickFOrm was returning array of arrays!
  1404. $unfiltered = HTML_QuickForm::arrayMerge($unfiltered, $value);
  1405. }
  1406. }
  1407. return $unfiltered;
  1408. }
  1409. /**
  1410. * Adds a validation rule for the given field
  1411. *
  1412. * If the element is in fact a group, it will be considered as a whole.
  1413. * To validate grouped elements as separated entities,
  1414. * use addGroupRule instead of addRule.
  1415. *
  1416. * @param string $element Form element name
  1417. * @param string $message Message to display for invalid data
  1418. * @param string $type Rule type, use getRegisteredRules() to get types
  1419. * @param string $format (optional)Required for extra rule data
  1420. * @param string $validation (optional)Where to perform validation: "server", "client"
  1421. * @param boolean $reset Client-side validation: reset the form element to its original value if there is an error?
  1422. * @param boolean $force Force the rule to be applied, even if the target form element does not exist
  1423. * @access public
  1424. */
  1425. function addRule($element, $message, $type, $format=null, $validation='server', $reset = false, $force = false)
  1426. {
  1427. parent::addRule($element, $message, $type, $format, $validation, $reset, $force);
  1428. if ($validation == 'client') {
  1429. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1430. }
  1431. } // end func addRule
  1432. /**
  1433. * Adds a validation rule for the given group of elements
  1434. *
  1435. * Only groups with a name can be assigned a validation rule
  1436. * Use addGroupRule when you need to validate elements inside the group.
  1437. * Use addRule if you need to validate the group as a whole. In this case,
  1438. * the same rule will be applied to all elements in the group.
  1439. * Use addRule if you need to validate the group against a function.
  1440. *
  1441. * @param string $group Form group name
  1442. * @param mixed $arg1 Array for multiple elements or error message string for one element
  1443. * @param string $type (optional)Rule type use getRegisteredRules() to get types
  1444. * @param string $format (optional)Required for extra rule data
  1445. * @param int $howmany (optional)How many valid elements should be in the group
  1446. * @param string $validation (optional)Where to perform validation: "server", "client"
  1447. * @param bool $reset Client-side: whether to reset the element's value to its original state if validation failed.
  1448. * @access public
  1449. */
  1450. function addGroupRule($group, $arg1, $type='', $format=null, $howmany=0, $validation = 'server', $reset = false)
  1451. {
  1452. parent::addGroupRule($group, $arg1, $type, $format, $howmany, $validation, $reset);
  1453. if (is_array($arg1)) {
  1454. foreach ($arg1 as $rules) {
  1455. foreach ($rules as $rule) {
  1456. $validation = (isset($rule[3]) && 'client' == $rule[3])? 'client': 'server';
  1457. if ('client' == $validation) {
  1458. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1459. }
  1460. }
  1461. }
  1462. } elseif (is_string($arg1)) {
  1463. if ($validation == 'client') {
  1464. $this->updateAttributes(array('onsubmit' => 'try { var myValidator = validate_' . $this->_formName . '; } catch(e) { return true; } return myValidator(this);'));
  1465. }
  1466. }
  1467. } // end func addGroupRule
  1468. // }}}
  1469. /**
  1470. * Returns the client side validation script
  1471. *
  1472. * The code here was copied from HTML_QuickForm_DHTMLRulesTableless who copied it from HTML_QuickForm
  1473. * and slightly modified to run rules per-element
  1474. * Needed to override this because of an error with client side validation of grouped elements.
  1475. *
  1476. * @access public
  1477. * @return string Javascript to perform validation, empty string if no 'client' rules were added
  1478. */
  1479. function getValidationScript()
  1480. {
  1481. if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
  1482. return '';
  1483. }
  1484. include_once('HTML/QuickForm/RuleRegistry.php');
  1485. $registry =& HTML_QuickForm_RuleRegistry::singleton();
  1486. $test = array();
  1487. $js_escape = array(
  1488. "\r" => '\r',
  1489. "\n" => '\n',
  1490. "\t" => '\t',
  1491. "'" => "\\'",
  1492. '"' => '\"',
  1493. '\\' => '\\\\'
  1494. );
  1495. foreach ($this->_rules as $elementName => $rules) {
  1496. foreach ($rules as $rule) {
  1497. if ('client' == $rule['validation']) {
  1498. unset($element); //TODO: find out how to properly initialize it
  1499. $dependent = isset($rule['dependent']) && is_array($rule['dependent']);
  1500. $rule['message'] = strtr($rule['message'], $js_escape);
  1501. if (isset($rule['group'])) {
  1502. $group =& $this->getElement($rule['group']);
  1503. // No JavaScript validation for frozen elements
  1504. if ($group->isFrozen()) {
  1505. continue 2;
  1506. }
  1507. $elements =& $group->getElements();
  1508. foreach (array_keys($elements) as $key) {
  1509. if ($elementName == $group->getElementName($key)) {
  1510. $element =& $elements[$key];
  1511. break;
  1512. }
  1513. }
  1514. } elseif ($dependent) {
  1515. $element = array();
  1516. $element[] =& $this->getElement($elementName);
  1517. foreach ($rule['dependent'] as $elName) {
  1518. $element[] =& $this->getElement($elName);
  1519. }
  1520. } else {
  1521. $element =& $this->getElement($elementName);
  1522. }
  1523. // No JavaScript validation for frozen elements
  1524. if (is_object($element) && $element->isFrozen()) {
  1525. continue 2;
  1526. } elseif (is_array($element)) {
  1527. foreach (array_keys($element) as $key) {
  1528. if ($element[$key]->isFrozen()) {
  1529. continue 3;
  1530. }
  1531. }
  1532. }
  1533. // Fix for bug displaying errors for elements in a group
  1534. //$test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
  1535. $test[$elementName][0][] = $registry->getValidationScript($element, $elementName, $rule);
  1536. $test[$elementName][1]=$element;
  1537. //end of fix
  1538. }
  1539. }
  1540. }
  1541. // Fix for MDL-9524. If you don't do this, then $element may be left as a reference to one of the fields in
  1542. // the form, and then that form field gets corrupted by the code that follows.
  1543. unset($element);
  1544. $js = '
  1545. <script type="text/javascript">
  1546. //<![CDATA[
  1547. var skipClientValidation = false;
  1548. function qf_errorHandler(element, _qfMsg) {
  1549. div = element.parentNode;
  1550. if (_qfMsg != \'\') {
  1551. var errorSpan = document.getElementById(\'id_error_\'+element.name);
  1552. if (!errorSpan) {
  1553. errorSpan = document.createElement("span");
  1554. errorSpan.id = \'id_error_\'+element.name;
  1555. errorSpan.className = "error";
  1556. element.parentNode.insertBefore(errorSpan, element.parentNode.firstChild);
  1557. }
  1558. while (errorSpan.firstChild) {
  1559. errorSpan.removeChild(errorSpan.firstChild);
  1560. }
  1561. errorSpan.appendChild(document.createTextNode(_qfMsg.substring(3)));
  1562. errorSpan.appendChild(document.createElement("br"));
  1563. if (div.className.substr(div.className.length - 6, 6) != " error"
  1564. && div.className != "error") {
  1565. div.className += " error";
  1566. }
  1567. return false;
  1568. } else {
  1569. var errorSpan = document.getElementById(\'id_error_\'+element.name);
  1570. if (errorSpan) {
  1571. errorSpan.parentNode.removeChild(errorSpan);
  1572. }
  1573. if (div.className.substr(div.className.length - 6, 6) == " error") {
  1574. div.className = div.className.substr(0, div.className.length - 6);
  1575. } else if (div.className == "error") {
  1576. div.className = "";
  1577. }
  1578. return true;
  1579. }
  1580. }';
  1581. $validateJS = '';
  1582. foreach ($test as $elementName => $jsandelement) {
  1583. // Fix for bug displaying errors for elements in a group
  1584. //unset($element);
  1585. list($jsArr,$element)=$jsandelement;
  1586. //end of fix
  1587. $escapedElementName = preg_replace_callback(
  1588. '/[_\[\]]/',
  1589. create_function('$matches', 'return sprintf("_%2x",ord($matches[0]));'),
  1590. $elementName);
  1591. $js .= '
  1592. function validate_' . $this->_formName . '_' . $escapedElementName . '(element) {
  1593. var value = \'\';
  1594. var errFlag = new Array();
  1595. var _qfGroups = {};
  1596. var _qfMsg = \'\';
  1597. var frm = element.parentNode;
  1598. while (frm && frm.nodeName.toUpperCase() != "FORM") {
  1599. frm = frm.parentNode;
  1600. }
  1601. ' . join("\n", $jsArr) . '
  1602. return qf_errorHandler(element, _qfMsg);
  1603. }
  1604. ';
  1605. $validateJS .= '
  1606. ret = validate_' . $this->_formName . '_' . $escapedElementName.'(frm.elements[\''.$elementName.'\']) && ret;
  1607. if (!ret && !first_focus) {
  1608. first_focus = true;
  1609. frm.elements[\''.$elementName.'\'].focus();
  1610. }
  1611. ';
  1612. // Fix for bug displaying errors for elements in a group
  1613. //unset($element);
  1614. //$element =& $this->getElement($elementName);
  1615. //end of fix
  1616. $valFunc = 'validate_' . $this->_formName . '_' . $escapedElementName . '(this)';
  1617. $onBlur = $element->getAttribute('onBlur');
  1618. $onChange = $element->getAttribute('onChange');
  1619. $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
  1620. 'onChange' => $onChange . $valFunc));
  1621. }
  1622. // do not rely on frm function parameter, because htmlarea breaks it when overloading the onsubmit method
  1623. $js .= '
  1624. function validate_' . $this->_formName . '(frm) {
  1625. if (skipClientValidation) {
  1626. return true;
  1627. }
  1628. var ret = true;
  1629. var frm = document.getElementById(\''. $this->_attributes['id'] .'\')
  1630. var first_focus = false;
  1631. ' . $validateJS . ';
  1632. return ret;
  1633. }
  1634. //]]>
  1635. </script>';
  1636. return $js;
  1637. } // end func getValidationScript
  1638. function _setDefaultRuleMessages(){
  1639. foreach ($this->_rules as $field => $rulesarr){
  1640. foreach ($rulesarr as $key => $rule){
  1641. if ($rule['message']===null){
  1642. $a=new stdClass();
  1643. $a->format=$rule['format'];
  1644. $str=get_string('err_'.$rule['type'], 'form', $a);
  1645. if (strpos($str, '[[')!==0){
  1646. $this->_rules[$field][$key]['message']=$str;
  1647. }
  1648. }
  1649. }
  1650. }
  1651. }
  1652. function getLockOptionObject(){
  1653. $result = array();
  1654. foreach ($this->_dependencies as $dependentOn => $conditions){
  1655. $result[$dependentOn] = array();
  1656. foreach ($conditions as $condition=>$values) {
  1657. $result[$dependentOn][$condition] = array();
  1658. foreach ($values as $value=>$dependents) {
  1659. $result[$dependentOn][$condition][$value] = array();
  1660. $i = 0;
  1661. foreach ($dependents as $dependent) {
  1662. $elements = $this->_getElNamesRecursive($dependent);
  1663. if (empty($elements)) {
  1664. // probably element inside of some group
  1665. $elements = array($dependent);
  1666. }
  1667. foreach($elements as $element) {
  1668. if ($element == $dependentOn) {
  1669. continue;
  1670. }
  1671. $result[$dependentOn][$condition][$value][] = $element;
  1672. }
  1673. }
  1674. }
  1675. }
  1676. }
  1677. return array($this->getAttribute('id'), $result);
  1678. }
  1679. /**
  1680. * @param mixed $element
  1681. * @return array
  1682. */
  1683. function _getElNamesRecursive($element) {
  1684. if (is_string($element)) {
  1685. if (!$this->elementExists($element)) {
  1686. return array();
  1687. }
  1688. $element = $this->getElement($element);
  1689. }
  1690. if (is_a($element, 'HTML_QuickForm_group')) {
  1691. $elsInGroup = $element->getElements();
  1692. $elNames = array();
  1693. foreach ($elsInGroup as $elInGroup){
  1694. if (is_a($elInGroup, 'HTML_QuickForm_group')) {
  1695. // not sure if this would work - groups nested in groups
  1696. $elNames = array_merge($elNames, $this->_getElNamesRecursive($elInGroup));
  1697. } else {
  1698. $elNames[] = $element->getElementName($elInGroup->getName());
  1699. }
  1700. }
  1701. } else if (is_a($element, 'HTML_QuickForm_header')) {
  1702. return array();
  1703. } else if (is_a($element, 'HTML_QuickForm_hidden')) {
  1704. return array();
  1705. } else if (method_exists($element, 'getPrivateName')) {
  1706. return array($element->getPrivateName());
  1707. } else {
  1708. $elNames = array($element->getName());
  1709. }
  1710. return $elNames;
  1711. }
  1712. /**
  1713. * Adds a dependency for $elementName which will be disabled if $condition is met.
  1714. * If $condition = 'notchecked' (default) then the condition is that the $dependentOn element
  1715. * is not checked. If $condition = 'checked' then the condition is that the $dependentOn element
  1716. * is checked. If $condition is something else (like "eq" for equals) then it is checked to see if the value
  1717. * of the $dependentOn element is $condition (such as equal) to $value.
  1718. *
  1719. * @param string $elementName the name of the element which will be disabled
  1720. * @param string $dependentOn the name of the element whose state will be checked for
  1721. * condition
  1722. * @param string $condition the condition to check
  1723. * @param mixed $value used in conjunction with condition.
  1724. */
  1725. function disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value='1'){
  1726. if (!array_key_exists($dependentOn, $this->_dependencies)) {
  1727. $this->_dependencies[$dependentOn] = array();
  1728. }
  1729. if (!array_key_exists($condition, $this->_dependencies[$dependentOn])) {
  1730. $this->_dependencies[$dependentOn][$condition] = array();
  1731. }
  1732. if (!array_key_exists($value, $this->_dependencies[$dependentOn][$condition])) {
  1733. $this->_dependencies[$dependentOn][$condition][$value] = array();
  1734. }
  1735. $this->_dependencies[$dependentOn][$condition][$value][] = $elementName;
  1736. }
  1737. function registerNoSubmitButton($buttonname){
  1738. $this->_noSubmitButtons[]=$buttonname;
  1739. }
  1740. /**
  1741. * @param string $buttonname
  1742. * @return mixed
  1743. */
  1744. function isNoSubmitButton($buttonname){
  1745. return (array_search($buttonname, $this->_noSubmitButtons)!==FALSE);
  1746. }
  1747. /**
  1748. * @param string $buttonname
  1749. */
  1750. function _registerCancelButton($addfieldsname){
  1751. $this->_cancelButtons[]=$addfieldsname;
  1752. }
  1753. /**
  1754. * Displays elements without HTML input tags.
  1755. * This method is different to freeze() in that it makes sure no hidden
  1756. * elements are included in the form.
  1757. * Note: If you want to make sure the submitted value is ignored, please use setDefaults().
  1758. *
  1759. * This function also removes all previously defined rules.
  1760. *
  1761. * @param mixed $elementList array or string of element(s) to be frozen
  1762. * @access public
  1763. */
  1764. function hardFreeze($elementList=null)
  1765. {
  1766. if (!isset($elementList)) {
  1767. $this->_freezeAll = true;
  1768. $elementList = array();
  1769. } else {
  1770. if (!is_array($elementList)) {
  1771. $elementList = preg_split('/[ ]*,[ ]*/', $elementList);
  1772. }
  1773. $elementList = array_flip($elementList);
  1774. }
  1775. foreach (array_keys($this->_elements) as $key) {
  1776. $name = $this->_elements[$key]->getName();
  1777. if ($this->_freezeAll || isset($elementList[$name])) {
  1778. $this->_elements[$key]->freeze();
  1779. $this->_elements[$key]->setPersistantFreeze(false);
  1780. unset($elementList[$name]);
  1781. // remove all rules
  1782. $this->_rules[$name] = array();
  1783. // if field is required, remove the rule
  1784. $unset = array_search($name, $this->_required);
  1785. if ($unset !== false) {
  1786. unset($this->_required[$unset]);
  1787. }
  1788. }
  1789. }
  1790. if (!empty($elementList)) {
  1791. return PEAR::raiseError(null, QUICKFORM_NONEXIST_ELEMENT, null, E_USER_WARNING, "Nonexistant element(s): '" . implode("', '", array_keys($elementList)) . "' in HTML_QuickForm::freeze()", 'HTML_QuickForm_Error', true);
  1792. }
  1793. return true;
  1794. }
  1795. /**
  1796. * Hard freeze all elements in a form except those whose names are in $elementList or hidden elements in a form.
  1797. *
  1798. * This function also removes all previously defined rules of elements it freezes.
  1799. *
  1800. * throws HTML_QuickForm_Error
  1801. *
  1802. * @param array $elementList array or string of element(s) not to be frozen
  1803. * @access public
  1804. */
  1805. function hardFreezeAllVisibleExcept($elementList)
  1806. {
  1807. $elementList = array_flip($elementList);
  1808. foreach (array_keys($this->_elements) as $key) {
  1809. $name = $this->_elements[$key]->getName();
  1810. $type = $this->_elements[$key]->getType();
  1811. if ($type == 'hidden'){
  1812. // leave hidden types as they are
  1813. } elseif (!isset($elementList[$name])) {
  1814. $this->_elements[$key]->freeze();
  1815. $this->_elements[$key]->setPersistantFreeze(false);
  1816. // remove all rules
  1817. $this->_rules[$name] = array();
  1818. // if field is required, remove the rule
  1819. $unset = array_search($name, $this->_required);
  1820. if ($unset !== false) {
  1821. unset($this->_required[$unset]);
  1822. }
  1823. }
  1824. }
  1825. return true;
  1826. }
  1827. /**
  1828. * Tells whether the form was already submitted
  1829. *
  1830. * This is useful since the _submitFiles and _submitValues arrays
  1831. * may be completely empty after the trackSubmit value is removed.
  1832. *
  1833. * @access public
  1834. * @return bool
  1835. */
  1836. function isSubmitted()
  1837. {
  1838. return parent::isSubmitted() && (!$this->isFrozen());
  1839. }
  1840. }
  1841. /**
  1842. * A renderer for MoodleQuickForm that only uses XHTML and CSS and no
  1843. * table tags, extends PEAR class HTML_QuickForm_Renderer_Tableless
  1844. *
  1845. * Stylesheet is part of standard theme and should be automatically included.
  1846. *
  1847. * @package moodlecore
  1848. * @copyright Jamie Pratt <me@jamiep.org>
  1849. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1850. */
  1851. class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
  1852. /**
  1853. * Element template array
  1854. * @var array
  1855. * @access private
  1856. */
  1857. var $_elementTemplates;
  1858. /**
  1859. * Template used when opening a hidden fieldset
  1860. * (i.e. a fieldset that is opened when there is no header element)
  1861. * @var string
  1862. * @access private
  1863. */
  1864. var $_openHiddenFieldsetTemplate = "\n\t<fieldset class=\"hidden\"><div>";
  1865. /**
  1866. * Header Template string
  1867. * @var string
  1868. * @access private
  1869. */
  1870. var $_headerTemplate =
  1871. "\n\t\t<legend class=\"ftoggler\">{header}</legend>\n\t\t<div class=\"advancedbutton\">{advancedimg}{button}</div><div class=\"fcontainer clearfix\">\n\t\t";
  1872. /**
  1873. * Template used when opening a fieldset
  1874. * @var string
  1875. * @access private
  1876. */
  1877. var $_openFieldsetTemplate = "\n\t<fieldset class=\"clearfix\" {id}>";
  1878. /**
  1879. * Template used when closing a fieldset
  1880. * @var string
  1881. * @access private
  1882. */
  1883. var $_closeFieldsetTemplate = "\n\t\t</div></fieldset>";
  1884. /**
  1885. * Required Note template string
  1886. * @var string
  1887. * @access private
  1888. */
  1889. var $_requiredNoteTemplate =
  1890. "\n\t\t<div class=\"fdescription required\">{requiredNote}</div>";
  1891. var $_advancedElements = array();
  1892. /**
  1893. * Whether to display advanced elements (on page load)
  1894. *
  1895. * @var integer 1 means show 0 means hide
  1896. */
  1897. var $_showAdvanced;
  1898. function MoodleQuickForm_Renderer(){
  1899. // switch next two lines for ol li containers for form items.
  1900. // $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>');
  1901. $this->_elementTemplates = array(
  1902. 'default'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div><div class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</div></div>',
  1903. 'fieldset'=>"\n\t\t".'<div class="fitem {advanced}<!-- BEGIN required --> required<!-- END required -->"><div class="fitemtitle"><div class="fgrouplabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><fieldset class="felement {type}<!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}</fieldset></div>',
  1904. 'static'=>"\n\t\t".'<div class="fitem {advanced}"><div class="fitemtitle"><div class="fstaticlabel"><label>{label}<!-- BEGIN required -->{req}<!-- END required -->{advancedimg} {help}</label></div></div><div class="felement fstatic <!-- BEGIN error --> error<!-- END error -->"><!-- BEGIN error --><span class="error">{error}</span><br /><!-- END error -->{element}&nbsp;</div></div>',
  1905. 'warning'=>"\n\t\t".'<div class="fitem {advanced}">{element}</div>',
  1906. 'nodisplay'=>'');
  1907. parent::HTML_QuickForm_Renderer_Tableless();
  1908. }
  1909. /**
  1910. * @param array $elements
  1911. */
  1912. function setAdvancedElements($elements){
  1913. $this->_advancedElements = $elements;
  1914. }
  1915. /**
  1916. * What to do when starting the form
  1917. *
  1918. * @param object $form MoodleQuickForm
  1919. */
  1920. function startForm(&$form){
  1921. $this->_reqHTML = $form->getReqHTML();
  1922. $this->_elementTemplates = str_replace('{req}', $this->_reqHTML, $this->_elementTemplates);
  1923. $this->_advancedHTML = $form->getAdvancedHTML();
  1924. $this->_showAdvanced = $form->getShowAdvanced();
  1925. parent::startForm($form);
  1926. if ($form->isFrozen()){
  1927. $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
  1928. } else {
  1929. $this->_formTemplate = "\n<form{attributes}>\n\t<div style=\"display: none;\">{hidden}</div>\n{content}\n</form>";
  1930. $this->_hiddenHtml .= $form->_pageparams;
  1931. }
  1932. }
  1933. /**
  1934. * @param object $group Passed by reference
  1935. * @param mixed $required
  1936. * @param mixed $error
  1937. */
  1938. function startGroup(&$group, $required, $error){
  1939. if (method_exists($group, 'getElementTemplateType')){
  1940. $html = $this->_elementTemplates[$group->getElementTemplateType()];
  1941. }else{
  1942. $html = $this->_elementTemplates['default'];
  1943. }
  1944. if ($this->_showAdvanced){
  1945. $advclass = ' advanced';
  1946. } else {
  1947. $advclass = ' advanced hide';
  1948. }
  1949. if (isset($this->_advancedElements[$group->getName()])){
  1950. $html =str_replace(' {advanced}', $advclass, $html);
  1951. $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
  1952. } else {
  1953. $html =str_replace(' {advanced}', '', $html);
  1954. $html =str_replace('{advancedimg}', '', $html);
  1955. }
  1956. if (method_exists($group, 'getHelpButton')){
  1957. $html =str_replace('{help}', $group->getHelpButton(), $html);
  1958. }else{
  1959. $html =str_replace('{help}', '', $html);
  1960. }
  1961. $html =str_replace('{name}', $group->getName(), $html);
  1962. $html =str_replace('{type}', 'fgroup', $html);
  1963. $this->_templates[$group->getName()]=$html;
  1964. // Fix for bug in tableless quickforms that didn't allow you to stop a
  1965. // fieldset before a group of elements.
  1966. // if the element name indicates the end of a fieldset, close the fieldset
  1967. if ( in_array($group->getName(), $this->_stopFieldsetElements)
  1968. && $this->_fieldsetsOpen > 0
  1969. ) {
  1970. $this->_html .= $this->_closeFieldsetTemplate;
  1971. $this->_fieldsetsOpen--;
  1972. }
  1973. parent::startGroup($group, $required, $error);
  1974. }
  1975. /**
  1976. * @param object $element
  1977. * @param mixed $required
  1978. * @param mixed $error
  1979. */
  1980. function renderElement(&$element, $required, $error){
  1981. //manipulate id of all elements before rendering
  1982. if (!is_null($element->getAttribute('id'))) {
  1983. $id = $element->getAttribute('id');
  1984. } else {
  1985. $id = $element->getName();
  1986. }
  1987. //strip qf_ prefix and replace '[' with '_' and strip ']'
  1988. $id = preg_replace(array('/^qf_|\]/', '/\[/'), array('', '_'), $id);
  1989. if (strpos($id, 'id_') !== 0){
  1990. $element->updateAttributes(array('id'=>'id_'.$id));
  1991. }
  1992. //adding stuff to place holders in template
  1993. //check if this is a group element first
  1994. if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
  1995. // so it gets substitutions for *each* element
  1996. $html = $this->_groupElementTemplate;
  1997. }
  1998. elseif (method_exists($element, 'getElementTemplateType')){
  1999. $html = $this->_elementTemplates[$element->getElementTemplateType()];
  2000. }else{
  2001. $html = $this->_elementTemplates['default'];
  2002. }
  2003. if ($this->_showAdvanced){
  2004. $advclass = ' advanced';
  2005. } else {
  2006. $advclass = ' advanced hide';
  2007. }
  2008. if (isset($this->_advancedElements[$element->getName()])){
  2009. $html =str_replace(' {advanced}', $advclass, $html);
  2010. } else {
  2011. $html =str_replace(' {advanced}', '', $html);
  2012. }
  2013. if (isset($this->_advancedElements[$element->getName()])||$element->getName() == 'mform_showadvanced'){
  2014. $html =str_replace('{advancedimg}', $this->_advancedHTML, $html);
  2015. } else {
  2016. $html =str_replace('{advancedimg}', '', $html);
  2017. }
  2018. $html =str_replace('{type}', 'f'.$element->getType(), $html);
  2019. $html =str_replace('{name}', $element->getName(), $html);
  2020. if (method_exists($element, 'getHelpButton')){
  2021. $html = str_replace('{help}', $element->getHelpButton(), $html);
  2022. }else{
  2023. $html = str_replace('{help}', '', $html);
  2024. }
  2025. if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
  2026. $this->_groupElementTemplate = $html;
  2027. }
  2028. elseif (!isset($this->_templates[$element->getName()])) {
  2029. $this->_templates[$element->getName()] = $html;
  2030. }
  2031. parent::renderElement($element, $required, $error);
  2032. }
  2033. /**
  2034. * @global moodle_page $PAGE
  2035. * @param object $form Passed by reference
  2036. */
  2037. function finishForm(&$form){
  2038. global $PAGE;
  2039. if ($form->isFrozen()){
  2040. $this->_hiddenHtml = '';
  2041. }
  2042. parent::finishForm($form);
  2043. if (!$form->isFrozen()) {
  2044. $args = $form->getLockOptionObject();
  2045. if (count($args[1]) > 0) {
  2046. $PAGE->requires->js_init_call('M.form.initFormDependencies', $args, false, moodleform::get_js_module());
  2047. }
  2048. }
  2049. }
  2050. /**
  2051. * Called when visiting a header element
  2052. *
  2053. * @param object $header An HTML_QuickForm_header element being visited
  2054. * @access public
  2055. * @return void
  2056. * @global moodle_page $PAGE
  2057. */
  2058. function renderHeader(&$header) {
  2059. global $PAGE;
  2060. $name = $header->getName();
  2061. $id = empty($name) ? '' : ' id="' . $name . '"';
  2062. $id = preg_replace(array('/\]/', '/\[/'), array('', '_'), $id);
  2063. if (is_null($header->_text)) {
  2064. $header_html = '';
  2065. } elseif (!empty($name) && isset($this->_templates[$name])) {
  2066. $header_html = str_replace('{header}', $header->toHtml(), $this->_templates[$name]);
  2067. } else {
  2068. $header_html = str_replace('{header}', $header->toHtml(), $this->_headerTemplate);
  2069. }
  2070. if (isset($this->_advancedElements[$name])){
  2071. $header_html =str_replace('{advancedimg}', $this->_advancedHTML, $header_html);
  2072. $elementName='mform_showadvanced';
  2073. if ($this->_showAdvanced==0){
  2074. $buttonlabel = get_string('showadvanced', 'form');
  2075. } else {
  2076. $buttonlabel = get_string('hideadvanced', 'form');
  2077. }
  2078. $button = '<input name="'.$elementName.'" class="showadvancedbtn" value="'.$buttonlabel.'" type="submit" />';
  2079. $PAGE->requires->js_init_call('M.form.initShowAdvanced', array(), false, moodleform::get_js_module());
  2080. $header_html = str_replace('{button}', $button, $header_html);
  2081. } else {
  2082. $header_html =str_replace('{advancedimg}', '', $header_html);
  2083. $header_html = str_replace('{button}', '', $header_html);
  2084. }
  2085. if ($this->_fieldsetsOpen > 0) {
  2086. $this->_html .= $this->_closeFieldsetTemplate;
  2087. $this->_fieldsetsOpen--;
  2088. }
  2089. $openFieldsetTemplate = str_replace('{id}', $id, $this->_openFieldsetTemplate);
  2090. if ($this->_showAdvanced){
  2091. $advclass = ' class="advanced"';
  2092. } else {
  2093. $advclass = ' class="advanced hide"';
  2094. }
  2095. if (isset($this->_advancedElements[$name])){
  2096. $openFieldsetTemplate = str_replace('{advancedclass}', $advclass, $openFieldsetTemplate);
  2097. } else {
  2098. $openFieldsetTemplate = str_replace('{advancedclass}', '', $openFieldsetTemplate);
  2099. }
  2100. $this->_html .= $openFieldsetTemplate . $header_html;
  2101. $this->_fieldsetsOpen++;
  2102. } // end func renderHeader
  2103. function getStopFieldsetElements(){
  2104. return $this->_stopFieldsetElements;
  2105. }
  2106. }
  2107. /**
  2108. * @global object $GLOBALS['_HTML_QuickForm_default_renderer']
  2109. * @name $_HTML_QuickForm_default_renderer
  2110. */
  2111. $GLOBALS['_HTML_QuickForm_default_renderer'] = new MoodleQuickForm_Renderer();
  2112. /** Please keep this list in alphabetical order. */
  2113. MoodleQuickForm::registerElementType('advcheckbox', "$CFG->libdir/form/advcheckbox.php", 'MoodleQuickForm_advcheckbox');
  2114. MoodleQuickForm::registerElementType('button', "$CFG->libdir/form/button.php", 'MoodleQuickForm_button');
  2115. MoodleQuickForm::registerElementType('cancel', "$CFG->libdir/form/cancel.php", 'MoodleQuickForm_cancel');
  2116. MoodleQuickForm::registerElementType('searchableselector', "$CFG->libdir/form/searchableselector.php", 'MoodleQuickForm_searchableselector');
  2117. MoodleQuickForm::registerElementType('checkbox', "$CFG->libdir/form/checkbox.php", 'MoodleQuickForm_checkbox');
  2118. MoodleQuickForm::registerElementType('date_selector', "$CFG->libdir/form/dateselector.php", 'MoodleQuickForm_date_selector');
  2119. MoodleQuickForm::registerElementType('date_time_selector', "$CFG->libdir/form/datetimeselector.php", 'MoodleQuickForm_date_time_selector');
  2120. MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php", 'MoodleQuickForm_duration');
  2121. MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
  2122. MoodleQuickForm::registerElementType('file', "$CFG->libdir/form/file.php", 'MoodleQuickForm_file');
  2123. MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
  2124. MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
  2125. MoodleQuickForm::registerElementType('format', "$CFG->libdir/form/format.php", 'MoodleQuickForm_format');
  2126. MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
  2127. MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
  2128. MoodleQuickForm::registerElementType('hidden', "$CFG->libdir/form/hidden.php", 'MoodleQuickForm_hidden');
  2129. MoodleQuickForm::registerElementType('htmleditor', "$CFG->libdir/form/htmleditor.php", 'MoodleQuickForm_htmleditor');
  2130. MoodleQuickForm::registerElementType('modgrade', "$CFG->libdir/form/modgrade.php", 'MoodleQuickForm_modgrade');
  2131. MoodleQuickForm::registerElementType('modvisible', "$CFG->libdir/form/modvisible.php", 'MoodleQuickForm_modvisible');
  2132. MoodleQuickForm::registerElementType('password', "$CFG->libdir/form/password.php", 'MoodleQuickForm_password');
  2133. MoodleQuickForm::registerElementType('passwordunmask', "$CFG->libdir/form/passwordunmask.php", 'MoodleQuickForm_passwordunmask');
  2134. MoodleQuickForm::registerElementType('questioncategory', "$CFG->libdir/form/questioncategory.php", 'MoodleQuickForm_questioncategory');
  2135. MoodleQuickForm::registerElementType('radio', "$CFG->libdir/form/radio.php", 'MoodleQuickForm_radio');
  2136. MoodleQuickForm::registerElementType('recaptcha', "$CFG->libdir/form/recaptcha.php", 'MoodleQuickForm_recaptcha');
  2137. MoodleQuickForm::registerElementType('select', "$CFG->libdir/form/select.php", 'MoodleQuickForm_select');
  2138. MoodleQuickForm::registerElementType('selectgroups', "$CFG->libdir/form/selectgroups.php", 'MoodleQuickForm_selectgroups');
  2139. MoodleQuickForm::registerElementType('selectwithlink', "$CFG->libdir/form/selectwithlink.php", 'MoodleQuickForm_selectwithlink');
  2140. MoodleQuickForm::registerElementType('selectyesno', "$CFG->libdir/form/selectyesno.php", 'MoodleQuickForm_selectyesno');
  2141. MoodleQuickForm::registerElementType('static', "$CFG->libdir/form/static.php", 'MoodleQuickForm_static');
  2142. MoodleQuickForm::registerElementType('submit', "$CFG->libdir/form/submit.php", 'MoodleQuickForm_submit');
  2143. MoodleQuickForm::registerElementType('submitlink', "$CFG->libdir/form/submitlink.php", 'MoodleQuickForm_submitlink');
  2144. MoodleQuickForm::registerElementType('tags', "$CFG->libdir/form/tags.php", 'MoodleQuickForm_tags');
  2145. MoodleQuickForm::registerElementType('text', "$CFG->libdir/form/text.php", 'MoodleQuickForm_text');
  2146. MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
  2147. MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
  2148. MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');