Proyectos de Subversion Moodle

Rev

| 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
declare(strict_types=1);
18
 
19
namespace core_reportbuilder\local\filters;
20
 
21
use DateTimeImmutable;
22
use lang_string;
23
use MoodleQuickForm;
24
use core_reportbuilder\local\helpers\database;
25
 
26
/**
27
 * Date report filter
28
 *
29
 * This filter accepts a unix timestamp to perform date filtering on
30
 *
31
 * @package     core_reportbuilder
32
 * @copyright   2021 Paul Holden <paulh@moodle.com>
33
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34
 */
35
class date extends base {
36
 
37
    /** @var int Any value */
38
    public const DATE_ANY = 0;
39
 
40
    /** @var int Non-empty (positive) value */
41
    public const DATE_NOT_EMPTY = 1;
42
 
43
    /** @var int Empty (zero) value */
44
    public const DATE_EMPTY = 2;
45
 
46
    /** @var int Date within defined range */
47
    public const DATE_RANGE = 3;
48
 
49
    /** @var int Date in the last [X relative date unit(s)] */
50
    public const DATE_LAST = 4;
51
 
52
    /** @var int Date in the previous [X relative date unit(s)] Kept for backwards compatibility */
53
    public const DATE_PREVIOUS = self::DATE_LAST;
54
 
55
    /** @var int Date in current [relative date unit] */
56
    public const DATE_CURRENT = 5;
57
 
58
    /** @var int Date in the next [X relative date unit(s)] */
59
    public const DATE_NEXT = 6;
60
 
61
    /** @var int Date in the past */
62
    public const DATE_PAST = 7;
63
 
64
    /** @var int Date in the future */
65
    public const DATE_FUTURE = 8;
66
 
67
    /** @var int Date before [X relative date unit(s)] */
68
    public const DATE_BEFORE = 9;
69
 
70
    /** @var int Date after [X relative date unit(s)] */
71
    public const DATE_AFTER = 10;
72
 
73
    /** @var int Relative date unit for an hour */
74
    public const DATE_UNIT_HOUR = 0;
75
 
76
    /** @var int Relative date unit for a day */
77
    public const DATE_UNIT_DAY = 1;
78
 
79
    /** @var int Relative date unit for a week */
80
    public const DATE_UNIT_WEEK = 2;
81
 
82
    /** @var int Relative date unit for a month */
83
    public const DATE_UNIT_MONTH = 3;
84
 
85
    /** @var int Relative date unit for a month */
86
    public const DATE_UNIT_YEAR = 4;
87
 
88
    /**
89
     * Return an array of operators available for this filter
90
     *
91
     * @return lang_string[]
92
     */
93
    private function get_operators(): array {
94
        $operators = [
95
            self::DATE_ANY => new lang_string('filterisanyvalue', 'core_reportbuilder'),
96
            self::DATE_NOT_EMPTY => new lang_string('filterisnotempty', 'core_reportbuilder'),
97
            self::DATE_EMPTY => new lang_string('filterisempty', 'core_reportbuilder'),
98
            self::DATE_RANGE => new lang_string('filterrange', 'core_reportbuilder'),
99
            self::DATE_BEFORE => new lang_string('filterdatebefore', 'core_reportbuilder'),
100
            self::DATE_AFTER => new lang_string('filterdateafter', 'core_reportbuilder'),
101
            self::DATE_LAST => new lang_string('filterdatelast', 'core_reportbuilder'),
102
            self::DATE_CURRENT => new lang_string('filterdatecurrent', 'core_reportbuilder'),
103
            self::DATE_NEXT => new lang_string('filterdatenext', 'core_reportbuilder'),
104
            self::DATE_PAST => new lang_string('filterdatepast', 'core_reportbuilder'),
105
            self::DATE_FUTURE => new lang_string('filterdatefuture', 'core_reportbuilder'),
106
        ];
107
 
108
        return $this->filter->restrict_limited_operators($operators);
109
    }
110
 
111
    /**
112
     * Setup form
113
     *
114
     * @param MoodleQuickForm $mform
115
     */
116
    public function setup_form(MoodleQuickForm $mform): void {
117
        // Operator selector.
118
        $operatorlabel = get_string('filterfieldoperator', 'core_reportbuilder', $this->get_header());
119
        $typesnounit = [self::DATE_ANY, self::DATE_NOT_EMPTY, self::DATE_EMPTY, self::DATE_RANGE,
120
            self::DATE_PAST, self::DATE_FUTURE];
121
 
122
        $elements[] = $mform->createElement('select', "{$this->name}_operator", $operatorlabel, $this->get_operators());
123
        $mform->setType("{$this->name}_operator", PARAM_INT);
124
        $mform->setDefault("{$this->name}_operator", self::DATE_ANY);
125
 
126
        // Value selector for last and next operators.
127
        $valuelabel = get_string('filterfieldvalue', 'core_reportbuilder', $this->get_header());
128
 
129
        $elements[] = $mform->createElement('text', "{$this->name}_value", $valuelabel, ['size' => 3]);
130
        $mform->setType("{$this->name}_value", PARAM_INT);
131
        $mform->setDefault("{$this->name}_value", 1);
132
        $mform->hideIf("{$this->name}_value", "{$this->name}_operator", 'in', array_merge($typesnounit, [self::DATE_CURRENT]));
133
 
134
        // Unit selector for last and next operators.
135
        $unitlabel = get_string('filterfieldunit', 'core_reportbuilder', $this->get_header());
136
        $units = [
137
            self::DATE_UNIT_HOUR => get_string('filterdatehours', 'core_reportbuilder'),
138
            self::DATE_UNIT_DAY => get_string('filterdatedays', 'core_reportbuilder'),
139
            self::DATE_UNIT_WEEK => get_string('filterdateweeks', 'core_reportbuilder'),
140
            self::DATE_UNIT_MONTH => get_string('filterdatemonths', 'core_reportbuilder'),
141
            self::DATE_UNIT_YEAR => get_string('filterdateyears', 'core_reportbuilder'),
142
        ];
143
 
144
        $elements[] = $mform->createElement('select', "{$this->name}_unit", $unitlabel, $units);
145
        $mform->setType("{$this->name}_unit", PARAM_INT);
146
        $mform->setDefault("{$this->name}_unit", self::DATE_UNIT_DAY);
147
        $mform->hideIf("{$this->name}_unit", "{$this->name}_operator", 'in', $typesnounit);
148
 
149
        // Add operator/value/unit group.
150
        $mform->addGroup($elements, "{$this->name}_group", $this->get_header(), '', false)
151
            ->setHiddenLabel(true);
152
 
153
        // Date selectors for range operator.
154
        $mform->addElement('date_selector', "{$this->name}_from", get_string('filterdatefrom', 'core_reportbuilder'),
155
            ['optional' => true]);
156
        $mform->setType("{$this->name}_from", PARAM_INT);
157
        $mform->setDefault("{$this->name}_from", 0);
158
        $mform->hideIf("{$this->name}_from", "{$this->name}_operator", 'neq', self::DATE_RANGE);
159
 
160
        $mform->addElement('date_selector', "{$this->name}_to", get_string('filterdateto', 'core_reportbuilder'),
161
            ['optional' => true]);
162
        $mform->setType("{$this->name}_to", PARAM_INT);
163
        $mform->setDefault("{$this->name}_to", 0);
164
        $mform->hideIf("{$this->name}_to", "{$this->name}_operator", 'neq', self::DATE_RANGE);
165
    }
166
 
167
    /**
168
     * Return filter SQL
169
     *
170
     * @param array $values
171
     * @return array
172
     */
173
    public function get_sql_filter(array $values): array {
174
        $fieldsql = $this->filter->get_field_sql();
175
        $params = $this->filter->get_field_params();
176
 
177
        $operator = (int) ($values["{$this->name}_operator"] ?? self::DATE_ANY);
178
        $dateunitvalue = (int) ($values["{$this->name}_value"] ?? 1);
179
        $dateunit = (int) ($values["{$this->name}_unit"] ?? self::DATE_UNIT_DAY);
180
 
181
        switch ($operator) {
182
            case self::DATE_NOT_EMPTY:
183
                $sql = "COALESCE({$fieldsql}, 0) <> 0";
184
                break;
185
            case self::DATE_EMPTY:
186
                $sql = "COALESCE({$fieldsql}, 0) = 0";
187
                break;
188
            case self::DATE_RANGE:
189
                $sql = '';
190
 
191
                $datefrom = (int)($values["{$this->name}_from"] ?? 0);
192
                $dateto = (int)($values["{$this->name}_to"] ?? 0);
193
 
194
                [$paramdatefrom, $paramdateto] = database::generate_param_names(2);
195
 
196
                if ($datefrom > 0 && $dateto > 0) {
197
                    $sql = "{$fieldsql} BETWEEN :{$paramdatefrom} AND :{$paramdateto}";
198
                    $params[$paramdatefrom] = $datefrom;
199
                    $params[$paramdateto] = $dateto;
200
                } else if ($datefrom > 0) {
201
                    $sql = "{$fieldsql} >= :{$paramdatefrom}";
202
                    $params[$paramdatefrom] = $datefrom;
203
                } else if ($dateto > 0) {
204
                    $sql = "{$fieldsql} < :{$paramdateto}";
205
                    $params[$paramdateto] = $dateto;
206
                }
207
 
208
                break;
209
            case self::DATE_BEFORE:
210
                $param = database::generate_param_name();
211
 
212
                // We can use the start date of the "Last" operator as the end date here.
213
                $sql = "{$fieldsql} < :{$param}";
214
                $params[$param] = self::get_relative_timeframe(self::DATE_LAST, $dateunitvalue, $dateunit)[0];
215
                break;
216
            case self::DATE_AFTER:
217
                $param = database::generate_param_name();
218
 
219
                // We can use the end date of the "Next" operator as the start date here.
220
                $sql = "{$fieldsql} > :{$param}";
221
                $params[$param] = self::get_relative_timeframe(self::DATE_NEXT, $dateunitvalue, $dateunit)[1];
222
                break;
223
            // Relative helper method can handle these three cases.
224
            case self::DATE_LAST:
225
            case self::DATE_CURRENT:
226
            case self::DATE_NEXT:
227
 
228
                // Last and next operators require a unit value greater than zero.
229
                if ($operator !== self::DATE_CURRENT && $dateunitvalue === 0) {
230
                    return ['', []];
231
                }
232
 
233
                // Generate parameters and SQL clause for the relative date comparison.
234
                [$paramdatefrom, $paramdateto] = database::generate_param_names(2);
235
                $sql = "{$fieldsql} BETWEEN :{$paramdatefrom} AND :{$paramdateto}";
236
 
237
                [
238
                    $params[$paramdatefrom],
239
                    $params[$paramdateto],
240
                ] = self::get_relative_timeframe($operator, $dateunitvalue, $dateunit);
241
 
242
                break;
243
            case self::DATE_PAST:
244
                $param = database::generate_param_name();
245
                $sql = "{$fieldsql} < :{$param}";
246
                $params[$param] = time();
247
                break;
248
            case self::DATE_FUTURE:
249
                $param = database::generate_param_name();
250
                $sql = "{$fieldsql} > :{$param}";
251
                $params[$param] = time();
252
                break;
253
            default:
254
                // Invalid or inactive filter.
255
                return ['', []];
256
        }
257
 
258
        return [$sql, $params];
259
    }
260
 
261
    /**
262
     * Return start and end time of given relative date period
263
     *
264
     * @param int $operator One of the ::DATE_LAST/CURRENT/NEXT constants
265
     * @param int $dateunitvalue Unit multiplier of the date unit
266
     * @param int $dateunit One of the ::DATE_UNIT_* constants
267
     * @return int[] Timestamps representing the start/end of timeframe
268
     */
269
    private static function get_relative_timeframe(int $operator, int $dateunitvalue, int $dateunit): array {
270
        // Initialise start/end time to now.
271
        $datestart = $dateend = new DateTimeImmutable();
272
 
273
        switch ($dateunit) {
274
            case self::DATE_UNIT_HOUR:
275
                if ($operator === self::DATE_CURRENT) {
276
                    $hour = (int) $datestart->format('G');
277
                    $datestart = $datestart->setTime($hour, 0);
278
                    $dateend = $dateend->setTime($hour, 59, 59);
279
                } else if ($operator === self::DATE_LAST) {
280
                    $datestart = $datestart->modify("-{$dateunitvalue} hour");
281
                } else if ($operator === self::DATE_NEXT) {
282
                    $dateend = $dateend->modify("+{$dateunitvalue} hour");
283
                }
284
                break;
285
            case self::DATE_UNIT_DAY:
286
                if ($operator === self::DATE_CURRENT) {
287
                    $datestart = $datestart->setTime(0, 0);
288
                    $dateend = $dateend->setTime(23, 59, 59);
289
                } else if ($operator === self::DATE_LAST) {
290
                    $datestart = $datestart->modify("-{$dateunitvalue} day");
291
                } else if ($operator === self::DATE_NEXT) {
292
                    $dateend = $dateend->modify("+{$dateunitvalue} day");
293
                }
294
 
295
                break;
296
            case self::DATE_UNIT_WEEK:
297
                if ($operator === self::DATE_CURRENT) {
298
                    // The first day of the week is determined by site calendar configuration/preferences.
299
                    $startweekday = \core_calendar\type_factory::get_calendar_instance()->get_starting_weekday();
300
                    $weekdays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
301
 
302
                    // If calculated start of week is after today (today is Tues/start of week is Weds), move back a week.
303
                    $datestartnow = $datestart->getTimestamp();
304
                    $datestart = $datestart->modify($weekdays[$startweekday] . ' this week')->setTime(0, 0);
305
                    if ($datestart->getTimestamp() > $datestartnow) {
306
                        $datestart = $datestart->modify('-1 week');
307
                    }
308
 
309
                    $dateend = $datestart->modify('+6 day')->setTime(23, 59, 59);
310
                } else if ($operator === self::DATE_LAST) {
311
                    $datestart = $datestart->modify("-{$dateunitvalue} week");
312
                } else if ($operator === self::DATE_NEXT) {
313
                    $dateend = $dateend->modify("+{$dateunitvalue} week");
314
                }
315
 
316
                break;
317
            case self::DATE_UNIT_MONTH:
318
                if ($operator === self::DATE_CURRENT) {
319
                    $datestart = $datestart->modify('first day of this month')->setTime(0, 0);
320
                    $dateend = $dateend->modify('last day of this month')->setTime(23, 59, 59);
321
                } else if ($operator === self::DATE_LAST) {
322
                    $datestart = $datestart->modify("-{$dateunitvalue} month");
323
                } else if ($operator === self::DATE_NEXT) {
324
                    $dateend = $dateend->modify("+{$dateunitvalue} month");
325
                }
326
 
327
                break;
328
            case self::DATE_UNIT_YEAR:
329
                if ($operator === self::DATE_CURRENT) {
330
                    $datestart = $datestart->modify('first day of january this year')->setTime(0, 0);
331
                    $dateend = $dateend->modify('last day of december this year')->setTime(23, 59, 59);
332
                } else if ($operator === self::DATE_LAST) {
333
                    $datestart = $datestart->modify("-{$dateunitvalue} year");
334
                } else if ($operator === self::DATE_NEXT) {
335
                    $dateend = $dateend->modify("+{$dateunitvalue} year");
336
                }
337
 
338
                break;
339
        }
340
 
341
        return [
342
            $datestart->getTimestamp(),
343
            $dateend->getTimestamp(),
344
        ];
345
    }
346
 
347
    /**
348
     * Return sample filter values
349
     *
350
     * @return array
351
     */
352
    public function get_sample_values(): array {
353
        return [
354
            "{$this->name}_operator" => self::DATE_CURRENT,
355
            "{$this->name}_unit" => self::DATE_UNIT_WEEK,
356
        ];
357
    }
358
}