MDL-62388 tool_dataprivacy: Fixing bs4stable table layout
[moodle.git] / lib / messagelib.php
blob0b5d300609d3c7d3d30abb912aa15bf7491817ca
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 * @todo MDL-55449 Drop support for stdClass in Moodle 3.6
54 * @category message
55 * @param \core\message\message $eventdata information about the message (component, userfrom, userto, ...)
56 * @return mixed the integer ID of the new message or false if there was a problem with submitted data
58 function message_send($eventdata) {
59 global $CFG, $DB;
61 // TODO MDL-55449 Drop support for stdClass in Moodle 3.6.
62 if ($eventdata instanceof \stdClass) {
63 if (!isset($eventdata->courseid)) {
64 $eventdata->courseid = null;
67 debugging('eventdata as \stdClass is deprecated. Please use core\message\message instead.', DEBUG_DEVELOPER);
70 //new message ID to return
71 $messageid = false;
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;
81 // By default a message is a notification. Only personal/private messages aren't notifications.
82 if (!isset($eventdata->notification)) {
83 $eventdata->notification = 1;
86 if (!is_object($eventdata->userto)) {
87 $eventdata->userto = core_user::get_user($eventdata->userto);
89 if (!is_object($eventdata->userfrom)) {
90 $eventdata->userfrom = core_user::get_user($eventdata->userfrom);
92 if (!$eventdata->userto) {
93 debugging('Attempt to send msg to unknown user', DEBUG_NORMAL);
94 return false;
96 if (!$eventdata->userfrom) {
97 debugging('Attempt to send msg from unknown user', DEBUG_NORMAL);
98 return false;
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)) {
105 debugging('Necessary properties missing in userto object, fetching full record', DEBUG_DEVELOPER);
106 $eventdata->userto = core_user::get_user($eventdata->userto->id);
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;
116 //after how long inactive should the user be considered logged off?
117 if (isset($CFG->block_online_users_timetosee)) {
118 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
119 } else {
120 $timetoshowusers = 300;//5 minutes
123 // Work out if the user is logged in or not
124 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
125 $userstate = 'loggedin';
126 } else {
127 $userstate = 'loggedoff';
130 // Check if we are creating a notification or message.
131 if ($eventdata->notification) {
132 $table = 'notifications';
134 $tabledata = new stdClass();
135 $tabledata->useridfrom = $eventdata->userfrom->id;
136 $tabledata->useridto = $eventdata->userto->id;
137 $tabledata->subject = $eventdata->subject;
138 $tabledata->fullmessage = $eventdata->fullmessage;
139 $tabledata->fullmessageformat = $eventdata->fullmessageformat;
140 $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
141 $tabledata->smallmessage = $eventdata->smallmessage;
142 $tabledata->eventtype = $eventdata->name;
143 $tabledata->component = $eventdata->component;
145 if (!empty($eventdata->contexturl)) {
146 $tabledata->contexturl = (string)$eventdata->contexturl;
147 } else {
148 $tabledata->contexturl = null;
151 if (!empty($eventdata->contexturlname)) {
152 $tabledata->contexturlname = (string)$eventdata->contexturlname;
153 } else {
154 $tabledata->contexturlname = null;
156 } else {
157 $table = 'messages';
159 if (!$conversationid = \core_message\api::get_conversation_between_users([$eventdata->userfrom->id,
160 $eventdata->userto->id])) {
161 $conversationid = \core_message\api::create_conversation_between_users([$eventdata->userfrom->id,
162 $eventdata->userto->id]);
165 $tabledata = new stdClass();
166 $tabledata->courseid = $eventdata->courseid;
167 $tabledata->useridfrom = $eventdata->userfrom->id;
168 $tabledata->conversationid = $conversationid;
169 $tabledata->subject = $eventdata->subject;
170 $tabledata->fullmessage = $eventdata->fullmessage;
171 $tabledata->fullmessageformat = $eventdata->fullmessageformat;
172 $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
173 $tabledata->smallmessage = $eventdata->smallmessage;
176 $tabledata->timecreated = time();
178 if (PHPUNIT_TEST and class_exists('phpunit_util')) {
179 // Add some more tests to make sure the normal code can actually work.
180 $componentdir = core_component::get_component_directory($eventdata->component);
181 if (!$componentdir or !is_dir($componentdir)) {
182 throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component);
184 if (!file_exists("$componentdir/db/messages.php")) {
185 throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
187 $messageproviders = null;
188 include("$componentdir/db/messages.php");
189 if (!isset($messageproviders[$eventdata->name])) {
190 throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' messages.php file");
192 unset($componentdir);
193 unset($messageproviders);
194 // Now ask phpunit if it wants to catch this message.
195 if (phpunit_util::is_redirecting_messages()) {
196 $messageid = $DB->insert_record($table, $tabledata);
197 $message = $DB->get_record($table, array('id' => $messageid));
199 // Add the useridto attribute for BC.
200 $message->useridto = $eventdata->userto->id;
202 // Mark the message/notification as read.
203 if ($eventdata->notification) {
204 \core_message\api::mark_notification_as_read($message);
205 } else {
206 \core_message\api::mark_message_as_read($eventdata->userto->id, $message);
209 // Unit tests need this detail.
210 $message->notification = $eventdata->notification;
211 phpunit_util::message_sent($message);
212 return $messageid;
216 // Fetch enabled processors.
217 // If we are dealing with a message some processors may want to handle it regardless of user and site settings.
218 if (!$eventdata->notification) {
219 $processors = array_filter(get_message_processors(false), function($processor) {
220 if ($processor->object->force_process_messages()) {
221 return true;
224 return ($processor->enabled && $processor->configured);
226 } else {
227 $processors = get_message_processors(true);
230 // Preset variables
231 $processorlist = array();
232 // Fill in the array of processors to be used based on default and user preferences
233 foreach ($processors as $processor) {
234 // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
235 if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
236 continue;
239 // First find out permissions
240 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
241 if (isset($defaultpreferences->{$defaultpreference})) {
242 $permitted = $defaultpreferences->{$defaultpreference};
243 } else {
244 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
245 // exist in the message_provider table (thus there is no default settings for them).
246 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
247 to message_send() are valid.";
248 throw new coding_exception($preferrormsg);
251 // Find out if user has configured this output
252 // Some processors cannot function without settings from the user
253 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
255 // DEBUG: notify if we are forcing unconfigured output
256 if ($permitted == 'forced' && !$userisconfigured) {
257 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
260 // Populate the list of processors we will be using
261 if (!$eventdata->notification && $processor->object->force_process_messages()) {
262 $processorlist[] = $processor->name;
263 } else if ($permitted == 'forced' && $userisconfigured) {
264 // An admin is forcing users to use this message processor. Use this processor unconditionally.
265 $processorlist[] = $processor->name;
266 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
267 // User has not disabled notifications
268 // See if user set any notification preferences, otherwise use site default ones
269 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
270 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto)) {
271 if (in_array($processor->name, explode(',', $userpreference))) {
272 $processorlist[] = $processor->name;
274 } else if (isset($defaultpreferences->{$userpreferencename})) {
275 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
276 $processorlist[] = $processor->name;
282 // Only cache messages, not notifications.
283 if (!$eventdata->notification) {
284 // Cache the timecreated value of the last message between these two users.
285 $cache = cache::make('core', 'message_time_last_message_between_users');
286 $key = \core_message\helper::get_last_message_time_created_cache_key($eventdata->userfrom->id,
287 $eventdata->userto->id);
288 $cache->set($key, $tabledata->timecreated);
291 // Store unread message just in case we get a fatal error any time later.
292 $tabledata->id = $DB->insert_record($table, $tabledata);
293 $eventdata->savedmessageid = $tabledata->id;
295 // Let the manager do the sending or buffering when db transaction in progress.
296 return \core\message\manager::send_message($eventdata, $tabledata, $processorlist);
301 * Updates the message_providers table with the current set of message providers
303 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
304 * @return boolean True on success
306 function message_update_providers($component='moodle') {
307 global $DB;
309 // load message providers from files
310 $fileproviders = message_get_providers_from_file($component);
312 // load message providers from the database
313 $dbproviders = message_get_providers_from_db($component);
315 foreach ($fileproviders as $messagename => $fileprovider) {
317 if (!empty($dbproviders[$messagename])) { // Already exists in the database
318 // check if capability has changed
319 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
320 // exact same message provider already present in db, ignore this entry
321 unset($dbproviders[$messagename]);
322 continue;
324 } else { // Update existing one
325 $provider = new stdClass();
326 $provider->id = $dbproviders[$messagename]->id;
327 $provider->capability = $fileprovider['capability'];
328 $DB->update_record('message_providers', $provider);
329 unset($dbproviders[$messagename]);
330 continue;
333 } else { // New message provider, add it
335 $provider = new stdClass();
336 $provider->name = $messagename;
337 $provider->component = $component;
338 $provider->capability = $fileprovider['capability'];
340 $transaction = $DB->start_delegated_transaction();
341 $DB->insert_record('message_providers', $provider);
342 message_set_default_message_preference($component, $messagename, $fileprovider);
343 $transaction->allow_commit();
347 foreach ($dbproviders as $dbprovider) { // Delete old ones
348 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
349 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
350 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
351 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
354 return true;
358 * This function populates default message preferences for all existing providers
359 * when the new message processor is added.
361 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
362 * @throws invalid_parameter_exception if $processorname does not exist in the database
364 function message_update_processors($processorname) {
365 global $DB;
367 // validate if our processor exists
368 $processor = $DB->get_records('message_processors', array('name' => $processorname));
369 if (empty($processor)) {
370 throw new invalid_parameter_exception();
373 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
375 $transaction = $DB->start_delegated_transaction();
376 foreach ($providers as $provider) {
377 // load message providers from files
378 $fileproviders = message_get_providers_from_file($provider->component);
379 foreach ($fileproviders as $messagename => $fileprovider) {
380 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
383 $transaction->allow_commit();
387 * Setting default messaging preferences for particular message provider
389 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
390 * @param string $messagename The name of message provider
391 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
392 * @param string $processorname The optional name of message processor
394 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
395 global $DB;
397 // Fetch message processors
398 $condition = null;
399 // If we need to process a particular processor, set the select condition
400 if (!empty($processorname)) {
401 $condition = array('name' => $processorname);
403 $processors = $DB->get_records('message_processors', $condition);
405 // load default messaging preferences
406 $defaultpreferences = get_message_output_default_preferences();
408 // Setting default preference
409 $componentproviderbase = $component.'_'.$messagename;
410 $loggedinpref = array();
411 $loggedoffpref = array();
412 // set 'permitted' preference first for each messaging processor
413 foreach ($processors as $processor) {
414 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
415 // if we do not have this setting yet, set it
416 if (!isset($defaultpreferences->{$preferencename})) {
417 // determine plugin default settings
418 $plugindefault = 0;
419 if (isset($fileprovider['defaults'][$processor->name])) {
420 $plugindefault = $fileprovider['defaults'][$processor->name];
422 // get string values of the settings
423 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
424 // store default preferences for current processor
425 set_config($preferencename, $permitted, 'message');
426 // save loggedin/loggedoff settings
427 if ($loggedin) {
428 $loggedinpref[] = $processor->name;
430 if ($loggedoff) {
431 $loggedoffpref[] = $processor->name;
435 // now set loggedin/loggedoff preferences
436 if (!empty($loggedinpref)) {
437 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
438 if (isset($defaultpreferences->{$preferencename})) {
439 // We have the default preferences for this message provider, which
440 // likely means that we have been adding a new processor. Add defaults
441 // to exisitng preferences.
442 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
444 set_config($preferencename, join(',', $loggedinpref), 'message');
446 if (!empty($loggedoffpref)) {
447 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
448 if (isset($defaultpreferences->{$preferencename})) {
449 // We have the default preferences for this message provider, which
450 // likely means that we have been adding a new processor. Add defaults
451 // to exisitng preferences.
452 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
454 set_config($preferencename, join(',', $loggedoffpref), 'message');
459 * Returns the active providers for the user specified, based on capability
461 * @param int $userid id of user
462 * @return array An array of message providers
464 function message_get_providers_for_user($userid) {
465 global $DB, $CFG;
467 $providers = get_message_providers();
469 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
470 if (!$CFG->messaging) {
471 foreach ($providers as $providerid => $provider) {
472 if ($provider->name == 'instantmessage') {
473 unset($providers[$providerid]);
474 break;
479 // If the component is an enrolment plugin, check it is enabled
480 foreach ($providers as $providerid => $provider) {
481 list($type, $name) = core_component::normalize_component($provider->component);
482 if ($type == 'enrol' && !enrol_is_enabled($name)) {
483 unset($providers[$providerid]);
487 // Now we need to check capabilities. We need to eliminate the providers
488 // where the user does not have the corresponding capability anywhere.
489 // Here we deal with the common simple case of the user having the
490 // capability in the system context. That handles $CFG->defaultuserroleid.
491 // For the remaining providers/capabilities, we need to do a more complex
492 // query involving all overrides everywhere.
493 $unsureproviders = array();
494 $unsurecapabilities = array();
495 $systemcontext = context_system::instance();
496 foreach ($providers as $providerid => $provider) {
497 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
498 // The provider is relevant to this user.
499 continue;
502 $unsureproviders[$providerid] = $provider;
503 $unsurecapabilities[$provider->capability] = 1;
504 unset($providers[$providerid]);
507 if (empty($unsureproviders)) {
508 // More complex checks are not required.
509 return $providers;
512 // Now check the unsure capabilities.
513 list($capcondition, $params) = $DB->get_in_or_equal(
514 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
515 $params['userid'] = $userid;
517 $sql = "SELECT DISTINCT rc.capability, 1
519 FROM {role_assignments} ra
520 JOIN {context} actx ON actx.id = ra.contextid
521 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
522 JOIN {context} cctx ON cctx.id = rc.contextid
524 WHERE ra.userid = :userid
525 AND rc.capability $capcondition
526 AND rc.permission > 0
527 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
528 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
530 if (!empty($CFG->defaultfrontpageroleid)) {
531 $frontpagecontext = context_course::instance(SITEID);
533 list($capcondition2, $params2) = $DB->get_in_or_equal(
534 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
535 $params = array_merge($params, $params2);
536 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
537 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
539 $sql .= "
540 UNION
542 SELECT DISTINCT rc.capability, 1
544 FROM {role_capabilities} rc
545 JOIN {context} cctx ON cctx.id = rc.contextid
547 WHERE rc.roleid = :frontpageroleid
548 AND rc.capability $capcondition2
549 AND rc.permission > 0
550 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
553 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
555 // Add back any providers based on the detailed capability check.
556 foreach ($unsureproviders as $providerid => $provider) {
557 if (array_key_exists($provider->capability, $relevantcapabilities)) {
558 $providers[$providerid] = $provider;
562 return $providers;
566 * Gets the message providers that are in the database for this component.
568 * This is an internal function used within messagelib.php
570 * @see message_update_providers()
571 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
572 * @return array An array of message providers
574 function message_get_providers_from_db($component) {
575 global $DB;
577 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
581 * Loads the messages definitions for a component from file
583 * If no messages are defined for the component, return an empty array.
584 * This is an internal function used within messagelib.php
586 * @see message_update_providers()
587 * @see message_update_processors()
588 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
589 * @return array An array of message providers or empty array if not exists
591 function message_get_providers_from_file($component) {
592 $defpath = core_component::get_component_directory($component).'/db/messages.php';
594 $messageproviders = array();
596 if (file_exists($defpath)) {
597 require($defpath);
600 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
601 if (empty($messageprovider['capability'])) {
602 $messageproviders[$name]['capability'] = NULL;
604 if (empty($messageprovider['defaults'])) {
605 $messageproviders[$name]['defaults'] = array();
609 return $messageproviders;
613 * Remove all message providers for particular component and corresponding settings
615 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
616 * @return void
618 function message_provider_uninstall($component) {
619 global $DB;
621 $transaction = $DB->start_delegated_transaction();
622 $DB->delete_records('message_providers', array('component' => $component));
623 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
624 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
625 $transaction->allow_commit();
626 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
627 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
631 * Uninstall a message processor
633 * @param string $name A message processor name like 'email', 'jabber'
635 function message_processor_uninstall($name) {
636 global $DB;
638 $transaction = $DB->start_delegated_transaction();
639 $DB->delete_records('message_processors', array('name' => $name));
640 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
641 // delete permission preferences only, we do not care about loggedin/loggedoff
642 // defaults, they will be removed on the next attempt to update the preferences
643 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
644 $transaction->allow_commit();
645 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
646 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));