MDL-58650 core_message: always use 'popup' processor for messages
[moodle.git] / lib / messagelib.php
CommitLineData
ce02a9bf 1<?php
ce02a9bf 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/>.
3b120e46 16
17/**
6fbd60ef 18 * Functions for interacting with the message system
3b120e46 19 *
6fbd60ef
AD
20 * @package core_message
21 * @copyright 2008 Luis Rodrigues and Martin Dougiamas
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3b120e46 23 */
24
78bfb562
PS
25defined('MOODLE_INTERNAL') || die();
26
1fcf0ca8 27require_once(__DIR__ . '/../message/lib.php');
2e075f41 28
3b120e46 29/**
7c7d3afa 30 * Called when a message provider wants to send a message.
75e4f98c 31 * This functions checks the message recipient's message processor configuration then
6fbd60ef 32 * sends the message to the configured processors
7c7d3afa 33 *
21cde6ac 34 * Required parameters of the $eventdata object:
305adb10
AD
35 * component string component name. must exist in message_providers
36 * name string message type name. must exist in message_providers
76a8aef9
RK
37 * userfrom object|int the user sending the message
38 * userto object|int the message recipient
fe983847 39 * subject string the message subject
21cde6ac
DM
40 * fullmessage string the full message in a given format
41 * fullmessageformat int the format if the full message (FORMAT_MOODLE, FORMAT_HTML, ..)
42 * fullmessagehtml string the full version (the message processor will choose with one to use)
43 * smallmessage string the small version of the message
44 *
45 * Optional parameters of the $eventdata object:
46 * notification bool should the message be considered as a notification rather than a personal message
47 * contexturl string if this is a notification then you can specify a url to view the event. For example the forum post the user is being notified of.
48 * contexturlname string the display text for contexturl
7c7d3afa 49 *
349f98ad
PS
50 * Note: processor failure is is not reported as false return value,
51 * earlier versions did not do it consistently either.
52 *
a29bcf78 53 * @todo MDL-55449 Drop support for stdClass in Moodle 3.6
6fbd60ef 54 * @category message
cc350fd9 55 * @param \core\message\message $eventdata information about the message (component, userfrom, userto, ...)
349f98ad 56 * @return mixed the integer ID of the new message or false if there was a problem with submitted data
3b120e46 57 */
7c7d3afa 58function message_send($eventdata) {
3b120e46 59 global $CFG, $DB;
60
a29bcf78 61 // TODO MDL-55449 Drop support for stdClass in Moodle 3.6.
cc350fd9
AD
62 if ($eventdata instanceof \stdClass) {
63 if (!isset($eventdata->courseid)) {
64 $eventdata->courseid = null;
65 }
66
67 debugging('eventdata as \stdClass is deprecated. Please use core\message\message instead.', DEBUG_DEVELOPER);
68 }
69
3a00a167 70 //new message ID to return
71 $messageid = false;
72
fd0f7ac5
RT
73 // Fetch default (site) preferences
74 $defaultpreferences = get_message_output_default_preferences();
75 $preferencebase = $eventdata->component.'_'.$eventdata->name;
76 // If message provider is disabled then don't do any processing.
77 if (!empty($defaultpreferences->{$preferencebase.'_disable'})) {
78 return $messageid;
79 }
80
5e12b369
JL
81 // By default a message is a notification. Only personal/private messages aren't notifications.
82 if (!isset($eventdata->notification)) {
83 $eventdata->notification = 1;
84 }
85
349f98ad 86 if (!is_object($eventdata->userto)) {
3bcf6b3c 87 $eventdata->userto = core_user::get_user($eventdata->userto);
fe983847 88 }
349f98ad 89 if (!is_object($eventdata->userfrom)) {
3bcf6b3c 90 $eventdata->userfrom = core_user::get_user($eventdata->userfrom);
fe983847 91 }
349f98ad
PS
92 if (!$eventdata->userto) {
93 debugging('Attempt to send msg to unknown user', DEBUG_NORMAL);
94 return false;
95 }
96 if (!$eventdata->userfrom) {
97 debugging('Attempt to send msg from unknown user', DEBUG_NORMAL);
98 return false;
99 }
100
101 // Verify all necessary data fields are present.
102 if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended)
103 or !isset($eventdata->userto->deleted) or !isset($eventdata->userto->emailstop)) {
104
105 debugging('Necessary properties missing in userto object, fetching full record', DEBUG_DEVELOPER);
106 $eventdata->userto = core_user::get_user($eventdata->userto->id);
107 }
3bcf6b3c
RT
108
109 $usertoisrealuser = (core_user::is_real_user($eventdata->userto->id) != false);
110 // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
111 if (!$usertoisrealuser && !empty($eventdata->userto->emailstop)) {
112 debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
113 return false;
114 }
115
1560760f 116 //after how long inactive should the user be considered logged off?
3b120e46 117 if (isset($CFG->block_online_users_timetosee)) {
118 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
119 } else {
1560760f 120 $timetoshowusers = 300;//5 minutes
3b120e46 121 }
122
1560760f 123 // Work out if the user is logged in or not
bc68fc9a 124 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
3b120e46 125 $userstate = 'loggedin';
1560760f
AD
126 } else {
127 $userstate = 'loggedoff';
3b120e46 128 }
117bd748 129
1560760f 130 // Create the message object
365a5941 131 $savemessage = new stdClass();
cc350fd9 132 $savemessage->courseid = $eventdata->courseid;
3b120e46 133 $savemessage->useridfrom = $eventdata->userfrom->id;
134 $savemessage->useridto = $eventdata->userto->id;
135 $savemessage->subject = $eventdata->subject;
136 $savemessage->fullmessage = $eventdata->fullmessage;
137 $savemessage->fullmessageformat = $eventdata->fullmessageformat;
138 $savemessage->fullmessagehtml = $eventdata->fullmessagehtml;
139 $savemessage->smallmessage = $eventdata->smallmessage;
5e12b369 140 $savemessage->notification = $eventdata->notification;
3274d5ca
RW
141 $savemessage->eventtype = $eventdata->name;
142 $savemessage->component = $eventdata->component;
ff5b4081 143
14a0e7dd 144 if (!empty($eventdata->contexturl)) {
349f98ad 145 $savemessage->contexturl = (string)$eventdata->contexturl;
14a0e7dd
AD
146 } else {
147 $savemessage->contexturl = null;
148 }
149
150 if (!empty($eventdata->contexturlname)) {
349f98ad 151 $savemessage->contexturlname = (string)$eventdata->contexturlname;
14a0e7dd
AD
152 } else {
153 $savemessage->contexturlname = null;
154 }
155
ff5b4081 156 $savemessage->timecreated = time();
3b120e46 157
4c9e03f0
PS
158 if (PHPUNIT_TEST and class_exists('phpunit_util')) {
159 // Add some more tests to make sure the normal code can actually work.
b0d1d941 160 $componentdir = core_component::get_component_directory($eventdata->component);
4c9e03f0
PS
161 if (!$componentdir or !is_dir($componentdir)) {
162 throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component);
163 }
164 if (!file_exists("$componentdir/db/messages.php")) {
165 throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
166 }
167 $messageproviders = null;
168 include("$componentdir/db/messages.php");
169 if (!isset($messageproviders[$eventdata->name])) {
170 throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' messages.php file");
171 }
172 unset($componentdir);
173 unset($messageproviders);
174 // Now ask phpunit if it wants to catch this message.
175 if (phpunit_util::is_redirecting_messages()) {
176 $savemessage->timeread = time();
177 $messageid = $DB->insert_record('message_read', $savemessage);
178 $message = $DB->get_record('message_read', array('id'=>$messageid));
179 phpunit_util::message_sent($message);
180 return $messageid;
181 }
182 }
183
685daf1a
MN
184 // Fetch enabled processors.
185 // If we are dealing with a message some processors may want to handle it regardless of user and site settings.
186 if (empty($savemessage->notification)) {
187 $processors = array_filter(get_message_processors(false), function($processor) {
188 if ($processor->object->force_process_messages()) {
189 return true;
190 }
191
192 return ($processor->enabled && $processor->configured);
193 });
194 } else {
195 $processors = get_message_processors(true);
196 }
2e075f41
RK
197
198 // Preset variables
199 $processorlist = array();
2e075f41
RK
200 // Fill in the array of processors to be used based on default and user preferences
201 foreach ($processors as $processor) {
3bcf6b3c
RT
202 // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
203 if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
204 continue;
205 }
206
2e075f41
RK
207 // First find out permissions
208 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
e8fc7940 209 if (isset($defaultpreferences->{$defaultpreference})) {
2e075f41
RK
210 $permitted = $defaultpreferences->{$defaultpreference};
211 } else {
ba4c451f
FM
212 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
213 // exist in the message_provider table (thus there is no default settings for them).
214 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
215 to message_send() are valid.";
216 throw new coding_exception($preferrormsg);
60dd7688 217 }
2e075f41
RK
218
219 // Find out if user has configured this output
bb3546f3 220 // Some processors cannot function without settings from the user
b46ca3d7 221 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
2e075f41 222
be34802d 223 // DEBUG: notify if we are forcing unconfigured output
b46ca3d7 224 if ($permitted == 'forced' && !$userisconfigured) {
2e075f41
RK
225 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
226 }
227
228 // Populate the list of processors we will be using
685daf1a
MN
229 if (empty($savemessage->notification) && $processor->object->force_process_messages()) {
230 $processorlist[] = $processor->name;
231 } else if ($permitted == 'forced' && $userisconfigured) {
d8aa5ec7 232 // An admin is forcing users to use this message processor. Use this processor unconditionally.
2e075f41 233 $processorlist[] = $processor->name;
bb3546f3 234 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
d8aa5ec7
AD
235 // User has not disabled notifications
236 // See if user set any notification preferences, otherwise use site default ones
2e075f41 237 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
349f98ad 238 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto)) {
2e075f41
RK
239 if (in_array($processor->name, explode(',', $userpreference))) {
240 $processorlist[] = $processor->name;
241 }
e8fc7940 242 } else if (isset($defaultpreferences->{$userpreferencename})) {
2e075f41
RK
243 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
244 $processorlist[] = $processor->name;
245 }
246 }
247 }
2044a2b2 248 }
3b120e46 249
fb1469d8
RW
250 // Only cache messages, not notifications.
251 if (empty($savemessage->notification)) {
252 // Cache the timecreated value of the last message between these two users.
ffd7798c
MN
253 $cache = cache::make('core', 'message_time_last_message_between_users');
254 $key = \core_message\helper::get_last_message_time_created_cache_key($savemessage->useridfrom,
255 $savemessage->useridto);
fb1469d8
RW
256 $cache->set($key, $savemessage->timecreated);
257 }
258
349f98ad
PS
259 // Store unread message just in case we get a fatal error any time later.
260 $savemessage->id = $DB->insert_record('message', $savemessage);
261 $eventdata->savedmessageid = $savemessage->id;
ab1bc5d2 262
349f98ad
PS
263 // Let the manager do the sending or buffering when db transaction in progress.
264 return \core\message\manager::send_message($eventdata, $savemessage, $processorlist);
3b120e46 265}
266
120b3758 267
268/**
6fbd60ef 269 * Updates the message_providers table with the current set of message providers
ebe0c008 270 *
6fbd60ef
AD
271 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
272 * @return boolean True on success
120b3758 273 */
274function message_update_providers($component='moodle') {
275 global $DB;
276
277 // load message providers from files
278 $fileproviders = message_get_providers_from_file($component);
279
280 // load message providers from the database
281 $dbproviders = message_get_providers_from_db($component);
282
283 foreach ($fileproviders as $messagename => $fileprovider) {
284
285 if (!empty($dbproviders[$messagename])) { // Already exists in the database
298925d4 286 // check if capability has changed
120b3758 287 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
288 // exact same message provider already present in db, ignore this entry
289 unset($dbproviders[$messagename]);
290 continue;
291
292 } else { // Update existing one
365a5941 293 $provider = new stdClass();
7c7d3afa
PS
294 $provider->id = $dbproviders[$messagename]->id;
295 $provider->capability = $fileprovider['capability'];
120b3758 296 $DB->update_record('message_providers', $provider);
297 unset($dbproviders[$messagename]);
298 continue;
299 }
300
301 } else { // New message provider, add it
302
365a5941 303 $provider = new stdClass();
120b3758 304 $provider->name = $messagename;
305 $provider->component = $component;
306 $provider->capability = $fileprovider['capability'];
307
7a04c476 308 $transaction = $DB->start_delegated_transaction();
120b3758 309 $DB->insert_record('message_providers', $provider);
7a04c476
RK
310 message_set_default_message_preference($component, $messagename, $fileprovider);
311 $transaction->allow_commit();
120b3758 312 }
313 }
314
315 foreach ($dbproviders as $dbprovider) { // Delete old ones
316 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
298925d4
RK
317 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
318 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
007bfe8b 319 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
120b3758 320 }
31afb0a4
RK
321
322 return true;
120b3758 323}
324
afed8d0f
RK
325/**
326 * This function populates default message preferences for all existing providers
327 * when the new message processor is added.
328 *
329 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
6fbd60ef 330 * @throws invalid_parameter_exception if $processorname does not exist in the database
afed8d0f
RK
331 */
332function message_update_processors($processorname) {
333 global $DB;
334
335 // validate if our processor exists
336 $processor = $DB->get_records('message_processors', array('name' => $processorname));
337 if (empty($processor)) {
338 throw new invalid_parameter_exception();
339 }
340
341 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
342
343 $transaction = $DB->start_delegated_transaction();
344 foreach ($providers as $provider) {
345 // load message providers from files
346 $fileproviders = message_get_providers_from_file($provider->component);
347 foreach ($fileproviders as $messagename => $fileprovider) {
348 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
349 }
350 }
351 $transaction->allow_commit();
352}
353
7a04c476 354/**
6fbd60ef 355 * Setting default messaging preferences for particular message provider
ebe0c008 356 *
7a04c476
RK
357 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
358 * @param string $messagename The name of message provider
359 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
6fbd60ef 360 * @param string $processorname The optional name of message processor
7a04c476 361 */
afed8d0f 362function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
7a04c476
RK
363 global $DB;
364
365 // Fetch message processors
afed8d0f
RK
366 $condition = null;
367 // If we need to process a particular processor, set the select condition
368 if (!empty($processorname)) {
369 $condition = array('name' => $processorname);
370 }
371 $processors = $DB->get_records('message_processors', $condition);
7a04c476
RK
372
373 // load default messaging preferences
374 $defaultpreferences = get_message_output_default_preferences();
375
ebe0c008 376 // Setting default preference
7a04c476
RK
377 $componentproviderbase = $component.'_'.$messagename;
378 $loggedinpref = array();
379 $loggedoffpref = array();
ebe0c008 380 // set 'permitted' preference first for each messaging processor
7a04c476
RK
381 foreach ($processors as $processor) {
382 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
ebe0c008 383 // if we do not have this setting yet, set it
e8fc7940 384 if (!isset($defaultpreferences->{$preferencename})) {
7a04c476
RK
385 // determine plugin default settings
386 $plugindefault = 0;
387 if (isset($fileprovider['defaults'][$processor->name])) {
388 $plugindefault = $fileprovider['defaults'][$processor->name];
389 }
390 // get string values of the settings
391 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
392 // store default preferences for current processor
393 set_config($preferencename, $permitted, 'message');
394 // save loggedin/loggedoff settings
395 if ($loggedin) {
396 $loggedinpref[] = $processor->name;
397 }
398 if ($loggedoff) {
399 $loggedoffpref[] = $processor->name;
400 }
401 }
402 }
ebe0c008 403 // now set loggedin/loggedoff preferences
7a04c476
RK
404 if (!empty($loggedinpref)) {
405 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
afed8d0f
RK
406 if (isset($defaultpreferences->{$preferencename})) {
407 // We have the default preferences for this message provider, which
408 // likely means that we have been adding a new processor. Add defaults
409 // to exisitng preferences.
410 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
411 }
7a04c476
RK
412 set_config($preferencename, join(',', $loggedinpref), 'message');
413 }
414 if (!empty($loggedoffpref)) {
415 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
afed8d0f
RK
416 if (isset($defaultpreferences->{$preferencename})) {
417 // We have the default preferences for this message provider, which
418 // likely means that we have been adding a new processor. Add defaults
419 // to exisitng preferences.
420 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
421 }
7a04c476
RK
422 set_config($preferencename, join(',', $loggedoffpref), 'message');
423 }
424}
425
120b3758 426/**
a8134ff6 427 * Returns the active providers for the user specified, based on capability
ebe0c008 428 *
a8134ff6 429 * @param int $userid id of user
6fbd60ef 430 * @return array An array of message providers
120b3758 431 */
a8134ff6 432function message_get_providers_for_user($userid) {
9f05a1a6 433 global $DB, $CFG;
120b3758 434
7fcd3c30 435 $providers = get_message_providers();
120b3758 436
2cf5ab10
TH
437 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
438 if (!$CFG->messaging) {
439 foreach ($providers as $providerid => $provider) {
440 if ($provider->name == 'instantmessage') {
441 unset($providers[$providerid]);
442 break;
120b3758 443 }
444 }
2cf5ab10 445 }
12188796 446
2cf5ab10
TH
447 // If the component is an enrolment plugin, check it is enabled
448 foreach ($providers as $providerid => $provider) {
56da374e 449 list($type, $name) = core_component::normalize_component($provider->component);
2cf5ab10 450 if ($type == 'enrol' && !enrol_is_enabled($name)) {
9f05a1a6 451 unset($providers[$providerid]);
2cf5ab10
TH
452 }
453 }
454
455 // Now we need to check capabilities. We need to eliminate the providers
456 // where the user does not have the corresponding capability anywhere.
457 // Here we deal with the common simple case of the user having the
458 // capability in the system context. That handles $CFG->defaultuserroleid.
459 // For the remaining providers/capabilities, we need to do a more complex
460 // query involving all overrides everywhere.
461 $unsureproviders = array();
462 $unsurecapabilities = array();
463 $systemcontext = context_system::instance();
464 foreach ($providers as $providerid => $provider) {
465 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
466 // The provider is relevant to this user.
12188796
AD
467 continue;
468 }
469
2cf5ab10
TH
470 $unsureproviders[$providerid] = $provider;
471 $unsurecapabilities[$provider->capability] = 1;
472 unset($providers[$providerid]);
473 }
474
475 if (empty($unsureproviders)) {
476 // More complex checks are not required.
477 return $providers;
478 }
479
480 // Now check the unsure capabilities.
481 list($capcondition, $params) = $DB->get_in_or_equal(
482 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
483 $params['userid'] = $userid;
484
485 $sql = "SELECT DISTINCT rc.capability, 1
486
487 FROM {role_assignments} ra
488 JOIN {context} actx ON actx.id = ra.contextid
489 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
490 JOIN {context} cctx ON cctx.id = rc.contextid
491
492 WHERE ra.userid = :userid
493 AND rc.capability $capcondition
494 AND rc.permission > 0
5c4685f0
DP
495 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
496 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
2cf5ab10
TH
497
498 if (!empty($CFG->defaultfrontpageroleid)) {
499 $frontpagecontext = context_course::instance(SITEID);
500
501 list($capcondition2, $params2) = $DB->get_in_or_equal(
502 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
503 $params = array_merge($params, $params2);
504 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
505 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
506
507 $sql .= "
5f7b0f2b 508 UNION
2cf5ab10
TH
509
510 SELECT DISTINCT rc.capability, 1
511
512 FROM {role_capabilities} rc
513 JOIN {context} cctx ON cctx.id = rc.contextid
514
515 WHERE rc.roleid = :frontpageroleid
516 AND rc.capability $capcondition2
517 AND rc.permission > 0
5c4685f0 518 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
2cf5ab10
TH
519 }
520
521 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
522
523 // Add back any providers based on the detailed capability check.
524 foreach ($unsureproviders as $providerid => $provider) {
525 if (array_key_exists($provider->capability, $relevantcapabilities)) {
526 $providers[$providerid] = $provider;
9f05a1a6 527 }
120b3758 528 }
529
530 return $providers;
531}
532
533/**
534 * Gets the message providers that are in the database for this component.
ebe0c008 535 *
6fbd60ef 536 * This is an internal function used within messagelib.php
120b3758 537 *
75e4f98c 538 * @see message_update_providers()
6fbd60ef
AD
539 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
540 * @return array An array of message providers
120b3758 541 */
542function message_get_providers_from_db($component) {
543 global $DB;
544
7c7d3afa 545 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
120b3758 546}
547
548/**
6fbd60ef 549 * Loads the messages definitions for a component from file
ebe0c008 550 *
6fbd60ef
AD
551 * If no messages are defined for the component, return an empty array.
552 * This is an internal function used within messagelib.php
120b3758 553 *
6fbd60ef
AD
554 * @see message_update_providers()
555 * @see message_update_processors()
556 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
557 * @return array An array of message providers or empty array if not exists
120b3758 558 */
559function message_get_providers_from_file($component) {
b0d1d941 560 $defpath = core_component::get_component_directory($component).'/db/messages.php';
120b3758 561
562 $messageproviders = array();
563
564 if (file_exists($defpath)) {
565 require($defpath);
566 }
567
568 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
569 if (empty($messageprovider['capability'])) {
570 $messageproviders[$name]['capability'] = NULL;
571 }
7a04c476
RK
572 if (empty($messageprovider['defaults'])) {
573 $messageproviders[$name]['defaults'] = array();
574 }
120b3758 575 }
576
577 return $messageproviders;
578}
579
580/**
6fbd60ef 581 * Remove all message providers for particular component and corresponding settings
ebe0c008 582 *
6fbd60ef 583 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
ebe0c008 584 * @return void
120b3758 585 */
8e265315 586function message_provider_uninstall($component) {
03dd0575 587 global $DB;
a813a748 588
7a04c476
RK
589 $transaction = $DB->start_delegated_transaction();
590 $DB->delete_records('message_providers', array('component' => $component));
591 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
592 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
593 $transaction->allow_commit();
007bfe8b
SH
594 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
595 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
2044a2b2 596}
8e265315
RK
597
598/**
6fbd60ef 599 * Uninstall a message processor
8e265315 600 *
6fbd60ef 601 * @param string $name A message processor name like 'email', 'jabber'
8e265315
RK
602 */
603function message_processor_uninstall($name) {
604 global $DB;
605
606 $transaction = $DB->start_delegated_transaction();
607 $DB->delete_records('message_processors', array('name' => $name));
3f9d9e28 608 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
8e265315
RK
609 // delete permission preferences only, we do not care about loggedin/loggedoff
610 // defaults, they will be removed on the next attempt to update the preferences
611 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
612 $transaction->allow_commit();
007bfe8b
SH
613 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
614 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));
8e265315 615}