on-demand release 4.0dev+
[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,
cf34245d
HN
101 callable $filter = null,
102 ?string $searchvalue = null
84d865d6 103 ) {
84d865d6 104
c755cb35 105 $fromquery = function($field, $timefrom, $lastseenmethod, $afterevent, $withduration) {
258a5705
CB
106 if (!$timefrom) {
107 return false;
108 }
84d865d6 109
258a5705
CB
110 return $this->timefield_pagination_from(
111 $field,
112 $timefrom,
113 $afterevent ? $afterevent->get_times()->{$lastseenmethod}()->getTimestamp() : null,
c755cb35
JP
114 $afterevent ? $afterevent->get_id() : null,
115 $withduration
258a5705
CB
116 );
117 };
84d865d6 118
258a5705
CB
119 $toquery = function($field, $timeto, $lastseenmethod, $afterevent) {
120 if (!$timeto) {
121 return false;
5a0974c7 122 }
84d865d6 123
258a5705
CB
124 return $this->timefield_pagination_to(
125 $field,
126 $timeto,
127 $afterevent ? $afterevent->get_times()->{$lastseenmethod}()->getTimestamp() : null,
128 $afterevent ? $afterevent->get_id() : null
129 );
130 };
131
c755cb35 132 $timesortfromquery = $fromquery('timesort', $timesortfrom, 'get_sort_time', $timesortafterevent, $withduration);
258a5705 133 $timesorttoquery = $toquery('timesort', $timesortto, 'get_sort_time', $timesortafterevent);
c755cb35 134 $timestartfromquery = $fromquery('timestart', $timestartfrom, 'get_start_time', $timestartafterevent, $withduration);
258a5705
CB
135 $timestarttoquery = $toquery('timestart', $timestartto, 'get_start_time', $timestartafterevent);
136
137 if (($timesortto && !$timesorttoquery) || ($timestartto && !$timestarttoquery)) {
138 return [];
84d865d6
RW
139 }
140
cf34245d
HN
141 $searchquery = $this->generate_search_subquery($searchvalue);
142
258a5705
CB
143 $params = array_merge(
144 $type ? ['type' => $type] : [],
145 $timesortfromquery ? $timesortfromquery['params'] : [],
146 $timesorttoquery ? $timesorttoquery['params'] : [],
147 $timestartfromquery ? $timestartfromquery['params'] : [],
cf34245d
HN
148 $timestarttoquery ? $timestarttoquery['params'] : [],
149 $searchquery ? $searchquery['params'] : [],
258a5705
CB
150 );
151
152 $where = array_merge(
153 $type ? ['type = :type'] : [],
154 $timesortfromquery ? $timesortfromquery['where'] : [],
155 $timesorttoquery ? $timesorttoquery['where'] : [],
156 $timestartfromquery ? $timestartfromquery['where'] : [],
cf34245d
HN
157 $timestarttoquery ? $timestarttoquery['where'] : [],
158 $searchquery ? [$searchquery['where']] : [],
258a5705 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
e099259a
SL
191 if (!$limitnum) {
192 break;
193 } else {
194 $offset += $limitnum;
195 }
e62cd85f
RW
196 }
197
198 return $events;
199 }
200
258a5705
CB
201 public function get_action_events_by_timesort(
202 \stdClass $user,
203 $timesortfrom = null,
204 $timesortto = null,
205 event_interface $afterevent = null,
644ffbd3 206 $limitnum = 20,
cf34245d
HN
207 $limittononsuspendedevents = false,
208 ?string $searchvalue = null
258a5705 209 ) {
4bd022ed
CB
210 $courseids = array_map(function($course) {
211 return $course->id;
644ffbd3 212 }, enrol_get_all_users_courses($user->id, $limittononsuspendedevents));
4bd022ed
CB
213
214 $groupids = array_reduce($courseids, function($carry, $courseid) use ($user) {
215 $groupings = groups_get_user_groups($courseid, $user->id);
216 // Grouping 0 is all groups.
217 return array_merge($carry, $groupings[0]);
218 }, []);
219
d268c5ba
MG
220 // Always include the site events.
221 $courseids = $courseids ? array_merge($courseids, [SITEID]) : $courseids;
222
258a5705
CB
223 return $this->get_events(
224 null,
225 null,
226 $timesortfrom,
227 $timesortto,
228 null,
229 $afterevent,
230 $limitnum,
231 CALENDAR_EVENT_TYPE_ACTION,
232 [$user->id],
4bd022ed
CB
233 $groupids ? $groupids : null,
234 $courseids ? $courseids : null,
c4172077 235 null, // All categories.
8d4e0f29
CB
236 true,
237 true,
258a5705
CB
238 function ($event) {
239 return $event instanceof action_event_interface;
cf34245d
HN
240 },
241 $searchvalue
258a5705
CB
242 );
243 }
244
e62cd85f
RW
245 public function get_action_events_by_course(
246 \stdClass $user,
247 \stdClass $course,
8aa761b0
MN
248 $timesortfrom = null,
249 $timesortto = null,
e62cd85f 250 event_interface $afterevent = null,
cf34245d
HN
251 $limitnum = 20,
252 ?string $searchvalue = null
e62cd85f 253 ) {
4bd022ed 254 $groupings = groups_get_user_groups($course->id, $user->id);
258a5705
CB
255 return array_values(
256 $this->get_events(
257 null,
258 null,
259 $timesortfrom,
260 $timesortto,
261 null,
262 $afterevent,
263 $limitnum,
264 CALENDAR_EVENT_TYPE_ACTION,
265 [$user->id],
4bd022ed 266 $groupings[0] ? $groupings[0] : null,
258a5705 267 [$course->id],
0085b0ea 268 [],
8d4e0f29
CB
269 true,
270 true,
258a5705 271 function ($event) use ($course) {
47a71017 272 return $event instanceof action_event_interface && $event->get_course()->get('id') == $course->id;
cf34245d
HN
273 },
274 $searchvalue
258a5705
CB
275 )
276 );
277 }
e62cd85f 278
20592f5f
JP
279 /**
280 * Generates SQL subquery and parameters for 'from' pagination.
281 *
282 * @param string $field
283 * @param int $timefrom
284 * @param int|null $lastseentime
285 * @param int|null $lastseenid
286 * @param bool $withduration
287 * @return array
288 */
258a5705
CB
289 protected function timefield_pagination_from(
290 $field,
291 $timefrom,
292 $lastseentime = null,
293 $lastseenid = null,
294 $withduration = true
295 ) {
296 $where = '';
297 $params = [];
e62cd85f 298
258a5705
CB
299 if ($lastseentime && $lastseentime >= $timefrom) {
300 $where = '((timesort = :timefrom1 AND e.id > :timefromid) OR timesort > :timefrom2)';
301 if ($field === 'timestart') {
302 $where = '((timestart = :timefrom1 AND e.id > :timefromid) OR timestart > :timefrom2' .
303 ($withduration ? ' OR timestart + timeduration > :timefrom3' : '') . ')';
5a0974c7 304 }
258a5705
CB
305 $params['timefromid'] = $lastseenid;
306 $params['timefrom1'] = $lastseentime;
307 $params['timefrom2'] = $lastseentime;
308 $params['timefrom3'] = $lastseentime;
309 } else {
310 $where = 'timesort >= :timefrom';
311 if ($field === 'timestart') {
312 $where = '(timestart >= :timefrom' .
313 ($withduration ? ' OR timestart + timeduration > :timefrom2' : '') . ')';
5a0974c7 314 }
258a5705
CB
315
316 $params['timefrom'] = $timefrom;
317 $params['timefrom2'] = $timefrom;
e62cd85f
RW
318 }
319
258a5705
CB
320 return ['where' => [$where], 'params' => $params];
321 }
84d865d6 322
20592f5f
JP
323 /**
324 * Generates SQL subquery and parameters for 'to' pagination.
325 *
326 * @param string $field
327 * @param int $timeto
328 * @param int|null $lastseentime
329 * @param int|null $lastseenid
330 * @return array|bool
331 */
258a5705
CB
332 protected function timefield_pagination_to(
333 $field,
334 $timeto,
335 $lastseentime = null,
336 $lastseenid = null
337 ) {
338 $where = [];
339 $params = [];
84d865d6 340
258a5705
CB
341 if ($lastseentime && $lastseentime > $timeto) {
342 // The last seen event from this set is after the time sort range which
343 // means all events in this range have been seen, so we can just return
344 // early here.
345 return false;
346 } else if ($lastseentime && $lastseentime == $timeto) {
347 $where[] = '((timesort = :timeto1 AND e.id > :timetoid) OR timesort < :timeto2)';
348 if ($field === 'timestart') {
349 $where[] = '((timestart = :timeto1 AND e.id > :timetoid) OR timestart < :timeto2)';
350 }
351 $params['timetoid'] = $lastseenid;
352 $params['timeto1'] = $timeto;
353 $params['timeto2'] = $timeto;
354 } else {
355 $where[] = ($field === 'timestart' ? 'timestart' : 'timesort') . ' <= :timeto';
356 $params['timeto'] = $timeto;
84d865d6
RW
357 }
358
258a5705 359 return ['where' => $where, 'params' => $params];
84d865d6
RW
360 }
361
362 /**
363 * Create an event from a database record.
364 *
365 * @param \stdClass $record The database record
20592f5f 366 * @return event_interface|null
84d865d6 367 */
258a5705 368 protected function transform_from_database_record(\stdClass $record) {
84d865d6
RW
369 return $this->factory->create_instance($record);
370 }
258a5705 371
20592f5f
JP
372 /**
373 * Fetches records from DB.
374 *
375 * @param int $userid
376 * @param string $whereconditions
377 * @param array $whereparams
378 * @param string $ordersql
379 * @param int $offset
380 * @param int $limitnum
381 * @return array
382 */
258a5705
CB
383 protected function get_from_db(
384 $userid,
385 $whereconditions,
386 $whereparams,
387 $ordersql,
388 $offset,
389 $limitnum
390 ) {
391 return array_values(
392 $this->retrievalstrategy->get_raw_events(
393 [$userid],
394 null,
395 null,
0085b0ea 396 null,
258a5705
CB
397 $whereconditions,
398 $whereparams,
399 $ordersql,
400 $offset,
401 $limitnum
402 )
403 );
404 }
cf34245d
HN
405
406 /**
407 * Generates SQL subquery and parameters for event searching.
408 *
409 * @param string|null $searchvalue Search value.
410 * @return array|null
411 */
412 protected function generate_search_subquery(?string $searchvalue): ?array {
413 global $DB;
414 if (!$searchvalue) {
415 return null;
416 }
417
418 // Course searching.
419 $whereconditions[] = $DB->sql_like('c.fullname', ':cfullname', false);
420 $params['cfullname'] = '%' . $DB->sql_like_escape($searchvalue) . '%';
421
422 // Activity name searching.
423 $whereconditions[] = $DB->sql_like('e.name', ':eventname', false);
424 $params['eventname'] = '%' . $DB->sql_like_escape($searchvalue) . '%';
425
426 // Activity type searching.
427 $whereconditions[] = $DB->sql_like('e.modulename', ':modulename', false);
428 $params['modulename'] = '%' . $DB->sql_like_escape($searchvalue) . '%';
429
430 $whereclause = '(' . implode(' OR ', $whereconditions) . ')';
431
432 return ['where' => $whereclause, 'params' => $params];
433 }
84d865d6 434}