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