MDL-41269 disable all logging during phpunit testing
[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 }
232 }
233
c61a3a5c 234 // Let developers validate their custom data (such as $this->data['other'], contextlevel, etc.).
fddd1018
PS
235 $event->validate_data();
236
d8a1f426
PS
237 return $event;
238 }
239
240 /**
241 * Override in subclass.
242 *
243 * Set all required data properties:
38d6fbfa 244 * 1/ crud - letter [crud]
3345e24f 245 * 2/ edulevel - using a constant self::LEVEL_*.
a85258ca 246 * 3/ objecttable - name of database table if objectid specified
4b734e74 247 *
fddd1018
PS
248 * Optionally it can set:
249 * a/ fixed system context
d8a1f426
PS
250 *
251 * @return void
252 */
253 protected abstract function init();
254
fddd1018 255 /**
c61a3a5c 256 * Let developers validate their custom data (such as $this->data['other'], contextlevel, etc.).
fddd1018
PS
257 *
258 * Throw \coding_exception or debugging() notice in case of any problems.
259 */
260 protected function validate_data() {
261 // Override if you want to validate event properties when
262 // creating new events.
263 }
264
4b734e74
PS
265 /**
266 * Returns localised general event name.
267 *
268 * Override in subclass, we can not make it static and abstract at the same time.
269 *
fc9fc9fb 270 * @return string
4b734e74
PS
271 */
272 public static function get_name() {
273 // Override in subclass with real lang string.
1ccc1268 274 $parts = explode('\\', get_called_class());
4b734e74 275 if (count($parts) !== 3) {
fc9fc9fb 276 return get_string('unknownevent', 'error');
4b734e74
PS
277 }
278 return $parts[0].': '.str_replace('_', ' ', $parts[2]);
279 }
280
281 /**
fc9fc9fb 282 * Returns non-localised event description with id's for admin use only.
05a970d3 283 *
fc9fc9fb 284 * @return string
4b734e74
PS
285 */
286 public function get_description() {
287 return null;
288 }
289
290 /**
291 * Define whether a user can view the event or not.
292 *
293 * @param int|\stdClass $user_or_id ID of the user.
294 * @return bool True if the user can view the event, false otherwise.
295 */
296 public function can_view($user_or_id = null) {
297 return is_siteadmin($user_or_id);
298 }
299
d8a1f426
PS
300 /**
301 * Restore event from existing historic data.
302 *
303 * @param array $data
b0cdc969 304 * @param array $logextra the format is standardised by logging API
d8a1f426
PS
305 * @return bool|\core\event\base
306 */
b0cdc969 307 public static final function restore(array $data, array $logextra) {
d8a1f426
PS
308 $classname = $data['eventname'];
309 $component = $data['component'];
310 $action = $data['action'];
132eff90 311 $target = $data['target'];
d8a1f426
PS
312
313 // Security: make 100% sure this really is an event class.
132eff90 314 if ($classname !== "\\{$component}\\event\\{$target}_{$action}") {
d8a1f426
PS
315 return false;
316 }
317
318 if (!class_exists($classname)) {
319 return false;
320 }
321 $event = new $classname();
322 if (!($event instanceof \core\event\base)) {
323 return false;
324 }
325
d8a1f426 326 $event->restored = true;
22626564
PS
327 $event->triggered = true;
328 $event->dispatched = true;
b0cdc969 329 $event->logextra = $logextra;
d8a1f426
PS
330
331 foreach (self::$fields as $key) {
4b734e74 332 if (!array_key_exists($key, $data)) {
d8a1f426 333 debugging("Event restore data must contain key $key");
4b734e74 334 $data[$key] = null;
d8a1f426
PS
335 }
336 }
4b734e74
PS
337 if (count($data) != count(self::$fields)) {
338 foreach ($data as $key => $value) {
339 if (!in_array($key, self::$fields)) {
340 debugging("Event restore data cannot contain key $key");
341 unset($data[$key]);
342 }
343 }
344 }
345 $event->data = $data;
d8a1f426
PS
346
347 return $event;
348 }
349
7eaca5a8
350 /**
351 * Create fake event from legacy log data.
352 *
353 * @param stdClass $legacy
354 * @return base
355 */
356 public static final function restore_legacy($legacy) {
357 $classname = get_called_class();
358 $event = new $classname();
359 $event->restored = true;
360 $event->triggered = true;
361 $event->dispatched = true;
362
363 $context = false;
364 $component = 'legacy';
365 if ($legacy->cmid) {
366 $context = \context_module::instance($legacy->cmid, IGNORE_MISSING);
367 $component = 'mod_'.$legacy->module;
368 } else if ($legacy->course) {
369 $context = \context_course::instance($legacy->course, IGNORE_MISSING);
370 }
371 if (!$context) {
372 $context = \context_system::instance();
373 }
374
375 $event->data = array();
376
377 $event->data['eventname'] = $legacy->module.'_'.$legacy->action;
378 $event->data['component'] = $component;
379 $event->data['action'] = $legacy->action;
380 $event->data['target'] = null;
381 $event->data['objecttable'] = null;
382 $event->data['objectid'] = null;
383 if (strpos($legacy->action, 'view') !== false) {
384 $event->data['crud'] = 'r';
385 } else if (strpos($legacy->action, 'print') !== false) {
386 $event->data['crud'] = 'r';
387 } else if (strpos($legacy->action, 'update') !== false) {
388 $event->data['crud'] = 'u';
389 } else if (strpos($legacy->action, 'hide') !== false) {
390 $event->data['crud'] = 'u';
391 } else if (strpos($legacy->action, 'move') !== false) {
392 $event->data['crud'] = 'u';
393 } else if (strpos($legacy->action, 'write') !== false) {
394 $event->data['crud'] = 'u';
395 } else if (strpos($legacy->action, 'tag') !== false) {
396 $event->data['crud'] = 'u';
397 } else if (strpos($legacy->action, 'remove') !== false) {
398 $event->data['crud'] = 'u';
399 } else if (strpos($legacy->action, 'delete') !== false) {
400 $event->data['crud'] = 'p';
401 } else if (strpos($legacy->action, 'create') !== false) {
402 $event->data['crud'] = 'c';
403 } else if (strpos($legacy->action, 'post') !== false) {
404 $event->data['crud'] = 'c';
405 } else if (strpos($legacy->action, 'add') !== false) {
406 $event->data['crud'] = 'c';
407 } else {
408 // End of guessing...
409 $event->data['crud'] = 'r';
410 }
411 $event->data['edulevel'] = $event::LEVEL_OTHER;
412 $event->data['contextid'] = $context->id;
413 $event->data['contextlevel'] = $context->contextlevel;
414 $event->data['contextinstanceid'] = $context->instanceid;
415 $event->data['userid'] = ($legacy->userid ? $legacy->userid : null);
416 $event->data['courseid'] = ($legacy->course ? $legacy->course : null);
417 $event->data['relateduserid'] = ($legacy->userid ? $legacy->userid : null);
418 $event->data['timecreated'] = $legacy->time;
419
420 $event->logextra = array('origin'=>$legacy->ip, 'realuserid'=>null);
421
422 $event->data['other'] = (array)$legacy;
423
424 return $event;
425 }
426
d8a1f426
PS
427 /**
428 * Returns event context.
429 * @return \context
430 */
431 public function get_context() {
432 if (isset($this->context)) {
433 return $this->context;
434 }
fdc729ea 435 $this->context = \context::instance_by_id($this->data['contextid'], IGNORE_MISSING);
d8a1f426
PS
436 return $this->context;
437 }
438
439 /**
440 * Returns relevant URL, override in subclasses.
4b734e74 441 * @return \moodle_url
d8a1f426
PS
442 */
443 public function get_url() {
444 return null;
445 }
446
447 /**
448 * Return standardised event data as array.
449 *
3345e24f 450 * @return array All elements are scalars except the 'other' field which is array.
d8a1f426
PS
451 */
452 public function get_data() {
453 return $this->data;
454 }
455
4b734e74
PS
456 /**
457 * Return auxiliary data that was stored in logs.
458 *
3345e24f
459 * List of standard properties:
460 * - origin: IP number, cli,cron
461 * - realuserid: id of the user when logged-in-as
05a970d3 462 *
4b734e74
PS
463 * @return array the format is standardised by logging API
464 */
b0cdc969
PS
465 public function get_logextra() {
466 return $this->logextra;
4b734e74
PS
467 }
468
d8a1f426
PS
469 /**
470 * Does this event replace legacy event?
471 *
82b1fb51
PS
472 * Note: do not use directly!
473 *
d8a1f426
PS
474 * @return null|string legacy event name
475 */
22446003 476 public static function get_legacy_eventname() {
d8a1f426
PS
477 return null;
478 }
479
480 /**
481 * Legacy event data if get_legacy_eventname() is not empty.
482 *
82b1fb51
PS
483 * Note: do not use directly!
484 *
d8a1f426
PS
485 * @return mixed
486 */
82b1fb51 487 protected function get_legacy_eventdata() {
d8a1f426
PS
488 return null;
489 }
490
491 /**
492 * Doest this event replace add_to_log() statement?
493 *
82b1fb51
PS
494 * Note: do not use directly!
495 *
d8a1f426
PS
496 * @return null|array of parameters to be passed to legacy add_to_log() function.
497 */
82b1fb51 498 protected function get_legacy_logdata() {
d8a1f426
PS
499 return null;
500 }
501
502 /**
503 * Validate all properties right before triggering the event.
504 *
505 * This throws coding exceptions for fatal problems and debugging for minor problems.
506 *
507 * @throws \coding_exception
508 */
509 protected final function validate_before_trigger() {
96f81ea3 510 global $DB, $CFG;
a85258ca 511
d8a1f426
PS
512 if (empty($this->data['crud'])) {
513 throw new \coding_exception('crud must be specified in init() method of each method');
514 }
3345e24f
515 if (!isset($this->data['edulevel'])) {
516 throw new \coding_exception('edulevel must be specified in init() method of each method');
d8a1f426 517 }
a85258ca
PS
518 if (!empty($this->data['objectid']) and empty($this->data['objecttable'])) {
519 throw new \coding_exception('objecttable must be specified in init() method if objectid present');
520 }
d8a1f426 521
96f81ea3 522 if ($CFG->debugdeveloper) {
d8a1f426
PS
523 // Ideally these should be coding exceptions, but we need to skip these for performance reasons
524 // on production servers.
4b734e74
PS
525
526 if (!in_array($this->data['crud'], array('c', 'r', 'u', 'd'), true)) {
96f81ea3 527 debugging("Invalid event crud value specified.", DEBUG_DEVELOPER);
4b734e74 528 }
3345e24f 529 if (!in_array($this->data['edulevel'], array(self::LEVEL_OTHER, self::LEVEL_TEACHING, self::LEVEL_PARTICIPATING))) {
38d6fbfa 530 // Bitwise combination of levels is not allowed at this stage.
3345e24f 531 debugging('Event property edulevel must a constant value, see event_base::LEVEL_*', DEBUG_DEVELOPER);
4b734e74 532 }
d8a1f426 533 if (self::$fields !== array_keys($this->data)) {
96f81ea3 534 debugging('Number of event data fields must not be changed in event classes', DEBUG_DEVELOPER);
d8a1f426 535 }
c4297815 536 $encoded = json_encode($this->data['other']);
49ff1342
AG
537 // The comparison here is not set to strict as whole float numbers will be converted to integers through JSON encoding /
538 // decoding and send an unwanted debugging message.
539 if ($encoded === false or $this->data['other'] != json_decode($encoded, true)) {
96f81ea3 540 debugging('other event data must be compatible with json encoding', DEBUG_DEVELOPER);
4b734e74
PS
541 }
542 if ($this->data['userid'] and !is_number($this->data['userid'])) {
96f81ea3 543 debugging('Event property userid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
544 }
545 if ($this->data['courseid'] and !is_number($this->data['courseid'])) {
96f81ea3 546 debugging('Event property courseid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
547 }
548 if ($this->data['objectid'] and !is_number($this->data['objectid'])) {
96f81ea3 549 debugging('Event property objectid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
550 }
551 if ($this->data['relateduserid'] and !is_number($this->data['relateduserid'])) {
96f81ea3 552 debugging('Event property relateduserid must be a number', DEBUG_DEVELOPER);
d8a1f426 553 }
a85258ca
PS
554 if ($this->data['objecttable']) {
555 if (!$DB->get_manager()->table_exists($this->data['objecttable'])) {
96f81ea3 556 debugging('Unknown table specified in objecttable field', DEBUG_DEVELOPER);
a85258ca 557 }
31e571cd
FM
558 if (!isset($this->data['objectid'])) {
559 debugging('Event property objectid must be set when objecttable is defined', DEBUG_DEVELOPER);
560 }
a85258ca 561 }
d8a1f426
PS
562 }
563 }
564
565 /**
566 * Trigger event.
567 */
568 public final function trigger() {
569 global $CFG;
570
571 if ($this->restored) {
572 throw new \coding_exception('Can not trigger restored event');
573 }
22626564 574 if ($this->triggered or $this->dispatched) {
d8a1f426
PS
575 throw new \coding_exception('Can not trigger event twice');
576 }
577
d8a1f426
PS
578 $this->validate_before_trigger();
579
22626564
PS
580 $this->triggered = true;
581
ef1987dc 582 if (isset($CFG->loglifetime) and $CFG->loglifetime != -1) {
d8a1f426 583 if ($data = $this->get_legacy_logdata()) {
7eaca5a8
584 $manager = get_log_manager();
585 if (method_exists($manager, 'legacy_add_to_log')) {
586 call_user_func_array(array($manager, 'legacy_add_to_log'), $data);
587 }
d8a1f426
PS
588 }
589 }
590
62401e8f
PS
591 if (PHPUNIT_TEST and \phpunit_util::is_redirecting_events()) {
592 $this->dispatched = true;
593 \phpunit_util::event_triggered($this);
594 return;
595 }
596
d8a1f426
PS
597 \core\event\manager::dispatch($this);
598
22626564
PS
599 $this->dispatched = true;
600
22446003 601 if ($legacyeventname = static::get_legacy_eventname()) {
f0f0e1fe 602 events_trigger_legacy($legacyeventname, $this->get_legacy_eventdata());
d8a1f426
PS
603 }
604 }
605
606 /**
22626564 607 * Was this event already triggered?
d8a1f426
PS
608 *
609 * @return bool
610 */
22626564 611 public final function is_triggered() {
d8a1f426
PS
612 return $this->triggered;
613 }
614
22626564
PS
615 /**
616 * Used from event manager to prevent direct access.
617 *
618 * @return bool
619 */
620 public final function is_dispatched() {
621 return $this->dispatched;
622 }
623
d8a1f426 624 /**
4b734e74 625 * Was this event restored?
d8a1f426
PS
626 *
627 * @return bool
628 */
22626564 629 public final function is_restored() {
d8a1f426
PS
630 return $this->restored;
631 }
632
633 /**
634 * Add cached data that will be most probably used in event observers.
635 *
636 * This is used to improve performance, but it is required for data
4b734e74 637 * that was just deleted.
d8a1f426
PS
638 *
639 * @param string $tablename
640 * @param \stdClass $record
300dbc66
PS
641 *
642 * @throws \coding_exception if used after ::trigger()
d8a1f426 643 */
fd4f3e9e 644 public final function add_record_snapshot($tablename, $record) {
96f81ea3 645 global $DB, $CFG;
d8a1f426 646
300dbc66
PS
647 if ($this->triggered) {
648 throw new \coding_exception('It is not possible to add snapshots after triggering of events');
649 }
650
d8a1f426
PS
651 // NOTE: this might use some kind of MUC cache,
652 // hopefully we will not run out of memory here...
96f81ea3 653 if ($CFG->debugdeveloper) {
d8a1f426 654 if (!$DB->get_manager()->table_exists($tablename)) {
96f81ea3 655 debugging("Invalid table name '$tablename' specified, database table does not exist.", DEBUG_DEVELOPER);
d8a1f426
PS
656 }
657 }
b396d40e 658 $this->recordsnapshots[$tablename][$record->id] = $record;
d8a1f426
PS
659 }
660
661 /**
662 * Returns cached record or fetches data from database if not cached.
663 *
664 * @param string $tablename
665 * @param int $id
666 * @return \stdClass
4ad6d5c5
PS
667 *
668 * @throws \coding_exception if used after ::restore()
d8a1f426 669 */
fd4f3e9e 670 public final function get_record_snapshot($tablename, $id) {
d8a1f426
PS
671 global $DB;
672
4ad6d5c5
PS
673 if ($this->restored) {
674 throw new \coding_exception('It is not possible to get snapshots from restored events');
675 }
676
b396d40e
PS
677 if (isset($this->recordsnapshots[$tablename][$id])) {
678 return $this->recordsnapshots[$tablename][$id];
d8a1f426
PS
679 }
680
681 $record = $DB->get_record($tablename, array('id'=>$id));
b396d40e 682 $this->recordsnapshots[$tablename][$id] = $record;
d8a1f426
PS
683
684 return $record;
685 }
686
687 /**
688 * Magic getter for read only access.
689 *
d8a1f426
PS
690 * @param string $name
691 * @return mixed
d8a1f426
PS
692 */
693 public function __get($name) {
3345e24f
694 if ($name === 'level') {
695 debugging('level property is deprecated, use edulevel property instead', DEBUG_DEVELOPER);
696 return $this->data['edulevel'];
697 }
d8a1f426
PS
698 if (array_key_exists($name, $this->data)) {
699 return $this->data[$name];
700 }
701
4b734e74 702 debugging("Accessing non-existent event property '$name'");
d8a1f426 703 }
605a8c33
PS
704
705 /**
706 * Magic setter.
707 *
708 * Note: we must not allow modification of data from outside,
709 * after trigger() the data MUST NOT CHANGE!!!
710 *
711 * @param string $name
712 * @param mixed $value
713 *
714 * @throws \coding_exception
715 */
716 public function __set($name, $value) {
717 throw new \coding_exception('Event properties must not be modified.');
718 }
719
720 /**
721 * Is data property set?
722 *
723 * @param string $name
724 * @return bool
725 */
726 public function __isset($name) {
3345e24f
727 if ($name === 'level') {
728 debugging('level property is deprecated, use edulevel property instead', DEBUG_DEVELOPER);
729 return isset($this->data['edulevel']);
730 }
605a8c33
PS
731 return isset($this->data[$name]);
732 }
ed17808d
PS
733
734 /**
735 * Create an iterator because magic vars can't be seen by 'foreach'.
736 *
737 * @return \ArrayIterator
738 */
739 public function getIterator() {
740 return new \ArrayIterator($this->data);
741 }
d8a1f426 742}