MDL-10870 A few more fixes to the file.php page's navigation
[moodle-pu.git] / lib / eventslib.php
blob81957a972749ec7f0002430c7fd7aed7b6876fb2
1 <?php
2 /**
3 * Library of functions for events manipulation.
4 *
5 * The public API is all at the end of this file.
7 * @author Martin Dougiamas and many others
8 * @version $Id$
9 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
10 * @package moodlecore
14 /**
15 * Loads the events definitions for the component (from file). If no
16 * events are defined for the component, we simply return an empty array.
17 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
18 * @return array of capabilities or empty array if not exists
20 * INTERNAL - to be used from eventslib only
22 function events_load_def($component) {
23 global $CFG;
25 if ($component == 'moodle') {
26 $defpath = $CFG->libdir.'/db/events.php';
28 } else if ($component == 'unittest') {
29 $defpath = $CFG->libdir.'/simpletest/fixtures/events.php';
31 } else {
32 $compparts = explode('/', $component);
34 if ($compparts[0] == 'block') {
35 // Blocks are an exception. Blocks directory is 'blocks', and not
36 // 'block'. So we need to jump through hoops.
37 $defpath = $CFG->dirroot.'/blocks/'.$compparts[1].'/db/events.php';
39 } else if ($compparts[0] == 'format') {
40 // Similar to the above, course formats are 'format' while they
41 // are stored in 'course/format'.
42 $defpath = $CFG->dirroot.'/course/format/'.$compparts[1].'/db/events.php';
44 } else if ($compparts[0] == 'gradeimport') {
45 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/events.php';
47 } else if ($compparts[0] == 'gradeexport') {
48 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/events.php';
50 } else if ($compparts[0] == 'gradereport') {
51 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/events.php';
53 } else {
54 $defpath = $CFG->dirroot.'/'.$component.'/db/events.php';
58 $handlers = array();
60 if (file_exists($defpath)) {
61 require($defpath);
64 return $handlers;
67 /**
68 * Gets the capabilities that have been cached in the database for this
69 * component.
70 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
71 * @return array of events
73 * INTERNAL - to be used from eventslib only
75 function events_get_cached($component) {
76 $cachedhandlers = array();
78 if ($storedhandlers = get_records('events_handlers', 'handlermodule', $component)) {
79 foreach ($storedhandlers as $handler) {
80 $cachedhandlers[$handler->eventname] = array (
81 'id' => $handler->id,
82 'handlerfile' => $handler->handlerfile,
83 'handlerfunction' => $handler->handlerfunction,
84 'schedule' => $handler->schedule);
88 return $cachedhandlers;
91 /**
92 * We can not removed all event handlers in table, then add them again
93 * because event handlers could be referenced by queued items
95 * Note that the absence of the db/events.php event definition file
96 * will cause any queued events for the component to be removed from
97 * the database.
99 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
100 * @return boolean
102 function events_update_definition($component='moodle') {
104 // load event definition from events.php
105 $filehandlers = events_load_def($component);
107 // load event definitions from db tables
108 // if we detect an event being already stored, we discard from this array later
109 // the remaining needs to be removed
110 $cachedhandlers = events_get_cached($component);
112 foreach ($filehandlers as $eventname => $filehandler) {
113 if (!empty($cachedhandlers[$eventname])) {
114 if ($cachedhandlers[$eventname]['handlerfile'] == $filehandler['handlerfile'] &&
115 $cachedhandlers[$eventname]['handlerfunction'] == serialize($filehandler['handlerfunction']) &&
116 $cachedhandlers[$eventname]['schedule'] == $filehandler['schedule']) {
117 // exact same event handler already present in db, ignore this entry
119 unset($cachedhandlers[$eventname]);
120 continue;
122 } else {
123 // same event name matches, this event has been updated, update the datebase
124 $handler = new object();
125 $handler->id = $cachedhandlers[$eventname]['id'];
126 $handler->handlerfile = $filehandler['handlerfile'];
127 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
128 $handler->schedule = $filehandler['schedule'];
130 update_record('events_handlers', $handler);
132 unset($cachedhandlers[$eventname]);
133 continue;
136 } else {
137 // if we are here, this event handler is not present in db (new)
138 // add it
139 $handler = new object();
140 $handler->eventname = $eventname;
141 $handler->handlermodule = $component;
142 $handler->handlerfile = $filehandler['handlerfile'];
143 $handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
144 $handler->schedule = $filehandler['schedule'];
146 insert_record('events_handlers', $handler);
150 // clean up the left overs, the entries in cachedevents array at this points are deprecated event handlers
151 // and should be removed, delete from db
152 events_cleanup($component, $cachedhandlers);
154 return true;
158 * Remove all event handlers and queued events
159 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
161 function events_uninstall($component) {
162 $cachedhandlers = events_get_cached($component);
163 events_cleanup($component, $cachedhandlers);
167 * Deletes cached events that are no longer needed by the component.
168 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
169 * @param $chachedevents - array of the cached events definitions that will be
170 * @return int - number of deprecated capabilities that have been removed
172 * INTERNAL - to be used from eventslib only
174 function events_cleanup($component, $cachedhandlers) {
175 $deletecount = 0;
176 foreach ($cachedhandlers as $eventname => $cachedhandler) {
177 if ($qhandlers = get_records('events_queue_handlers', 'handlerid', $cachedhandler['id'])) {
178 debugging("Removing pending events from queue before deleting of event handler: $component - $eventname");
179 foreach ($qhandlers as $qhandler) {
180 events_dequeue($qhandler);
183 if (delete_records('events_handlers', 'eventname', $eventname, 'handlermodule', $component)) {
184 $deletecount++;
187 return $deletecount;
190 /****************** End of Events handler Definition code *******************/
193 * puts a handler on queue
194 * @param object handler - event handler object from db
195 * @param object eventdata - event data object
196 * @return id number of new queue handler
198 * INTERNAL - to be used from eventslib only
200 function events_queue_handler($handler, $event, $errormessage) {
202 if ($qhandler = get_record('events_queue_handlers', 'queuedeventid', $event->id, 'handlerid', $handler->id)) {
203 debugging("Please check code: Event id $event->id is already queued in handler id $qhandler->id");
204 return $qhandler->id;
207 // make a new queue handler
208 $qhandler = new object();
209 $qhandler->queuedeventid = $event->id;
210 $qhandler->handlerid = $handler->id;
211 $qhandler->errormessage = addslashes($errormessage);
212 $qhandler->timemodified = time();
213 if ($handler->schedule == 'instant' and $handler->status == 1) {
214 $qhandler->status = 1; //already one failed attempt to dispatch this event
215 } else {
216 $qhandler->status = 0;
219 return insert_record('events_queue_handlers', $qhandler);
223 * trigger a single event with a specified handler
224 * @param handler - hander object from db
225 * @param eventdata - event dataobject
226 * @param errormessage - error message indicating problem
227 * @return bool - success or fail
229 * INTERNAL - to be used from eventslib only
231 function events_dispatch($handler, $eventdata, &$errormessage) {
232 global $CFG;
234 $function = unserialize($handler->handlerfunction);
236 if (is_callable($function)) {
237 // oki, no need for includes
239 } else if (file_exists($CFG->dirroot.$handler->handlerfile)) {
240 include_once($CFG->dirroot.$handler->handlerfile);
242 } else {
243 $errormessage = "Handler file of component $handler->handlermodule: $handler->handlerfile can not be found!";
244 return false;
247 // checks for handler validity
248 if (is_callable($function)) {
249 return call_user_func($function, $eventdata);
251 } else {
252 $errormessage = "Handler function of component $handler->handlermodule: $handler->handlerfunction not callable function or class method!";
253 return false;
258 * given a queued handler, call the respective event handler to process the event
259 * @param object qhandler - events_queued_handler object from db
260 * @return boolean meaning success, or NULL on fatal failure
262 * INTERNAL - to be used from eventslib only
264 function events_process_queued_handler($qhandler) {
265 global $CFG;
267 // get handler
268 if (!$handler = get_record('events_handlers', 'id', $qhandler->handlerid)) {
269 debugging("Error processing queue handler $qhandler->id, missing handler id: $qhandler->handlerid");
270 //irrecoverable error, remove broken queue handler
271 events_dequeue($qhandler);
272 return NULL;
275 // get event object
276 if (!$event = get_record('events_queue', 'id', $qhandler->queuedeventid)) {
277 // can't proceed with no event object - might happen when two crons running at the same time
278 debugging("Error processing queue handler $qhandler->id, missing event id: $qhandler->queuedeventid");
279 //irrecoverable error, remove broken queue handler
280 events_dequeue($qhandler);
281 return NULL;
284 // call the function specified by the handler
285 $errormessage = 'Unknown error';
286 if (events_dispatch($handler, unserialize($event->eventdata), $errormessage)) {
287 //everything ok
288 events_dequeue($qhandler);
289 return true;
291 } else {
292 //dispatching failed
293 $qh = new object();
294 $qh->id = $qhandler->id;
295 $qh->errormessage = addslashes($errormessage);
296 $qh->timemodified = time();
297 $qh->status = $qhandler->status + 1;
298 update_record('events_queue_handlers', $qh);
299 return false;
304 * removes this queued handler from the events_queued_handler table
305 * removes events_queue record from events_queue if no more references to this event object exists
306 * @param object qhandler - events_queued_handler object from db
308 * INTERNAL - to be used from eventslib only
310 function events_dequeue($qhandler) {
311 // first delete the queue handler
312 delete_records('events_queue_handlers', 'id', $qhandler->id);
314 // if no more queued handler is pointing to the same event - delete the event too
315 if (!record_exists('events_queue_handlers', 'queuedeventid', $qhandler->queuedeventid)) {
316 delete_records('events_queue', 'id', $qhandler->queuedeventid);
322 /****** Public events API starts here, do not use functions above in 3rd party code ******/
326 * Events cron will try to empty the events queue by processing all the queued events handlers
327 * @param string eventname - empty means all
328 * @return number of dispatched+removed broken events
330 * PUBLIC
332 function events_cron($eventname='') {
333 global $CFG;
335 $failed = array();
336 $processed = 0;
338 if ($eventname) {
339 $sql = "SELECT qh.* FROM {$CFG->prefix}events_queue_handlers qh, {$CFG->prefix}events_handlers h
340 WHERE qh.handlerid = h.id AND h.eventname='$eventname'
341 ORDER BY qh.id";
342 } else {
343 $sql = "SELECT * FROM {$CFG->prefix}events_queue_handlers
344 ORDER BY id";
347 if ($rs = get_recordset_sql($sql)) {
348 if ($rs->RecordCount() > 0) {
349 while ($qhandler = rs_fetch_next_record($rs)) {
350 if (in_array($qhandler->handlerid, $failed)) {
351 // do not try to dispatch any later events when one already failed
352 continue;
354 $status = events_process_queued_handler($qhandler);
355 if ($status === false) {
356 $failed[] = $qhandler->handlerid;
357 } else {
358 $processed++;
362 rs_close($rs);
364 return $processed;
369 * Function to call all eventhandlers when triggering an event
370 * @param eventname - name of the event
371 * @param eventdata - event data object
372 * @return number of failed events
374 * PUBLIC
376 function events_trigger($eventname, $eventdata) {
377 global $CFG, $USER;
379 $failedcount = 0; // number of failed events.
380 $event = false;
382 // pull out all registered event handlers
383 if ($handlers = get_records('events_handlers', 'eventname', $eventname)) {
384 foreach ($handlers as $handler) {
386 $errormessage = '';
388 if ($handler->schedule == 'instant') {
389 if ($handler->status) {
390 //check if previous pending events processed
391 if (!record_exists('events_queue_handlers', 'handlerid', $handler->id)) {
392 // ok, queue is empty, lets reset the status back to 0 == ok
393 $handler->status = 0;
394 set_field('events_handlers', 'status', 0, 'id', $handler->id);
398 // dispatch the event only if instant schedule and status ok
399 if (!$handler->status) {
400 $errormessage = 'Unknown error';;
401 if (events_dispatch($handler, $eventdata, $errormessage)) {
402 continue;
404 // set error count to 1 == send next instant into cron queue
405 set_field('events_handlers', 'status', 1, 'id', $handler->id);
407 } else {
408 // increment the error status counter
409 $handler->status++;
410 set_field('events_handlers', 'status', $handler->status, 'id', $handler->id);
413 // update the failed counter
414 $failedcount ++;
416 } else if ($handler->schedule == 'cron') {
417 //ok - use queuing of events only
419 } else {
420 // unknown schedule - fallback to cron type
421 debugging("Unknown handler schedule type: $handler->schedule");
424 // if even type is not instant, or dispatch failed, queue it
425 if ($event === false) {
426 $event = new object();
427 $event->userid = $USER->id;
428 $event->eventdata = serialize($eventdata);
429 $event->timecreated = time();
430 if (debugging()) {
431 $dump = '';
432 $callers = debug_backtrace();
433 foreach ($callers as $caller) {
434 $dump .= 'line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
435 if (isset($caller['function'])) {
436 $dump .= ': call to ';
437 if (isset($caller['class'])) {
438 $dump .= $caller['class'] . $caller['type'];
440 $dump .= $caller['function'] . '()';
442 $dump .= "\n";
444 $event->stackdump = addslashes($dump);
445 } else {
446 $event->stackdump = '';
448 $event->id = insert_record('events_queue', $event);
450 events_queue_handler($handler, $event, $errormessage);
452 } else {
453 //debugging("No handler found for event: $eventname");
456 return $failedcount;
460 * checks if an event is registered for this component
461 * @param string eventname - name of the event
462 * @param string component - component name, can be mod/data or moodle
463 * @return bool
465 * PUBLIC
467 function events_is_registered($eventname, $component) {
468 return record_exists('events_handlers', 'handlermodule', $component, 'eventname', $eventname);
472 * checks if an event is queued for processing - either cron handlers attached or failed instant handlers
473 * @param string eventname - name of the event
474 * @return int number of queued events
476 * PUBLIC
478 function events_pending_count($eventname) {
479 global $CFG;
481 $sql = "SELECT COUNT(*) FROM {$CFG->prefix}events_queue_handlers qh, {$CFG->prefix}events_handlers h
482 WHERE qh.handlerid = h.id AND h.eventname='$eventname'";
483 return count_records_sql($sql);