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