PageRenderTime 62ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/formslib.php

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