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