MDL-45216 events: Unit tests for core/event/manager.
[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
5999e40f
MN
19defined('MOODLE_INTERNAL') || die();
20
d8a1f426
PS
21/**
22 * Base event class.
23 *
24 * @package core
25 * @copyright 2013 Petr Skoda {@link http://skodak.org}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
d8a1f426
PS
29/**
30 * All other event classes must extend this class.
31 *
32 * @package core
9638600b 33 * @since Moodle 2.6
d8a1f426
PS
34 * @copyright 2013 Petr Skoda {@link http://skodak.org}
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 *
37 * @property-read string $eventname Name of the event (=== class name with leading \)
38 * @property-read string $component Full frankenstyle component name
39 * @property-read string $action what happened
660f049f 40 * @property-read string $target what/who was target of the action
a85258ca 41 * @property-read string $objecttable name of database table where is object record stored
d8a1f426
PS
42 * @property-read int $objectid optional id of the object
43 * @property-read string $crud letter indicating event type
3345e24f 44 * @property-read int $edulevel log level (one of the constants LEVEL_)
d8a1f426
PS
45 * @property-read int $contextid
46 * @property-read int $contextlevel
47 * @property-read int $contextinstanceid
48 * @property-read int $userid who did this?
49 * @property-read int $courseid
50 * @property-read int $relateduserid
bc293202
51 * @property-read int $anonymous 1 means event should not be visible in reports, 0 means normal event,
52 * create() argument may be also true/false.
c4297815 53 * @property-read mixed $other array or scalar, can not contain objects
d8a1f426
PS
54 * @property-read int $timecreated
55 */
ed17808d 56abstract class base implements \IteratorAggregate {
38d6fbfa
FM
57
58 /**
59 * Other level.
60 */
61 const LEVEL_OTHER = 0;
62
63 /**
64 * Teaching level.
65 *
66 * Any event that is performed by someone (typically a teacher) and has a teaching value,
67 * anything that is affecting the learning experience/environment of the students.
68 */
69 const LEVEL_TEACHING = 1;
70
71 /**
72 * Participating level.
73 *
74 * Any event that is performed by a user, and is related (or could be related) to his learning experience.
75 */
76 const LEVEL_PARTICIPATING = 2;
77
d8a1f426
PS
78 /** @var array event data */
79 protected $data;
80
4b734e74 81 /** @var array the format is standardised by logging API */
b0cdc969 82 protected $logextra;
4b734e74 83
d8a1f426
PS
84 /** @var \context of this event */
85 protected $context;
86
22626564
PS
87 /**
88 * @var bool indicates if event was already triggered,
89 * this prevents second attempt to trigger event.
90 */
d8a1f426
PS
91 private $triggered;
92
22626564
PS
93 /**
94 * @var bool indicates if event was already dispatched,
95 * this prevents direct calling of manager::dispatch($event).
96 */
97 private $dispatched;
98
99 /**
100 * @var bool indicates if event was restored from storage,
101 * this prevents triggering of restored events.
102 */
d8a1f426
PS
103 private $restored;
104
105 /** @var array list of event properties */
106 private static $fields = array(
3345e24f 107 'eventname', 'component', 'action', 'target', 'objecttable', 'objectid', 'crud', 'edulevel', 'contextid',
bc293202 108 'contextlevel', 'contextinstanceid', 'userid', 'courseid', 'relateduserid', 'anonymous', 'other',
4b734e74 109 'timecreated');
d8a1f426
PS
110
111 /** @var array simple record cache */
fd4f3e9e 112 private $recordsnapshots = array();
d8a1f426
PS
113
114 /**
115 * Private constructor, use create() or restore() methods instead.
116 */
117 private final function __construct() {
118 $this->data = array_fill_keys(self::$fields, null);
b6c7ab22
AA
119
120 // Define some basic details.
121 $classname = get_called_class();
122 $parts = explode('\\', $classname);
123 if (count($parts) !== 3 or $parts[1] !== 'event') {
124 throw new \coding_exception("Invalid event class name '$classname', it must be defined in component\\event\\
125 namespace");
126 }
127 $this->data['eventname'] = '\\'.$classname;
128 $this->data['component'] = $parts[0];
129
130 $pos = strrpos($parts[2], '_');
131 if ($pos === false) {
132 throw new \coding_exception("Invalid event class name '$classname', there must be at least one underscore separating
133 object and action words");
134 }
135 $this->data['target'] = substr($parts[2], 0, $pos);
136 $this->data['action'] = substr($parts[2], $pos + 1);
d8a1f426
PS
137 }
138
139 /**
140 * Create new event.
141 *
142 * The optional data keys as:
143 * 1/ objectid - the id of the object specified in class name
144 * 2/ context - the context of this event
c4297815 145 * 3/ other - the other data describing the event, can not contain objects
d8a1f426
PS
146 * 4/ relateduserid - the id of user which is somehow related to this event
147 *
148 * @param array $data
149 * @return \core\event\base returns instance of new event
150 *
151 * @throws \coding_exception
152 */
153 public static final function create(array $data = null) {
3345e24f 154 global $USER, $CFG;
d8a1f426
PS
155
156 $data = (array)$data;
157
158 /** @var \core\event\base $event */
159 $event = new static();
160 $event->triggered = false;
161 $event->restored = false;
22626564 162 $event->dispatched = false;
d8a1f426 163
bc293202
164 // By default all events are visible in logs.
165 $event->data['anonymous'] = 0;
166
fb23739e
PS
167 // Set static event data specific for child class.
168 $event->init();
169
3345e24f
170 if (isset($event->data['level'])) {
171 if (!isset($event->data['edulevel'])) {
172 debugging('level property is deprecated, use edulevel property instead', DEBUG_DEVELOPER);
173 $event->data['edulevel'] = $event->data['level'];
174 }
175 unset($event->data['level']);
176 }
177
4b734e74
PS
178 // Set automatic data.
179 $event->data['timecreated'] = time();
180
4b734e74 181 // Set optional data or use defaults.
d8a1f426
PS
182 $event->data['objectid'] = isset($data['objectid']) ? $data['objectid'] : null;
183 $event->data['courseid'] = isset($data['courseid']) ? $data['courseid'] : null;
184 $event->data['userid'] = isset($data['userid']) ? $data['userid'] : $USER->id;
c4297815 185 $event->data['other'] = isset($data['other']) ? $data['other'] : null;
d8a1f426 186 $event->data['relateduserid'] = isset($data['relateduserid']) ? $data['relateduserid'] : null;
bc293202
187 if (isset($data['anonymous'])) {
188 $event->data['anonymous'] = $data['anonymous'];
189 }
190 $event->data['anonymous'] = (int)(bool)$event->data['anonymous'];
d8a1f426 191
fddd1018 192 if (isset($event->context)) {
097011c4
PS
193 if (isset($data['context'])) {
194 debugging('Context was already set in init() method, ignoring context parameter', DEBUG_DEVELOPER);
fddd1018 195 }
fddd1018
PS
196
197 } else if (!empty($data['context'])) {
d8a1f426 198 $event->context = $data['context'];
27af3e62
PS
199
200 } else if (!empty($data['contextid'])) {
097011c4
PS
201 $event->context = \context::instance_by_id($data['contextid'], MUST_EXIST);
202
27af3e62 203 } else {
fddd1018 204 throw new \coding_exception('context (or contextid) is a required event property, system context may be hardcoded in init() method.');
d8a1f426 205 }
d8a1f426 206
097011c4
PS
207 $event->data['contextid'] = $event->context->id;
208 $event->data['contextlevel'] = $event->context->contextlevel;
209 $event->data['contextinstanceid'] = $event->context->instanceid;
210
d8a1f426 211 if (!isset($event->data['courseid'])) {
097011c4 212 if ($coursecontext = $event->context->get_course_context(false)) {
513d8793 213 $event->data['courseid'] = $coursecontext->instanceid;
d8a1f426
PS
214 } else {
215 $event->data['courseid'] = 0;
216 }
217 }
218
097011c4 219 if (!array_key_exists('relateduserid', $data) and $event->context->contextlevel == CONTEXT_USER) {
d8a1f426
PS
220 $event->data['relateduserid'] = $event->context->instanceid;
221 }
222
4b734e74 223 // Warn developers if they do something wrong.
96f81ea3 224 if ($CFG->debugdeveloper) {
660f049f 225 static $automatickeys = array('eventname', 'component', 'action', 'target', 'contextlevel', 'contextinstanceid', 'timecreated');
3345e24f 226 static $initkeys = array('crud', 'level', 'objecttable', 'edulevel');
4b734e74
PS
227
228 foreach ($data as $key => $ignored) {
229 if ($key === 'context') {
230 continue;
231
232 } else if (in_array($key, $automatickeys)) {
96f81ea3 233 debugging("Data key '$key' is not allowed in \\core\\event\\base::create() method, it is set automatically", DEBUG_DEVELOPER);
4b734e74
PS
234
235 } else if (in_array($key, $initkeys)) {
96f81ea3 236 debugging("Data key '$key' is not allowed in \\core\\event\\base::create() method, you need to set it in init() method", DEBUG_DEVELOPER);
4b734e74
PS
237
238 } else if (!in_array($key, self::$fields)) {
239 debugging("Data key '$key' does not exist in \\core\\event\\base");
d8a1f426
PS
240 }
241 }
9ede00db
242 $expectedcourseid = 0;
243 if ($coursecontext = $event->context->get_course_context(false)) {
244 $expectedcourseid = $coursecontext->instanceid;
245 }
246 if ($expectedcourseid != $event->data['courseid']) {
247 debugging("Inconsistent courseid - context combination detected.", DEBUG_DEVELOPER);
248 }
d8a1f426
PS
249 }
250
c61a3a5c 251 // Let developers validate their custom data (such as $this->data['other'], contextlevel, etc.).
fddd1018
PS
252 $event->validate_data();
253
d8a1f426
PS
254 return $event;
255 }
256
257 /**
258 * Override in subclass.
259 *
260 * Set all required data properties:
38d6fbfa 261 * 1/ crud - letter [crud]
3345e24f 262 * 2/ edulevel - using a constant self::LEVEL_*.
a85258ca 263 * 3/ objecttable - name of database table if objectid specified
4b734e74 264 *
fddd1018
PS
265 * Optionally it can set:
266 * a/ fixed system context
d8a1f426
PS
267 *
268 * @return void
269 */
270 protected abstract function init();
271
fddd1018 272 /**
c61a3a5c 273 * Let developers validate their custom data (such as $this->data['other'], contextlevel, etc.).
fddd1018
PS
274 *
275 * Throw \coding_exception or debugging() notice in case of any problems.
276 */
277 protected function validate_data() {
278 // Override if you want to validate event properties when
279 // creating new events.
280 }
281
4b734e74
PS
282 /**
283 * Returns localised general event name.
284 *
285 * Override in subclass, we can not make it static and abstract at the same time.
286 *
fc9fc9fb 287 * @return string
4b734e74
PS
288 */
289 public static function get_name() {
290 // Override in subclass with real lang string.
1ccc1268 291 $parts = explode('\\', get_called_class());
4b734e74 292 if (count($parts) !== 3) {
fc9fc9fb 293 return get_string('unknownevent', 'error');
4b734e74
PS
294 }
295 return $parts[0].': '.str_replace('_', ' ', $parts[2]);
296 }
297
298 /**
fc9fc9fb 299 * Returns non-localised event description with id's for admin use only.
05a970d3 300 *
fc9fc9fb 301 * @return string
4b734e74
PS
302 */
303 public function get_description() {
304 return null;
305 }
306
307 /**
bc22fa93
308 * This method was originally intended for granular
309 * access control on the event level, unfortunately
310 * the proper implementation would be too expensive
311 * in many cases.
312 *
313 * @deprecated since 2.7
4b734e74
PS
314 *
315 * @param int|\stdClass $user_or_id ID of the user.
316 * @return bool True if the user can view the event, false otherwise.
317 */
318 public function can_view($user_or_id = null) {
15f009e1 319 debugging('can_view() method is deprecated, use anonymous flag instead if necessary.', DEBUG_DEVELOPER);
4b734e74
PS
320 return is_siteadmin($user_or_id);
321 }
322
d8a1f426
PS
323 /**
324 * Restore event from existing historic data.
325 *
326 * @param array $data
b0cdc969 327 * @param array $logextra the format is standardised by logging API
d8a1f426
PS
328 * @return bool|\core\event\base
329 */
b0cdc969 330 public static final function restore(array $data, array $logextra) {
d8a1f426
PS
331 $classname = $data['eventname'];
332 $component = $data['component'];
333 $action = $data['action'];
132eff90 334 $target = $data['target'];
d8a1f426
PS
335
336 // Security: make 100% sure this really is an event class.
132eff90 337 if ($classname !== "\\{$component}\\event\\{$target}_{$action}") {
d8a1f426
PS
338 return false;
339 }
340
341 if (!class_exists($classname)) {
d409944a 342 return self::restore_unknown($data, $logextra);
d8a1f426
PS
343 }
344 $event = new $classname();
345 if (!($event instanceof \core\event\base)) {
346 return false;
347 }
348
85a4b8a3 349 $event->init(); // Init method of events could be setting custom properties.
d8a1f426 350 $event->restored = true;
22626564
PS
351 $event->triggered = true;
352 $event->dispatched = true;
b0cdc969 353 $event->logextra = $logextra;
d8a1f426
PS
354
355 foreach (self::$fields as $key) {
4b734e74 356 if (!array_key_exists($key, $data)) {
d8a1f426 357 debugging("Event restore data must contain key $key");
4b734e74 358 $data[$key] = null;
d8a1f426
PS
359 }
360 }
4b734e74
PS
361 if (count($data) != count(self::$fields)) {
362 foreach ($data as $key => $value) {
363 if (!in_array($key, self::$fields)) {
364 debugging("Event restore data cannot contain key $key");
365 unset($data[$key]);
366 }
367 }
368 }
369 $event->data = $data;
d8a1f426
PS
370
371 return $event;
372 }
373
d409944a
PS
374 /**
375 * Restore unknown event.
376 *
377 * @param array $data
378 * @param array $logextra
379 * @return unknown_logged
380 */
381 protected static final function restore_unknown(array $data, array $logextra) {
382 $classname = '\core\event\unknown_logged';
383
384 /** @var unknown_logged $event */
385 $event = new $classname();
386 $event->restored = true;
387 $event->triggered = true;
388 $event->dispatched = true;
389 $event->data = $data;
390 $event->logextra = $logextra;
391
392 return $event;
393 }
394
7eaca5a8
395 /**
396 * Create fake event from legacy log data.
397 *
81fbecc0 398 * @param \stdClass $legacy
7eaca5a8
399 * @return base
400 */
401 public static final function restore_legacy($legacy) {
402 $classname = get_called_class();
81fbecc0 403 /** @var base $event */
7eaca5a8
404 $event = new $classname();
405 $event->restored = true;
406 $event->triggered = true;
407 $event->dispatched = true;
408
409 $context = false;
410 $component = 'legacy';
411 if ($legacy->cmid) {
412 $context = \context_module::instance($legacy->cmid, IGNORE_MISSING);
413 $component = 'mod_'.$legacy->module;
414 } else if ($legacy->course) {
415 $context = \context_course::instance($legacy->course, IGNORE_MISSING);
416 }
417 if (!$context) {
418 $context = \context_system::instance();
419 }
420
421 $event->data = array();
422
423 $event->data['eventname'] = $legacy->module.'_'.$legacy->action;
424 $event->data['component'] = $component;
425 $event->data['action'] = $legacy->action;
426 $event->data['target'] = null;
427 $event->data['objecttable'] = null;
428 $event->data['objectid'] = null;
429 if (strpos($legacy->action, 'view') !== false) {
430 $event->data['crud'] = 'r';
431 } else if (strpos($legacy->action, 'print') !== false) {
432 $event->data['crud'] = 'r';
433 } else if (strpos($legacy->action, 'update') !== false) {
434 $event->data['crud'] = 'u';
435 } else if (strpos($legacy->action, 'hide') !== false) {
436 $event->data['crud'] = 'u';
437 } else if (strpos($legacy->action, 'move') !== false) {
438 $event->data['crud'] = 'u';
439 } else if (strpos($legacy->action, 'write') !== false) {
440 $event->data['crud'] = 'u';
441 } else if (strpos($legacy->action, 'tag') !== false) {
442 $event->data['crud'] = 'u';
443 } else if (strpos($legacy->action, 'remove') !== false) {
444 $event->data['crud'] = 'u';
445 } else if (strpos($legacy->action, 'delete') !== false) {
446 $event->data['crud'] = 'p';
447 } else if (strpos($legacy->action, 'create') !== false) {
448 $event->data['crud'] = 'c';
449 } else if (strpos($legacy->action, 'post') !== false) {
450 $event->data['crud'] = 'c';
451 } else if (strpos($legacy->action, 'add') !== false) {
452 $event->data['crud'] = 'c';
453 } else {
454 // End of guessing...
455 $event->data['crud'] = 'r';
456 }
457 $event->data['edulevel'] = $event::LEVEL_OTHER;
458 $event->data['contextid'] = $context->id;
459 $event->data['contextlevel'] = $context->contextlevel;
460 $event->data['contextinstanceid'] = $context->instanceid;
461 $event->data['userid'] = ($legacy->userid ? $legacy->userid : null);
462 $event->data['courseid'] = ($legacy->course ? $legacy->course : null);
463 $event->data['relateduserid'] = ($legacy->userid ? $legacy->userid : null);
464 $event->data['timecreated'] = $legacy->time;
465
81fbecc0
466 $event->logextra = array();
467 if ($legacy->ip) {
468 $event->logextra['origin'] = 'web';
469 $event->logextra['ip'] = $legacy->ip;
470 } else {
471 $event->logextra['origin'] = 'cli';
472 $event->logextra['ip'] = null;
473 }
474 $event->logextra['realuserid'] = null;
7eaca5a8
475
476 $event->data['other'] = (array)$legacy;
477
478 return $event;
479 }
480
d8a1f426
PS
481 /**
482 * Returns event context.
483 * @return \context
484 */
485 public function get_context() {
486 if (isset($this->context)) {
487 return $this->context;
488 }
fdc729ea 489 $this->context = \context::instance_by_id($this->data['contextid'], IGNORE_MISSING);
d8a1f426
PS
490 return $this->context;
491 }
492
493 /**
494 * Returns relevant URL, override in subclasses.
4b734e74 495 * @return \moodle_url
d8a1f426
PS
496 */
497 public function get_url() {
498 return null;
499 }
500
501 /**
502 * Return standardised event data as array.
503 *
3345e24f 504 * @return array All elements are scalars except the 'other' field which is array.
d8a1f426
PS
505 */
506 public function get_data() {
507 return $this->data;
508 }
509
4b734e74
PS
510 /**
511 * Return auxiliary data that was stored in logs.
512 *
3345e24f
513 * List of standard properties:
514 * - origin: IP number, cli,cron
515 * - realuserid: id of the user when logged-in-as
05a970d3 516 *
4b734e74
PS
517 * @return array the format is standardised by logging API
518 */
b0cdc969
PS
519 public function get_logextra() {
520 return $this->logextra;
4b734e74
PS
521 }
522
d8a1f426
PS
523 /**
524 * Does this event replace legacy event?
525 *
82b1fb51
PS
526 * Note: do not use directly!
527 *
d8a1f426
PS
528 * @return null|string legacy event name
529 */
22446003 530 public static function get_legacy_eventname() {
d8a1f426
PS
531 return null;
532 }
533
534 /**
535 * Legacy event data if get_legacy_eventname() is not empty.
536 *
82b1fb51
PS
537 * Note: do not use directly!
538 *
d8a1f426
PS
539 * @return mixed
540 */
82b1fb51 541 protected function get_legacy_eventdata() {
d8a1f426
PS
542 return null;
543 }
544
545 /**
546 * Doest this event replace add_to_log() statement?
547 *
82b1fb51
PS
548 * Note: do not use directly!
549 *
d8a1f426
PS
550 * @return null|array of parameters to be passed to legacy add_to_log() function.
551 */
82b1fb51 552 protected function get_legacy_logdata() {
d8a1f426
PS
553 return null;
554 }
555
556 /**
557 * Validate all properties right before triggering the event.
558 *
559 * This throws coding exceptions for fatal problems and debugging for minor problems.
560 *
561 * @throws \coding_exception
562 */
563 protected final function validate_before_trigger() {
96f81ea3 564 global $DB, $CFG;
a85258ca 565
d8a1f426
PS
566 if (empty($this->data['crud'])) {
567 throw new \coding_exception('crud must be specified in init() method of each method');
568 }
3345e24f
569 if (!isset($this->data['edulevel'])) {
570 throw new \coding_exception('edulevel must be specified in init() method of each method');
d8a1f426 571 }
a85258ca
PS
572 if (!empty($this->data['objectid']) and empty($this->data['objecttable'])) {
573 throw new \coding_exception('objecttable must be specified in init() method if objectid present');
574 }
d8a1f426 575
96f81ea3 576 if ($CFG->debugdeveloper) {
d8a1f426
PS
577 // Ideally these should be coding exceptions, but we need to skip these for performance reasons
578 // on production servers.
4b734e74
PS
579
580 if (!in_array($this->data['crud'], array('c', 'r', 'u', 'd'), true)) {
96f81ea3 581 debugging("Invalid event crud value specified.", DEBUG_DEVELOPER);
4b734e74 582 }
3345e24f 583 if (!in_array($this->data['edulevel'], array(self::LEVEL_OTHER, self::LEVEL_TEACHING, self::LEVEL_PARTICIPATING))) {
38d6fbfa 584 // Bitwise combination of levels is not allowed at this stage.
3345e24f 585 debugging('Event property edulevel must a constant value, see event_base::LEVEL_*', DEBUG_DEVELOPER);
4b734e74 586 }
d8a1f426 587 if (self::$fields !== array_keys($this->data)) {
96f81ea3 588 debugging('Number of event data fields must not be changed in event classes', DEBUG_DEVELOPER);
d8a1f426 589 }
c4297815 590 $encoded = json_encode($this->data['other']);
49ff1342
AG
591 // The comparison here is not set to strict as whole float numbers will be converted to integers through JSON encoding /
592 // decoding and send an unwanted debugging message.
593 if ($encoded === false or $this->data['other'] != json_decode($encoded, true)) {
96f81ea3 594 debugging('other event data must be compatible with json encoding', DEBUG_DEVELOPER);
4b734e74
PS
595 }
596 if ($this->data['userid'] and !is_number($this->data['userid'])) {
96f81ea3 597 debugging('Event property userid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
598 }
599 if ($this->data['courseid'] and !is_number($this->data['courseid'])) {
96f81ea3 600 debugging('Event property courseid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
601 }
602 if ($this->data['objectid'] and !is_number($this->data['objectid'])) {
96f81ea3 603 debugging('Event property objectid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
604 }
605 if ($this->data['relateduserid'] and !is_number($this->data['relateduserid'])) {
96f81ea3 606 debugging('Event property relateduserid must be a number', DEBUG_DEVELOPER);
d8a1f426 607 }
a85258ca
PS
608 if ($this->data['objecttable']) {
609 if (!$DB->get_manager()->table_exists($this->data['objecttable'])) {
96f81ea3 610 debugging('Unknown table specified in objecttable field', DEBUG_DEVELOPER);
a85258ca 611 }
31e571cd
FM
612 if (!isset($this->data['objectid'])) {
613 debugging('Event property objectid must be set when objecttable is defined', DEBUG_DEVELOPER);
614 }
a85258ca 615 }
d8a1f426
PS
616 }
617 }
618
619 /**
620 * Trigger event.
621 */
622 public final function trigger() {
623 global $CFG;
624
625 if ($this->restored) {
626 throw new \coding_exception('Can not trigger restored event');
627 }
22626564 628 if ($this->triggered or $this->dispatched) {
d8a1f426
PS
629 throw new \coding_exception('Can not trigger event twice');
630 }
631
d8a1f426
PS
632 $this->validate_before_trigger();
633
22626564
PS
634 $this->triggered = true;
635
ef1987dc 636 if (isset($CFG->loglifetime) and $CFG->loglifetime != -1) {
d8a1f426 637 if ($data = $this->get_legacy_logdata()) {
7eaca5a8
638 $manager = get_log_manager();
639 if (method_exists($manager, 'legacy_add_to_log')) {
c3ba899a
MG
640 if (is_array($data[0])) {
641 // Some events require several entries in 'log' table.
642 foreach ($data as $d) {
643 call_user_func_array(array($manager, 'legacy_add_to_log'), $d);
644 }
645 } else {
646 call_user_func_array(array($manager, 'legacy_add_to_log'), $data);
647 }
7eaca5a8 648 }
d8a1f426
PS
649 }
650 }
651
62401e8f
PS
652 if (PHPUNIT_TEST and \phpunit_util::is_redirecting_events()) {
653 $this->dispatched = true;
654 \phpunit_util::event_triggered($this);
655 return;
656 }
657
d8a1f426
PS
658 \core\event\manager::dispatch($this);
659
22626564
PS
660 $this->dispatched = true;
661
22446003 662 if ($legacyeventname = static::get_legacy_eventname()) {
f0f0e1fe 663 events_trigger_legacy($legacyeventname, $this->get_legacy_eventdata());
d8a1f426
PS
664 }
665 }
666
667 /**
22626564 668 * Was this event already triggered?
d8a1f426
PS
669 *
670 * @return bool
671 */
22626564 672 public final function is_triggered() {
d8a1f426
PS
673 return $this->triggered;
674 }
675
22626564
PS
676 /**
677 * Used from event manager to prevent direct access.
678 *
679 * @return bool
680 */
681 public final function is_dispatched() {
682 return $this->dispatched;
683 }
684
d8a1f426 685 /**
4b734e74 686 * Was this event restored?
d8a1f426
PS
687 *
688 * @return bool
689 */
22626564 690 public final function is_restored() {
d8a1f426
PS
691 return $this->restored;
692 }
693
694 /**
695 * Add cached data that will be most probably used in event observers.
696 *
697 * This is used to improve performance, but it is required for data
4b734e74 698 * that was just deleted.
d8a1f426
PS
699 *
700 * @param string $tablename
701 * @param \stdClass $record
300dbc66
PS
702 *
703 * @throws \coding_exception if used after ::trigger()
d8a1f426 704 */
fd4f3e9e 705 public final function add_record_snapshot($tablename, $record) {
96f81ea3 706 global $DB, $CFG;
d8a1f426 707
300dbc66
PS
708 if ($this->triggered) {
709 throw new \coding_exception('It is not possible to add snapshots after triggering of events');
710 }
711
92e2e855
MG
712 // Special case for course module, allow instance of cm_info to be passed instead of stdClass.
713 if ($tablename === 'course_modules' && $record instanceof \cm_info) {
714 $record = $record->get_course_module_record();
715 }
fc755767 716
d8a1f426
PS
717 // NOTE: this might use some kind of MUC cache,
718 // hopefully we will not run out of memory here...
96f81ea3 719 if ($CFG->debugdeveloper) {
92e2e855
MG
720 if (!($record instanceof \stdClass)) {
721 debugging('Argument $record must be an instance of stdClass.', DEBUG_DEVELOPER);
722 }
d8a1f426 723 if (!$DB->get_manager()->table_exists($tablename)) {
96f81ea3 724 debugging("Invalid table name '$tablename' specified, database table does not exist.", DEBUG_DEVELOPER);
5e70ea26
MG
725 } else {
726 $columns = $DB->get_columns($tablename);
727 $missingfields = array_diff(array_keys($columns), array_keys((array)$record));
728 if (!empty($missingfields)) {
729 debugging("Fields list in snapshot record does not match fields list in '$tablename'. Record is missing fields: ".
730 join(', ', $missingfields), DEBUG_DEVELOPER);
731 }
d8a1f426
PS
732 }
733 }
b396d40e 734 $this->recordsnapshots[$tablename][$record->id] = $record;
d8a1f426
PS
735 }
736
737 /**
738 * Returns cached record or fetches data from database if not cached.
739 *
740 * @param string $tablename
741 * @param int $id
742 * @return \stdClass
4ad6d5c5
PS
743 *
744 * @throws \coding_exception if used after ::restore()
d8a1f426 745 */
fd4f3e9e 746 public final function get_record_snapshot($tablename, $id) {
d8a1f426
PS
747 global $DB;
748
4ad6d5c5
PS
749 if ($this->restored) {
750 throw new \coding_exception('It is not possible to get snapshots from restored events');
751 }
752
b396d40e 753 if (isset($this->recordsnapshots[$tablename][$id])) {
5e70ea26 754 return clone($this->recordsnapshots[$tablename][$id]);
d8a1f426
PS
755 }
756
757 $record = $DB->get_record($tablename, array('id'=>$id));
b396d40e 758 $this->recordsnapshots[$tablename][$id] = $record;
d8a1f426
PS
759
760 return $record;
761 }
762
763 /**
764 * Magic getter for read only access.
765 *
d8a1f426
PS
766 * @param string $name
767 * @return mixed
d8a1f426
PS
768 */
769 public function __get($name) {
3345e24f
770 if ($name === 'level') {
771 debugging('level property is deprecated, use edulevel property instead', DEBUG_DEVELOPER);
772 return $this->data['edulevel'];
773 }
d8a1f426
PS
774 if (array_key_exists($name, $this->data)) {
775 return $this->data[$name];
776 }
777
4b734e74 778 debugging("Accessing non-existent event property '$name'");
d8a1f426 779 }
605a8c33
PS
780
781 /**
782 * Magic setter.
783 *
784 * Note: we must not allow modification of data from outside,
785 * after trigger() the data MUST NOT CHANGE!!!
786 *
787 * @param string $name
788 * @param mixed $value
789 *
790 * @throws \coding_exception
791 */
792 public function __set($name, $value) {
793 throw new \coding_exception('Event properties must not be modified.');
794 }
795
796 /**
797 * Is data property set?
798 *
799 * @param string $name
800 * @return bool
801 */
802 public function __isset($name) {
3345e24f
803 if ($name === 'level') {
804 debugging('level property is deprecated, use edulevel property instead', DEBUG_DEVELOPER);
805 return isset($this->data['edulevel']);
806 }
605a8c33
PS
807 return isset($this->data[$name]);
808 }
ed17808d
PS
809
810 /**
811 * Create an iterator because magic vars can't be seen by 'foreach'.
812 *
813 * @return \ArrayIterator
814 */
815 public function getIterator() {
816 return new \ArrayIterator($this->data);
817 }
d8a1f426 818}