MDL-59713 forms: prevent php warning when 'optional' option is missing
[moodle.git] / lib / form / datetimeselector.php
CommitLineData
4a0e2e63 1<?php
6c1fd304
RT
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/>.
25fe66b0 16
6c1fd304
RT
17
18/**
19 * Group of date and time input element
20 *
21 * Contains class for a group of elements used to input a date and time.
22 *
23 * @package core_form
24 * @copyright 2006 Jamie Pratt <me@jamiep.org>
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
25fe66b0 27
e9d39a32 28global $CFG;
25fe66b0 29require_once($CFG->libdir . '/form/group.php');
30require_once($CFG->libdir . '/formslib.php');
e9d39a32 31
32/**
6c1fd304 33 * Element used to input a date and time.
e2294b98 34 *
6c1fd304 35 * Class for a group of elements used to input a date and time.
e2294b98 36 *
6c1fd304
RT
37 * @package core_form
38 * @category form
39 * @copyright 2006 Jamie Pratt <me@jamiep.org>
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e9d39a32 41 */
2f00e1b2
MN
42class MoodleQuickForm_date_time_selector extends MoodleQuickForm_group {
43
e9d39a32 44 /**
2f00e1b2 45 * Options for the element.
6dd59aab 46 *
6c1fd304
RT
47 * startyear => int start of range of years that can be selected
48 * stopyear => int last year that can be selected
49 * defaulttime => default time value if the field is currently not set
fa70f635
RT
50 * timezone => int|float|string (optional) timezone modifier used for edge case only.
51 * If not specified, then date is caclulated based on current user timezone.
52 * Note: dst will be calculated for string timezones only
53 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
6c1fd304
RT
54 * step => step to increment minutes by
55 * optional => if true, show a checkbox beside the date to turn it on (or off)
56 * @var array
57 */
1d43da02 58 protected $_options = array();
e9d39a32 59
34f9862e
MN
60 /**
61 * @var array These complement separators, they are appended to the resultant HTML.
62 */
63 protected $_wrap = array('', '');
64
65 /**
66 * @var null|bool Keeps track of whether the date selector was initialised using createElement
67 * or addElement. If true, createElement was used signifying the element has been
68 * added to a group - see MDL-39187.
69 */
70 protected $_usedcreateelement = true;
e2294b98 71
6c1fd304
RT
72 /**
73 * Class constructor
74 *
75 * @param string $elementName Element's name
76 * @param mixed $elementLabel Label(s) for an element
77 * @param array $options Options to control the element's display
78 * @param mixed $attributes Either a typical HTML attribute string or an associative array
79 */
1a0df553 80 public function __construct($elementName = null, $elementLabel = null, $options = array(), $attributes = null) {
1d43da02
MN
81 // Get the calendar type used - see MDL-18375.
82 $calendartype = \core_calendar\type_factory::get_calendar_instance();
83 $this->_options = array('startyear' => $calendartype->get_min_year(), 'stopyear' => $calendartype->get_max_year(),
84 'defaulttime' => 0, 'timezone' => 99, 'step' => 5, 'optional' => false);
85
32fada5c 86 // TODO MDL-52313 Replace with the call to parent::__construct().
1a0df553 87 HTML_QuickForm_element::__construct($elementName, $elementLabel, $attributes);
e9d39a32 88 $this->_persistantFreeze = true;
89 $this->_appendName = true;
90 $this->_type = 'date_time_selector';
91 // set the options, do not bother setting bogus ones
92 if (is_array($options)) {
93 foreach ($options as $name => $value) {
94 if (isset($this->_options[$name])) {
95 if (is_array($value) && is_array($this->_options[$name])) {
96 $this->_options[$name] = @array_merge($this->_options[$name], $value);
97 } else {
98 $this->_options[$name] = $value;
99 }
100 }
101 }
102 }
1d43da02 103
29cb1e83 104 // The YUI2 calendar only supports the gregorian calendar type.
6b7d0d3e 105 if ($calendartype->get_name() === 'gregorian') {
29cb1e83
MN
106 form_init_date_js();
107 }
e9d39a32 108 }
109
1a0df553
MG
110 /**
111 * Old syntax of class constructor. Deprecated in PHP7.
112 *
113 * @deprecated since Moodle 3.1
114 */
115 public function MoodleQuickForm_date_time_selector($elementName = null, $elementLabel = null, $options = array(), $attributes = null) {
116 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
117 self::__construct($elementName, $elementLabel, $options, $attributes);
118 }
119
6c1fd304
RT
120 /**
121 * This will create date group element constisting of day, month and year.
122 *
123 * @access private
124 */
2f00e1b2
MN
125 function _createElements() {
126 global $OUTPUT;
f40df210 127
2f00e1b2 128 // Get the calendar type used - see MDL-18375.
6eafa4dd 129 $calendartype = \core_calendar\type_factory::get_calendar_instance();
73412d96 130
1d43da02
MN
131 for ($i = 0; $i <= 23; $i++) {
132 $hours[$i] = sprintf("%02d", $i);
e9d39a32 133 }
1d43da02
MN
134 for ($i = 0; $i < 60; $i += $this->_options['step']) {
135 $minutes[$i] = sprintf("%02d", $i);
e9d39a32 136 }
2f00e1b2
MN
137
138 $this->_elements = array();
1d43da02 139 $dateformat = $calendartype->get_date_order($this->_options['startyear'], $this->_options['stopyear']);
bb13339a
NK
140 if (right_to_left()) { // Display time to the right of date, in RTL mode.
141 $this->_elements[] = $this->createFormElement('select', 'minute', get_string('minute', 'form'),
142 $minutes, $this->getAttributes(), true);
143 $this->_elements[] = $this->createFormElement('select', 'hour', get_string('hour', 'form'),
144 $hours, $this->getAttributes(), true);
145 // Reverse date element (Should be: Day, Month, Year), in RTL mode.
146 $dateformat = array_reverse($dateformat);
147 }
73412d96
AG
148 foreach ($dateformat as $key => $date) {
149 // E_STRICT creating elements without forms is nasty because it internally uses $this
721e2def 150 $this->_elements[] = $this->createFormElement('select', $key, get_string($key, 'form'), $date, $this->getAttributes(), true);
73412d96 151 }
bb13339a
NK
152 if (!right_to_left()) { // Display time to the left of date, in LTR mode.
153 $this->_elements[] = $this->createFormElement('select', 'hour', get_string('hour', 'form'), $hours,
154 $this->getAttributes(), true);
155 $this->_elements[] = $this->createFormElement('select', 'minute', get_string('minute', 'form'), $minutes,
156 $this->getAttributes(), true);
4454447d 157 }
29cb1e83 158 // The YUI2 calendar only supports the gregorian calendar type so only display the calendar image if this is being used.
6b7d0d3e 159 if ($calendartype->get_name() === 'gregorian') {
83e9f0ad 160 $image = $OUTPUT->pix_icon('i/calendar', get_string('calendar', 'calendar'), 'moodle');
721e2def 161 $this->_elements[] = $this->createFormElement('link', 'calendar',
83e9f0ad
AN
162 null, '#', $image,
163 array('class' => 'visibleifjs'));
29cb1e83 164 }
46e648b6 165 // If optional we add a checkbox which the user can use to turn if on
29cb1e83 166 if ($this->_options['optional']) {
721e2def 167 $this->_elements[] = $this->createFormElement('checkbox', 'enabled', null, get_string('enable'), $this->getAttributes(), true);
46e648b6 168 }
44875d78 169 foreach ($this->_elements as $element){
170 if (method_exists($element, 'setHiddenLabel')){
171 $element->setHiddenLabel(true);
172 }
173 }
e9d39a32 174
175 }
176
11f260f4 177 /**
178 * Called by HTML_QuickForm whenever form event is made on this element
179 *
6c1fd304
RT
180 * @param string $event Name of event
181 * @param mixed $arg event arguments
182 * @param object $caller calling object
183 * @return bool
11f260f4 184 */
2f00e1b2 185 function onQuickFormEvent($event, $arg, &$caller) {
721e2def 186 $this->setMoodleForm($caller);
11f260f4 187 switch ($event) {
188 case 'updateValue':
deed22ea
MN
189 // Constant values override both default and submitted ones
190 // default values are overriden by submitted.
11f260f4 191 $value = $this->_findValue($caller->_constantValues);
192 if (null === $value) {
deed22ea
MN
193 // If no boxes were checked, then there is no value in the array
194 // yet we don't want to display default value in this case.
11f260f4 195 if ($caller->isSubmitted()) {
196 $value = $this->_findValue($caller->_submitValues);
197 } else {
198 $value = $this->_findValue($caller->_defaultValues);
199 }
200 }
201 $requestvalue=$value;
202 if ($value == 0) {
6282381d 203 $value = $this->_options['defaulttime'];
204 if (!$value) {
205 $value = time();
206 }
11f260f4 207 }
208 if (!is_array($value)) {
deed22ea
MN
209 $calendartype = \core_calendar\type_factory::get_calendar_instance();
210 $currentdate = $calendartype->timestamp_to_date_array($value, $this->_options['timezone']);
5aed3009 211 // Round minutes to the previous multiple of step.
212 $currentdate['minutes'] -= $currentdate['minutes'] % $this->_options['step'];
11f260f4 213 $value = array(
a044c05d 214 'minute' => $currentdate['minutes'],
215 'hour' => $currentdate['hours'],
11f260f4 216 'day' => $currentdate['mday'],
217 'month' => $currentdate['mon'],
218 'year' => $currentdate['year']);
deed22ea
MN
219 // If optional, default to off, unless a date was provided.
220 if ($this->_options['optional']) {
25fe66b0 221 $value['enabled'] = $requestvalue != 0;
11f260f4 222 }
5aed3009 223 } else {
7c1b6150 224 $value['enabled'] = isset($value['enabled']);
5aed3009 225 }
deed22ea 226 if (null !== $value) {
11f260f4 227 $this->setValue($value);
228 }
229 break;
230 case 'createElement':
a4cdbff8 231 if (isset($arg[2]['optional']) && $arg[2]['optional']) {
e019dccc
MN
232 // When using the function addElement, rather than createElement, we still
233 // enter this case, making this check necessary.
234 if ($this->_usedcreateelement) {
235 $caller->disabledIf($arg[0] . '[day]', $arg[0] . '[enabled]');
236 $caller->disabledIf($arg[0] . '[month]', $arg[0] . '[enabled]');
237 $caller->disabledIf($arg[0] . '[year]', $arg[0] . '[enabled]');
238 $caller->disabledIf($arg[0] . '[hour]', $arg[0] . '[enabled]');
239 $caller->disabledIf($arg[0] . '[minute]', $arg[0] . '[enabled]');
240 } else {
241 $caller->disabledIf($arg[0], $arg[0] . '[enabled]');
242 }
11f260f4 243 }
244 return parent::onQuickFormEvent($event, $arg, $caller);
245 break;
34f9862e
MN
246 case 'addElement':
247 $this->_usedcreateelement = false;
248 return parent::onQuickFormEvent($event, $arg, $caller);
249 break;
11f260f4 250 default:
251 return parent::onQuickFormEvent($event, $arg, $caller);
e9d39a32 252 }
e9d39a32 253 }
254
6c1fd304
RT
255 /**
256 * Returns HTML for advchecbox form element.
257 *
258 * @return string
259 */
2f00e1b2 260 function toHtml() {
e9d39a32 261 include_once('HTML/QuickForm/Renderer/Default.php');
bd69b9db 262 $renderer = new HTML_QuickForm_Renderer_Default();
e9d39a32 263 $renderer->setElementTemplate('{element}');
264 parent::accept($renderer);
34f9862e
MN
265
266 $html = $this->_wrap[0];
267 if ($this->_usedcreateelement) {
268 $html .= html_writer::tag('span', $renderer->toHtml(), array('class' => 'fdate_time_selector'));
269 } else {
270 $html .= $renderer->toHtml();
271 }
272 $html .= $this->_wrap[1];
273
274 return $html;
e9d39a32 275 }
276
6c1fd304
RT
277 /**
278 * Accepts a renderer
279 *
280 * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
281 * @param bool $required Whether a group is required
282 * @param string $error An error message associated with a group
283 */
2f00e1b2 284 function accept(&$renderer, $required = false, $error = null) {
e9d39a32 285 $renderer->renderElement($this, $required, $error);
286 }
287
e9d39a32 288 /**
289 * Output a timestamp. Give it the name of the group.
290 *
6c1fd304
RT
291 * @param array $submitValues values submitted.
292 * @param bool $assoc specifies if returned array is associative
e9d39a32 293 * @return array
294 */
2f00e1b2 295 function exportValue(&$submitValues, $assoc = false) {
0e630310 296 $valuearray = array();
297 foreach ($this->_elements as $element){
298 $thisexport = $element->exportValue($submitValues[$this->getName()], true);
11f260f4 299 if ($thisexport!=null){
0e630310 300 $valuearray += $thisexport;
301 }
302 }
46e648b6 303 if (count($valuearray)){
304 if($this->_options['optional']) {
11f260f4 305 // If checkbox is on, the value is zero, so go no further
25fe66b0 306 if(empty($valuearray['enabled'])) {
80180e0f 307 return $this->_prepareValue(0, $assoc);
46e648b6 308 }
309 }
2f00e1b2 310 // Get the calendar type used - see MDL-18375.
6eafa4dd 311 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2f00e1b2
MN
312 $gregoriandate = $calendartype->convert_to_gregorian($valuearray['year'],
313 $valuearray['month'],
314 $valuearray['day'],
315 $valuearray['hour'],
316 $valuearray['minute']);
80180e0f 317 $value = make_timestamp($gregoriandate['year'],
2f00e1b2
MN
318 $gregoriandate['month'],
319 $gregoriandate['day'],
320 $gregoriandate['hour'],
321 $gregoriandate['minute'],
322 0,
323 $this->_options['timezone'],
324 true);
46e648b6 325
80180e0f 326 return $this->_prepareValue($value, $assoc);
46e648b6 327 } else {
0e630310 328 return null;
329 }
e9d39a32 330 }
e9d39a32 331}