Merge branch 'MDL-62560-master'
[moodle.git] / lib / messagelib.php
blobb808981d8ba1b82aaeeb8588f9ff086894207608
1 <?php
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.
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/>.
17 /**
18 * Functions for interacting with the message system
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
25 defined('MOODLE_INTERNAL') || die();
27 require_once(__DIR__ . '/../message/lib.php');
29 /**
30 * Called when a message provider wants to send a message.
31 * This functions checks the message recipient's message processor configuration then
32 * sends the message to the configured processors
34 * Required parameters of the $eventdata object:
35 * component string component name. must exist in message_providers
36 * name string message type name. must exist in message_providers
37 * userfrom object|int the user sending the message
38 * userto object|int the message recipient
39 * subject string the message subject
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
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
50 * Note: processor failure is is not reported as false return value,
51 * earlier versions did not do it consistently either.
53 * @category message
54 * @param \core\message\message $eventdata information about the message (component, userfrom, userto, ...)
55 * @return mixed the integer ID of the new message or false if there was a problem with submitted data
57 function message_send(\core\message\message $eventdata) {
58 global $CFG, $DB;
60 //new message ID to return
61 $messageid = false;
63 // Fetch default (site) preferences
64 $defaultpreferences = get_message_output_default_preferences();
65 $preferencebase = $eventdata->component.'_'.$eventdata->name;
67 // If the message provider is disabled via preferences, then don't send the message.
68 if (!empty($defaultpreferences->{$preferencebase.'_disable'})) {
69 return $messageid;
72 // By default a message is a notification. Only personal/private messages aren't notifications.
73 if (!isset($eventdata->notification)) {
74 $eventdata->notification = 1;
77 if (!is_object($eventdata->userto)) {
78 $eventdata->userto = core_user::get_user($eventdata->userto);
80 if (!is_object($eventdata->userfrom)) {
81 $eventdata->userfrom = core_user::get_user($eventdata->userfrom);
83 if (!$eventdata->userto) {
84 debugging('Attempt to send msg to unknown user', DEBUG_NORMAL);
85 return false;
87 if (!$eventdata->userfrom) {
88 debugging('Attempt to send msg from unknown user', DEBUG_NORMAL);
89 return false;
92 // If the provider's component is disabled or the user can't receive messages from it, don't send the message.
93 $isproviderallowed = false;
94 foreach (message_get_providers_for_user($eventdata->userto->id) as $provider) {
95 if ($provider->component === $eventdata->component && $provider->name === $eventdata->name) {
96 $isproviderallowed = true;
97 break;
100 if (!$isproviderallowed) {
101 debugging('Attempt to send msg from a provider '.$eventdata->component.'/'.$eventdata->name.
102 ' that is inactive or not allowed for the user id='.$eventdata->userto->id, DEBUG_NORMAL);
103 return false;
106 // Verify all necessary data fields are present.
107 if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended)
108 or !isset($eventdata->userto->deleted) or !isset($eventdata->userto->emailstop)) {
110 debugging('Necessary properties missing in userto object, fetching full record', DEBUG_DEVELOPER);
111 $eventdata->userto = core_user::get_user($eventdata->userto->id);
114 $usertoisrealuser = (core_user::is_real_user($eventdata->userto->id) != false);
115 // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
116 if (!$usertoisrealuser && !empty($eventdata->userto->emailstop)) {
117 debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
118 return false;
121 //after how long inactive should the user be considered logged off?
122 if (isset($CFG->block_online_users_timetosee)) {
123 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
124 } else {
125 $timetoshowusers = 300;//5 minutes
128 // Work out if the user is logged in or not
129 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
130 $userstate = 'loggedin';
131 } else {
132 $userstate = 'loggedoff';
135 // Check if we are creating a notification or message.
136 if ($eventdata->notification) {
137 $table = 'notifications';
139 $tabledata = new stdClass();
140 $tabledata->useridfrom = $eventdata->userfrom->id;
141 $tabledata->useridto = $eventdata->userto->id;
142 $tabledata->subject = $eventdata->subject;
143 $tabledata->fullmessage = $eventdata->fullmessage;
144 $tabledata->fullmessageformat = $eventdata->fullmessageformat;
145 $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
146 $tabledata->smallmessage = $eventdata->smallmessage;
147 $tabledata->eventtype = $eventdata->name;
148 $tabledata->component = $eventdata->component;
150 if (!empty($eventdata->contexturl)) {
151 $tabledata->contexturl = (string)$eventdata->contexturl;
152 } else {
153 $tabledata->contexturl = null;
156 if (!empty($eventdata->contexturlname)) {
157 $tabledata->contexturlname = (string)$eventdata->contexturlname;
158 } else {
159 $tabledata->contexturlname = null;
161 } else {
162 $table = 'messages';
164 if (!$conversationid = \core_message\api::get_conversation_between_users([$eventdata->userfrom->id,
165 $eventdata->userto->id])) {
166 $conversation = \core_message\api::create_conversation(
167 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
169 $eventdata->userfrom->id,
170 $eventdata->userto->id
173 $conversationid = $conversation->id;
176 $tabledata = new stdClass();
177 $tabledata->courseid = $eventdata->courseid;
178 $tabledata->useridfrom = $eventdata->userfrom->id;
179 $tabledata->conversationid = $conversationid;
180 $tabledata->subject = $eventdata->subject;
181 $tabledata->fullmessage = $eventdata->fullmessage;
182 $tabledata->fullmessageformat = $eventdata->fullmessageformat;
183 $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
184 $tabledata->smallmessage = $eventdata->smallmessage;
187 $tabledata->timecreated = time();
189 if (PHPUNIT_TEST and class_exists('phpunit_util')) {
190 // Add some more tests to make sure the normal code can actually work.
191 $componentdir = core_component::get_component_directory($eventdata->component);
192 if (!$componentdir or !is_dir($componentdir)) {
193 throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component);
195 if (!file_exists("$componentdir/db/messages.php")) {
196 throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
198 $messageproviders = null;
199 include("$componentdir/db/messages.php");
200 if (!isset($messageproviders[$eventdata->name])) {
201 throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' messages.php file");
203 unset($componentdir);
204 unset($messageproviders);
205 // Now ask phpunit if it wants to catch this message.
206 if (phpunit_util::is_redirecting_messages()) {
207 $messageid = $DB->insert_record($table, $tabledata);
208 $message = $DB->get_record($table, array('id' => $messageid));
210 // Add the useridto attribute for BC.
211 $message->useridto = $eventdata->userto->id;
213 // Mark the message/notification as read.
214 if ($eventdata->notification) {
215 \core_message\api::mark_notification_as_read($message);
216 } else {
217 \core_message\api::mark_message_as_read($eventdata->userto->id, $message);
220 // Unit tests need this detail.
221 $message->notification = $eventdata->notification;
222 phpunit_util::message_sent($message);
223 return $messageid;
227 // Fetch enabled processors.
228 // If we are dealing with a message some processors may want to handle it regardless of user and site settings.
229 if (!$eventdata->notification) {
230 $processors = array_filter(get_message_processors(false), function($processor) {
231 if ($processor->object->force_process_messages()) {
232 return true;
235 return ($processor->enabled && $processor->configured);
237 } else {
238 $processors = get_message_processors(true);
241 // Preset variables
242 $processorlist = array();
243 // Fill in the array of processors to be used based on default and user preferences
244 foreach ($processors as $processor) {
245 // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
246 if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
247 continue;
250 // First find out permissions
251 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
252 if (isset($defaultpreferences->{$defaultpreference})) {
253 $permitted = $defaultpreferences->{$defaultpreference};
254 } else {
255 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
256 // exist in the message_provider table (thus there is no default settings for them).
257 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
258 to message_send() are valid.";
259 throw new coding_exception($preferrormsg);
262 // Find out if user has configured this output
263 // Some processors cannot function without settings from the user
264 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
266 // DEBUG: notify if we are forcing unconfigured output
267 if ($permitted == 'forced' && !$userisconfigured) {
268 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
271 // Populate the list of processors we will be using
272 if (!$eventdata->notification && $processor->object->force_process_messages()) {
273 $processorlist[] = $processor->name;
274 } else if ($permitted == 'forced' && $userisconfigured) {
275 // An admin is forcing users to use this message processor. Use this processor unconditionally.
276 $processorlist[] = $processor->name;
277 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
278 // User has not disabled notifications
279 // See if user set any notification preferences, otherwise use site default ones
280 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
281 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto)) {
282 if (in_array($processor->name, explode(',', $userpreference))) {
283 $processorlist[] = $processor->name;
285 } else if (isset($defaultpreferences->{$userpreferencename})) {
286 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
287 $processorlist[] = $processor->name;
293 // Only cache messages, not notifications.
294 if (!$eventdata->notification) {
295 // Cache the timecreated value of the last message between these two users.
296 $cache = cache::make('core', 'message_time_last_message_between_users');
297 $key = \core_message\helper::get_last_message_time_created_cache_key($eventdata->userfrom->id,
298 $eventdata->userto->id);
299 $cache->set($key, $tabledata->timecreated);
302 // Store unread message just in case we get a fatal error any time later.
303 $tabledata->id = $DB->insert_record($table, $tabledata);
304 $eventdata->savedmessageid = $tabledata->id;
306 // Let the manager do the sending or buffering when db transaction in progress.
307 return \core\message\manager::send_message($eventdata, $tabledata, $processorlist);
312 * Updates the message_providers table with the current set of message providers
314 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
315 * @return boolean True on success
317 function message_update_providers($component='moodle') {
318 global $DB;
320 // load message providers from files
321 $fileproviders = message_get_providers_from_file($component);
323 // load message providers from the database
324 $dbproviders = message_get_providers_from_db($component);
326 foreach ($fileproviders as $messagename => $fileprovider) {
328 if (!empty($dbproviders[$messagename])) { // Already exists in the database
329 // check if capability has changed
330 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
331 // exact same message provider already present in db, ignore this entry
332 unset($dbproviders[$messagename]);
333 continue;
335 } else { // Update existing one
336 $provider = new stdClass();
337 $provider->id = $dbproviders[$messagename]->id;
338 $provider->capability = $fileprovider['capability'];
339 $DB->update_record('message_providers', $provider);
340 unset($dbproviders[$messagename]);
341 continue;
344 } else { // New message provider, add it
346 $provider = new stdClass();
347 $provider->name = $messagename;
348 $provider->component = $component;
349 $provider->capability = $fileprovider['capability'];
351 $transaction = $DB->start_delegated_transaction();
352 $DB->insert_record('message_providers', $provider);
353 message_set_default_message_preference($component, $messagename, $fileprovider);
354 $transaction->allow_commit();
358 foreach ($dbproviders as $dbprovider) { // Delete old ones
359 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
360 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
361 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
362 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
365 return true;
369 * This function populates default message preferences for all existing providers
370 * when the new message processor is added.
372 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
373 * @throws invalid_parameter_exception if $processorname does not exist in the database
375 function message_update_processors($processorname) {
376 global $DB;
378 // validate if our processor exists
379 $processor = $DB->get_records('message_processors', array('name' => $processorname));
380 if (empty($processor)) {
381 throw new invalid_parameter_exception();
384 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
386 $transaction = $DB->start_delegated_transaction();
387 foreach ($providers as $provider) {
388 // load message providers from files
389 $fileproviders = message_get_providers_from_file($provider->component);
390 foreach ($fileproviders as $messagename => $fileprovider) {
391 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
394 $transaction->allow_commit();
398 * Setting default messaging preferences for particular message provider
400 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
401 * @param string $messagename The name of message provider
402 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
403 * @param string $processorname The optional name of message processor
405 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
406 global $DB;
408 // Fetch message processors
409 $condition = null;
410 // If we need to process a particular processor, set the select condition
411 if (!empty($processorname)) {
412 $condition = array('name' => $processorname);
414 $processors = $DB->get_records('message_processors', $condition);
416 // load default messaging preferences
417 $defaultpreferences = get_message_output_default_preferences();
419 // Setting default preference
420 $componentproviderbase = $component.'_'.$messagename;
421 $loggedinpref = array();
422 $loggedoffpref = array();
423 // set 'permitted' preference first for each messaging processor
424 foreach ($processors as $processor) {
425 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
426 // if we do not have this setting yet, set it
427 if (!isset($defaultpreferences->{$preferencename})) {
428 // determine plugin default settings
429 $plugindefault = 0;
430 if (isset($fileprovider['defaults'][$processor->name])) {
431 $plugindefault = $fileprovider['defaults'][$processor->name];
433 // get string values of the settings
434 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
435 // store default preferences for current processor
436 set_config($preferencename, $permitted, 'message');
437 // save loggedin/loggedoff settings
438 if ($loggedin) {
439 $loggedinpref[] = $processor->name;
441 if ($loggedoff) {
442 $loggedoffpref[] = $processor->name;
446 // now set loggedin/loggedoff preferences
447 if (!empty($loggedinpref)) {
448 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
449 if (isset($defaultpreferences->{$preferencename})) {
450 // We have the default preferences for this message provider, which
451 // likely means that we have been adding a new processor. Add defaults
452 // to exisitng preferences.
453 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
455 set_config($preferencename, join(',', $loggedinpref), 'message');
457 if (!empty($loggedoffpref)) {
458 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
459 if (isset($defaultpreferences->{$preferencename})) {
460 // We have the default preferences for this message provider, which
461 // likely means that we have been adding a new processor. Add defaults
462 // to exisitng preferences.
463 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
465 set_config($preferencename, join(',', $loggedoffpref), 'message');
470 * Returns the active providers for the user specified, based on capability
472 * @param int $userid id of user
473 * @return array An array of message providers
475 function message_get_providers_for_user($userid) {
476 global $DB, $CFG;
478 $providers = get_message_providers();
480 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
481 if (!$CFG->messaging) {
482 foreach ($providers as $providerid => $provider) {
483 if ($provider->name == 'instantmessage') {
484 unset($providers[$providerid]);
485 break;
490 // If the component is an enrolment plugin, check it is enabled
491 foreach ($providers as $providerid => $provider) {
492 list($type, $name) = core_component::normalize_component($provider->component);
493 if ($type == 'enrol' && !enrol_is_enabled($name)) {
494 unset($providers[$providerid]);
498 // Now we need to check capabilities. We need to eliminate the providers
499 // where the user does not have the corresponding capability anywhere.
500 // Here we deal with the common simple case of the user having the
501 // capability in the system context. That handles $CFG->defaultuserroleid.
502 // For the remaining providers/capabilities, we need to do a more complex
503 // query involving all overrides everywhere.
504 $unsureproviders = array();
505 $unsurecapabilities = array();
506 $systemcontext = context_system::instance();
507 foreach ($providers as $providerid => $provider) {
508 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
509 // The provider is relevant to this user.
510 continue;
513 $unsureproviders[$providerid] = $provider;
514 $unsurecapabilities[$provider->capability] = 1;
515 unset($providers[$providerid]);
518 if (empty($unsureproviders)) {
519 // More complex checks are not required.
520 return $providers;
523 // Now check the unsure capabilities.
524 list($capcondition, $params) = $DB->get_in_or_equal(
525 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
526 $params['userid'] = $userid;
528 $sql = "SELECT DISTINCT rc.capability, 1
530 FROM {role_assignments} ra
531 JOIN {context} actx ON actx.id = ra.contextid
532 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
533 JOIN {context} cctx ON cctx.id = rc.contextid
535 WHERE ra.userid = :userid
536 AND rc.capability $capcondition
537 AND rc.permission > 0
538 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
539 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
541 if (!empty($CFG->defaultfrontpageroleid)) {
542 $frontpagecontext = context_course::instance(SITEID);
544 list($capcondition2, $params2) = $DB->get_in_or_equal(
545 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
546 $params = array_merge($params, $params2);
547 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
548 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
550 $sql .= "
551 UNION
553 SELECT DISTINCT rc.capability, 1
555 FROM {role_capabilities} rc
556 JOIN {context} cctx ON cctx.id = rc.contextid
558 WHERE rc.roleid = :frontpageroleid
559 AND rc.capability $capcondition2
560 AND rc.permission > 0
561 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
564 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
566 // Add back any providers based on the detailed capability check.
567 foreach ($unsureproviders as $providerid => $provider) {
568 if (array_key_exists($provider->capability, $relevantcapabilities)) {
569 $providers[$providerid] = $provider;
573 return $providers;
577 * Gets the message providers that are in the database for this component.
579 * This is an internal function used within messagelib.php
581 * @see message_update_providers()
582 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
583 * @return array An array of message providers
585 function message_get_providers_from_db($component) {
586 global $DB;
588 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
592 * Loads the messages definitions for a component from file
594 * If no messages are defined for the component, return an empty array.
595 * This is an internal function used within messagelib.php
597 * @see message_update_providers()
598 * @see message_update_processors()
599 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
600 * @return array An array of message providers or empty array if not exists
602 function message_get_providers_from_file($component) {
603 $defpath = core_component::get_component_directory($component).'/db/messages.php';
605 $messageproviders = array();
607 if (file_exists($defpath)) {
608 require($defpath);
611 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
612 if (empty($messageprovider['capability'])) {
613 $messageproviders[$name]['capability'] = NULL;
615 if (empty($messageprovider['defaults'])) {
616 $messageproviders[$name]['defaults'] = array();
620 return $messageproviders;
624 * Remove all message providers for particular component and corresponding settings
626 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
627 * @return void
629 function message_provider_uninstall($component) {
630 global $DB;
632 $transaction = $DB->start_delegated_transaction();
633 $DB->delete_records('message_providers', array('component' => $component));
634 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
635 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
636 $transaction->allow_commit();
637 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
638 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
642 * Uninstall a message processor
644 * @param string $name A message processor name like 'email', 'jabber'
646 function message_processor_uninstall($name) {
647 global $DB;
649 $transaction = $DB->start_delegated_transaction();
650 $DB->delete_records('message_processors', array('name' => $name));
651 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
652 // delete permission preferences only, we do not care about loggedin/loggedoff
653 // defaults, they will be removed on the next attempt to update the preferences
654 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
655 $transaction->allow_commit();
656 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
657 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));