MDL-58578 mod_assign: Correctly update user override priority
[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,
98 $withduration = true,
99 $ignorehidden = true,
100 callable $filter = null
84d865d6 101 ) {
84d865d6
RW
102 if ($limitnum < 1 || $limitnum > 50) {
103 throw new limit_invalid_parameter_exception("Limit must be between 1 and 50 (inclusive)");
104 }
105
c755cb35 106 $fromquery = function($field, $timefrom, $lastseenmethod, $afterevent, $withduration) {
258a5705
CB
107 if (!$timefrom) {
108 return false;
109 }
84d865d6 110
258a5705
CB
111 return $this->timefield_pagination_from(
112 $field,
113 $timefrom,
114 $afterevent ? $afterevent->get_times()->{$lastseenmethod}()->getTimestamp() : null,
c755cb35
JP
115 $afterevent ? $afterevent->get_id() : null,
116 $withduration
258a5705
CB
117 );
118 };
84d865d6 119
258a5705
CB
120 $toquery = function($field, $timeto, $lastseenmethod, $afterevent) {
121 if (!$timeto) {
122 return false;
5a0974c7 123 }
84d865d6 124
258a5705
CB
125 return $this->timefield_pagination_to(
126 $field,
127 $timeto,
128 $afterevent ? $afterevent->get_times()->{$lastseenmethod}()->getTimestamp() : null,
129 $afterevent ? $afterevent->get_id() : null
130 );
131 };
132
c755cb35 133 $timesortfromquery = $fromquery('timesort', $timesortfrom, 'get_sort_time', $timesortafterevent, $withduration);
258a5705 134 $timesorttoquery = $toquery('timesort', $timesortto, 'get_sort_time', $timesortafterevent);
c755cb35 135 $timestartfromquery = $fromquery('timestart', $timestartfrom, 'get_start_time', $timestartafterevent, $withduration);
258a5705
CB
136 $timestarttoquery = $toquery('timestart', $timestartto, 'get_start_time', $timestartafterevent);
137
138 if (($timesortto && !$timesorttoquery) || ($timestartto && !$timestarttoquery)) {
139 return [];
84d865d6
RW
140 }
141
258a5705
CB
142 $params = array_merge(
143 $type ? ['type' => $type] : [],
144 $timesortfromquery ? $timesortfromquery['params'] : [],
145 $timesorttoquery ? $timesorttoquery['params'] : [],
146 $timestartfromquery ? $timestartfromquery['params'] : [],
147 $timestarttoquery ? $timestarttoquery['params'] : []
148 );
149
150 $where = array_merge(
151 $type ? ['type = :type'] : [],
152 $timesortfromquery ? $timesortfromquery['where'] : [],
153 $timesorttoquery ? $timesorttoquery['where'] : [],
154 $timestartfromquery ? $timestartfromquery['where'] : [],
155 $timestarttoquery ? $timestarttoquery['where'] : []
156 );
84d865d6
RW
157
158 $offset = 0;
159 $events = [];
258a5705
CB
160
161 while ($records = array_values($this->retrievalstrategy->get_raw_events(
162 $usersfilter,
163 $groupsfilter,
164 $coursesfilter,
165 $where,
166 $params,
5c85bfe1 167 "e.timesort ASC, e.id ASC",
258a5705
CB
168 $offset,
169 $limitnum,
258a5705
CB
170 $ignorehidden
171 ))) {
e62cd85f
RW
172 foreach ($records as $record) {
173 if ($event = $this->transform_from_database_record($record)) {
258a5705
CB
174 $filtertest = $filter ? $filter($event) : true;
175
176 if ($event && $filtertest) {
e62cd85f
RW
177 $events[] = $event;
178 }
179
180 if (count($events) == $limitnum) {
181 // We've got all of the events so break both loops.
182 break 2;
183 }
184 }
185 }
186
187 $offset += $limitnum;
188 }
189
190 return $events;
191 }
192
258a5705
CB
193 public function get_action_events_by_timesort(
194 \stdClass $user,
195 $timesortfrom = null,
196 $timesortto = null,
197 event_interface $afterevent = null,
198 $limitnum = 20
199 ) {
200 return $this->get_events(
201 null,
202 null,
203 $timesortfrom,
204 $timesortto,
205 null,
206 $afterevent,
207 $limitnum,
208 CALENDAR_EVENT_TYPE_ACTION,
209 [$user->id],
210 null,
211 null,
8d4e0f29
CB
212 true,
213 true,
258a5705
CB
214 function ($event) {
215 return $event instanceof action_event_interface;
216 }
217 );
218 }
219
e62cd85f
RW
220 public function get_action_events_by_course(
221 \stdClass $user,
222 \stdClass $course,
8aa761b0
MN
223 $timesortfrom = null,
224 $timesortto = null,
e62cd85f 225 event_interface $afterevent = null,
8aa761b0 226 $limitnum = 20
e62cd85f 227 ) {
258a5705
CB
228 return array_values(
229 $this->get_events(
230 null,
231 null,
232 $timesortfrom,
233 $timesortto,
234 null,
235 $afterevent,
236 $limitnum,
237 CALENDAR_EVENT_TYPE_ACTION,
238 [$user->id],
239 null,
240 [$course->id],
8d4e0f29
CB
241 true,
242 true,
258a5705
CB
243 function ($event) use ($course) {
244 return $event instanceof action_event_interface && $event->get_course()->get_id() == $course->id;
245 }
246 )
247 );
248 }
e62cd85f 249
20592f5f
JP
250 /**
251 * Generates SQL subquery and parameters for 'from' pagination.
252 *
253 * @param string $field
254 * @param int $timefrom
255 * @param int|null $lastseentime
256 * @param int|null $lastseenid
257 * @param bool $withduration
258 * @return array
259 */
258a5705
CB
260 protected function timefield_pagination_from(
261 $field,
262 $timefrom,
263 $lastseentime = null,
264 $lastseenid = null,
265 $withduration = true
266 ) {
267 $where = '';
268 $params = [];
e62cd85f 269
258a5705
CB
270 if ($lastseentime && $lastseentime >= $timefrom) {
271 $where = '((timesort = :timefrom1 AND e.id > :timefromid) OR timesort > :timefrom2)';
272 if ($field === 'timestart') {
273 $where = '((timestart = :timefrom1 AND e.id > :timefromid) OR timestart > :timefrom2' .
274 ($withduration ? ' OR timestart + timeduration > :timefrom3' : '') . ')';
5a0974c7 275 }
258a5705
CB
276 $params['timefromid'] = $lastseenid;
277 $params['timefrom1'] = $lastseentime;
278 $params['timefrom2'] = $lastseentime;
279 $params['timefrom3'] = $lastseentime;
280 } else {
281 $where = 'timesort >= :timefrom';
282 if ($field === 'timestart') {
283 $where = '(timestart >= :timefrom' .
284 ($withduration ? ' OR timestart + timeduration > :timefrom2' : '') . ')';
5a0974c7 285 }
258a5705
CB
286
287 $params['timefrom'] = $timefrom;
288 $params['timefrom2'] = $timefrom;
e62cd85f
RW
289 }
290
258a5705
CB
291 return ['where' => [$where], 'params' => $params];
292 }
84d865d6 293
20592f5f
JP
294 /**
295 * Generates SQL subquery and parameters for 'to' pagination.
296 *
297 * @param string $field
298 * @param int $timeto
299 * @param int|null $lastseentime
300 * @param int|null $lastseenid
301 * @return array|bool
302 */
258a5705
CB
303 protected function timefield_pagination_to(
304 $field,
305 $timeto,
306 $lastseentime = null,
307 $lastseenid = null
308 ) {
309 $where = [];
310 $params = [];
84d865d6 311
258a5705
CB
312 if ($lastseentime && $lastseentime > $timeto) {
313 // The last seen event from this set is after the time sort range which
314 // means all events in this range have been seen, so we can just return
315 // early here.
316 return false;
317 } else if ($lastseentime && $lastseentime == $timeto) {
318 $where[] = '((timesort = :timeto1 AND e.id > :timetoid) OR timesort < :timeto2)';
319 if ($field === 'timestart') {
320 $where[] = '((timestart = :timeto1 AND e.id > :timetoid) OR timestart < :timeto2)';
321 }
322 $params['timetoid'] = $lastseenid;
323 $params['timeto1'] = $timeto;
324 $params['timeto2'] = $timeto;
325 } else {
326 $where[] = ($field === 'timestart' ? 'timestart' : 'timesort') . ' <= :timeto';
327 $params['timeto'] = $timeto;
84d865d6
RW
328 }
329
258a5705 330 return ['where' => $where, 'params' => $params];
84d865d6
RW
331 }
332
333 /**
334 * Create an event from a database record.
335 *
336 * @param \stdClass $record The database record
20592f5f 337 * @return event_interface|null
84d865d6 338 */
258a5705 339 protected function transform_from_database_record(\stdClass $record) {
20592f5f
JP
340 if ($record->courseid == 0 && $record->instance && $record->modulename) {
341 list($course, $cm) = get_course_and_cm_from_instance($record->instance, $record->modulename);
342 $record->courseid = $course->id;
343 }
258a5705 344
84d865d6
RW
345 return $this->factory->create_instance($record);
346 }
258a5705 347
20592f5f
JP
348 /**
349 * Fetches records from DB.
350 *
351 * @param int $userid
352 * @param string $whereconditions
353 * @param array $whereparams
354 * @param string $ordersql
355 * @param int $offset
356 * @param int $limitnum
357 * @return array
358 */
258a5705
CB
359 protected function get_from_db(
360 $userid,
361 $whereconditions,
362 $whereparams,
363 $ordersql,
364 $offset,
365 $limitnum
366 ) {
367 return array_values(
368 $this->retrievalstrategy->get_raw_events(
369 [$userid],
370 null,
371 null,
372 $whereconditions,
373 $whereparams,
374 $ordersql,
375 $offset,
376 $limitnum
377 )
378 );
379 }
84d865d6 380}