Merge branch 'wip-mdl-30121-m22' of git://github.com/rajeshtaneja/moodle into MOODLE_...
[moodle.git] / lib / eventslib.php
blob6ceaf5e0059dd833ff5ce66f3b4e2bca464b2894
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 :" .
349 $e->getMessage() . "\n" . format_backtrace($e->getTrace(), true);
350 if (!empty($e->debuginfo)) {
351 $errormessage .= $e->debuginfo;
355 //dispatching failed
356 $qh = new stdClass();
357 $qh->id = $qhandler->id;
358 $qh->errormessage = $errormessage;
359 $qh->timemodified = time();
360 $qh->status = $qhandler->status + 1;
361 $DB->update_record('events_queue_handlers', $qh);
363 return false;
367 * Removes this queued handler from the events_queued_handler table
369 * Removes events_queue record from events_queue if no more references to this event object exists
371 * INTERNAL - to be used from eventslib only
373 * @param object $qhandler events_queued_handler object from db
375 function events_dequeue($qhandler) {
376 global $DB;
378 // first delete the queue handler
379 $DB->delete_records('events_queue_handlers', array('id'=>$qhandler->id));
381 // if no more queued handler is pointing to the same event - delete the event too
382 if (!$DB->record_exists('events_queue_handlers', array('queuedeventid'=>$qhandler->queuedeventid))) {
383 $DB->delete_records('events_queue', array('id'=>$qhandler->queuedeventid));
388 * Returns handlers for given event. Uses caching for better perf.
390 * INTERNAL - to be used from eventslib only
392 * @staticvar array $handlers
393 * @param string $eventanme name of even or 'reset'
394 * @return mixed array of handlers or false otherwise
396 function events_get_handlers($eventname) {
397 global $DB;
398 static $handlers = array();
400 if ($eventname === 'reset') {
401 $handlers = array();
402 return false;
405 if (!array_key_exists($eventname, $handlers)) {
406 $handlers[$eventname] = $DB->get_records('events_handlers', array('eventname'=>$eventname));
409 return $handlers[$eventname];
412 /****** Public events API starts here, do not use functions above in 3rd party code ******/
416 * Events cron will try to empty the events queue by processing all the queued events handlers
418 * PUBLIC
420 * @param string $eventname empty means all
421 * @return number of dispatched events
423 function events_cron($eventname='') {
424 global $DB;
426 $failed = array();
427 $processed = 0;
429 if ($eventname) {
430 $sql = "SELECT qh.*
431 FROM {events_queue_handlers} qh, {events_handlers} h
432 WHERE qh.handlerid = h.id AND h.eventname=?
433 ORDER BY qh.id";
434 $params = array($eventname);
435 } else {
436 $sql = "SELECT *
437 FROM {events_queue_handlers}
438 ORDER BY id";
439 $params = array();
442 $rs = $DB->get_recordset_sql($sql, $params);
443 foreach ($rs as $qhandler) {
444 if (isset($failed[$qhandler->handlerid])) {
445 // do not try to dispatch any later events when one already asked for retry or ended with exception
446 continue;
448 $status = events_process_queued_handler($qhandler);
449 if ($status === false) {
450 // handler is asking for retry, do not send other events to this handler now
451 $failed[$qhandler->handlerid] = $qhandler->handlerid;
452 } else if ($status === NULL) {
453 // means completely broken handler, event data was purged
454 $failed[$qhandler->handlerid] = $qhandler->handlerid;
455 } else {
456 $processed++;
459 $rs->close();
461 // remove events that do not have any handlers waiting
462 $sql = "SELECT eq.id
463 FROM {events_queue} eq
464 LEFT JOIN {events_queue_handlers} qh ON qh.queuedeventid = eq.id
465 WHERE qh.id IS NULL";
466 $rs = $DB->get_recordset_sql($sql);
467 foreach ($rs as $event) {
468 //debugging('Purging stale event '.$event->id);
469 $DB->delete_records('events_queue', array('id'=>$event->id));
471 $rs->close();
473 return $processed;
478 * Function to call all event handlers when triggering an event
480 * PUBLIC
482 * @param string $eventname name of the event
483 * @param object $eventdata event data object
484 * @return int number of failed events
486 function events_trigger($eventname, $eventdata) {
487 global $CFG, $USER, $DB;
489 $failedcount = 0; // number of failed events.
491 // pull out all registered event handlers
492 if ($handlers = events_get_handlers($eventname)) {
493 foreach ($handlers as $handler) {
494 $errormessage = '';
496 if ($handler->schedule === 'instant') {
497 if ($handler->status) {
498 //check if previous pending events processed
499 if (!$DB->record_exists('events_queue_handlers', array('handlerid'=>$handler->id))) {
500 // ok, queue is empty, lets reset the status back to 0 == ok
501 $handler->status = 0;
502 $DB->set_field('events_handlers', 'status', 0, array('id'=>$handler->id));
503 // reset static handler cache
504 events_get_handlers('reset');
508 // dispatch the event only if instant schedule and status ok
509 if ($handler->status or (!$handler->internal and $DB->is_transaction_started())) {
510 // increment the error status counter
511 $handler->status++;
512 $DB->set_field('events_handlers', 'status', $handler->status, array('id'=>$handler->id));
513 // reset static handler cache
514 events_get_handlers('reset');
516 } else {
517 $errormessage = 'Unknown error';;
518 $result = events_dispatch($handler, $eventdata, $errormessage);
519 if ($result === true) {
520 // everything is fine - event dispatched
521 continue;
522 } else if ($result === false) {
523 // retry later - set error count to 1 == send next instant into cron queue
524 $DB->set_field('events_handlers', 'status', 1, array('id'=>$handler->id));
525 // reset static handler cache
526 events_get_handlers('reset');
527 } else {
528 // internal problem - ignore the event completely
529 $failedcount ++;
530 continue;
534 // update the failed counter
535 $failedcount ++;
537 } else if ($handler->schedule === 'cron') {
538 //ok - use queueing of events only
540 } else {
541 // unknown schedule - ignore event completely
542 debugging("Unknown handler schedule type: $handler->schedule");
543 $failedcount ++;
544 continue;
547 // if even type is not instant, or dispatch asked for retry, queue it
548 $event = new stdClass();
549 $event->userid = $USER->id;
550 $event->eventdata = base64_encode(serialize($eventdata));
551 $event->timecreated = time();
552 if (debugging()) {
553 $dump = '';
554 $callers = debug_backtrace();
555 foreach ($callers as $caller) {
556 if (!isset($caller['line'])) {
557 $caller['line'] = '?';
559 if (!isset($caller['file'])) {
560 $caller['file'] = '?';
562 $dump .= 'line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
563 if (isset($caller['function'])) {
564 $dump .= ': call to ';
565 if (isset($caller['class'])) {
566 $dump .= $caller['class'] . $caller['type'];
568 $dump .= $caller['function'] . '()';
570 $dump .= "\n";
572 $event->stackdump = $dump;
573 } else {
574 $event->stackdump = '';
576 $event->id = $DB->insert_record('events_queue', $event);
577 events_queue_handler($handler, $event, $errormessage);
579 } else {
580 // No handler found for this event name - this is ok!
583 return $failedcount;
587 * checks if an event is registered for this component
589 * @param string $eventname name of the event
590 * @param string $component component name, can be mod/data or moodle
591 * @return bool
593 function events_is_registered($eventname, $component) {
594 global $DB;
595 return $DB->record_exists('events_handlers', array('component'=>$component, 'eventname'=>$eventname));
599 * checks if an event is queued for processing - either cron handlers attached or failed instant handlers
601 * PUBLIC
603 * @param string $eventname name of the event
604 * @return int number of queued events
606 function events_pending_count($eventname) {
607 global $DB;
609 $sql = "SELECT COUNT('x')
610 FROM {events_queue_handlers} qh
611 JOIN {events_handlers} h ON h.id = qh.handlerid
612 WHERE h.eventname = ?";
614 return $DB->count_records_sql($sql, array($eventname));