Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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