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