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