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