Merge branch 'm20_MDL-26672_aiccfix' of git://github.com/danmarsden/moodle
[moodle.git] / lib / eventslib.php
blob9cc29382abbcadab72e4868b083af4622fe82ac1
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Library of functions for events manipulation.
21 * The public API is all at the end of this file.
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core
26 * @subpackage event
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * Loads the events definitions for the component (from file). If no
33 * events are defined for the component, we simply return an empty array.
35 * INTERNAL - to be used from eventslib only
37 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
38 * @return array of capabilities or empty array if not exists
40 function events_load_def($component) {
41 global $CFG;
42 if ($component === 'unittest') {
43 $defpath = $CFG->dirroot.'/lib/simpletest/fixtures/events.php';
44 } else {
45 $defpath = get_component_directory($component).'/db/events.php';
48 $handlers = array();
50 if (file_exists($defpath)) {
51 require($defpath);
54 // make sure the definitions are valid and complete; tell devs what is wrong
55 foreach ($handlers as $eventname => $handler) {
56 if ($eventname === 'reset') {
57 debugging("'reset' can not be used as event name.");
58 unset($handlers['reset']);
59 continue;
61 if (!is_array($handler)) {
62 debugging("Handler of '$eventname' must be specified as array'");
63 unset($handlers[$eventname]);
64 continue;
66 if (!isset($handler['handlerfile'])) {
67 debugging("Handler of '$eventname' must include 'handlerfile' key'");
68 unset($handlers[$eventname]);
69 continue;
71 if (!isset($handler['handlerfunction'])) {
72 debugging("Handler of '$eventname' must include 'handlerfunction' key'");
73 unset($handlers[$eventname]);
74 continue;
76 if (!isset($handler['schedule'])) {
77 $handler['schedule'] = 'instant';
79 if ($handler['schedule'] !== 'instant' and $handler['schedule'] !== 'cron') {
80 debugging("Handler of '$eventname' must include valid 'schedule' type (instant or cron)'");
81 unset($handlers[$eventname]);
82 continue;
84 if (!isset($handler['internal'])) {
85 $handler['internal'] = 1;
87 $handlers[$eventname] = $handler;
90 return $handlers;
93 /**
94 * Gets the capabilities that have been cached in the database for this
95 * component.
97 * INTERNAL - to be used from eventslib only
99 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
100 * @return array of events
102 function events_get_cached($component) {
103 global $DB;
105 $cachedhandlers = array();
107 if ($storedhandlers = $DB->get_records('events_handlers', array('component'=>$component))) {
108 foreach ($storedhandlers as $handler) {
109 $cachedhandlers[$handler->eventname] = array (
110 'id' => $handler->id,
111 'handlerfile' => $handler->handlerfile,
112 'handlerfunction' => $handler->handlerfunction,
113 'schedule' => $handler->schedule,
114 'internal' => $handler->internal);
118 return $cachedhandlers;
122 * We can not removed all event handlers in table, then add them again
123 * because event handlers could be referenced by queued items
125 * Note that the absence of the db/events.php event definition file
126 * will cause any queued events for the component to be removed from
127 * the database.
129 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
130 * @return boolean always returns true
132 function events_update_definition($component='moodle') {
133 global $DB;
135 // load event definition from events.php
136 $filehandlers = events_load_def($component);
138 // load event definitions from db tables
139 // if we detect an event being already stored, we discard from this array later
140 // the remaining needs to be removed
141 $cachedhandlers = events_get_cached($component);
143 foreach ($filehandlers as $eventname => $filehandler) {
144 if (!empty($cachedhandlers[$eventname])) {
145 if ($cachedhandlers[$eventname]['handlerfile'] === $filehandler['handlerfile'] &&
146 $cachedhandlers[$eventname]['handlerfunction'] === serialize($filehandler['handlerfunction']) &&
147 $cachedhandlers[$eventname]['schedule'] === $filehandler['schedule'] &&
148 $cachedhandlers[$eventname]['internal'] == $filehandler['internal']) {
149 // exact same event handler already present in db, ignore this entry
151 unset($cachedhandlers[$eventname]);
152 continue;
154 } else {
155 // same event name matches, this event has been updated, update the datebase
156 $handler = new stdClass();
157 $handler->id = $cachedhandlers[$eventname]['id'];
158 $handler->handlerfile = $filehandler['handlerfile'];
159 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
160 $handler->schedule = $filehandler['schedule'];
161 $handler->internal = $filehandler['internal'];
163 $DB->update_record('events_handlers', $handler);
165 unset($cachedhandlers[$eventname]);
166 continue;
169 } else {
170 // if we are here, this event handler is not present in db (new)
171 // add it
172 $handler = new stdClass();
173 $handler->eventname = $eventname;
174 $handler->component = $component;
175 $handler->handlerfile = $filehandler['handlerfile'];
176 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
177 $handler->schedule = $filehandler['schedule'];
178 $handler->status = 0;
179 $handler->internal = $filehandler['internal'];
181 $DB->insert_record('events_handlers', $handler);
185 // clean up the left overs, the entries in cached events array at this points are deprecated event handlers
186 // and should be removed, delete from db
187 events_cleanup($component, $cachedhandlers);
189 events_get_handlers('reset');
191 return true;
195 * Remove all event handlers and queued events
197 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
199 function events_uninstall($component) {
200 $cachedhandlers = events_get_cached($component);
201 events_cleanup($component, $cachedhandlers);
203 events_get_handlers('reset');
207 * Deletes cached events that are no longer needed by the component.
209 * INTERNAL - to be used from eventslib only
211 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
212 * @param array $cachedhandlers array of the cached events definitions that will be
213 * @return int number of unused handlers that have been removed
215 function events_cleanup($component, $cachedhandlers) {
216 global $DB;
218 $deletecount = 0;
219 foreach ($cachedhandlers as $eventname => $cachedhandler) {
220 if ($qhandlers = $DB->get_records('events_queue_handlers', array('handlerid'=>$cachedhandler['id']))) {
221 //debugging("Removing pending events from queue before deleting of event handler: $component - $eventname");
222 foreach ($qhandlers as $qhandler) {
223 events_dequeue($qhandler);
226 $DB->delete_records('events_handlers', array('eventname'=>$eventname, 'component'=>$component));
227 $deletecount++;
230 return $deletecount;
233 /****************** End of Events handler Definition code *******************/
236 * puts a handler on queue
238 * INTERNAL - to be used from eventslib only
240 * @param object $handler event handler object from db
241 * @param object $event event data object
242 * @param string $errormessage The error message indicating the problem
243 * @return id number of new queue handler
245 function events_queue_handler($handler, $event, $errormessage) {
246 global $DB;
248 if ($qhandler = $DB->get_record('events_queue_handlers', array('queuedeventid'=>$event->id, 'handlerid'=>$handler->id))) {
249 debugging("Please check code: Event id $event->id is already queued in handler id $qhandler->id");
250 return $qhandler->id;
253 // make a new queue handler
254 $qhandler = new stdClass();
255 $qhandler->queuedeventid = $event->id;
256 $qhandler->handlerid = $handler->id;
257 $qhandler->errormessage = $errormessage;
258 $qhandler->timemodified = time();
259 if ($handler->schedule === 'instant' and $handler->status == 1) {
260 $qhandler->status = 1; //already one failed attempt to dispatch this event
261 } else {
262 $qhandler->status = 0;
265 return $DB->insert_record('events_queue_handlers', $qhandler);
269 * trigger a single event with a specified handler
271 * INTERNAL - to be used from eventslib only
273 * @param handler $hander object from db
274 * @param eventdata $eventdata dataobject
275 * @param string $errormessage error message indicating problem
276 * @return bool true means event processed, false means retry event later; may throw exception, NULL means internal error
278 function events_dispatch($handler, $eventdata, &$errormessage) {
279 global $CFG;
281 $function = unserialize($handler->handlerfunction);
283 if (is_callable($function)) {
284 // oki, no need for includes
286 } else if (file_exists($CFG->dirroot.$handler->handlerfile)) {
287 include_once($CFG->dirroot.$handler->handlerfile);
289 } else {
290 $errormessage = "Handler file of component $handler->component: $handler->handlerfile can not be found!";
291 return null;
294 // checks for handler validity
295 if (is_callable($function)) {
296 $result = call_user_func($function, $eventdata);
297 if ($result === false) {
298 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction requested resending of event!";
299 return false;
301 return true;
303 } else {
304 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction not callable function or class method!";
305 return null;
310 * given a queued handler, call the respective event handler to process the event
312 * INTERNAL - to be used from eventslib only
314 * @param object $qhandler events_queued_handler object from db
315 * @return boolean true means event processed, false means retry later, NULL means fatal failure
317 function events_process_queued_handler($qhandler) {
318 global $DB;
320 // get handler
321 if (!$handler = $DB->get_record('events_handlers', array('id'=>$qhandler->handlerid))) {
322 debugging("Error processing queue handler $qhandler->id, missing handler id: $qhandler->handlerid");
323 //irrecoverable error, remove broken queue handler
324 events_dequeue($qhandler);
325 return NULL;
328 // get event object
329 if (!$event = $DB->get_record('events_queue', array('id'=>$qhandler->queuedeventid))) {
330 // can't proceed with no event object - might happen when two crons running at the same time
331 debugging("Error processing queue handler $qhandler->id, missing event id: $qhandler->queuedeventid");
332 //irrecoverable error, remove broken queue handler
333 events_dequeue($qhandler);
334 return NULL;
337 // call the function specified by the handler
338 try {
339 $errormessage = 'Unknown error';
340 if (events_dispatch($handler, unserialize(base64_decode($event->eventdata)), $errormessage)) {
341 //everything ok
342 events_dequeue($qhandler);
343 return true;
345 } catch (Exception $e) {
346 // the problem here is that we do not want one broken handler to stop all others,
347 // cron handlers are very tricky because the needed data might have been deleted before the cron execution
348 $errormessage = "Handler function of component $handler->component: $handler->handlerfunction threw exception :".$e->getMessage();
351 //dispatching failed
352 $qh = new stdClass();
353 $qh->id = $qhandler->id;
354 $qh->errormessage = $errormessage;
355 $qh->timemodified = time();
356 $qh->status = $qhandler->status + 1;
357 $DB->update_record('events_queue_handlers', $qh);
359 return false;
363 * Removes this queued handler from the events_queued_handler table
365 * Removes events_queue record from events_queue if no more references to this event object exists
367 * INTERNAL - to be used from eventslib only
369 * @param object $qhandler events_queued_handler object from db
371 function events_dequeue($qhandler) {
372 global $DB;
374 // first delete the queue handler
375 $DB->delete_records('events_queue_handlers', array('id'=>$qhandler->id));
377 // if no more queued handler is pointing to the same event - delete the event too
378 if (!$DB->record_exists('events_queue_handlers', array('queuedeventid'=>$qhandler->queuedeventid))) {
379 $DB->delete_records('events_queue', array('id'=>$qhandler->queuedeventid));
384 * Returns handlers for given event. Uses caching for better perf.
386 * INTERNAL - to be used from eventslib only
388 * @staticvar array $handlers
389 * @param string $eventanme name of even or 'reset'
390 * @return mixed array of handlers or false otherwise
392 function events_get_handlers($eventname) {
393 global $DB;
394 static $handlers = array();
396 if ($eventname === 'reset') {
397 $handlers = array();
398 return false;
401 if (!array_key_exists($eventname, $handlers)) {
402 $handlers[$eventname] = $DB->get_records('events_handlers', array('eventname'=>$eventname));
405 return $handlers[$eventname];
408 /****** Public events API starts here, do not use functions above in 3rd party code ******/
412 * Events cron will try to empty the events queue by processing all the queued events handlers
414 * PUBLIC
416 * @param string $eventname empty means all
417 * @return number of dispatched events
419 function events_cron($eventname='') {
420 global $DB;
422 $failed = array();
423 $processed = 0;
425 if ($eventname) {
426 $sql = "SELECT qh.*
427 FROM {events_queue_handlers} qh, {events_handlers} h
428 WHERE qh.handlerid = h.id AND h.eventname=?
429 ORDER BY qh.id";
430 $params = array($eventname);
431 } else {
432 $sql = "SELECT *
433 FROM {events_queue_handlers}
434 ORDER BY id";
435 $params = array();
438 $rs = $DB->get_recordset_sql($sql, $params);
439 foreach ($rs as $qhandler) {
440 if (isset($failed[$qhandler->handlerid])) {
441 // do not try to dispatch any later events when one already asked for retry or ended with exception
442 continue;
444 $status = events_process_queued_handler($qhandler);
445 if ($status === false) {
446 // handler is asking for retry, do not send other events to this handler now
447 $failed[$qhandler->handlerid] = $qhandler->handlerid;
448 } else if ($status === NULL) {
449 // means completely broken handler, event data was purged
450 $failed[$qhandler->handlerid] = $qhandler->handlerid;
451 } else {
452 $processed++;
455 $rs->close();
457 // remove events that do not have any handlers waiting
458 $sql = "SELECT eq.id
459 FROM {events_queue} eq
460 LEFT JOIN {events_queue_handlers} qh ON qh.queuedeventid = eq.id
461 WHERE qh.id IS NULL";
462 $rs = $DB->get_recordset_sql($sql);
463 foreach ($rs as $event) {
464 //debugging('Purging stale event '.$event->id);
465 $DB->delete_records('events_queue', array('id'=>$event->id));
467 $rs->close();
469 return $processed;
474 * Function to call all event handlers when triggering an event
476 * PUBLIC
478 * @param string $eventname name of the event
479 * @param object $eventdata event data object
480 * @return int number of failed events
482 function events_trigger($eventname, $eventdata) {
483 global $CFG, $USER, $DB;
485 $failedcount = 0; // number of failed events.
487 // pull out all registered event handlers
488 if ($handlers = events_get_handlers($eventname)) {
489 foreach ($handlers as $handler) {
490 $errormessage = '';
492 if ($handler->schedule === 'instant') {
493 if ($handler->status) {
494 //check if previous pending events processed
495 if (!$DB->record_exists('events_queue_handlers', array('handlerid'=>$handler->id))) {
496 // ok, queue is empty, lets reset the status back to 0 == ok
497 $handler->status = 0;
498 $DB->set_field('events_handlers', 'status', 0, array('id'=>$handler->id));
499 // reset static handler cache
500 events_get_handlers('reset');
504 // dispatch the event only if instant schedule and status ok
505 if ($handler->status or (!$handler->internal and $DB->is_transaction_started())) {
506 // increment the error status counter
507 $handler->status++;
508 $DB->set_field('events_handlers', 'status', $handler->status, array('id'=>$handler->id));
509 // reset static handler cache
510 events_get_handlers('reset');
512 } else {
513 $errormessage = 'Unknown error';;
514 $result = events_dispatch($handler, $eventdata, $errormessage);
515 if ($result === true) {
516 // everything is fine - event dispatched
517 continue;
518 } else if ($result === false) {
519 // retry later - set error count to 1 == send next instant into cron queue
520 $DB->set_field('events_handlers', 'status', 1, array('id'=>$handler->id));
521 // reset static handler cache
522 events_get_handlers('reset');
523 } else {
524 // internal problem - ignore the event completely
525 $failedcount ++;
526 continue;
530 // update the failed counter
531 $failedcount ++;
533 } else if ($handler->schedule === 'cron') {
534 //ok - use queueing of events only
536 } else {
537 // unknown schedule - ignore event completely
538 debugging("Unknown handler schedule type: $handler->schedule");
539 $failedcount ++;
540 continue;
543 // if even type is not instant, or dispatch asked for retry, queue it
544 $event = new stdClass();
545 $event->userid = $USER->id;
546 $event->eventdata = base64_encode(serialize($eventdata));
547 $event->timecreated = time();
548 if (debugging()) {
549 $dump = '';
550 $callers = debug_backtrace();
551 foreach ($callers as $caller) {
552 if (!isset($caller['line'])) {
553 $caller['line'] = '?';
555 if (!isset($caller['file'])) {
556 $caller['file'] = '?';
558 $dump .= 'line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
559 if (isset($caller['function'])) {
560 $dump .= ': call to ';
561 if (isset($caller['class'])) {
562 $dump .= $caller['class'] . $caller['type'];
564 $dump .= $caller['function'] . '()';
566 $dump .= "\n";
568 $event->stackdump = $dump;
569 } else {
570 $event->stackdump = '';
572 $event->id = $DB->insert_record('events_queue', $event);
573 events_queue_handler($handler, $event, $errormessage);
575 } else {
576 // No handler found for this event name - this is ok!
579 return $failedcount;
583 * checks if an event is registered for this component
585 * @param string $eventname name of the event
586 * @param string $component component name, can be mod/data or moodle
587 * @return bool
589 function events_is_registered($eventname, $component) {
590 global $DB;
591 return $DB->record_exists('events_handlers', array('component'=>$component, 'eventname'=>$eventname));
595 * checks if an event is queued for processing - either cron handlers attached or failed instant handlers
597 * PUBLIC
599 * @param string $eventname name of the event
600 * @return int number of queued events
602 function events_pending_count($eventname) {
603 global $DB;
605 $sql = "SELECT COUNT('x')
606 FROM {events_queue_handlers} qh
607 JOIN {events_handlers} h ON h.id = qh.handlerid
608 WHERE h.eventname = ?";
610 return $DB->count_records_sql($sql, array($eventname));