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