MDL-39846 improve validation and enable hardcoding of system context
[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
19/**
20 * Base event class.
21 *
22 * @package core
23 * @copyright 2013 Petr Skoda {@link http://skodak.org}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27
28/**
29 * All other event classes must extend this class.
30 *
31 * @package core
32 * @copyright 2013 Petr Skoda {@link http://skodak.org}
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 *
35 * @property-read string $eventname Name of the event (=== class name with leading \)
36 * @property-read string $component Full frankenstyle component name
37 * @property-read string $action what happened
38 * @property-read string $object what/who was object of the action (usually similar to database table name)
a85258ca 39 * @property-read string $objecttable name of database table where is object record stored
d8a1f426
PS
40 * @property-read int $objectid optional id of the object
41 * @property-read string $crud letter indicating event type
4b734e74 42 * @property-read int $level log level (number between 1 and 100)
d8a1f426
PS
43 * @property-read int $contextid
44 * @property-read int $contextlevel
45 * @property-read int $contextinstanceid
46 * @property-read int $userid who did this?
47 * @property-read int $courseid
48 * @property-read int $relateduserid
c4297815 49 * @property-read mixed $other array or scalar, can not contain objects
d8a1f426
PS
50 * @property-read int $timecreated
51 */
ed17808d 52abstract class base implements \IteratorAggregate {
d8a1f426
PS
53 /** @var array event data */
54 protected $data;
55
4b734e74 56 /** @var array the format is standardised by logging API */
b0cdc969 57 protected $logextra;
4b734e74 58
d8a1f426
PS
59 /** @var \context of this event */
60 protected $context;
61
22626564
PS
62 /**
63 * @var bool indicates if event was already triggered,
64 * this prevents second attempt to trigger event.
65 */
d8a1f426
PS
66 private $triggered;
67
22626564
PS
68 /**
69 * @var bool indicates if event was already dispatched,
70 * this prevents direct calling of manager::dispatch($event).
71 */
72 private $dispatched;
73
74 /**
75 * @var bool indicates if event was restored from storage,
76 * this prevents triggering of restored events.
77 */
d8a1f426
PS
78 private $restored;
79
80 /** @var array list of event properties */
81 private static $fields = array(
a85258ca 82 'eventname', 'component', 'action', 'object', 'objecttable', 'objectid', 'crud', 'level', 'contextid',
c4297815 83 'contextlevel', 'contextinstanceid', 'userid', 'courseid', 'relateduserid', 'other',
4b734e74 84 'timecreated');
d8a1f426
PS
85
86 /** @var array simple record cache */
b396d40e 87 protected $recordsnapshots = array();
d8a1f426
PS
88
89 /**
90 * Private constructor, use create() or restore() methods instead.
91 */
92 private final function __construct() {
93 $this->data = array_fill_keys(self::$fields, null);
94 }
95
96 /**
97 * Create new event.
98 *
99 * The optional data keys as:
100 * 1/ objectid - the id of the object specified in class name
101 * 2/ context - the context of this event
c4297815 102 * 3/ other - the other data describing the event, can not contain objects
d8a1f426
PS
103 * 4/ relateduserid - the id of user which is somehow related to this event
104 *
105 * @param array $data
106 * @return \core\event\base returns instance of new event
107 *
108 * @throws \coding_exception
109 */
110 public static final function create(array $data = null) {
111 global $PAGE, $USER;
112
113 $data = (array)$data;
114
115 /** @var \core\event\base $event */
116 $event = new static();
117 $event->triggered = false;
118 $event->restored = false;
22626564 119 $event->dispatched = false;
d8a1f426 120
4b734e74
PS
121 // Set automatic data.
122 $event->data['timecreated'] = time();
123
d8a1f426
PS
124 $classname = get_class($event);
125 $parts = explode('\\', $classname);
126 if (count($parts) !== 3 or $parts[1] !== 'event') {
127 throw new \coding_exception("Invalid event class name '$classname', it must be defined in component\\event\\ namespace");
128 }
129 $event->data['eventname'] = '\\'.$classname;
130 $event->data['component'] = $parts[0];
131
132 $pos = strrpos($parts[2], '_');
133 if ($pos === false) {
134 throw new \coding_exception("Invalid event class name '$classname', there must be at least one underscore separating object and action words");
135 }
136 $event->data['object'] = substr($parts[2], 0, $pos);
137 $event->data['action'] = substr($parts[2], $pos+1);
138
fddd1018
PS
139 // Set static event data specific for child class.
140 $event->init();
141
4b734e74 142 // Set optional data or use defaults.
d8a1f426
PS
143 $event->data['objectid'] = isset($data['objectid']) ? $data['objectid'] : null;
144 $event->data['courseid'] = isset($data['courseid']) ? $data['courseid'] : null;
145 $event->data['userid'] = isset($data['userid']) ? $data['userid'] : $USER->id;
c4297815 146 $event->data['other'] = isset($data['other']) ? $data['other'] : null;
d8a1f426
PS
147 $event->data['relateduserid'] = isset($data['relateduserid']) ? $data['relateduserid'] : null;
148
fddd1018
PS
149 if (isset($event->context)) {
150 if (isset($data['context']) and $event->context->id != $data['context']->id) {
151 throw new \coding_exception('Given context does not match expected context');
152 }
153 $event->data['contextid'] = $event->context->id;
154 $event->data['contextlevel'] = $event->context->contextlevel;
155 $event->data['contextinstanceid'] = $event->context->instanceid;
156
157 } else if (!empty($data['context'])) {
d8a1f426 158 $event->context = $data['context'];
fddd1018
PS
159 if (isset($event->data['contextlevel']) and $event->data['contextlevel'] != $event->context->contextlevel) {
160 throw new \coding_exception('Context does not match expected context level');
161 }
27af3e62
PS
162 $event->data['contextid'] = $event->context->id;
163 $event->data['contextlevel'] = $event->context->contextlevel;
164 $event->data['contextinstanceid'] = $event->context->instanceid;
165
166 } else if (!empty($data['contextid'])) {
167 $event->context = null;
168 if (isset($data['contextlevel']) and isset($data['contextinstanceid'])) {
169 // Useful especially when deleting contexts because we can nto fetch it from DB anymore.
170 $event->data['contextid'] = $data['contextid'];
171 $event->data['contextlevel'] = $data['contextlevel'];
172 $event->data['contextinstanceid'] = $data['contextinstanceid'];
173 $event->context = \context::instance_by_id($data['contextid'], IGNORE_MISSING);
174 } else {
175 $event->context = \context::instance_by_id($data['contextid'], MUST_EXIST);
176 $event->data['contextid'] = $event->context->id;
177 $event->data['contextlevel'] = $event->context->contextlevel;
178 $event->data['contextinstanceid'] = $event->context->instanceid;
179 }
180 } else {
fddd1018 181 throw new \coding_exception('context (or contextid) is a required event property, system context may be hardcoded in init() method.');
d8a1f426 182 }
d8a1f426
PS
183
184 if (!isset($event->data['courseid'])) {
27af3e62 185 if ($event->context and $coursecontext = $event->context->get_course_context(false)) {
d8a1f426
PS
186 $event->data['courseid'] = $coursecontext->id;
187 } else {
188 $event->data['courseid'] = 0;
189 }
190 }
191
27af3e62 192 if (!array_key_exists('relateduserid', $data) and $event->context and $event->context->contextlevel == CONTEXT_USER) {
d8a1f426
PS
193 $event->data['relateduserid'] = $event->context->instanceid;
194 }
195
4b734e74 196 // Warn developers if they do something wrong.
ed17808d 197 if (debugging('', DEBUG_DEVELOPER)) { // This should be replaced by new $CFG->slowdebug flag if introduced.
4b734e74 198 static $automatickeys = array('eventname', 'component', 'action', 'object', 'timecreated');
a85258ca 199 static $initkeys = array('crud', 'level', 'objecttable');
4b734e74
PS
200
201 foreach ($data as $key => $ignored) {
202 if ($key === 'context') {
203 continue;
204
205 } else if (in_array($key, $automatickeys)) {
206 debugging("Data key '$key' is not allowed in \\core\\event\\base::create() method, it is set automatically");
207
208 } else if (in_array($key, $initkeys)) {
209 debugging("Data key '$key' is not allowed in \\core\\event\\base::create() method, you need to set it in init() method");
210
211 } else if (!in_array($key, self::$fields)) {
212 debugging("Data key '$key' does not exist in \\core\\event\\base");
d8a1f426
PS
213 }
214 }
215 }
216
fddd1018
PS
217 // Let developers validate their custom data (such as $this->date['other']).
218 $event->validate_data();
219
d8a1f426
PS
220 return $event;
221 }
222
223 /**
224 * Override in subclass.
225 *
226 * Set all required data properties:
fddd1018
PS
227 * 1/ crud - letter [crud] TODO: MDL-37658
228 * 2/ level - number 1...100 TODO: MDL-37658
a85258ca 229 * 3/ objecttable - name of database table if objectid specified
4b734e74 230 *
fddd1018
PS
231 * Optionally it can set:
232 * a/ fixed system context
233 * b/ required context level
d8a1f426
PS
234 *
235 * @return void
236 */
237 protected abstract function init();
238
fddd1018
PS
239 /**
240 * Let developers validate their custom data (such as $this->date['other']).
241 *
242 * Throw \coding_exception or debugging() notice in case of any problems.
243 */
244 protected function validate_data() {
245 // Override if you want to validate event properties when
246 // creating new events.
247 }
248
4b734e74
PS
249 /**
250 * Returns localised general event name.
251 *
252 * Override in subclass, we can not make it static and abstract at the same time.
253 *
05a970d3
PS
254 * TODO: MDL-37658
255 *
4b734e74
PS
256 * @return string|\lang_string
257 */
258 public static function get_name() {
259 // Override in subclass with real lang string.
260 $parts = explode('\\', __CLASS__);
261 if (count($parts) !== 3) {
262 return 'unknown event';
263 }
264 return $parts[0].': '.str_replace('_', ' ', $parts[2]);
265 }
266
267 /**
268 * Returns localised description of what happened.
269 *
05a970d3
PS
270 * TODO: MDL-37658
271 *
4b734e74
PS
272 * @return string|\lang_string
273 */
274 public function get_description() {
275 return null;
276 }
277
278 /**
279 * Define whether a user can view the event or not.
280 *
281 * @param int|\stdClass $user_or_id ID of the user.
282 * @return bool True if the user can view the event, false otherwise.
283 */
284 public function can_view($user_or_id = null) {
285 return is_siteadmin($user_or_id);
286 }
287
d8a1f426
PS
288 /**
289 * Restore event from existing historic data.
290 *
291 * @param array $data
b0cdc969 292 * @param array $logextra the format is standardised by logging API
d8a1f426
PS
293 * @return bool|\core\event\base
294 */
b0cdc969 295 public static final function restore(array $data, array $logextra) {
d8a1f426
PS
296 $classname = $data['eventname'];
297 $component = $data['component'];
298 $action = $data['action'];
299 $object = $data['object'];
300
301 // Security: make 100% sure this really is an event class.
302 if ($classname !== "\\{$component}\\event\\{$object}_{$action}") {
303 return false;
304 }
305
306 if (!class_exists($classname)) {
307 return false;
308 }
309 $event = new $classname();
310 if (!($event instanceof \core\event\base)) {
311 return false;
312 }
313
d8a1f426 314 $event->restored = true;
22626564
PS
315 $event->triggered = true;
316 $event->dispatched = true;
b0cdc969 317 $event->logextra = $logextra;
d8a1f426
PS
318
319 foreach (self::$fields as $key) {
4b734e74 320 if (!array_key_exists($key, $data)) {
d8a1f426 321 debugging("Event restore data must contain key $key");
4b734e74 322 $data[$key] = null;
d8a1f426
PS
323 }
324 }
4b734e74
PS
325 if (count($data) != count(self::$fields)) {
326 foreach ($data as $key => $value) {
327 if (!in_array($key, self::$fields)) {
328 debugging("Event restore data cannot contain key $key");
329 unset($data[$key]);
330 }
331 }
332 }
333 $event->data = $data;
d8a1f426
PS
334
335 return $event;
336 }
337
d8a1f426
PS
338 /**
339 * Returns event context.
340 * @return \context
341 */
342 public function get_context() {
343 if (isset($this->context)) {
344 return $this->context;
345 }
346 $this->context = \context::instance_by_id($this->data['contextid'], false);
347 return $this->context;
348 }
349
350 /**
351 * Returns relevant URL, override in subclasses.
4b734e74 352 * @return \moodle_url
d8a1f426
PS
353 */
354 public function get_url() {
355 return null;
356 }
357
358 /**
359 * Return standardised event data as array.
360 *
d8a1f426
PS
361 * @return array
362 */
363 public function get_data() {
364 return $this->data;
365 }
366
4b734e74
PS
367 /**
368 * Return auxiliary data that was stored in logs.
369 *
05a970d3
PS
370 * TODO: MDL-37658
371 *
4b734e74
PS
372 * @return array the format is standardised by logging API
373 */
b0cdc969
PS
374 public function get_logextra() {
375 return $this->logextra;
4b734e74
PS
376 }
377
d8a1f426
PS
378 /**
379 * Does this event replace legacy event?
380 *
381 * @return null|string legacy event name
382 */
383 public function get_legacy_eventname() {
384 return null;
385 }
386
387 /**
388 * Legacy event data if get_legacy_eventname() is not empty.
389 *
390 * @return mixed
391 */
392 public function get_legacy_eventdata() {
393 return null;
394 }
395
396 /**
397 * Doest this event replace add_to_log() statement?
398 *
399 * @return null|array of parameters to be passed to legacy add_to_log() function.
400 */
401 public function get_legacy_logdata() {
402 return null;
403 }
404
405 /**
406 * Validate all properties right before triggering the event.
407 *
408 * This throws coding exceptions for fatal problems and debugging for minor problems.
409 *
410 * @throws \coding_exception
411 */
412 protected final function validate_before_trigger() {
a85258ca
PS
413 global $DB;
414
d8a1f426
PS
415 if (empty($this->data['crud'])) {
416 throw new \coding_exception('crud must be specified in init() method of each method');
417 }
418 if (empty($this->data['level'])) {
419 throw new \coding_exception('level must be specified in init() method of each method');
420 }
a85258ca
PS
421 if (!empty($this->data['objectid']) and empty($this->data['objecttable'])) {
422 throw new \coding_exception('objecttable must be specified in init() method if objectid present');
423 }
d8a1f426 424
a85258ca 425 if (debugging('', DEBUG_DEVELOPER)) { // This should be replaced by new $CFG->slowdebug flag if introduced.
d8a1f426
PS
426 // Ideally these should be coding exceptions, but we need to skip these for performance reasons
427 // on production servers.
4b734e74
PS
428
429 if (!in_array($this->data['crud'], array('c', 'r', 'u', 'd'), true)) {
430 debugging("Invalid event crud value specified.");
431 }
432 if (!is_number($this->data['level'])) {
433 debugging('Event property level must be a number');
434 }
d8a1f426 435 if (self::$fields !== array_keys($this->data)) {
4b734e74 436 debugging('Number of event data fields must not be changed in event classes');
d8a1f426 437 }
c4297815
PS
438 $encoded = json_encode($this->data['other']);
439 if ($encoded === false or $this->data['other'] !== json_decode($encoded, true)) {
440 debugging('other event data must be compatible with json encoding');
4b734e74
PS
441 }
442 if ($this->data['userid'] and !is_number($this->data['userid'])) {
443 debugging('Event property userid must be a number');
444 }
445 if ($this->data['courseid'] and !is_number($this->data['courseid'])) {
446 debugging('Event property courseid must be a number');
447 }
448 if ($this->data['objectid'] and !is_number($this->data['objectid'])) {
449 debugging('Event property objectid must be a number');
450 }
451 if ($this->data['relateduserid'] and !is_number($this->data['relateduserid'])) {
452 debugging('Event property relateduserid must be a number');
d8a1f426 453 }
a85258ca
PS
454 if ($this->data['objecttable']) {
455 if (!$DB->get_manager()->table_exists($this->data['objecttable'])) {
456 debugging('Unknown table specified in objecttable field');
457 }
458 }
d8a1f426
PS
459 }
460 }
461
462 /**
463 * Trigger event.
464 */
465 public final function trigger() {
466 global $CFG;
467
468 if ($this->restored) {
469 throw new \coding_exception('Can not trigger restored event');
470 }
22626564 471 if ($this->triggered or $this->dispatched) {
d8a1f426
PS
472 throw new \coding_exception('Can not trigger event twice');
473 }
474
d8a1f426
PS
475 $this->validate_before_trigger();
476
22626564
PS
477 $this->triggered = true;
478
d8a1f426
PS
479 if (!empty($CFG->loglifetime)) {
480 if ($data = $this->get_legacy_logdata()) {
481 call_user_func_array('add_to_log', $data);
482 }
483 }
484
62401e8f
PS
485 if (PHPUNIT_TEST and \phpunit_util::is_redirecting_events()) {
486 $this->dispatched = true;
487 \phpunit_util::event_triggered($this);
488 return;
489 }
490
d8a1f426
PS
491 \core\event\manager::dispatch($this);
492
22626564
PS
493 $this->dispatched = true;
494
d8a1f426
PS
495 if ($legacyeventname = $this->get_legacy_eventname()) {
496 events_trigger($legacyeventname, $this->get_legacy_eventdata());
497 }
498 }
499
500 /**
22626564 501 * Was this event already triggered?
d8a1f426
PS
502 *
503 * @return bool
504 */
22626564 505 public final function is_triggered() {
d8a1f426
PS
506 return $this->triggered;
507 }
508
22626564
PS
509 /**
510 * Used from event manager to prevent direct access.
511 *
512 * @return bool
513 */
514 public final function is_dispatched() {
515 return $this->dispatched;
516 }
517
d8a1f426 518 /**
4b734e74 519 * Was this event restored?
d8a1f426
PS
520 *
521 * @return bool
522 */
22626564 523 public final function is_restored() {
d8a1f426
PS
524 return $this->restored;
525 }
526
527 /**
528 * Add cached data that will be most probably used in event observers.
529 *
530 * This is used to improve performance, but it is required for data
4b734e74 531 * that was just deleted.
d8a1f426
PS
532 *
533 * @param string $tablename
534 * @param \stdClass $record
300dbc66
PS
535 *
536 * @throws \coding_exception if used after ::trigger()
d8a1f426 537 */
5fef139c 538 public function add_record_snapshot($tablename, $record) {
d8a1f426
PS
539 global $DB;
540
300dbc66
PS
541 if ($this->triggered) {
542 throw new \coding_exception('It is not possible to add snapshots after triggering of events');
543 }
544
d8a1f426
PS
545 // NOTE: this might use some kind of MUC cache,
546 // hopefully we will not run out of memory here...
ed17808d 547 if (debugging('', DEBUG_DEVELOPER)) { // This should be replaced by new $CFG->slowdebug flag if introduced.
d8a1f426
PS
548 if (!$DB->get_manager()->table_exists($tablename)) {
549 debugging("Invalid table name '$tablename' specified, database table does not exist.");
550 }
551 }
b396d40e 552 $this->recordsnapshots[$tablename][$record->id] = $record;
d8a1f426
PS
553 }
554
555 /**
556 * Returns cached record or fetches data from database if not cached.
557 *
558 * @param string $tablename
559 * @param int $id
560 * @return \stdClass
4ad6d5c5
PS
561 *
562 * @throws \coding_exception if used after ::restore()
d8a1f426 563 */
5fef139c 564 public function get_record_snapshot($tablename, $id) {
d8a1f426
PS
565 global $DB;
566
4ad6d5c5
PS
567 if ($this->restored) {
568 throw new \coding_exception('It is not possible to get snapshots from restored events');
569 }
570
b396d40e
PS
571 if (isset($this->recordsnapshots[$tablename][$id])) {
572 return $this->recordsnapshots[$tablename][$id];
d8a1f426
PS
573 }
574
575 $record = $DB->get_record($tablename, array('id'=>$id));
b396d40e 576 $this->recordsnapshots[$tablename][$id] = $record;
d8a1f426
PS
577
578 return $record;
579 }
580
581 /**
582 * Magic getter for read only access.
583 *
d8a1f426
PS
584 * @param string $name
585 * @return mixed
d8a1f426
PS
586 */
587 public function __get($name) {
588 if (array_key_exists($name, $this->data)) {
589 return $this->data[$name];
590 }
591
4b734e74 592 debugging("Accessing non-existent event property '$name'");
d8a1f426 593 }
605a8c33
PS
594
595 /**
596 * Magic setter.
597 *
598 * Note: we must not allow modification of data from outside,
599 * after trigger() the data MUST NOT CHANGE!!!
600 *
601 * @param string $name
602 * @param mixed $value
603 *
604 * @throws \coding_exception
605 */
606 public function __set($name, $value) {
607 throw new \coding_exception('Event properties must not be modified.');
608 }
609
610 /**
611 * Is data property set?
612 *
613 * @param string $name
614 * @return bool
615 */
616 public function __isset($name) {
617 return isset($this->data[$name]);
618 }
ed17808d
PS
619
620 /**
621 * Create an iterator because magic vars can't be seen by 'foreach'.
622 *
623 * @return \ArrayIterator
624 */
625 public function getIterator() {
626 return new \ArrayIterator($this->data);
627 }
d8a1f426 628}