MDL-63086 block_rss_client: Move skip time calculation to task
[moodle.git] / lib / messagelib.php
blob060e50847c7a37460b43a508f83e4abc79a4f7d2
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;
66 // If message provider is disabled then don't do any processing.
67 if (!empty($defaultpreferences->{$preferencebase.'_disable'})) {
68 return $messageid;
71 // By default a message is a notification. Only personal/private messages aren't notifications.
72 if (!isset($eventdata->notification)) {
73 $eventdata->notification = 1;
76 if (!is_object($eventdata->userto)) {
77 $eventdata->userto = core_user::get_user($eventdata->userto);
79 if (!is_object($eventdata->userfrom)) {
80 $eventdata->userfrom = core_user::get_user($eventdata->userfrom);
82 if (!$eventdata->userto) {
83 debugging('Attempt to send msg to unknown user', DEBUG_NORMAL);
84 return false;
86 if (!$eventdata->userfrom) {
87 debugging('Attempt to send msg from unknown user', DEBUG_NORMAL);
88 return false;
91 // Verify all necessary data fields are present.
92 if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended)
93 or !isset($eventdata->userto->deleted) or !isset($eventdata->userto->emailstop)) {
95 debugging('Necessary properties missing in userto object, fetching full record', DEBUG_DEVELOPER);
96 $eventdata->userto = core_user::get_user($eventdata->userto->id);
99 $usertoisrealuser = (core_user::is_real_user($eventdata->userto->id) != false);
100 // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
101 if (!$usertoisrealuser && !empty($eventdata->userto->emailstop)) {
102 debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
103 return false;
106 //after how long inactive should the user be considered logged off?
107 if (isset($CFG->block_online_users_timetosee)) {
108 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
109 } else {
110 $timetoshowusers = 300;//5 minutes
113 // Work out if the user is logged in or not
114 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
115 $userstate = 'loggedin';
116 } else {
117 $userstate = 'loggedoff';
120 // Check if we are creating a notification or message.
121 if ($eventdata->notification) {
122 $table = 'notifications';
124 $tabledata = new stdClass();
125 $tabledata->useridfrom = $eventdata->userfrom->id;
126 $tabledata->useridto = $eventdata->userto->id;
127 $tabledata->subject = $eventdata->subject;
128 $tabledata->fullmessage = $eventdata->fullmessage;
129 $tabledata->fullmessageformat = $eventdata->fullmessageformat;
130 $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
131 $tabledata->smallmessage = $eventdata->smallmessage;
132 $tabledata->eventtype = $eventdata->name;
133 $tabledata->component = $eventdata->component;
135 if (!empty($eventdata->contexturl)) {
136 $tabledata->contexturl = (string)$eventdata->contexturl;
137 } else {
138 $tabledata->contexturl = null;
141 if (!empty($eventdata->contexturlname)) {
142 $tabledata->contexturlname = (string)$eventdata->contexturlname;
143 } else {
144 $tabledata->contexturlname = null;
146 } else {
147 $table = 'messages';
149 if (!$conversationid = \core_message\api::get_conversation_between_users([$eventdata->userfrom->id,
150 $eventdata->userto->id])) {
151 $conversationid = \core_message\api::create_conversation_between_users([$eventdata->userfrom->id,
152 $eventdata->userto->id]);
155 $tabledata = new stdClass();
156 $tabledata->courseid = $eventdata->courseid;
157 $tabledata->useridfrom = $eventdata->userfrom->id;
158 $tabledata->conversationid = $conversationid;
159 $tabledata->subject = $eventdata->subject;
160 $tabledata->fullmessage = $eventdata->fullmessage;
161 $tabledata->fullmessageformat = $eventdata->fullmessageformat;
162 $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
163 $tabledata->smallmessage = $eventdata->smallmessage;
166 $tabledata->timecreated = time();
168 if (PHPUNIT_TEST and class_exists('phpunit_util')) {
169 // Add some more tests to make sure the normal code can actually work.
170 $componentdir = core_component::get_component_directory($eventdata->component);
171 if (!$componentdir or !is_dir($componentdir)) {
172 throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component);
174 if (!file_exists("$componentdir/db/messages.php")) {
175 throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
177 $messageproviders = null;
178 include("$componentdir/db/messages.php");
179 if (!isset($messageproviders[$eventdata->name])) {
180 throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' messages.php file");
182 unset($componentdir);
183 unset($messageproviders);
184 // Now ask phpunit if it wants to catch this message.
185 if (phpunit_util::is_redirecting_messages()) {
186 $messageid = $DB->insert_record($table, $tabledata);
187 $message = $DB->get_record($table, array('id' => $messageid));
189 // Add the useridto attribute for BC.
190 $message->useridto = $eventdata->userto->id;
192 // Mark the message/notification as read.
193 if ($eventdata->notification) {
194 \core_message\api::mark_notification_as_read($message);
195 } else {
196 \core_message\api::mark_message_as_read($eventdata->userto->id, $message);
199 // Unit tests need this detail.
200 $message->notification = $eventdata->notification;
201 phpunit_util::message_sent($message);
202 return $messageid;
206 // Fetch enabled processors.
207 // If we are dealing with a message some processors may want to handle it regardless of user and site settings.
208 if (!$eventdata->notification) {
209 $processors = array_filter(get_message_processors(false), function($processor) {
210 if ($processor->object->force_process_messages()) {
211 return true;
214 return ($processor->enabled && $processor->configured);
216 } else {
217 $processors = get_message_processors(true);
220 // Preset variables
221 $processorlist = array();
222 // Fill in the array of processors to be used based on default and user preferences
223 foreach ($processors as $processor) {
224 // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
225 if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
226 continue;
229 // First find out permissions
230 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
231 if (isset($defaultpreferences->{$defaultpreference})) {
232 $permitted = $defaultpreferences->{$defaultpreference};
233 } else {
234 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
235 // exist in the message_provider table (thus there is no default settings for them).
236 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
237 to message_send() are valid.";
238 throw new coding_exception($preferrormsg);
241 // Find out if user has configured this output
242 // Some processors cannot function without settings from the user
243 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
245 // DEBUG: notify if we are forcing unconfigured output
246 if ($permitted == 'forced' && !$userisconfigured) {
247 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
250 // Populate the list of processors we will be using
251 if (!$eventdata->notification && $processor->object->force_process_messages()) {
252 $processorlist[] = $processor->name;
253 } else if ($permitted == 'forced' && $userisconfigured) {
254 // An admin is forcing users to use this message processor. Use this processor unconditionally.
255 $processorlist[] = $processor->name;
256 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
257 // User has not disabled notifications
258 // See if user set any notification preferences, otherwise use site default ones
259 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
260 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto)) {
261 if (in_array($processor->name, explode(',', $userpreference))) {
262 $processorlist[] = $processor->name;
264 } else if (isset($defaultpreferences->{$userpreferencename})) {
265 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
266 $processorlist[] = $processor->name;
272 // Only cache messages, not notifications.
273 if (!$eventdata->notification) {
274 // Cache the timecreated value of the last message between these two users.
275 $cache = cache::make('core', 'message_time_last_message_between_users');
276 $key = \core_message\helper::get_last_message_time_created_cache_key($eventdata->userfrom->id,
277 $eventdata->userto->id);
278 $cache->set($key, $tabledata->timecreated);
281 // Store unread message just in case we get a fatal error any time later.
282 $tabledata->id = $DB->insert_record($table, $tabledata);
283 $eventdata->savedmessageid = $tabledata->id;
285 // Let the manager do the sending or buffering when db transaction in progress.
286 return \core\message\manager::send_message($eventdata, $tabledata, $processorlist);
291 * Updates the message_providers table with the current set of message providers
293 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
294 * @return boolean True on success
296 function message_update_providers($component='moodle') {
297 global $DB;
299 // load message providers from files
300 $fileproviders = message_get_providers_from_file($component);
302 // load message providers from the database
303 $dbproviders = message_get_providers_from_db($component);
305 foreach ($fileproviders as $messagename => $fileprovider) {
307 if (!empty($dbproviders[$messagename])) { // Already exists in the database
308 // check if capability has changed
309 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
310 // exact same message provider already present in db, ignore this entry
311 unset($dbproviders[$messagename]);
312 continue;
314 } else { // Update existing one
315 $provider = new stdClass();
316 $provider->id = $dbproviders[$messagename]->id;
317 $provider->capability = $fileprovider['capability'];
318 $DB->update_record('message_providers', $provider);
319 unset($dbproviders[$messagename]);
320 continue;
323 } else { // New message provider, add it
325 $provider = new stdClass();
326 $provider->name = $messagename;
327 $provider->component = $component;
328 $provider->capability = $fileprovider['capability'];
330 $transaction = $DB->start_delegated_transaction();
331 $DB->insert_record('message_providers', $provider);
332 message_set_default_message_preference($component, $messagename, $fileprovider);
333 $transaction->allow_commit();
337 foreach ($dbproviders as $dbprovider) { // Delete old ones
338 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
339 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
340 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
341 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
344 return true;
348 * This function populates default message preferences for all existing providers
349 * when the new message processor is added.
351 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
352 * @throws invalid_parameter_exception if $processorname does not exist in the database
354 function message_update_processors($processorname) {
355 global $DB;
357 // validate if our processor exists
358 $processor = $DB->get_records('message_processors', array('name' => $processorname));
359 if (empty($processor)) {
360 throw new invalid_parameter_exception();
363 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
365 $transaction = $DB->start_delegated_transaction();
366 foreach ($providers as $provider) {
367 // load message providers from files
368 $fileproviders = message_get_providers_from_file($provider->component);
369 foreach ($fileproviders as $messagename => $fileprovider) {
370 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
373 $transaction->allow_commit();
377 * Setting default messaging preferences for particular message provider
379 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
380 * @param string $messagename The name of message provider
381 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
382 * @param string $processorname The optional name of message processor
384 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
385 global $DB;
387 // Fetch message processors
388 $condition = null;
389 // If we need to process a particular processor, set the select condition
390 if (!empty($processorname)) {
391 $condition = array('name' => $processorname);
393 $processors = $DB->get_records('message_processors', $condition);
395 // load default messaging preferences
396 $defaultpreferences = get_message_output_default_preferences();
398 // Setting default preference
399 $componentproviderbase = $component.'_'.$messagename;
400 $loggedinpref = array();
401 $loggedoffpref = array();
402 // set 'permitted' preference first for each messaging processor
403 foreach ($processors as $processor) {
404 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
405 // if we do not have this setting yet, set it
406 if (!isset($defaultpreferences->{$preferencename})) {
407 // determine plugin default settings
408 $plugindefault = 0;
409 if (isset($fileprovider['defaults'][$processor->name])) {
410 $plugindefault = $fileprovider['defaults'][$processor->name];
412 // get string values of the settings
413 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
414 // store default preferences for current processor
415 set_config($preferencename, $permitted, 'message');
416 // save loggedin/loggedoff settings
417 if ($loggedin) {
418 $loggedinpref[] = $processor->name;
420 if ($loggedoff) {
421 $loggedoffpref[] = $processor->name;
425 // now set loggedin/loggedoff preferences
426 if (!empty($loggedinpref)) {
427 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
428 if (isset($defaultpreferences->{$preferencename})) {
429 // We have the default preferences for this message provider, which
430 // likely means that we have been adding a new processor. Add defaults
431 // to exisitng preferences.
432 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
434 set_config($preferencename, join(',', $loggedinpref), 'message');
436 if (!empty($loggedoffpref)) {
437 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
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 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
444 set_config($preferencename, join(',', $loggedoffpref), 'message');
449 * Returns the active providers for the user specified, based on capability
451 * @param int $userid id of user
452 * @return array An array of message providers
454 function message_get_providers_for_user($userid) {
455 global $DB, $CFG;
457 $providers = get_message_providers();
459 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
460 if (!$CFG->messaging) {
461 foreach ($providers as $providerid => $provider) {
462 if ($provider->name == 'instantmessage') {
463 unset($providers[$providerid]);
464 break;
469 // If the component is an enrolment plugin, check it is enabled
470 foreach ($providers as $providerid => $provider) {
471 list($type, $name) = core_component::normalize_component($provider->component);
472 if ($type == 'enrol' && !enrol_is_enabled($name)) {
473 unset($providers[$providerid]);
477 // Now we need to check capabilities. We need to eliminate the providers
478 // where the user does not have the corresponding capability anywhere.
479 // Here we deal with the common simple case of the user having the
480 // capability in the system context. That handles $CFG->defaultuserroleid.
481 // For the remaining providers/capabilities, we need to do a more complex
482 // query involving all overrides everywhere.
483 $unsureproviders = array();
484 $unsurecapabilities = array();
485 $systemcontext = context_system::instance();
486 foreach ($providers as $providerid => $provider) {
487 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
488 // The provider is relevant to this user.
489 continue;
492 $unsureproviders[$providerid] = $provider;
493 $unsurecapabilities[$provider->capability] = 1;
494 unset($providers[$providerid]);
497 if (empty($unsureproviders)) {
498 // More complex checks are not required.
499 return $providers;
502 // Now check the unsure capabilities.
503 list($capcondition, $params) = $DB->get_in_or_equal(
504 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
505 $params['userid'] = $userid;
507 $sql = "SELECT DISTINCT rc.capability, 1
509 FROM {role_assignments} ra
510 JOIN {context} actx ON actx.id = ra.contextid
511 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
512 JOIN {context} cctx ON cctx.id = rc.contextid
514 WHERE ra.userid = :userid
515 AND rc.capability $capcondition
516 AND rc.permission > 0
517 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
518 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
520 if (!empty($CFG->defaultfrontpageroleid)) {
521 $frontpagecontext = context_course::instance(SITEID);
523 list($capcondition2, $params2) = $DB->get_in_or_equal(
524 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
525 $params = array_merge($params, $params2);
526 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
527 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
529 $sql .= "
530 UNION
532 SELECT DISTINCT rc.capability, 1
534 FROM {role_capabilities} rc
535 JOIN {context} cctx ON cctx.id = rc.contextid
537 WHERE rc.roleid = :frontpageroleid
538 AND rc.capability $capcondition2
539 AND rc.permission > 0
540 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
543 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
545 // Add back any providers based on the detailed capability check.
546 foreach ($unsureproviders as $providerid => $provider) {
547 if (array_key_exists($provider->capability, $relevantcapabilities)) {
548 $providers[$providerid] = $provider;
552 return $providers;
556 * Gets the message providers that are in the database for this component.
558 * This is an internal function used within messagelib.php
560 * @see message_update_providers()
561 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
562 * @return array An array of message providers
564 function message_get_providers_from_db($component) {
565 global $DB;
567 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
571 * Loads the messages definitions for a component from file
573 * If no messages are defined for the component, return an empty array.
574 * This is an internal function used within messagelib.php
576 * @see message_update_providers()
577 * @see message_update_processors()
578 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
579 * @return array An array of message providers or empty array if not exists
581 function message_get_providers_from_file($component) {
582 $defpath = core_component::get_component_directory($component).'/db/messages.php';
584 $messageproviders = array();
586 if (file_exists($defpath)) {
587 require($defpath);
590 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
591 if (empty($messageprovider['capability'])) {
592 $messageproviders[$name]['capability'] = NULL;
594 if (empty($messageprovider['defaults'])) {
595 $messageproviders[$name]['defaults'] = array();
599 return $messageproviders;
603 * Remove all message providers for particular component and corresponding settings
605 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
606 * @return void
608 function message_provider_uninstall($component) {
609 global $DB;
611 $transaction = $DB->start_delegated_transaction();
612 $DB->delete_records('message_providers', array('component' => $component));
613 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
614 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
615 $transaction->allow_commit();
616 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
617 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
621 * Uninstall a message processor
623 * @param string $name A message processor name like 'email', 'jabber'
625 function message_processor_uninstall($name) {
626 global $DB;
628 $transaction = $DB->start_delegated_transaction();
629 $DB->delete_records('message_processors', array('name' => $name));
630 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
631 // delete permission preferences only, we do not care about loggedin/loggedoff
632 // defaults, they will be removed on the next attempt to update the preferences
633 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
634 $transaction->allow_commit();
635 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
636 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));