weekly release 3.3dev
[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?
b64af72c 49 * @property-read int $courseid the courseid of the event context, 0 for contexts above course
d8a1f426 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
6920d390
MN
78 /**
79 * The value used when an id can not be mapped during a restore.
80 */
81 const NOT_MAPPED = -31337;
82
f74fe5ba
MN
83 /**
84 * The value used when an id can not be found during a restore.
85 */
86 const NOT_FOUND = -31338;
87
d8a1f426
PS
88 /** @var array event data */
89 protected $data;
90
4b734e74 91 /** @var array the format is standardised by logging API */
b0cdc969 92 protected $logextra;
4b734e74 93
d8a1f426
PS
94 /** @var \context of this event */
95 protected $context;
96
22626564
PS
97 /**
98 * @var bool indicates if event was already triggered,
99 * this prevents second attempt to trigger event.
100 */
d8a1f426
PS
101 private $triggered;
102
22626564
PS
103 /**
104 * @var bool indicates if event was already dispatched,
105 * this prevents direct calling of manager::dispatch($event).
106 */
107 private $dispatched;
108
109 /**
110 * @var bool indicates if event was restored from storage,
111 * this prevents triggering of restored events.
112 */
d8a1f426
PS
113 private $restored;
114
115 /** @var array list of event properties */
116 private static $fields = array(
3345e24f 117 'eventname', 'component', 'action', 'target', 'objecttable', 'objectid', 'crud', 'edulevel', 'contextid',
bc293202 118 'contextlevel', 'contextinstanceid', 'userid', 'courseid', 'relateduserid', 'anonymous', 'other',
4b734e74 119 'timecreated');
d8a1f426
PS
120
121 /** @var array simple record cache */
fd4f3e9e 122 private $recordsnapshots = array();
d8a1f426
PS
123
124 /**
125 * Private constructor, use create() or restore() methods instead.
126 */
127 private final function __construct() {
128 $this->data = array_fill_keys(self::$fields, null);
b6c7ab22
AA
129
130 // Define some basic details.
131 $classname = get_called_class();
132 $parts = explode('\\', $classname);
133 if (count($parts) !== 3 or $parts[1] !== 'event') {
134 throw new \coding_exception("Invalid event class name '$classname', it must be defined in component\\event\\
135 namespace");
136 }
137 $this->data['eventname'] = '\\'.$classname;
138 $this->data['component'] = $parts[0];
139
140 $pos = strrpos($parts[2], '_');
141 if ($pos === false) {
142 throw new \coding_exception("Invalid event class name '$classname', there must be at least one underscore separating
143 object and action words");
144 }
145 $this->data['target'] = substr($parts[2], 0, $pos);
146 $this->data['action'] = substr($parts[2], $pos + 1);
d8a1f426
PS
147 }
148
149 /**
150 * Create new event.
151 *
152 * The optional data keys as:
153 * 1/ objectid - the id of the object specified in class name
154 * 2/ context - the context of this event
c4297815 155 * 3/ other - the other data describing the event, can not contain objects
d8a1f426
PS
156 * 4/ relateduserid - the id of user which is somehow related to this event
157 *
158 * @param array $data
159 * @return \core\event\base returns instance of new event
160 *
161 * @throws \coding_exception
162 */
163 public static final function create(array $data = null) {
3345e24f 164 global $USER, $CFG;
d8a1f426
PS
165
166 $data = (array)$data;
167
168 /** @var \core\event\base $event */
169 $event = new static();
170 $event->triggered = false;
171 $event->restored = false;
22626564 172 $event->dispatched = false;
d8a1f426 173
bc293202
174 // By default all events are visible in logs.
175 $event->data['anonymous'] = 0;
176
fb23739e
PS
177 // Set static event data specific for child class.
178 $event->init();
179
3345e24f
180 if (isset($event->data['level'])) {
181 if (!isset($event->data['edulevel'])) {
182 debugging('level property is deprecated, use edulevel property instead', DEBUG_DEVELOPER);
183 $event->data['edulevel'] = $event->data['level'];
184 }
185 unset($event->data['level']);
186 }
187
4b734e74
PS
188 // Set automatic data.
189 $event->data['timecreated'] = time();
190
4b734e74 191 // Set optional data or use defaults.
d8a1f426
PS
192 $event->data['objectid'] = isset($data['objectid']) ? $data['objectid'] : null;
193 $event->data['courseid'] = isset($data['courseid']) ? $data['courseid'] : null;
194 $event->data['userid'] = isset($data['userid']) ? $data['userid'] : $USER->id;
c4297815 195 $event->data['other'] = isset($data['other']) ? $data['other'] : null;
d8a1f426 196 $event->data['relateduserid'] = isset($data['relateduserid']) ? $data['relateduserid'] : null;
bc293202
197 if (isset($data['anonymous'])) {
198 $event->data['anonymous'] = $data['anonymous'];
199 }
200 $event->data['anonymous'] = (int)(bool)$event->data['anonymous'];
d8a1f426 201
fddd1018 202 if (isset($event->context)) {
097011c4
PS
203 if (isset($data['context'])) {
204 debugging('Context was already set in init() method, ignoring context parameter', DEBUG_DEVELOPER);
fddd1018 205 }
fddd1018
PS
206
207 } else if (!empty($data['context'])) {
d8a1f426 208 $event->context = $data['context'];
27af3e62
PS
209
210 } else if (!empty($data['contextid'])) {
097011c4
PS
211 $event->context = \context::instance_by_id($data['contextid'], MUST_EXIST);
212
27af3e62 213 } else {
fddd1018 214 throw new \coding_exception('context (or contextid) is a required event property, system context may be hardcoded in init() method.');
d8a1f426 215 }
d8a1f426 216
097011c4
PS
217 $event->data['contextid'] = $event->context->id;
218 $event->data['contextlevel'] = $event->context->contextlevel;
219 $event->data['contextinstanceid'] = $event->context->instanceid;
220
d8a1f426 221 if (!isset($event->data['courseid'])) {
097011c4 222 if ($coursecontext = $event->context->get_course_context(false)) {
513d8793 223 $event->data['courseid'] = $coursecontext->instanceid;
d8a1f426
PS
224 } else {
225 $event->data['courseid'] = 0;
226 }
227 }
228
097011c4 229 if (!array_key_exists('relateduserid', $data) and $event->context->contextlevel == CONTEXT_USER) {
d8a1f426
PS
230 $event->data['relateduserid'] = $event->context->instanceid;
231 }
232
4b734e74 233 // Warn developers if they do something wrong.
96f81ea3 234 if ($CFG->debugdeveloper) {
660f049f 235 static $automatickeys = array('eventname', 'component', 'action', 'target', 'contextlevel', 'contextinstanceid', 'timecreated');
3345e24f 236 static $initkeys = array('crud', 'level', 'objecttable', 'edulevel');
4b734e74
PS
237
238 foreach ($data as $key => $ignored) {
239 if ($key === 'context') {
240 continue;
241
242 } else if (in_array($key, $automatickeys)) {
96f81ea3 243 debugging("Data key '$key' is not allowed in \\core\\event\\base::create() method, it is set automatically", DEBUG_DEVELOPER);
4b734e74
PS
244
245 } else if (in_array($key, $initkeys)) {
96f81ea3 246 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
247
248 } else if (!in_array($key, self::$fields)) {
249 debugging("Data key '$key' does not exist in \\core\\event\\base");
d8a1f426
PS
250 }
251 }
9ede00db
252 $expectedcourseid = 0;
253 if ($coursecontext = $event->context->get_course_context(false)) {
254 $expectedcourseid = $coursecontext->instanceid;
255 }
256 if ($expectedcourseid != $event->data['courseid']) {
257 debugging("Inconsistent courseid - context combination detected.", DEBUG_DEVELOPER);
258 }
d8a1f426
PS
259 }
260
c61a3a5c 261 // Let developers validate their custom data (such as $this->data['other'], contextlevel, etc.).
fddd1018
PS
262 $event->validate_data();
263
d8a1f426
PS
264 return $event;
265 }
266
267 /**
268 * Override in subclass.
269 *
270 * Set all required data properties:
38d6fbfa 271 * 1/ crud - letter [crud]
3345e24f 272 * 2/ edulevel - using a constant self::LEVEL_*.
a85258ca 273 * 3/ objecttable - name of database table if objectid specified
4b734e74 274 *
fddd1018
PS
275 * Optionally it can set:
276 * a/ fixed system context
d8a1f426
PS
277 *
278 * @return void
279 */
280 protected abstract function init();
281
fddd1018 282 /**
c61a3a5c 283 * Let developers validate their custom data (such as $this->data['other'], contextlevel, etc.).
fddd1018
PS
284 *
285 * Throw \coding_exception or debugging() notice in case of any problems.
286 */
287 protected function validate_data() {
288 // Override if you want to validate event properties when
289 // creating new events.
290 }
291
4b734e74
PS
292 /**
293 * Returns localised general event name.
294 *
295 * Override in subclass, we can not make it static and abstract at the same time.
296 *
fc9fc9fb 297 * @return string
4b734e74
PS
298 */
299 public static function get_name() {
300 // Override in subclass with real lang string.
1ccc1268 301 $parts = explode('\\', get_called_class());
4b734e74 302 if (count($parts) !== 3) {
fc9fc9fb 303 return get_string('unknownevent', 'error');
4b734e74
PS
304 }
305 return $parts[0].': '.str_replace('_', ' ', $parts[2]);
306 }
307
51d85c7c
AN
308 /**
309 * Returns the event name complete with metadata information.
310 *
311 * This includes information about whether the event has been deprecated so should not be used in all situations -
312 * for example within reports themselves.
313 *
314 * If overriding this function, please ensure that you call the parent version too.
315 *
316 * @return string
317 */
318 public static function get_name_with_info() {
319 $return = static::get_name();
320
321 if (static::is_deprecated()) {
322 $return = get_string('deprecatedeventname', 'core', $return);
323 }
324
325 return $return;
326 }
327
4b734e74 328 /**
fc9fc9fb 329 * Returns non-localised event description with id's for admin use only.
05a970d3 330 *
fc9fc9fb 331 * @return string
4b734e74
PS
332 */
333 public function get_description() {
334 return null;
335 }
336
337 /**
bc22fa93
338 * This method was originally intended for granular
339 * access control on the event level, unfortunately
340 * the proper implementation would be too expensive
341 * in many cases.
342 *
343 * @deprecated since 2.7
4b734e74
PS
344 *
345 * @param int|\stdClass $user_or_id ID of the user.
346 * @return bool True if the user can view the event, false otherwise.
347 */
348 public function can_view($user_or_id = null) {
15f009e1 349 debugging('can_view() method is deprecated, use anonymous flag instead if necessary.', DEBUG_DEVELOPER);
4b734e74
PS
350 return is_siteadmin($user_or_id);
351 }
352
d8a1f426
PS
353 /**
354 * Restore event from existing historic data.
355 *
356 * @param array $data
b0cdc969 357 * @param array $logextra the format is standardised by logging API
d8a1f426
PS
358 * @return bool|\core\event\base
359 */
b0cdc969 360 public static final function restore(array $data, array $logextra) {
d8a1f426
PS
361 $classname = $data['eventname'];
362 $component = $data['component'];
363 $action = $data['action'];
132eff90 364 $target = $data['target'];
d8a1f426
PS
365
366 // Security: make 100% sure this really is an event class.
132eff90 367 if ($classname !== "\\{$component}\\event\\{$target}_{$action}") {
d8a1f426
PS
368 return false;
369 }
370
371 if (!class_exists($classname)) {
d409944a 372 return self::restore_unknown($data, $logextra);
d8a1f426
PS
373 }
374 $event = new $classname();
375 if (!($event instanceof \core\event\base)) {
376 return false;
377 }
378
85a4b8a3 379 $event->init(); // Init method of events could be setting custom properties.
d8a1f426 380 $event->restored = true;
22626564
PS
381 $event->triggered = true;
382 $event->dispatched = true;
b0cdc969 383 $event->logextra = $logextra;
d8a1f426
PS
384
385 foreach (self::$fields as $key) {
4b734e74 386 if (!array_key_exists($key, $data)) {
d8a1f426 387 debugging("Event restore data must contain key $key");
4b734e74 388 $data[$key] = null;
d8a1f426
PS
389 }
390 }
4b734e74
PS
391 if (count($data) != count(self::$fields)) {
392 foreach ($data as $key => $value) {
393 if (!in_array($key, self::$fields)) {
394 debugging("Event restore data cannot contain key $key");
395 unset($data[$key]);
396 }
397 }
398 }
399 $event->data = $data;
d8a1f426
PS
400
401 return $event;
402 }
403
d409944a
PS
404 /**
405 * Restore unknown event.
406 *
407 * @param array $data
408 * @param array $logextra
409 * @return unknown_logged
410 */
411 protected static final function restore_unknown(array $data, array $logextra) {
412 $classname = '\core\event\unknown_logged';
413
414 /** @var unknown_logged $event */
415 $event = new $classname();
416 $event->restored = true;
417 $event->triggered = true;
418 $event->dispatched = true;
419 $event->data = $data;
420 $event->logextra = $logextra;
421
422 return $event;
423 }
424
7eaca5a8
425 /**
426 * Create fake event from legacy log data.
427 *
81fbecc0 428 * @param \stdClass $legacy
7eaca5a8
429 * @return base
430 */
431 public static final function restore_legacy($legacy) {
432 $classname = get_called_class();
81fbecc0 433 /** @var base $event */
7eaca5a8
434 $event = new $classname();
435 $event->restored = true;
436 $event->triggered = true;
437 $event->dispatched = true;
438
439 $context = false;
440 $component = 'legacy';
441 if ($legacy->cmid) {
442 $context = \context_module::instance($legacy->cmid, IGNORE_MISSING);
443 $component = 'mod_'.$legacy->module;
444 } else if ($legacy->course) {
445 $context = \context_course::instance($legacy->course, IGNORE_MISSING);
446 }
447 if (!$context) {
448 $context = \context_system::instance();
449 }
450
451 $event->data = array();
452
453 $event->data['eventname'] = $legacy->module.'_'.$legacy->action;
454 $event->data['component'] = $component;
455 $event->data['action'] = $legacy->action;
456 $event->data['target'] = null;
457 $event->data['objecttable'] = null;
458 $event->data['objectid'] = null;
459 if (strpos($legacy->action, 'view') !== false) {
460 $event->data['crud'] = 'r';
461 } else if (strpos($legacy->action, 'print') !== false) {
462 $event->data['crud'] = 'r';
463 } else if (strpos($legacy->action, 'update') !== false) {
464 $event->data['crud'] = 'u';
465 } else if (strpos($legacy->action, 'hide') !== false) {
466 $event->data['crud'] = 'u';
467 } else if (strpos($legacy->action, 'move') !== false) {
468 $event->data['crud'] = 'u';
469 } else if (strpos($legacy->action, 'write') !== false) {
470 $event->data['crud'] = 'u';
471 } else if (strpos($legacy->action, 'tag') !== false) {
472 $event->data['crud'] = 'u';
473 } else if (strpos($legacy->action, 'remove') !== false) {
474 $event->data['crud'] = 'u';
475 } else if (strpos($legacy->action, 'delete') !== false) {
476 $event->data['crud'] = 'p';
477 } else if (strpos($legacy->action, 'create') !== false) {
478 $event->data['crud'] = 'c';
479 } else if (strpos($legacy->action, 'post') !== false) {
480 $event->data['crud'] = 'c';
481 } else if (strpos($legacy->action, 'add') !== false) {
482 $event->data['crud'] = 'c';
483 } else {
484 // End of guessing...
485 $event->data['crud'] = 'r';
486 }
487 $event->data['edulevel'] = $event::LEVEL_OTHER;
488 $event->data['contextid'] = $context->id;
489 $event->data['contextlevel'] = $context->contextlevel;
490 $event->data['contextinstanceid'] = $context->instanceid;
491 $event->data['userid'] = ($legacy->userid ? $legacy->userid : null);
492 $event->data['courseid'] = ($legacy->course ? $legacy->course : null);
493 $event->data['relateduserid'] = ($legacy->userid ? $legacy->userid : null);
494 $event->data['timecreated'] = $legacy->time;
495
81fbecc0
496 $event->logextra = array();
497 if ($legacy->ip) {
498 $event->logextra['origin'] = 'web';
499 $event->logextra['ip'] = $legacy->ip;
500 } else {
501 $event->logextra['origin'] = 'cli';
502 $event->logextra['ip'] = null;
503 }
504 $event->logextra['realuserid'] = null;
7eaca5a8
505
506 $event->data['other'] = (array)$legacy;
507
508 return $event;
509 }
510
6920d390
MN
511 /**
512 * This is used when restoring course logs where it is required that we
513 * map the objectid to it's new value in the new course.
514 *
515 * Does nothing in the base class except display a debugging message warning
516 * the user that the event does not contain the required functionality to
517 * map this information. For events that do not store an objectid this won't
518 * be called, so no debugging message will be displayed.
519 *
520 * Example of usage:
521 *
522 * return array('db' => 'assign_submissions', 'restore' => 'submission');
523 *
524 * If the objectid can not be mapped during restore set the value to \core\event\base::NOT_MAPPED, example -
525 *
526 * return array('db' => 'some_table', 'restore' => \core\event\base::NOT_MAPPED);
527 *
528 * Note - it isn't necessary to specify the 'db' and 'restore' values in this case, so you can also use -
529 *
530 * return \core\event\base::NOT_MAPPED;
531 *
532 * The 'db' key refers to the database table and the 'restore' key refers to
533 * the name of the restore element the objectid is associated with. In many
534 * cases these will be the same.
535 *
536 * @return string the name of the restore mapping the objectid links to
537 */
538 public static function get_objectid_mapping() {
63b5a5fa 539 debugging('In order to restore course logs accurately the event "' . get_called_class() . '" must define the
6920d390
MN
540 function get_objectid_mapping().', DEBUG_DEVELOPER);
541
542 return false;
543 }
544
901a7ff7
MN
545 /**
546 * This is used when restoring course logs where it is required that we
547 * map the information in 'other' to it's new value in the new course.
548 *
549 * Does nothing in the base class except display a debugging message warning
550 * the user that the event does not contain the required functionality to
551 * map this information. For events that do not store any other information this
552 * won't be called, so no debugging message will be displayed.
553 *
554 * Example of usage:
555 *
556 * $othermapped = array();
557 * $othermapped['discussionid'] = array('db' => 'forum_discussions', 'restore' => 'forum_discussion');
558 * $othermapped['forumid'] = array('db' => 'forum', 'restore' => 'forum');
559 * return $othermapped;
560 *
561 * If an id can not be mapped during restore we set it to \core\event\base::NOT_MAPPED, example -
562 *
563 * $othermapped = array();
564 * $othermapped['someid'] = array('db' => 'some_table', 'restore' => \core\event\base::NOT_MAPPED);
565 * return $othermapped;
566 *
567 * Note - it isn't necessary to specify the 'db' and 'restore' values in this case, so you can also use -
568 *
569 * $othermapped = array();
570 * $othermapped['someid'] = \core\event\base::NOT_MAPPED;
571 * return $othermapped;
572 *
573 * The 'db' key refers to the database table and the 'restore' key refers to
574 * the name of the restore element the other value is associated with. In many
575 * cases these will be the same.
576 *
577 * @return array an array of other values and their corresponding mapping
578 */
579 public static function get_other_mapping() {
63b5a5fa 580 debugging('In order to restore course logs accurately the event "' . get_called_class() . '" must define the
901a7ff7
MN
581 function get_other_mapping().', DEBUG_DEVELOPER);
582 }
583
cc662b06
AG
584 /**
585 * Get static information about an event.
586 * This is used in reports and is not for general use.
587 *
588 * @return array Static information about the event.
589 */
590 public static final function get_static_info() {
591 /** Var \core\event\base $event. */
592 $event = new static();
593 // Set static event data specific for child class.
594 $event->init();
595 return array(
596 'eventname' => $event->data['eventname'],
597 'component' => $event->data['component'],
598 'target' => $event->data['target'],
599 'action' => $event->data['action'],
600 'crud' => $event->data['crud'],
601 'edulevel' => $event->data['edulevel'],
602 'objecttable' => $event->data['objecttable'],
603 );
604 }
605
606 /**
607 * Get an explanation of what the class does.
608 * By default returns the phpdocs from the child event class. Ideally this should
609 * be overridden to return a translatable get_string style markdown.
610 * e.g. return new lang_string('eventyourspecialevent', 'plugin_type');
611 *
612 * @return string An explanation of the event formatted in markdown style.
613 */
614 public static function get_explanation() {
615 $ref = new \ReflectionClass(get_called_class());
616 $docblock = $ref->getDocComment();
617
618 // Check that there is something to work on.
619 if (empty($docblock)) {
620 return null;
621 }
622
623 $docblocklines = explode("\n", $docblock);
624 // Remove the bulk of the comment characters.
625 $pattern = "/(^\s*\/\*\*|^\s+\*\s|^\s+\*)/";
626 $cleanline = array();
627 foreach ($docblocklines as $line) {
628 $templine = preg_replace($pattern, '', $line);
629 // If there is nothing on the line then don't add it to the array.
630 if (!empty($templine)) {
631 $cleanline[] = rtrim($templine);
632 }
633 // If we get to a line starting with an @ symbol then we don't want the rest.
634 if (preg_match("/^@|\//", $templine)) {
635 // Get rid of the last entry (it contains an @ symbol).
636 array_pop($cleanline);
637 // Break out of this foreach loop.
638 break;
639 }
640 }
641 // Add a line break to the sanitised lines.
642 $explanation = implode("\n", $cleanline);
643
644 return $explanation;
645 }
646
d8a1f426
PS
647 /**
648 * Returns event context.
649 * @return \context
650 */
651 public function get_context() {
652 if (isset($this->context)) {
653 return $this->context;
654 }
fdc729ea 655 $this->context = \context::instance_by_id($this->data['contextid'], IGNORE_MISSING);
d8a1f426
PS
656 return $this->context;
657 }
658
659 /**
660 * Returns relevant URL, override in subclasses.
4b734e74 661 * @return \moodle_url
d8a1f426
PS
662 */
663 public function get_url() {
664 return null;
665 }
666
667 /**
668 * Return standardised event data as array.
669 *
3345e24f 670 * @return array All elements are scalars except the 'other' field which is array.
d8a1f426
PS
671 */
672 public function get_data() {
673 return $this->data;
674 }
675
4b734e74
PS
676 /**
677 * Return auxiliary data that was stored in logs.
678 *
3345e24f
679 * List of standard properties:
680 * - origin: IP number, cli,cron
681 * - realuserid: id of the user when logged-in-as
05a970d3 682 *
4b734e74
PS
683 * @return array the format is standardised by logging API
684 */
b0cdc969
PS
685 public function get_logextra() {
686 return $this->logextra;
4b734e74
PS
687 }
688
d8a1f426
PS
689 /**
690 * Does this event replace legacy event?
691 *
82b1fb51
PS
692 * Note: do not use directly!
693 *
d8a1f426
PS
694 * @return null|string legacy event name
695 */
22446003 696 public static function get_legacy_eventname() {
d8a1f426
PS
697 return null;
698 }
699
700 /**
701 * Legacy event data if get_legacy_eventname() is not empty.
702 *
82b1fb51
PS
703 * Note: do not use directly!
704 *
d8a1f426
PS
705 * @return mixed
706 */
82b1fb51 707 protected function get_legacy_eventdata() {
d8a1f426
PS
708 return null;
709 }
710
711 /**
712 * Doest this event replace add_to_log() statement?
713 *
82b1fb51
PS
714 * Note: do not use directly!
715 *
d8a1f426
PS
716 * @return null|array of parameters to be passed to legacy add_to_log() function.
717 */
82b1fb51 718 protected function get_legacy_logdata() {
d8a1f426
PS
719 return null;
720 }
721
722 /**
723 * Validate all properties right before triggering the event.
724 *
725 * This throws coding exceptions for fatal problems and debugging for minor problems.
726 *
727 * @throws \coding_exception
728 */
729 protected final function validate_before_trigger() {
96f81ea3 730 global $DB, $CFG;
a85258ca 731
d8a1f426
PS
732 if (empty($this->data['crud'])) {
733 throw new \coding_exception('crud must be specified in init() method of each method');
734 }
3345e24f
735 if (!isset($this->data['edulevel'])) {
736 throw new \coding_exception('edulevel must be specified in init() method of each method');
d8a1f426 737 }
a85258ca
PS
738 if (!empty($this->data['objectid']) and empty($this->data['objecttable'])) {
739 throw new \coding_exception('objecttable must be specified in init() method if objectid present');
740 }
d8a1f426 741
96f81ea3 742 if ($CFG->debugdeveloper) {
d8a1f426
PS
743 // Ideally these should be coding exceptions, but we need to skip these for performance reasons
744 // on production servers.
4b734e74
PS
745
746 if (!in_array($this->data['crud'], array('c', 'r', 'u', 'd'), true)) {
96f81ea3 747 debugging("Invalid event crud value specified.", DEBUG_DEVELOPER);
4b734e74 748 }
3345e24f 749 if (!in_array($this->data['edulevel'], array(self::LEVEL_OTHER, self::LEVEL_TEACHING, self::LEVEL_PARTICIPATING))) {
38d6fbfa 750 // Bitwise combination of levels is not allowed at this stage.
3345e24f 751 debugging('Event property edulevel must a constant value, see event_base::LEVEL_*', DEBUG_DEVELOPER);
4b734e74 752 }
d8a1f426 753 if (self::$fields !== array_keys($this->data)) {
96f81ea3 754 debugging('Number of event data fields must not be changed in event classes', DEBUG_DEVELOPER);
d8a1f426 755 }
c4297815 756 $encoded = json_encode($this->data['other']);
49ff1342
AG
757 // The comparison here is not set to strict as whole float numbers will be converted to integers through JSON encoding /
758 // decoding and send an unwanted debugging message.
759 if ($encoded === false or $this->data['other'] != json_decode($encoded, true)) {
96f81ea3 760 debugging('other event data must be compatible with json encoding', DEBUG_DEVELOPER);
4b734e74
PS
761 }
762 if ($this->data['userid'] and !is_number($this->data['userid'])) {
96f81ea3 763 debugging('Event property userid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
764 }
765 if ($this->data['courseid'] and !is_number($this->data['courseid'])) {
96f81ea3 766 debugging('Event property courseid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
767 }
768 if ($this->data['objectid'] and !is_number($this->data['objectid'])) {
96f81ea3 769 debugging('Event property objectid must be a number', DEBUG_DEVELOPER);
4b734e74
PS
770 }
771 if ($this->data['relateduserid'] and !is_number($this->data['relateduserid'])) {
96f81ea3 772 debugging('Event property relateduserid must be a number', DEBUG_DEVELOPER);
d8a1f426 773 }
a85258ca
PS
774 if ($this->data['objecttable']) {
775 if (!$DB->get_manager()->table_exists($this->data['objecttable'])) {
96f81ea3 776 debugging('Unknown table specified in objecttable field', DEBUG_DEVELOPER);
a85258ca 777 }
31e571cd
FM
778 if (!isset($this->data['objectid'])) {
779 debugging('Event property objectid must be set when objecttable is defined', DEBUG_DEVELOPER);
780 }
a85258ca 781 }
d8a1f426
PS
782 }
783 }
784
785 /**
786 * Trigger event.
787 */
788 public final function trigger() {
789 global $CFG;
790
791 if ($this->restored) {
792 throw new \coding_exception('Can not trigger restored event');
793 }
22626564 794 if ($this->triggered or $this->dispatched) {
d8a1f426
PS
795 throw new \coding_exception('Can not trigger event twice');
796 }
797
d8a1f426
PS
798 $this->validate_before_trigger();
799
22626564
PS
800 $this->triggered = true;
801
ef1987dc 802 if (isset($CFG->loglifetime) and $CFG->loglifetime != -1) {
d8a1f426 803 if ($data = $this->get_legacy_logdata()) {
7eaca5a8
804 $manager = get_log_manager();
805 if (method_exists($manager, 'legacy_add_to_log')) {
c3ba899a
MG
806 if (is_array($data[0])) {
807 // Some events require several entries in 'log' table.
808 foreach ($data as $d) {
809 call_user_func_array(array($manager, 'legacy_add_to_log'), $d);
810 }
811 } else {
812 call_user_func_array(array($manager, 'legacy_add_to_log'), $data);
813 }
7eaca5a8 814 }
d8a1f426
PS
815 }
816 }
817
62401e8f
PS
818 if (PHPUNIT_TEST and \phpunit_util::is_redirecting_events()) {
819 $this->dispatched = true;
820 \phpunit_util::event_triggered($this);
821 return;
822 }
823
d8a1f426
PS
824 \core\event\manager::dispatch($this);
825
22626564
PS
826 $this->dispatched = true;
827
22446003 828 if ($legacyeventname = static::get_legacy_eventname()) {
f0f0e1fe 829 events_trigger_legacy($legacyeventname, $this->get_legacy_eventdata());
d8a1f426
PS
830 }
831 }
832
833 /**
22626564 834 * Was this event already triggered?
d8a1f426
PS
835 *
836 * @return bool
837 */
22626564 838 public final function is_triggered() {
d8a1f426
PS
839 return $this->triggered;
840 }
841
22626564
PS
842 /**
843 * Used from event manager to prevent direct access.
844 *
845 * @return bool
846 */
847 public final function is_dispatched() {
848 return $this->dispatched;
849 }
850
d8a1f426 851 /**
4b734e74 852 * Was this event restored?
d8a1f426
PS
853 *
854 * @return bool
855 */
22626564 856 public final function is_restored() {
d8a1f426
PS
857 return $this->restored;
858 }
859
860 /**
861 * Add cached data that will be most probably used in event observers.
862 *
863 * This is used to improve performance, but it is required for data
4b734e74 864 * that was just deleted.
d8a1f426
PS
865 *
866 * @param string $tablename
867 * @param \stdClass $record
300dbc66
PS
868 *
869 * @throws \coding_exception if used after ::trigger()
d8a1f426 870 */
fd4f3e9e 871 public final function add_record_snapshot($tablename, $record) {
96f81ea3 872 global $DB, $CFG;
d8a1f426 873
300dbc66
PS
874 if ($this->triggered) {
875 throw new \coding_exception('It is not possible to add snapshots after triggering of events');
876 }
877
92e2e855
MG
878 // Special case for course module, allow instance of cm_info to be passed instead of stdClass.
879 if ($tablename === 'course_modules' && $record instanceof \cm_info) {
880 $record = $record->get_course_module_record();
881 }
fc755767 882
d8a1f426
PS
883 // NOTE: this might use some kind of MUC cache,
884 // hopefully we will not run out of memory here...
96f81ea3 885 if ($CFG->debugdeveloper) {
92e2e855
MG
886 if (!($record instanceof \stdClass)) {
887 debugging('Argument $record must be an instance of stdClass.', DEBUG_DEVELOPER);
888 }
d8a1f426 889 if (!$DB->get_manager()->table_exists($tablename)) {
96f81ea3 890 debugging("Invalid table name '$tablename' specified, database table does not exist.", DEBUG_DEVELOPER);
5e70ea26
MG
891 } else {
892 $columns = $DB->get_columns($tablename);
893 $missingfields = array_diff(array_keys($columns), array_keys((array)$record));
894 if (!empty($missingfields)) {
895 debugging("Fields list in snapshot record does not match fields list in '$tablename'. Record is missing fields: ".
896 join(', ', $missingfields), DEBUG_DEVELOPER);
897 }
d8a1f426
PS
898 }
899 }
b396d40e 900 $this->recordsnapshots[$tablename][$record->id] = $record;
d8a1f426
PS
901 }
902
903 /**
904 * Returns cached record or fetches data from database if not cached.
905 *
906 * @param string $tablename
907 * @param int $id
908 * @return \stdClass
4ad6d5c5
PS
909 *
910 * @throws \coding_exception if used after ::restore()
d8a1f426 911 */
fd4f3e9e 912 public final function get_record_snapshot($tablename, $id) {
d8a1f426
PS
913 global $DB;
914
4ad6d5c5
PS
915 if ($this->restored) {
916 throw new \coding_exception('It is not possible to get snapshots from restored events');
917 }
918
b396d40e 919 if (isset($this->recordsnapshots[$tablename][$id])) {
5e70ea26 920 return clone($this->recordsnapshots[$tablename][$id]);
d8a1f426
PS
921 }
922
923 $record = $DB->get_record($tablename, array('id'=>$id));
b396d40e 924 $this->recordsnapshots[$tablename][$id] = $record;
d8a1f426
PS
925
926 return $record;
927 }
928
929 /**
930 * Magic getter for read only access.
931 *
d8a1f426
PS
932 * @param string $name
933 * @return mixed
d8a1f426
PS
934 */
935 public function __get($name) {
3345e24f
936 if ($name === 'level') {
937 debugging('level property is deprecated, use edulevel property instead', DEBUG_DEVELOPER);
938 return $this->data['edulevel'];
939 }
d8a1f426
PS
940 if (array_key_exists($name, $this->data)) {
941 return $this->data[$name];
942 }
943
4b734e74 944 debugging("Accessing non-existent event property '$name'");
d8a1f426 945 }
605a8c33
PS
946
947 /**
948 * Magic setter.
949 *
950 * Note: we must not allow modification of data from outside,
951 * after trigger() the data MUST NOT CHANGE!!!
952 *
953 * @param string $name
954 * @param mixed $value
955 *
956 * @throws \coding_exception
957 */
958 public function __set($name, $value) {
959 throw new \coding_exception('Event properties must not be modified.');
960 }
961
962 /**
963 * Is data property set?
964 *
965 * @param string $name
966 * @return bool
967 */
968 public function __isset($name) {
3345e24f
969 if ($name === 'level') {
970 debugging('level property is deprecated, use edulevel property instead', DEBUG_DEVELOPER);
971 return isset($this->data['edulevel']);
972 }
605a8c33
PS
973 return isset($this->data[$name]);
974 }
ed17808d
PS
975
976 /**
977 * Create an iterator because magic vars can't be seen by 'foreach'.
978 *
979 * @return \ArrayIterator
980 */
981 public function getIterator() {
982 return new \ArrayIterator($this->data);
983 }
51d85c7c
AN
984
985 /**
986 * Whether this event has been marked as deprecated.
987 *
988 * Events cannot be deprecated in the normal fashion as they must remain to support historical data.
989 * Once they are deprecated, there is no way to trigger the event, so it does not make sense to list it in some
990 * parts of the UI (e.g. Event Monitor).
991 *
992 * @return boolean
993 */
994 public static function is_deprecated() {
995 return false;
996 }
d8a1f426 997}