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