forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventslib.php
executable file
·519 lines (441 loc) · 18 KB
/
eventslib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
<?php
/**
* Library of functions for events manipulation.
*
* The public API is all at the end of this file.
*
* @author Martin Dougiamas and many others
* @version $Id$
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodlecore
*/
/**
* Loads the events definitions for the component (from file). If no
* events are defined for the component, we simply return an empty array.
* @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
* @return array of capabilities or empty array if not exists
*
* INTERNAL - to be used from eventslib only
*/
function events_load_def($component) {
global $CFG;
if ($component == 'moodle') {
$defpath = $CFG->libdir.'/db/events.php';
} else if ($component == 'unittest') {
$defpath = $CFG->libdir.'/simpletest/fixtures/events.php';
} else {
$compparts = explode('/', $component);
if ($compparts[0] == 'block') {
// Blocks are an exception. Blocks directory is 'blocks', and not
// 'block'. So we need to jump through hoops.
$defpath = $CFG->dirroot.'/blocks/'.$compparts[1].'/db/events.php';
} else if ($compparts[0] == 'format') {
// Similar to the above, course formats are 'format' while they
// are stored in 'course/format'.
$defpath = $CFG->dirroot.'/course/format/'.$compparts[1].'/db/events.php';
} else if ($compparts[0] == 'gradeimport') {
$defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/events.php';
} else if ($compparts[0] == 'gradeexport') {
$defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/events.php';
} else if ($compparts[0] == 'gradereport') {
$defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/events.php';
} else if ($compparts[0] == 'portfolio'){
$defpath = $CFG->dirroot.'/portfolio/type/'.$compparts[1].'/db/events.php';
} else {
$defpath = $CFG->dirroot.'/'.$component.'/db/events.php';
}
}
$handlers = array();
if (file_exists($defpath)) {
require($defpath);
}
return $handlers;
}
/**
* Gets the capabilities that have been cached in the database for this
* component.
* @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
* @return array of events
*
* INTERNAL - to be used from eventslib only
*/
function events_get_cached($component) {
global $DB;
$cachedhandlers = array();
if ($storedhandlers = $DB->get_records('events_handlers', array('handlermodule'=>$component))) {
foreach ($storedhandlers as $handler) {
$cachedhandlers[$handler->eventname] = array (
'id' => $handler->id,
'handlerfile' => $handler->handlerfile,
'handlerfunction' => $handler->handlerfunction,
'schedule' => $handler->schedule);
}
}
return $cachedhandlers;
}
/**
* We can not removed all event handlers in table, then add them again
* because event handlers could be referenced by queued items
*
* Note that the absence of the db/events.php event definition file
* will cause any queued events for the component to be removed from
* the database.
*
* @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
* @return boolean
*/
function events_update_definition($component='moodle') {
global $DB;
// load event definition from events.php
$filehandlers = events_load_def($component);
// load event definitions from db tables
// if we detect an event being already stored, we discard from this array later
// the remaining needs to be removed
$cachedhandlers = events_get_cached($component);
foreach ($filehandlers as $eventname => $filehandler) {
if (!empty($cachedhandlers[$eventname])) {
if ($cachedhandlers[$eventname]['handlerfile'] == $filehandler['handlerfile'] &&
$cachedhandlers[$eventname]['handlerfunction'] == serialize($filehandler['handlerfunction']) &&
$cachedhandlers[$eventname]['schedule'] == $filehandler['schedule']) {
// exact same event handler already present in db, ignore this entry
unset($cachedhandlers[$eventname]);
continue;
} else {
// same event name matches, this event has been updated, update the datebase
$handler = new object();
$handler->id = $cachedhandlers[$eventname]['id'];
$handler->handlerfile = $filehandler['handlerfile'];
$handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
$handler->schedule = $filehandler['schedule'];
$DB->update_record('events_handlers', $handler);
unset($cachedhandlers[$eventname]);
continue;
}
} else {
// if we are here, this event handler is not present in db (new)
// add it
$handler = new object();
$handler->eventname = $eventname;
$handler->handlermodule = $component;
$handler->handlerfile = $filehandler['handlerfile'];
$handler->handlerfunction = serialize($filehandler['handlerfunction']); // static class methods stored as array
$handler->schedule = $filehandler['schedule'];
$DB->insert_record('events_handlers', $handler);
}
}
// clean up the left overs, the entries in cachedevents array at this points are deprecated event handlers
// and should be removed, delete from db
events_cleanup($component, $cachedhandlers);
return true;
}
/**
* Remove all event handlers and queued events
* @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
*/
function events_uninstall($component) {
$cachedhandlers = events_get_cached($component);
events_cleanup($component, $cachedhandlers);
}
/**
* Deletes cached events that are no longer needed by the component.
* @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
* @param $chachedevents - array of the cached events definitions that will be
* @return int - number of deprecated capabilities that have been removed
*
* INTERNAL - to be used from eventslib only
*/
function events_cleanup($component, $cachedhandlers) {
global $DB;
$deletecount = 0;
foreach ($cachedhandlers as $eventname => $cachedhandler) {
if ($qhandlers = $DB->get_records('events_queue_handlers', array('handlerid'=>$cachedhandler['id']))) {
debugging("Removing pending events from queue before deleting of event handler: $component - $eventname");
foreach ($qhandlers as $qhandler) {
events_dequeue($qhandler);
}
}
if ($DB->delete_records('events_handlers', array('eventname'=>$eventname, 'handlermodule'=>$component))) {
$deletecount++;
}
}
return $deletecount;
}
/****************** End of Events handler Definition code *******************/
/**
* puts a handler on queue
* @param object handler - event handler object from db
* @param object eventdata - event data object
* @return id number of new queue handler
*
* INTERNAL - to be used from eventslib only
*/
function events_queue_handler($handler, $event, $errormessage) {
global $DB;
if ($qhandler = $DB->get_record('events_queue_handlers', array('queuedeventid'=>$event->id, 'handlerid'=>$handler->id))) {
debugging("Please check code: Event id $event->id is already queued in handler id $qhandler->id");
return $qhandler->id;
}
// make a new queue handler
$qhandler = new object();
$qhandler->queuedeventid = $event->id;
$qhandler->handlerid = $handler->id;
$qhandler->errormessage = $errormessage;
$qhandler->timemodified = time();
if ($handler->schedule == 'instant' and $handler->status == 1) {
$qhandler->status = 1; //already one failed attempt to dispatch this event
} else {
$qhandler->status = 0;
}
return $DB->insert_record('events_queue_handlers', $qhandler);
}
/**
* trigger a single event with a specified handler
* @param handler - hander object from db
* @param eventdata - event dataobject
* @param errormessage - error message indicating problem
* @return bool - success or fail
*
* INTERNAL - to be used from eventslib only
*/
function events_dispatch($handler, $eventdata, &$errormessage) {
global $CFG;
$function = unserialize($handler->handlerfunction);
if (is_callable($function)) {
// oki, no need for includes
} else if (file_exists($CFG->dirroot.$handler->handlerfile)) {
include_once($CFG->dirroot.$handler->handlerfile);
} else {
$errormessage = "Handler file of component $handler->handlermodule: $handler->handlerfile can not be found!";
return false;
}
// checks for handler validity
if (is_callable($function)) {
return call_user_func($function, $eventdata);
} else {
$errormessage = "Handler function of component $handler->handlermodule: $handler->handlerfunction not callable function or class method!";
return false;
}
}
/**
* given a queued handler, call the respective event handler to process the event
* @param object qhandler - events_queued_handler object from db
* @return boolean meaning success, or NULL on fatal failure
*
* INTERNAL - to be used from eventslib only
*/
function events_process_queued_handler($qhandler) {
global $CFG, $DB;
// get handler
if (!$handler = $DB->get_record('events_handlers', array('id'=>$qhandler->handlerid))) {
debugging("Error processing queue handler $qhandler->id, missing handler id: $qhandler->handlerid");
//irrecoverable error, remove broken queue handler
events_dequeue($qhandler);
return NULL;
}
// get event object
if (!$event = $DB->get_record('events_queue', array('id'=>$qhandler->queuedeventid))) {
// can't proceed with no event object - might happen when two crons running at the same time
debugging("Error processing queue handler $qhandler->id, missing event id: $qhandler->queuedeventid");
//irrecoverable error, remove broken queue handler
events_dequeue($qhandler);
return NULL;
}
// call the function specified by the handler
$errormessage = 'Unknown error';
if (events_dispatch($handler, unserialize(base64_decode($event->eventdata)), $errormessage)) {
//everything ok
events_dequeue($qhandler);
return true;
} else {
//dispatching failed
$qh = new object();
$qh->id = $qhandler->id;
$qh->errormessage = $errormessage;
$qh->timemodified = time();
$qh->status = $qhandler->status + 1;
$DB->update_record('events_queue_handlers', $qh);
return false;
}
}
/**
* removes this queued handler from the events_queued_handler table
* removes events_queue record from events_queue if no more references to this event object exists
* @param object qhandler - events_queued_handler object from db
*
* INTERNAL - to be used from eventslib only
*/
function events_dequeue($qhandler) {
global $DB;
// first delete the queue handler
$DB->delete_records('events_queue_handlers', array('id'=>$qhandler->id));
// if no more queued handler is pointing to the same event - delete the event too
if (!$DB->record_exists('events_queue_handlers', array('queuedeventid'=>$qhandler->queuedeventid))) {
$DB->delete_records('events_queue', array('id'=>$qhandler->queuedeventid));
}
}
/**
* Returns hanflers for given event. Uses caching for better perf.
* @param string $eventanme name of even or 'reset'
* @return mixed array of handlers or false otherwise
*
* INTERNAL - to be used from eventslib only
*/
function events_get_handlers($eventname) {
global $DB;
static $handlers = array();
if ($eventname == 'reset') {
$handlers = array();
return false;
}
if (!array_key_exists($eventname, $handlers)) {
$handlers[$eventname] = $DB->get_records('events_handlers', array('eventname'=>$eventname));
}
return $handlers[$eventname];
}
/****** Public events API starts here, do not use functions above in 3rd party code ******/
/**
* Events cron will try to empty the events queue by processing all the queued events handlers
* @param string eventname - empty means all
* @return number of dispatched+removed broken events
*
* PUBLIC
*/
function events_cron($eventname='') {
global $DB;
$failed = array();
$processed = 0;
if ($eventname) {
$sql = "SELECT qh.*
FROM {events_queue_handlers} qh, {events_handlers} h
WHERE qh.handlerid = h.id AND h.eventname=?
ORDER BY qh.id";
$params = array($eventname);
} else {
$sql = "SELECT *
FROM {events_queue_handlers}
ORDER BY id";
$params = array();
}
if ($rs = $DB->get_recordset_sql($sql, $params)) {
foreach ($rs as $qhandler) {
if (in_array($qhandler->handlerid, $failed)) {
// do not try to dispatch any later events when one already failed
continue;
}
$status = events_process_queued_handler($qhandler);
if ($status === false) {
$failed[] = $qhandler->handlerid;
} else {
$processed++;
}
}
$rs->close();
}
return $processed;
}
/**
* Function to call all eventhandlers when triggering an event
* @param eventname - name of the event
* @param eventdata - event data object
* @return number of failed events
*
* PUBLIC
*/
function events_trigger($eventname, $eventdata) {
global $CFG, $USER, $DB;
$failedcount = 0; // number of failed events.
$event = false;
// pull out all registered event handlers
if ($handlers = events_get_handlers($eventname)) {
foreach ($handlers as $handler) {
$errormessage = '';
if ($handler->schedule == 'instant') {
if ($handler->status) {
//check if previous pending events processed
if (!$DB->record_exists('events_queue_handlers', array('handlerid'=>$handler->id))) {
// ok, queue is empty, lets reset the status back to 0 == ok
$handler->status = 0;
$DB->set_field('events_handlers', 'status', 0, array('id'=>$handler->id));
}
}
// dispatch the event only if instant schedule and status ok
if (!$handler->status) {
$errormessage = 'Unknown error';;
if (events_dispatch($handler, $eventdata, $errormessage)) {
continue;
}
// set error count to 1 == send next instant into cron queue
$DB->set_field('events_handlers', 'status', 1, array('id'=>$handler->id));
} else {
// increment the error status counter
$handler->status++;
$DB->set_field('events_handlers', 'status', $handler->status, array('id'=>$handler->id));
}
// update the failed counter
$failedcount ++;
} else if ($handler->schedule == 'cron') {
//ok - use queuing of events only
} else {
// unknown schedule - fallback to cron type
debugging("Unknown handler schedule type: $handler->schedule");
}
// if even type is not instant, or dispatch failed, queue it
if ($event === false) {
$event = new object();
$event->userid = $USER->id;
$event->eventdata = base64_encode(serialize($eventdata));
$event->timecreated = time();
if (debugging()) {
$dump = '';
$callers = debug_backtrace();
foreach ($callers as $caller) {
$dump .= 'line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
if (isset($caller['function'])) {
$dump .= ': call to ';
if (isset($caller['class'])) {
$dump .= $caller['class'] . $caller['type'];
}
$dump .= $caller['function'] . '()';
}
$dump .= "\n";
}
$event->stackdump = $dump;
} else {
$event->stackdump = '';
}
$event->id = $DB->insert_record('events_queue', $event);
}
events_queue_handler($handler, $event, $errormessage);
}
} else {
//debugging("No handler found for event: $eventname");
}
return $failedcount;
}
/**
* checks if an event is registered for this component
* @param string eventname - name of the event
* @param string component - component name, can be mod/data or moodle
* @return bool
*
* PUBLIC
*/
function events_is_registered($eventname, $component) {
global $DB;
return $DB->record_exists('events_handlers', array('handlermodule'=>$component, 'eventname'=>$eventname));
}
/**
* checks if an event is queued for processing - either cron handlers attached or failed instant handlers
* @param string eventname - name of the event
* @return int number of queued events
*
* PUBLIC
*/
function events_pending_count($eventname) {
global $CFG, $DB;
$sql = "SELECT COUNT('x')
FROM {events_queue_handlers} qh, {events_handlers} h
WHERE qh.handlerid = h.id AND h.eventname=?";
return $DB->count_records_sql($sql, array($eventname));
}
?>