PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/form/duration.php

https://bitbucket.org/moodle/moodle
PHP | 306 lines | 167 code | 19 blank | 120 comment | 32 complexity | 3aef82a5d523144588eb3153044ef0f2 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-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. * Duration form element
  18. *
  19. * Contains class to create length of time for element.
  20. *
  21. * @package core_form
  22. * @copyright 2009 Tim Hunt
  23. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24. */
  25. global $CFG;
  26. require_once($CFG->libdir . '/form/group.php');
  27. require_once($CFG->libdir . '/formslib.php');
  28. require_once($CFG->libdir . '/form/text.php');
  29. /**
  30. * Duration element
  31. *
  32. * HTML class for a length of time. For example, 30 minutes of 4 days. The
  33. * values returned to PHP is the duration in seconds (an int rounded to the nearest second).
  34. *
  35. * @package core_form
  36. * @category form
  37. * @copyright 2009 Tim Hunt
  38. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  39. */
  40. class MoodleQuickForm_duration extends MoodleQuickForm_group {
  41. /**
  42. * Control the field names for form elements
  43. * optional => if true, show a checkbox beside the element to turn it on (or off)
  44. * defaultunit => which unit is default when the form is blank (default Minutes).
  45. * @var array
  46. */
  47. protected $_options = ['optional' => false, 'defaultunit' => MINSECS];
  48. /** @var array associative array of time units (days, hours, minutes, seconds) */
  49. private $_units = null;
  50. /**
  51. * constructor
  52. *
  53. * @param ?string $elementName Element's name
  54. * @param mixed $elementLabel Label(s) for an element
  55. * @param array $options Options to control the element's display. Recognised values are
  56. * 'optional' => true/false - whether to display an 'enabled' checkbox next to the element.
  57. * 'defaultunit' => 1|MINSECS|HOURSECS|DAYSECS|WEEKSECS - the default unit to display when
  58. * the time is blank. If not specified, minutes is used.
  59. * 'units' => array containing some or all of 1, MINSECS, HOURSECS, DAYSECS and WEEKSECS
  60. * which unit choices to offer.
  61. * @param mixed $attributes Either a typical HTML attribute string or an associative array
  62. */
  63. public function __construct($elementName = null, $elementLabel = null,
  64. $options = [], $attributes = null) {
  65. parent::__construct($elementName, $elementLabel, $attributes);
  66. $this->_persistantFreeze = true;
  67. $this->_appendName = true;
  68. $this->_type = 'duration';
  69. // Set the options, do not bother setting bogus ones
  70. if (!is_array($options)) {
  71. $options = [];
  72. }
  73. $this->_options['optional'] = !empty($options['optional']);
  74. if (isset($options['defaultunit'])) {
  75. if (!array_key_exists($options['defaultunit'], $this->get_units())) {
  76. throw new coding_exception($options['defaultunit'] .
  77. ' is not a recognised unit in MoodleQuickForm_duration.');
  78. }
  79. $this->_options['defaultunit'] = $options['defaultunit'];
  80. }
  81. if (isset($options['units'])) {
  82. if (!is_array($options['units'])) {
  83. throw new coding_exception(
  84. 'When creating a duration form field, units option must be an array.');
  85. }
  86. // Validate and register requested units.
  87. $availableunits = $this->get_units();
  88. $displayunits = [];
  89. foreach ($options['units'] as $requestedunit) {
  90. if (!isset($availableunits[$requestedunit])) {
  91. throw new coding_exception($requestedunit .
  92. ' is not a recognised unit in MoodleQuickForm_duration.');
  93. }
  94. $displayunits[$requestedunit] = $availableunits[$requestedunit];
  95. }
  96. krsort($displayunits, SORT_NUMERIC);
  97. $this->_options['units'] = $displayunits;
  98. }
  99. }
  100. /**
  101. * Old syntax of class constructor. Deprecated in PHP7.
  102. *
  103. * @deprecated since Moodle 3.1
  104. */
  105. public function MoodleQuickForm_duration($elementName = null, $elementLabel = null,
  106. $options = [], $attributes = null) {
  107. debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
  108. self::__construct($elementName, $elementLabel, $options, $attributes);
  109. }
  110. /**
  111. * Returns time associative array of unit length.
  112. *
  113. * @return array unit length in seconds => string unit name.
  114. */
  115. public function get_units() {
  116. if (is_null($this->_units)) {
  117. $this->_units = [
  118. WEEKSECS => get_string('weeks'),
  119. DAYSECS => get_string('days'),
  120. HOURSECS => get_string('hours'),
  121. MINSECS => get_string('minutes'),
  122. 1 => get_string('seconds'),
  123. ];
  124. }
  125. return $this->_units;
  126. }
  127. /**
  128. * Get the units to be used for this field.
  129. *
  130. * The ones specified in the options passed to the constructor, or all by default.
  131. *
  132. * @return array number of seconds => lang string.
  133. */
  134. protected function get_units_used() {
  135. if (!empty($this->_options['units'])) {
  136. return $this->_options['units'];
  137. } else {
  138. return $this->get_units();
  139. }
  140. }
  141. /**
  142. * Converts seconds to the best possible time unit. for example
  143. * 1800 -> [30, MINSECS] = 30 minutes.
  144. *
  145. * @param int $seconds an amout of time in seconds.
  146. * @return array associative array ($number => $unit)
  147. */
  148. public function seconds_to_unit($seconds) {
  149. if ($seconds == 0) {
  150. return [0, $this->_options['defaultunit']];
  151. }
  152. foreach ($this->get_units_used() as $unit => $notused) {
  153. if (fmod($seconds, $unit) == 0) {
  154. return [$seconds / $unit, $unit];
  155. }
  156. }
  157. return [$seconds, 1];
  158. }
  159. /**
  160. * Override of standard quickforms method to create this element.
  161. */
  162. function _createElements() {
  163. $attributes = $this->getAttributes();
  164. if (is_null($attributes)) {
  165. $attributes = [];
  166. }
  167. if (!isset($attributes['size'])) {
  168. $attributes['size'] = 3;
  169. }
  170. $this->_elements = [];
  171. // E_STRICT creating elements without forms is nasty because it internally uses $this
  172. $number = $this->createFormElement('text', 'number',
  173. get_string('time', 'form'), $attributes, true);
  174. $number->set_force_ltr(true);
  175. $this->_elements[] = $number;
  176. unset($attributes['size']);
  177. $this->_elements[] = $this->createFormElement('select', 'timeunit',
  178. get_string('timeunit', 'form'), $this->get_units_used(), $attributes, true);
  179. // If optional we add a checkbox which the user can use to turn if on
  180. if($this->_options['optional']) {
  181. $this->_elements[] = $this->createFormElement('checkbox', 'enabled', null,
  182. get_string('enable'), $this->getAttributes(), true);
  183. }
  184. foreach ($this->_elements as $element){
  185. if (method_exists($element, 'setHiddenLabel')){
  186. $element->setHiddenLabel(true);
  187. }
  188. }
  189. }
  190. /**
  191. * Called by HTML_QuickForm whenever form event is made on this element
  192. *
  193. * @param string $event Name of event
  194. * @param mixed $arg event arguments
  195. * @param MoodleQuickForm $caller calling object
  196. * @return bool
  197. */
  198. function onQuickFormEvent($event, $arg, &$caller) {
  199. $this->setMoodleForm($caller);
  200. switch ($event) {
  201. case 'updateValue':
  202. // constant values override both default and submitted ones
  203. // default values are overriden by submitted
  204. $value = $this->_findValue($caller->_constantValues);
  205. if (null === $value) {
  206. // if no boxes were checked, then there is no value in the array
  207. // yet we don't want to display default value in this case
  208. if ($caller->isSubmitted() && !$caller->is_new_repeat($this->getName())) {
  209. $value = $this->_findValue($caller->_submitValues);
  210. } else {
  211. $value = $this->_findValue($caller->_defaultValues);
  212. }
  213. }
  214. if (!is_array($value)) {
  215. list($number, $unit) = $this->seconds_to_unit($value);
  216. $value = ['number' => $number, 'timeunit' => $unit];
  217. // If optional, default to off, unless a date was provided
  218. if ($this->_options['optional']) {
  219. $value['enabled'] = $number != 0;
  220. }
  221. } else {
  222. $value['enabled'] = isset($value['enabled']);
  223. }
  224. if (null !== $value){
  225. $this->setValue($value);
  226. }
  227. break;
  228. case 'createElement':
  229. if (!empty($arg[2]['optional'])) {
  230. $caller->disabledIf($arg[0], $arg[0] . '[enabled]');
  231. }
  232. $caller->setType($arg[0] . '[number]', PARAM_FLOAT);
  233. return parent::onQuickFormEvent($event, $arg, $caller);
  234. default:
  235. return parent::onQuickFormEvent($event, $arg, $caller);
  236. }
  237. }
  238. /**
  239. * Returns HTML for advchecbox form element.
  240. *
  241. * @return string
  242. */
  243. function toHtml() {
  244. include_once('HTML/QuickForm/Renderer/Default.php');
  245. $renderer = new HTML_QuickForm_Renderer_Default();
  246. $renderer->setElementTemplate('{element}');
  247. parent::accept($renderer);
  248. return $renderer->toHtml();
  249. }
  250. /**
  251. * Accepts a renderer
  252. *
  253. * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
  254. * @param bool $required Whether a group is required
  255. * @param ?string $error An error message associated with a group
  256. */
  257. function accept(&$renderer, $required = false, $error = null) {
  258. $renderer->renderElement($this, $required, $error);
  259. }
  260. /**
  261. * Output a timestamp. Give it the name of the group.
  262. * Override of standard quickforms method.
  263. *
  264. * @param array $submitValues
  265. * @param bool $assoc whether to return the value as associative array
  266. * @return array field name => value. The value is the time interval in seconds.
  267. */
  268. function exportValue(&$submitValues, $assoc = false) {
  269. // Get the values from all the child elements.
  270. $valuearray = [];
  271. foreach ($this->_elements as $element) {
  272. $thisexport = $element->exportValue($submitValues[$this->getName()], true);
  273. if (!is_null($thisexport)) {
  274. $valuearray += $thisexport;
  275. }
  276. }
  277. // Convert the value to an integer number of seconds.
  278. if (empty($valuearray)) {
  279. return null;
  280. }
  281. if ($this->_options['optional'] && empty($valuearray['enabled'])) {
  282. return $this->_prepareValue(0, $assoc);
  283. }
  284. return $this->_prepareValue(
  285. (int) round($valuearray['number'] * $valuearray['timeunit']), $assoc);
  286. }
  287. }