MDL-64063 core_calendar: events by time considers enrolment status.
[moodle.git] / calendar / classes / local / event / data_access / event_vault.php
CommitLineData
84d865d6
RW
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 * Event vault class
19 *
20 * @package core_calendar
21 * @copyright 2017 Ryan Wyllie <ryan@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace core_calendar\local\event\data_access;
26
20592f5f
JP
27defined('MOODLE_INTERNAL') || die();
28
42e76c3f
CB
29use core_calendar\local\event\entities\action_event_interface;
30use core_calendar\local\event\entities\event_interface;
84d865d6 31use core_calendar\local\event\exceptions\limit_invalid_parameter_exception;
42e76c3f
CB
32use core_calendar\local\event\factories\action_factory_interface;
33use core_calendar\local\event\factories\event_factory_interface;
34use core_calendar\local\event\strategies\raw_event_retrieval_strategy_interface;
84d865d6
RW
35
36/**
20592f5f
JP
37 * Event vault class.
38 *
84d865d6
RW
39 * This class will handle interacting with the database layer to retrieve
40 * the records. This is required to house the complex logic required for
41 * pagination because it's not a one-to-one mapping between database records
42 * and users.
43 *
44 * This is a repository. It's called a vault to reduce confusion because
45 * Moodle has already taken the name repository. Vault is cooler anyway.
46 *
47 * @copyright 2017 Ryan Wyllie <ryan@moodle.com>
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 */
50class event_vault implements event_vault_interface {
51
5a0974c7
RW
52 /**
53 * @var event_factory_interface $factory Factory for creating events.
54 */
258a5705
CB
55 protected $factory;
56
57 /**
58 * @var raw_event_retrieval_strategy_interface $retrievalstrategy Strategy for getting events from the DB.
59 */
60 protected $retrievalstrategy;
84d865d6
RW
61
62 /**
63 * Create an event vault.
64 *
65 * @param event_factory_interface $factory An event factory
20592f5f 66 * @param raw_event_retrieval_strategy_interface $retrievalstrategy
84d865d6 67 */
258a5705
CB
68 public function __construct(
69 event_factory_interface $factory,
70 raw_event_retrieval_strategy_interface $retrievalstrategy
71 ) {
84d865d6 72 $this->factory = $factory;
258a5705 73 $this->retrievalstrategy = $retrievalstrategy;
84d865d6
RW
74 }
75
5e6e3bab 76 public function get_event_by_id($id) {
84d865d6
RW
77 global $DB;
78
79 if ($record = $DB->get_record('event', ['id' => $id])) {
80 return $this->transform_from_database_record($record);
81 } else {
82 return false;
83 }
84 }
85
258a5705
CB
86 public function get_events(
87 $timestartfrom = null,
88 $timestartto = null,
5e6e3bab
MN
89 $timesortfrom = null,
90 $timesortto = null,
258a5705
CB
91 event_interface $timestartafterevent = null,
92 event_interface $timesortafterevent = null,
93 $limitnum = 20,
94 $type = null,
95 array $usersfilter = null,
96 array $groupsfilter = null,
97 array $coursesfilter = null,
0085b0ea 98 array $categoriesfilter = null,
258a5705
CB
99 $withduration = true,
100 $ignorehidden = true,
101 callable $filter = null
84d865d6 102 ) {
349d3796
AN
103 if ($limitnum < 1 || $limitnum > 200) {
104 throw new limit_invalid_parameter_exception("Limit must be between 1 and 200 (inclusive)");
84d865d6
RW
105 }
106
c755cb35 107 $fromquery = function($field, $timefrom, $lastseenmethod, $afterevent, $withduration) {
258a5705
CB
108 if (!$timefrom) {
109 return false;
110 }
84d865d6 111
258a5705
CB
112 return $this->timefield_pagination_from(
113 $field,
114 $timefrom,
115 $afterevent ? $afterevent->get_times()->{$lastseenmethod}()->getTimestamp() : null,
c755cb35
JP
116 $afterevent ? $afterevent->get_id() : null,
117 $withduration
258a5705
CB
118 );
119 };
84d865d6 120
258a5705
CB
121 $toquery = function($field, $timeto, $lastseenmethod, $afterevent) {
122 if (!$timeto) {
123 return false;
5a0974c7 124 }
84d865d6 125
258a5705
CB
126 return $this->timefield_pagination_to(
127 $field,
128 $timeto,
129 $afterevent ? $afterevent->get_times()->{$lastseenmethod}()->getTimestamp() : null,
130 $afterevent ? $afterevent->get_id() : null
131 );
132 };
133
c755cb35 134 $timesortfromquery = $fromquery('timesort', $timesortfrom, 'get_sort_time', $timesortafterevent, $withduration);
258a5705 135 $timesorttoquery = $toquery('timesort', $timesortto, 'get_sort_time', $timesortafterevent);
c755cb35 136 $timestartfromquery = $fromquery('timestart', $timestartfrom, 'get_start_time', $timestartafterevent, $withduration);
258a5705
CB
137 $timestarttoquery = $toquery('timestart', $timestartto, 'get_start_time', $timestartafterevent);
138
139 if (($timesortto && !$timesorttoquery) || ($timestartto && !$timestarttoquery)) {
140 return [];
84d865d6
RW
141 }
142
258a5705
CB
143 $params = array_merge(
144 $type ? ['type' => $type] : [],
145 $timesortfromquery ? $timesortfromquery['params'] : [],
146 $timesorttoquery ? $timesorttoquery['params'] : [],
147 $timestartfromquery ? $timestartfromquery['params'] : [],
148 $timestarttoquery ? $timestarttoquery['params'] : []
149 );
150
151 $where = array_merge(
152 $type ? ['type = :type'] : [],
153 $timesortfromquery ? $timesortfromquery['where'] : [],
154 $timesorttoquery ? $timesorttoquery['where'] : [],
155 $timestartfromquery ? $timestartfromquery['where'] : [],
156 $timestarttoquery ? $timestarttoquery['where'] : []
157 );
84d865d6
RW
158
159 $offset = 0;
160 $events = [];
258a5705
CB
161
162 while ($records = array_values($this->retrievalstrategy->get_raw_events(
163 $usersfilter,
164 $groupsfilter,
165 $coursesfilter,
0085b0ea 166 $categoriesfilter,
258a5705
CB
167 $where,
168 $params,
919b5c95 169 "COALESCE(e.timesort, e.timestart) ASC, e.id ASC",
258a5705
CB
170 $offset,
171 $limitnum,
258a5705
CB
172 $ignorehidden
173 ))) {
e62cd85f
RW
174 foreach ($records as $record) {
175 if ($event = $this->transform_from_database_record($record)) {
258a5705
CB
176 $filtertest = $filter ? $filter($event) : true;
177
178 if ($event && $filtertest) {
e62cd85f
RW
179 $events[] = $event;
180 }
181
182 if (count($events) == $limitnum) {
183 // We've got all of the events so break both loops.
184 break 2;
185 }
186 }
187 }
188
189 $offset += $limitnum;
190 }
191
192 return $events;
193 }
194
258a5705
CB
195 public function get_action_events_by_timesort(
196 \stdClass $user,
197 $timesortfrom = null,
198 $timesortto = null,
199 event_interface $afterevent = null,
644ffbd3
AG
200 $limitnum = 20,
201 $limittononsuspendedevents = false
258a5705 202 ) {
4bd022ed
CB
203 $courseids = array_map(function($course) {
204 return $course->id;
644ffbd3 205 }, enrol_get_all_users_courses($user->id, $limittononsuspendedevents));
4bd022ed
CB
206
207 $groupids = array_reduce($courseids, function($carry, $courseid) use ($user) {
208 $groupings = groups_get_user_groups($courseid, $user->id);
209 // Grouping 0 is all groups.
210 return array_merge($carry, $groupings[0]);
211 }, []);
212
258a5705
CB
213 return $this->get_events(
214 null,
215 null,
216 $timesortfrom,
217 $timesortto,
218 null,
219 $afterevent,
220 $limitnum,
221 CALENDAR_EVENT_TYPE_ACTION,
222 [$user->id],
4bd022ed
CB
223 $groupids ? $groupids : null,
224 $courseids ? $courseids : null,
c4172077 225 null, // All categories.
8d4e0f29
CB
226 true,
227 true,
258a5705
CB
228 function ($event) {
229 return $event instanceof action_event_interface;
230 }
231 );
232 }
233
e62cd85f
RW
234 public function get_action_events_by_course(
235 \stdClass $user,
236 \stdClass $course,
8aa761b0
MN
237 $timesortfrom = null,
238 $timesortto = null,
e62cd85f 239 event_interface $afterevent = null,
8aa761b0 240 $limitnum = 20
e62cd85f 241 ) {
4bd022ed 242 $groupings = groups_get_user_groups($course->id, $user->id);
258a5705
CB
243 return array_values(
244 $this->get_events(
245 null,
246 null,
247 $timesortfrom,
248 $timesortto,
249 null,
250 $afterevent,
251 $limitnum,
252 CALENDAR_EVENT_TYPE_ACTION,
253 [$user->id],
4bd022ed 254 $groupings[0] ? $groupings[0] : null,
258a5705 255 [$course->id],
0085b0ea 256 [],
8d4e0f29
CB
257 true,
258 true,
258a5705 259 function ($event) use ($course) {
47a71017 260 return $event instanceof action_event_interface && $event->get_course()->get('id') == $course->id;
258a5705
CB
261 }
262 )
263 );
264 }
e62cd85f 265
20592f5f
JP
266 /**
267 * Generates SQL subquery and parameters for 'from' pagination.
268 *
269 * @param string $field
270 * @param int $timefrom
271 * @param int|null $lastseentime
272 * @param int|null $lastseenid
273 * @param bool $withduration
274 * @return array
275 */
258a5705
CB
276 protected function timefield_pagination_from(
277 $field,
278 $timefrom,
279 $lastseentime = null,
280 $lastseenid = null,
281 $withduration = true
282 ) {
283 $where = '';
284 $params = [];
e62cd85f 285
258a5705
CB
286 if ($lastseentime && $lastseentime >= $timefrom) {
287 $where = '((timesort = :timefrom1 AND e.id > :timefromid) OR timesort > :timefrom2)';
288 if ($field === 'timestart') {
289 $where = '((timestart = :timefrom1 AND e.id > :timefromid) OR timestart > :timefrom2' .
290 ($withduration ? ' OR timestart + timeduration > :timefrom3' : '') . ')';
5a0974c7 291 }
258a5705
CB
292 $params['timefromid'] = $lastseenid;
293 $params['timefrom1'] = $lastseentime;
294 $params['timefrom2'] = $lastseentime;
295 $params['timefrom3'] = $lastseentime;
296 } else {
297 $where = 'timesort >= :timefrom';
298 if ($field === 'timestart') {
299 $where = '(timestart >= :timefrom' .
300 ($withduration ? ' OR timestart + timeduration > :timefrom2' : '') . ')';
5a0974c7 301 }
258a5705
CB
302
303 $params['timefrom'] = $timefrom;
304 $params['timefrom2'] = $timefrom;
e62cd85f
RW
305 }
306
258a5705
CB
307 return ['where' => [$where], 'params' => $params];
308 }
84d865d6 309
20592f5f
JP
310 /**
311 * Generates SQL subquery and parameters for 'to' pagination.
312 *
313 * @param string $field
314 * @param int $timeto
315 * @param int|null $lastseentime
316 * @param int|null $lastseenid
317 * @return array|bool
318 */
258a5705
CB
319 protected function timefield_pagination_to(
320 $field,
321 $timeto,
322 $lastseentime = null,
323 $lastseenid = null
324 ) {
325 $where = [];
326 $params = [];
84d865d6 327
258a5705
CB
328 if ($lastseentime && $lastseentime > $timeto) {
329 // The last seen event from this set is after the time sort range which
330 // means all events in this range have been seen, so we can just return
331 // early here.
332 return false;
333 } else if ($lastseentime && $lastseentime == $timeto) {
334 $where[] = '((timesort = :timeto1 AND e.id > :timetoid) OR timesort < :timeto2)';
335 if ($field === 'timestart') {
336 $where[] = '((timestart = :timeto1 AND e.id > :timetoid) OR timestart < :timeto2)';
337 }
338 $params['timetoid'] = $lastseenid;
339 $params['timeto1'] = $timeto;
340 $params['timeto2'] = $timeto;
341 } else {
342 $where[] = ($field === 'timestart' ? 'timestart' : 'timesort') . ' <= :timeto';
343 $params['timeto'] = $timeto;
84d865d6
RW
344 }
345
258a5705 346 return ['where' => $where, 'params' => $params];
84d865d6
RW
347 }
348
349 /**
350 * Create an event from a database record.
351 *
352 * @param \stdClass $record The database record
20592f5f 353 * @return event_interface|null
84d865d6 354 */
258a5705 355 protected function transform_from_database_record(\stdClass $record) {
84d865d6
RW
356 return $this->factory->create_instance($record);
357 }
258a5705 358
20592f5f
JP
359 /**
360 * Fetches records from DB.
361 *
362 * @param int $userid
363 * @param string $whereconditions
364 * @param array $whereparams
365 * @param string $ordersql
366 * @param int $offset
367 * @param int $limitnum
368 * @return array
369 */
258a5705
CB
370 protected function get_from_db(
371 $userid,
372 $whereconditions,
373 $whereparams,
374 $ordersql,
375 $offset,
376 $limitnum
377 ) {
378 return array_values(
379 $this->retrievalstrategy->get_raw_events(
380 [$userid],
381 null,
382 null,
0085b0ea 383 null,
258a5705
CB
384 $whereconditions,
385 $whereparams,
386 $ordersql,
387 $offset,
388 $limitnum
389 )
390 );
391 }
84d865d6 392}