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