MDL-51177 core: Ignore built files in stylelint
[moodle.git] / lib / messagelib.php
blob16ccefef9d2a77b045d5e0c6d48d32538143ccb1
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 $conversationid = \core_message\api::create_conversation_between_users([$eventdata->userfrom->id,
167 $eventdata->userto->id]);
170 $tabledata = new stdClass();
171 $tabledata->courseid = $eventdata->courseid;
172 $tabledata->useridfrom = $eventdata->userfrom->id;
173 $tabledata->conversationid = $conversationid;
174 $tabledata->subject = $eventdata->subject;
175 $tabledata->fullmessage = $eventdata->fullmessage;
176 $tabledata->fullmessageformat = $eventdata->fullmessageformat;
177 $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
178 $tabledata->smallmessage = $eventdata->smallmessage;
181 $tabledata->timecreated = time();
183 if (PHPUNIT_TEST and class_exists('phpunit_util')) {
184 // Add some more tests to make sure the normal code can actually work.
185 $componentdir = core_component::get_component_directory($eventdata->component);
186 if (!$componentdir or !is_dir($componentdir)) {
187 throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component);
189 if (!file_exists("$componentdir/db/messages.php")) {
190 throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
192 $messageproviders = null;
193 include("$componentdir/db/messages.php");
194 if (!isset($messageproviders[$eventdata->name])) {
195 throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' messages.php file");
197 unset($componentdir);
198 unset($messageproviders);
199 // Now ask phpunit if it wants to catch this message.
200 if (phpunit_util::is_redirecting_messages()) {
201 $messageid = $DB->insert_record($table, $tabledata);
202 $message = $DB->get_record($table, array('id' => $messageid));
204 // Add the useridto attribute for BC.
205 $message->useridto = $eventdata->userto->id;
207 // Mark the message/notification as read.
208 if ($eventdata->notification) {
209 \core_message\api::mark_notification_as_read($message);
210 } else {
211 \core_message\api::mark_message_as_read($eventdata->userto->id, $message);
214 // Unit tests need this detail.
215 $message->notification = $eventdata->notification;
216 phpunit_util::message_sent($message);
217 return $messageid;
221 // Fetch enabled processors.
222 // If we are dealing with a message some processors may want to handle it regardless of user and site settings.
223 if (!$eventdata->notification) {
224 $processors = array_filter(get_message_processors(false), function($processor) {
225 if ($processor->object->force_process_messages()) {
226 return true;
229 return ($processor->enabled && $processor->configured);
231 } else {
232 $processors = get_message_processors(true);
235 // Preset variables
236 $processorlist = array();
237 // Fill in the array of processors to be used based on default and user preferences
238 foreach ($processors as $processor) {
239 // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
240 if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
241 continue;
244 // First find out permissions
245 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
246 if (isset($defaultpreferences->{$defaultpreference})) {
247 $permitted = $defaultpreferences->{$defaultpreference};
248 } else {
249 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
250 // exist in the message_provider table (thus there is no default settings for them).
251 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
252 to message_send() are valid.";
253 throw new coding_exception($preferrormsg);
256 // Find out if user has configured this output
257 // Some processors cannot function without settings from the user
258 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
260 // DEBUG: notify if we are forcing unconfigured output
261 if ($permitted == 'forced' && !$userisconfigured) {
262 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
265 // Populate the list of processors we will be using
266 if (!$eventdata->notification && $processor->object->force_process_messages()) {
267 $processorlist[] = $processor->name;
268 } else if ($permitted == 'forced' && $userisconfigured) {
269 // An admin is forcing users to use this message processor. Use this processor unconditionally.
270 $processorlist[] = $processor->name;
271 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
272 // User has not disabled notifications
273 // See if user set any notification preferences, otherwise use site default ones
274 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
275 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto)) {
276 if (in_array($processor->name, explode(',', $userpreference))) {
277 $processorlist[] = $processor->name;
279 } else if (isset($defaultpreferences->{$userpreferencename})) {
280 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
281 $processorlist[] = $processor->name;
287 // Only cache messages, not notifications.
288 if (!$eventdata->notification) {
289 // Cache the timecreated value of the last message between these two users.
290 $cache = cache::make('core', 'message_time_last_message_between_users');
291 $key = \core_message\helper::get_last_message_time_created_cache_key($eventdata->userfrom->id,
292 $eventdata->userto->id);
293 $cache->set($key, $tabledata->timecreated);
296 // Store unread message just in case we get a fatal error any time later.
297 $tabledata->id = $DB->insert_record($table, $tabledata);
298 $eventdata->savedmessageid = $tabledata->id;
300 // Let the manager do the sending or buffering when db transaction in progress.
301 return \core\message\manager::send_message($eventdata, $tabledata, $processorlist);
306 * Updates the message_providers table with the current set of message providers
308 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
309 * @return boolean True on success
311 function message_update_providers($component='moodle') {
312 global $DB;
314 // load message providers from files
315 $fileproviders = message_get_providers_from_file($component);
317 // load message providers from the database
318 $dbproviders = message_get_providers_from_db($component);
320 foreach ($fileproviders as $messagename => $fileprovider) {
322 if (!empty($dbproviders[$messagename])) { // Already exists in the database
323 // check if capability has changed
324 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
325 // exact same message provider already present in db, ignore this entry
326 unset($dbproviders[$messagename]);
327 continue;
329 } else { // Update existing one
330 $provider = new stdClass();
331 $provider->id = $dbproviders[$messagename]->id;
332 $provider->capability = $fileprovider['capability'];
333 $DB->update_record('message_providers', $provider);
334 unset($dbproviders[$messagename]);
335 continue;
338 } else { // New message provider, add it
340 $provider = new stdClass();
341 $provider->name = $messagename;
342 $provider->component = $component;
343 $provider->capability = $fileprovider['capability'];
345 $transaction = $DB->start_delegated_transaction();
346 $DB->insert_record('message_providers', $provider);
347 message_set_default_message_preference($component, $messagename, $fileprovider);
348 $transaction->allow_commit();
352 foreach ($dbproviders as $dbprovider) { // Delete old ones
353 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
354 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
355 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
356 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
359 return true;
363 * This function populates default message preferences for all existing providers
364 * when the new message processor is added.
366 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
367 * @throws invalid_parameter_exception if $processorname does not exist in the database
369 function message_update_processors($processorname) {
370 global $DB;
372 // validate if our processor exists
373 $processor = $DB->get_records('message_processors', array('name' => $processorname));
374 if (empty($processor)) {
375 throw new invalid_parameter_exception();
378 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
380 $transaction = $DB->start_delegated_transaction();
381 foreach ($providers as $provider) {
382 // load message providers from files
383 $fileproviders = message_get_providers_from_file($provider->component);
384 foreach ($fileproviders as $messagename => $fileprovider) {
385 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
388 $transaction->allow_commit();
392 * Setting default messaging preferences for particular message provider
394 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
395 * @param string $messagename The name of message provider
396 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
397 * @param string $processorname The optional name of message processor
399 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
400 global $DB;
402 // Fetch message processors
403 $condition = null;
404 // If we need to process a particular processor, set the select condition
405 if (!empty($processorname)) {
406 $condition = array('name' => $processorname);
408 $processors = $DB->get_records('message_processors', $condition);
410 // load default messaging preferences
411 $defaultpreferences = get_message_output_default_preferences();
413 // Setting default preference
414 $componentproviderbase = $component.'_'.$messagename;
415 $loggedinpref = array();
416 $loggedoffpref = array();
417 // set 'permitted' preference first for each messaging processor
418 foreach ($processors as $processor) {
419 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
420 // if we do not have this setting yet, set it
421 if (!isset($defaultpreferences->{$preferencename})) {
422 // determine plugin default settings
423 $plugindefault = 0;
424 if (isset($fileprovider['defaults'][$processor->name])) {
425 $plugindefault = $fileprovider['defaults'][$processor->name];
427 // get string values of the settings
428 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
429 // store default preferences for current processor
430 set_config($preferencename, $permitted, 'message');
431 // save loggedin/loggedoff settings
432 if ($loggedin) {
433 $loggedinpref[] = $processor->name;
435 if ($loggedoff) {
436 $loggedoffpref[] = $processor->name;
440 // now set loggedin/loggedoff preferences
441 if (!empty($loggedinpref)) {
442 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
443 if (isset($defaultpreferences->{$preferencename})) {
444 // We have the default preferences for this message provider, which
445 // likely means that we have been adding a new processor. Add defaults
446 // to exisitng preferences.
447 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
449 set_config($preferencename, join(',', $loggedinpref), 'message');
451 if (!empty($loggedoffpref)) {
452 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
453 if (isset($defaultpreferences->{$preferencename})) {
454 // We have the default preferences for this message provider, which
455 // likely means that we have been adding a new processor. Add defaults
456 // to exisitng preferences.
457 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
459 set_config($preferencename, join(',', $loggedoffpref), 'message');
464 * Returns the active providers for the user specified, based on capability
466 * @param int $userid id of user
467 * @return array An array of message providers
469 function message_get_providers_for_user($userid) {
470 global $DB, $CFG;
472 $providers = get_message_providers();
474 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
475 if (!$CFG->messaging) {
476 foreach ($providers as $providerid => $provider) {
477 if ($provider->name == 'instantmessage') {
478 unset($providers[$providerid]);
479 break;
484 // If the component is an enrolment plugin, check it is enabled
485 foreach ($providers as $providerid => $provider) {
486 list($type, $name) = core_component::normalize_component($provider->component);
487 if ($type == 'enrol' && !enrol_is_enabled($name)) {
488 unset($providers[$providerid]);
492 // Now we need to check capabilities. We need to eliminate the providers
493 // where the user does not have the corresponding capability anywhere.
494 // Here we deal with the common simple case of the user having the
495 // capability in the system context. That handles $CFG->defaultuserroleid.
496 // For the remaining providers/capabilities, we need to do a more complex
497 // query involving all overrides everywhere.
498 $unsureproviders = array();
499 $unsurecapabilities = array();
500 $systemcontext = context_system::instance();
501 foreach ($providers as $providerid => $provider) {
502 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
503 // The provider is relevant to this user.
504 continue;
507 $unsureproviders[$providerid] = $provider;
508 $unsurecapabilities[$provider->capability] = 1;
509 unset($providers[$providerid]);
512 if (empty($unsureproviders)) {
513 // More complex checks are not required.
514 return $providers;
517 // Now check the unsure capabilities.
518 list($capcondition, $params) = $DB->get_in_or_equal(
519 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
520 $params['userid'] = $userid;
522 $sql = "SELECT DISTINCT rc.capability, 1
524 FROM {role_assignments} ra
525 JOIN {context} actx ON actx.id = ra.contextid
526 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
527 JOIN {context} cctx ON cctx.id = rc.contextid
529 WHERE ra.userid = :userid
530 AND rc.capability $capcondition
531 AND rc.permission > 0
532 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
533 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
535 if (!empty($CFG->defaultfrontpageroleid)) {
536 $frontpagecontext = context_course::instance(SITEID);
538 list($capcondition2, $params2) = $DB->get_in_or_equal(
539 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
540 $params = array_merge($params, $params2);
541 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
542 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
544 $sql .= "
545 UNION
547 SELECT DISTINCT rc.capability, 1
549 FROM {role_capabilities} rc
550 JOIN {context} cctx ON cctx.id = rc.contextid
552 WHERE rc.roleid = :frontpageroleid
553 AND rc.capability $capcondition2
554 AND rc.permission > 0
555 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
558 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
560 // Add back any providers based on the detailed capability check.
561 foreach ($unsureproviders as $providerid => $provider) {
562 if (array_key_exists($provider->capability, $relevantcapabilities)) {
563 $providers[$providerid] = $provider;
567 return $providers;
571 * Gets the message providers that are in the database for this component.
573 * This is an internal function used within messagelib.php
575 * @see message_update_providers()
576 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
577 * @return array An array of message providers
579 function message_get_providers_from_db($component) {
580 global $DB;
582 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
586 * Loads the messages definitions for a component from file
588 * If no messages are defined for the component, return an empty array.
589 * This is an internal function used within messagelib.php
591 * @see message_update_providers()
592 * @see message_update_processors()
593 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
594 * @return array An array of message providers or empty array if not exists
596 function message_get_providers_from_file($component) {
597 $defpath = core_component::get_component_directory($component).'/db/messages.php';
599 $messageproviders = array();
601 if (file_exists($defpath)) {
602 require($defpath);
605 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
606 if (empty($messageprovider['capability'])) {
607 $messageproviders[$name]['capability'] = NULL;
609 if (empty($messageprovider['defaults'])) {
610 $messageproviders[$name]['defaults'] = array();
614 return $messageproviders;
618 * Remove all message providers for particular component and corresponding settings
620 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
621 * @return void
623 function message_provider_uninstall($component) {
624 global $DB;
626 $transaction = $DB->start_delegated_transaction();
627 $DB->delete_records('message_providers', array('component' => $component));
628 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
629 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
630 $transaction->allow_commit();
631 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
632 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
636 * Uninstall a message processor
638 * @param string $name A message processor name like 'email', 'jabber'
640 function message_processor_uninstall($name) {
641 global $DB;
643 $transaction = $DB->start_delegated_transaction();
644 $DB->delete_records('message_processors', array('name' => $name));
645 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
646 // delete permission preferences only, we do not care about loggedin/loggedoff
647 // defaults, they will be removed on the next attempt to update the preferences
648 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
649 $transaction->allow_commit();
650 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
651 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));