MDL-39846 prevent use of snapshots in restored events
[moodle.git] / lib / classes / event / base.php
CommitLineData
d8a1f426
PS
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
17namespace core\event;
18
19/**
20 * Base event class.
21 *
22 * @package core
23 * @copyright 2013 Petr Skoda {@link http://skodak.org}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27
28/**
29 * All other event classes must extend this class.
30 *
31 * @package core
32 * @copyright 2013 Petr Skoda {@link http://skodak.org}
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 *
35 * @property-read string $eventname Name of the event (=== class name with leading \)
36 * @property-read string $component Full frankenstyle component name
37 * @property-read string $action what happened
38 * @property-read string $object what/who was object of the action (usually similar to database table name)
a85258ca 39 * @property-read string $objecttable name of database table where is object record stored
d8a1f426
PS
40 * @property-read int $objectid optional id of the object
41 * @property-read string $crud letter indicating event type
4b734e74 42 * @property-read int $level log level (number between 1 and 100)
d8a1f426
PS
43 * @property-read int $contextid
44 * @property-read int $contextlevel
45 * @property-read int $contextinstanceid
46 * @property-read int $userid who did this?
47 * @property-read int $courseid
48 * @property-read int $relateduserid
c4297815 49 * @property-read mixed $other array or scalar, can not contain objects
d8a1f426
PS
50 * @property-read int $timecreated
51 */
ed17808d 52abstract class base implements \IteratorAggregate {
d8a1f426
PS
53 /** @var array event data */
54 protected $data;
55
4b734e74 56 /** @var array the format is standardised by logging API */
b0cdc969 57 protected $logextra;
4b734e74 58
d8a1f426
PS
59 /** @var \context of this event */
60 protected $context;
61
22626564
PS
62 /**
63 * @var bool indicates if event was already triggered,
64 * this prevents second attempt to trigger event.
65 */
d8a1f426
PS
66 private $triggered;
67
22626564
PS
68 /**
69 * @var bool indicates if event was already dispatched,
70 * this prevents direct calling of manager::dispatch($event).
71 */
72 private $dispatched;
73
74 /**
75 * @var bool indicates if event was restored from storage,
76 * this prevents triggering of restored events.
77 */
d8a1f426
PS
78 private $restored;
79
80 /** @var array list of event properties */
81 private static $fields = array(
a85258ca 82 'eventname', 'component', 'action', 'object', 'objecttable', 'objectid', 'crud', 'level', 'contextid',
c4297815 83 'contextlevel', 'contextinstanceid', 'userid', 'courseid', 'relateduserid', 'other',
4b734e74 84 'timecreated');
d8a1f426
PS
85
86 /** @var array simple record cache */
b396d40e 87 protected $recordsnapshots = array();
d8a1f426
PS
88
89 /**
90 * Private constructor, use create() or restore() methods instead.
91 */
92 private final function __construct() {
93 $this->data = array_fill_keys(self::$fields, null);
94 }
95
96 /**
97 * Create new event.
98 *
99 * The optional data keys as:
100 * 1/ objectid - the id of the object specified in class name
101 * 2/ context - the context of this event
c4297815 102 * 3/ other - the other data describing the event, can not contain objects
d8a1f426
PS
103 * 4/ relateduserid - the id of user which is somehow related to this event
104 *
105 * @param array $data
106 * @return \core\event\base returns instance of new event
107 *
108 * @throws \coding_exception
109 */
110 public static final function create(array $data = null) {
111 global $PAGE, $USER;
112
113 $data = (array)$data;
114
115 /** @var \core\event\base $event */
116 $event = new static();
117 $event->triggered = false;
118 $event->restored = false;
22626564 119 $event->dispatched = false;
d8a1f426 120
4b734e74
PS
121 // Set automatic data.
122 $event->data['timecreated'] = time();
123
d8a1f426
PS
124 $classname = get_class($event);
125 $parts = explode('\\', $classname);
126 if (count($parts) !== 3 or $parts[1] !== 'event') {
127 throw new \coding_exception("Invalid event class name '$classname', it must be defined in component\\event\\ namespace");
128 }
129 $event->data['eventname'] = '\\'.$classname;
130 $event->data['component'] = $parts[0];
131
132 $pos = strrpos($parts[2], '_');
133 if ($pos === false) {
134 throw new \coding_exception("Invalid event class name '$classname', there must be at least one underscore separating object and action words");
135 }
136 $event->data['object'] = substr($parts[2], 0, $pos);
137 $event->data['action'] = substr($parts[2], $pos+1);
138
4b734e74 139 // Set optional data or use defaults.
d8a1f426
PS
140 $event->data['objectid'] = isset($data['objectid']) ? $data['objectid'] : null;
141 $event->data['courseid'] = isset($data['courseid']) ? $data['courseid'] : null;
142 $event->data['userid'] = isset($data['userid']) ? $data['userid'] : $USER->id;
c4297815 143 $event->data['other'] = isset($data['other']) ? $data['other'] : null;
d8a1f426
PS
144 $event->data['relateduserid'] = isset($data['relateduserid']) ? $data['relateduserid'] : null;
145
27af3e62 146 if (!empty($data['context'])) {
d8a1f426 147 $event->context = $data['context'];
27af3e62
PS
148 $event->data['contextid'] = $event->context->id;
149 $event->data['contextlevel'] = $event->context->contextlevel;
150 $event->data['contextinstanceid'] = $event->context->instanceid;
151
152 } else if (!empty($data['contextid'])) {
153 $event->context = null;
154 if (isset($data['contextlevel']) and isset($data['contextinstanceid'])) {
155 // Useful especially when deleting contexts because we can nto fetch it from DB anymore.
156 $event->data['contextid'] = $data['contextid'];
157 $event->data['contextlevel'] = $data['contextlevel'];
158 $event->data['contextinstanceid'] = $data['contextinstanceid'];
159 $event->context = \context::instance_by_id($data['contextid'], IGNORE_MISSING);
160 } else {
161 $event->context = \context::instance_by_id($data['contextid'], MUST_EXIST);
162 $event->data['contextid'] = $event->context->id;
163 $event->data['contextlevel'] = $event->context->contextlevel;
164 $event->data['contextinstanceid'] = $event->context->instanceid;
165 }
166 } else {
167 throw new \coding_exception('context (or contextid) is a required event property.');
d8a1f426 168 }
d8a1f426
PS
169
170 if (!isset($event->data['courseid'])) {
27af3e62 171 if ($event->context and $coursecontext = $event->context->get_course_context(false)) {
d8a1f426
PS
172 $event->data['courseid'] = $coursecontext->id;
173 } else {
174 $event->data['courseid'] = 0;
175 }
176 }
177
27af3e62 178 if (!array_key_exists('relateduserid', $data) and $event->context and $event->context->contextlevel == CONTEXT_USER) {
d8a1f426
PS
179 $event->data['relateduserid'] = $event->context->instanceid;
180 }
181
c4297815 182 // Set static event data specific for child class, this should also validate other data.
4b734e74 183 $event->init();
d8a1f426 184
4b734e74 185 // Warn developers if they do something wrong.
ed17808d 186 if (debugging('', DEBUG_DEVELOPER)) { // This should be replaced by new $CFG->slowdebug flag if introduced.
4b734e74 187 static $automatickeys = array('eventname', 'component', 'action', 'object', 'timecreated');
a85258ca 188 static $initkeys = array('crud', 'level', 'objecttable');
4b734e74
PS
189
190 foreach ($data as $key => $ignored) {
191 if ($key === 'context') {
192 continue;
193
194 } else if (in_array($key, $automatickeys)) {
195 debugging("Data key '$key' is not allowed in \\core\\event\\base::create() method, it is set automatically");
196
197 } else if (in_array($key, $initkeys)) {
198 debugging("Data key '$key' is not allowed in \\core\\event\\base::create() method, you need to set it in init() method");
199
200 } else if (!in_array($key, self::$fields)) {
201 debugging("Data key '$key' does not exist in \\core\\event\\base");
d8a1f426
PS
202 }
203 }
204 }
205
d8a1f426
PS
206 return $event;
207 }
208
209 /**
210 * Override in subclass.
211 *
212 * Set all required data properties:
4b734e74
PS
213 * 1/ crud - letter [crud]
214 * 2/ level - number 1...100
a85258ca 215 * 3/ objecttable - name of database table if objectid specified
4b734e74 216 *
05a970d3
PS
217 * TODO: MDL-37658
218 *
c4297815 219 * Optionally validate $this->data['other'].
d8a1f426
PS
220 *
221 * @return void
222 */
223 protected abstract function init();
224
4b734e74
PS
225 /**
226 * Returns localised general event name.
227 *
228 * Override in subclass, we can not make it static and abstract at the same time.
229 *
05a970d3
PS
230 * TODO: MDL-37658
231 *
4b734e74
PS
232 * @return string|\lang_string
233 */
234 public static function get_name() {
235 // Override in subclass with real lang string.
236 $parts = explode('\\', __CLASS__);
237 if (count($parts) !== 3) {
238 return 'unknown event';
239 }
240 return $parts[0].': '.str_replace('_', ' ', $parts[2]);
241 }
242
243 /**
244 * Returns localised description of what happened.
245 *
05a970d3
PS
246 * TODO: MDL-37658
247 *
4b734e74
PS
248 * @return string|\lang_string
249 */
250 public function get_description() {
251 return null;
252 }
253
254 /**
255 * Define whether a user can view the event or not.
256 *
257 * @param int|\stdClass $user_or_id ID of the user.
258 * @return bool True if the user can view the event, false otherwise.
259 */
260 public function can_view($user_or_id = null) {
261 return is_siteadmin($user_or_id);
262 }
263
d8a1f426
PS
264 /**
265 * Restore event from existing historic data.
266 *
267 * @param array $data
b0cdc969 268 * @param array $logextra the format is standardised by logging API
d8a1f426
PS
269 * @return bool|\core\event\base
270 */
b0cdc969 271 public static final function restore(array $data, array $logextra) {
d8a1f426
PS
272 $classname = $data['eventname'];
273 $component = $data['component'];
274 $action = $data['action'];
275 $object = $data['object'];
276
277 // Security: make 100% sure this really is an event class.
278 if ($classname !== "\\{$component}\\event\\{$object}_{$action}") {
279 return false;
280 }
281
282 if (!class_exists($classname)) {
283 return false;
284 }
285 $event = new $classname();
286 if (!($event instanceof \core\event\base)) {
287 return false;
288 }
289
d8a1f426 290 $event->restored = true;
22626564
PS
291 $event->triggered = true;
292 $event->dispatched = true;
b0cdc969 293 $event->logextra = $logextra;
d8a1f426
PS
294
295 foreach (self::$fields as $key) {
4b734e74 296 if (!array_key_exists($key, $data)) {
d8a1f426 297 debugging("Event restore data must contain key $key");
4b734e74 298 $data[$key] = null;
d8a1f426
PS
299 }
300 }
4b734e74
PS
301 if (count($data) != count(self::$fields)) {
302 foreach ($data as $key => $value) {
303 if (!in_array($key, self::$fields)) {
304 debugging("Event restore data cannot contain key $key");
305 unset($data[$key]);
306 }
307 }
308 }
309 $event->data = $data;
d8a1f426
PS
310
311 return $event;
312 }
313
d8a1f426
PS
314 /**
315 * Returns event context.
316 * @return \context
317 */
318 public function get_context() {
319 if (isset($this->context)) {
320 return $this->context;
321 }
322 $this->context = \context::instance_by_id($this->data['contextid'], false);
323 return $this->context;
324 }
325
326 /**
327 * Returns relevant URL, override in subclasses.
4b734e74 328 * @return \moodle_url
d8a1f426
PS
329 */
330 public function get_url() {
331 return null;
332 }
333
334 /**
335 * Return standardised event data as array.
336 *
d8a1f426
PS
337 * @return array
338 */
339 public function get_data() {
340 return $this->data;
341 }
342
4b734e74
PS
343 /**
344 * Return auxiliary data that was stored in logs.
345 *
05a970d3
PS
346 * TODO: MDL-37658
347 *
4b734e74
PS
348 * @return array the format is standardised by logging API
349 */
b0cdc969
PS
350 public function get_logextra() {
351 return $this->logextra;
4b734e74
PS
352 }
353
d8a1f426
PS
354 /**
355 * Does this event replace legacy event?
356 *
357 * @return null|string legacy event name
358 */
359 public function get_legacy_eventname() {
360 return null;
361 }
362
363 /**
364 * Legacy event data if get_legacy_eventname() is not empty.
365 *
366 * @return mixed
367 */
368 public function get_legacy_eventdata() {
369 return null;
370 }
371
372 /**
373 * Doest this event replace add_to_log() statement?
374 *
375 * @return null|array of parameters to be passed to legacy add_to_log() function.
376 */
377 public function get_legacy_logdata() {
378 return null;
379 }
380
381 /**
382 * Validate all properties right before triggering the event.
383 *
384 * This throws coding exceptions for fatal problems and debugging for minor problems.
385 *
386 * @throws \coding_exception
387 */
388 protected final function validate_before_trigger() {
a85258ca
PS
389 global $DB;
390
d8a1f426
PS
391 if (empty($this->data['crud'])) {
392 throw new \coding_exception('crud must be specified in init() method of each method');
393 }
394 if (empty($this->data['level'])) {
395 throw new \coding_exception('level must be specified in init() method of each method');
396 }
a85258ca
PS
397 if (!empty($this->data['objectid']) and empty($this->data['objecttable'])) {
398 throw new \coding_exception('objecttable must be specified in init() method if objectid present');
399 }
d8a1f426 400
a85258ca 401 if (debugging('', DEBUG_DEVELOPER)) { // This should be replaced by new $CFG->slowdebug flag if introduced.
d8a1f426
PS
402 // Ideally these should be coding exceptions, but we need to skip these for performance reasons
403 // on production servers.
4b734e74
PS
404
405 if (!in_array($this->data['crud'], array('c', 'r', 'u', 'd'), true)) {
406 debugging("Invalid event crud value specified.");
407 }
408 if (!is_number($this->data['level'])) {
409 debugging('Event property level must be a number');
410 }
d8a1f426 411 if (self::$fields !== array_keys($this->data)) {
4b734e74 412 debugging('Number of event data fields must not be changed in event classes');
d8a1f426 413 }
c4297815
PS
414 $encoded = json_encode($this->data['other']);
415 if ($encoded === false or $this->data['other'] !== json_decode($encoded, true)) {
416 debugging('other event data must be compatible with json encoding');
4b734e74
PS
417 }
418 if ($this->data['userid'] and !is_number($this->data['userid'])) {
419 debugging('Event property userid must be a number');
420 }
421 if ($this->data['courseid'] and !is_number($this->data['courseid'])) {
422 debugging('Event property courseid must be a number');
423 }
424 if ($this->data['objectid'] and !is_number($this->data['objectid'])) {
425 debugging('Event property objectid must be a number');
426 }
427 if ($this->data['relateduserid'] and !is_number($this->data['relateduserid'])) {
428 debugging('Event property relateduserid must be a number');
d8a1f426 429 }
a85258ca
PS
430 if ($this->data['objecttable']) {
431 if (!$DB->get_manager()->table_exists($this->data['objecttable'])) {
432 debugging('Unknown table specified in objecttable field');
433 }
434 }
d8a1f426
PS
435 }
436 }
437
438 /**
439 * Trigger event.
440 */
441 public final function trigger() {
442 global $CFG;
443
444 if ($this->restored) {
445 throw new \coding_exception('Can not trigger restored event');
446 }
22626564 447 if ($this->triggered or $this->dispatched) {
d8a1f426
PS
448 throw new \coding_exception('Can not trigger event twice');
449 }
450
d8a1f426
PS
451 $this->validate_before_trigger();
452
22626564
PS
453 $this->triggered = true;
454
d8a1f426
PS
455 if (!empty($CFG->loglifetime)) {
456 if ($data = $this->get_legacy_logdata()) {
457 call_user_func_array('add_to_log', $data);
458 }
459 }
460
62401e8f
PS
461 if (PHPUNIT_TEST and \phpunit_util::is_redirecting_events()) {
462 $this->dispatched = true;
463 \phpunit_util::event_triggered($this);
464 return;
465 }
466
d8a1f426
PS
467 \core\event\manager::dispatch($this);
468
22626564
PS
469 $this->dispatched = true;
470
d8a1f426
PS
471 if ($legacyeventname = $this->get_legacy_eventname()) {
472 events_trigger($legacyeventname, $this->get_legacy_eventdata());
473 }
474 }
475
476 /**
22626564 477 * Was this event already triggered?
d8a1f426
PS
478 *
479 * @return bool
480 */
22626564 481 public final function is_triggered() {
d8a1f426
PS
482 return $this->triggered;
483 }
484
22626564
PS
485 /**
486 * Used from event manager to prevent direct access.
487 *
488 * @return bool
489 */
490 public final function is_dispatched() {
491 return $this->dispatched;
492 }
493
d8a1f426 494 /**
4b734e74 495 * Was this event restored?
d8a1f426
PS
496 *
497 * @return bool
498 */
22626564 499 public final function is_restored() {
d8a1f426
PS
500 return $this->restored;
501 }
502
503 /**
504 * Add cached data that will be most probably used in event observers.
505 *
506 * This is used to improve performance, but it is required for data
4b734e74 507 * that was just deleted.
d8a1f426
PS
508 *
509 * @param string $tablename
510 * @param \stdClass $record
300dbc66
PS
511 *
512 * @throws \coding_exception if used after ::trigger()
d8a1f426 513 */
5fef139c 514 public function add_record_snapshot($tablename, $record) {
d8a1f426
PS
515 global $DB;
516
300dbc66
PS
517 if ($this->triggered) {
518 throw new \coding_exception('It is not possible to add snapshots after triggering of events');
519 }
520
d8a1f426
PS
521 // NOTE: this might use some kind of MUC cache,
522 // hopefully we will not run out of memory here...
ed17808d 523 if (debugging('', DEBUG_DEVELOPER)) { // This should be replaced by new $CFG->slowdebug flag if introduced.
d8a1f426
PS
524 if (!$DB->get_manager()->table_exists($tablename)) {
525 debugging("Invalid table name '$tablename' specified, database table does not exist.");
526 }
527 }
b396d40e 528 $this->recordsnapshots[$tablename][$record->id] = $record;
d8a1f426
PS
529 }
530
531 /**
532 * Returns cached record or fetches data from database if not cached.
533 *
534 * @param string $tablename
535 * @param int $id
536 * @return \stdClass
4ad6d5c5
PS
537 *
538 * @throws \coding_exception if used after ::restore()
d8a1f426 539 */
5fef139c 540 public function get_record_snapshot($tablename, $id) {
d8a1f426
PS
541 global $DB;
542
4ad6d5c5
PS
543 if ($this->restored) {
544 throw new \coding_exception('It is not possible to get snapshots from restored events');
545 }
546
b396d40e
PS
547 if (isset($this->recordsnapshots[$tablename][$id])) {
548 return $this->recordsnapshots[$tablename][$id];
d8a1f426
PS
549 }
550
551 $record = $DB->get_record($tablename, array('id'=>$id));
b396d40e 552 $this->recordsnapshots[$tablename][$id] = $record;
d8a1f426
PS
553
554 return $record;
555 }
556
557 /**
558 * Magic getter for read only access.
559 *
d8a1f426
PS
560 * @param string $name
561 * @return mixed
d8a1f426
PS
562 */
563 public function __get($name) {
564 if (array_key_exists($name, $this->data)) {
565 return $this->data[$name];
566 }
567
4b734e74 568 debugging("Accessing non-existent event property '$name'");
d8a1f426 569 }
605a8c33
PS
570
571 /**
572 * Magic setter.
573 *
574 * Note: we must not allow modification of data from outside,
575 * after trigger() the data MUST NOT CHANGE!!!
576 *
577 * @param string $name
578 * @param mixed $value
579 *
580 * @throws \coding_exception
581 */
582 public function __set($name, $value) {
583 throw new \coding_exception('Event properties must not be modified.');
584 }
585
586 /**
587 * Is data property set?
588 *
589 * @param string $name
590 * @return bool
591 */
592 public function __isset($name) {
593 return isset($this->data[$name]);
594 }
ed17808d
PS
595
596 /**
597 * Create an iterator because magic vars can't be seen by 'foreach'.
598 *
599 * @return \ArrayIterator
600 */
601 public function getIterator() {
602 return new \ArrayIterator($this->data);
603 }
d8a1f426 604}