Merge branch '44711-27' of git://github.com/samhemelryk/moodle into MOODLE_27_STABLE
[moodle.git] / lib / messagelib.php
blob02c6cfcb4e16a2e3b084d85eeb88d32b4b31ba21
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(dirname(dirname(__FILE__)) . '/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 * @category message
51 * @param object $eventdata information about the message (component, userfrom, userto, ...)
52 * @return mixed the integer ID of the new message or false if there was a problem with a processor
54 function message_send($eventdata) {
55 global $CFG, $DB;
57 //new message ID to return
58 $messageid = false;
60 // Fetch default (site) preferences
61 $defaultpreferences = get_message_output_default_preferences();
62 $preferencebase = $eventdata->component.'_'.$eventdata->name;
63 // If message provider is disabled then don't do any processing.
64 if (!empty($defaultpreferences->{$preferencebase.'_disable'})) {
65 return $messageid;
68 //TODO: we need to solve problems with database transactions here somehow, for now we just prevent transactions - sorry
69 $DB->transactions_forbidden();
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_number($eventdata->userto)) {
77 $eventdata->userto = core_user::get_user($eventdata->userto);
79 if (is_int($eventdata->userfrom)) {
80 $eventdata->userfrom = core_user::get_user($eventdata->userfrom);
83 $usertoisrealuser = (core_user::is_real_user($eventdata->userto->id) != false);
84 // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
85 if (!$usertoisrealuser && !empty($eventdata->userto->emailstop)) {
86 debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
87 return false;
90 if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended) or !isset($eventdata->userto->deleted)) {
91 $eventdata->userto = core_user::get_user($eventdata->userto->id);
94 //after how long inactive should the user be considered logged off?
95 if (isset($CFG->block_online_users_timetosee)) {
96 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
97 } else {
98 $timetoshowusers = 300;//5 minutes
101 // Work out if the user is logged in or not
102 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
103 $userstate = 'loggedin';
104 } else {
105 $userstate = 'loggedoff';
108 // Create the message object
109 $savemessage = new stdClass();
110 $savemessage->useridfrom = $eventdata->userfrom->id;
111 $savemessage->useridto = $eventdata->userto->id;
112 $savemessage->subject = $eventdata->subject;
113 $savemessage->fullmessage = $eventdata->fullmessage;
114 $savemessage->fullmessageformat = $eventdata->fullmessageformat;
115 $savemessage->fullmessagehtml = $eventdata->fullmessagehtml;
116 $savemessage->smallmessage = $eventdata->smallmessage;
117 $savemessage->notification = $eventdata->notification;
119 if (!empty($eventdata->contexturl)) {
120 $savemessage->contexturl = $eventdata->contexturl;
121 } else {
122 $savemessage->contexturl = null;
125 if (!empty($eventdata->contexturlname)) {
126 $savemessage->contexturlname = $eventdata->contexturlname;
127 } else {
128 $savemessage->contexturlname = null;
131 $savemessage->timecreated = time();
133 if (PHPUNIT_TEST and class_exists('phpunit_util')) {
134 // Add some more tests to make sure the normal code can actually work.
135 $componentdir = core_component::get_component_directory($eventdata->component);
136 if (!$componentdir or !is_dir($componentdir)) {
137 throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component);
139 if (!file_exists("$componentdir/db/messages.php")) {
140 throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
142 $messageproviders = null;
143 include("$componentdir/db/messages.php");
144 if (!isset($messageproviders[$eventdata->name])) {
145 throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' messages.php file");
147 unset($componentdir);
148 unset($messageproviders);
149 // Now ask phpunit if it wants to catch this message.
150 if (phpunit_util::is_redirecting_messages()) {
151 $savemessage->timeread = time();
152 $messageid = $DB->insert_record('message_read', $savemessage);
153 $message = $DB->get_record('message_read', array('id'=>$messageid));
154 phpunit_util::message_sent($message);
155 return $messageid;
159 // Fetch enabled processors
160 $processors = get_message_processors(true);
162 // Preset variables
163 $processorlist = array();
164 // Fill in the array of processors to be used based on default and user preferences
165 foreach ($processors as $processor) {
166 // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
167 if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
168 continue;
171 // First find out permissions
172 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
173 if (isset($defaultpreferences->{$defaultpreference})) {
174 $permitted = $defaultpreferences->{$defaultpreference};
175 } else {
176 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
177 // exist in the message_provider table (thus there is no default settings for them).
178 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
179 to message_send() are valid.";
180 throw new coding_exception($preferrormsg);
183 // Find out if user has configured this output
184 // Some processors cannot function without settings from the user
185 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
187 // DEBUG: notify if we are forcing unconfigured output
188 if ($permitted == 'forced' && !$userisconfigured) {
189 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
192 // Warn developers that necessary data is missing regardless of how the processors are configured
193 if (!isset($eventdata->userto->emailstop)) {
194 debugging('userto->emailstop is not set. Retrieving it from the user table');
195 $eventdata->userto->emailstop = $DB->get_field('user', 'emailstop', array('id'=>$eventdata->userto->id));
198 // Populate the list of processors we will be using
199 if ($permitted == 'forced' && $userisconfigured) {
200 // An admin is forcing users to use this message processor. Use this processor unconditionally.
201 $processorlist[] = $processor->name;
202 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
203 // User has not disabled notifications
204 // See if user set any notification preferences, otherwise use site default ones
205 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
206 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto->id)) {
207 if (in_array($processor->name, explode(',', $userpreference))) {
208 $processorlist[] = $processor->name;
210 } else if (isset($defaultpreferences->{$userpreferencename})) {
211 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
212 $processorlist[] = $processor->name;
218 if (empty($processorlist) && $savemessage->notification) {
219 //if they have deselected all processors and its a notification mark it read. The user doesnt want to be bothered
220 $savemessage->timeread = time();
221 $messageid = $DB->insert_record('message_read', $savemessage);
222 } else { // Process the message
223 // Store unread message just in case we can not send it
224 $messageid = $savemessage->id = $DB->insert_record('message', $savemessage);
225 $eventdata->savedmessageid = $savemessage->id;
227 // Try to deliver the message to each processor
228 if (!empty($processorlist)) {
229 foreach ($processorlist as $procname) {
230 if (!$processors[$procname]->object->send_message($eventdata)) {
231 debugging('Error calling message processor '.$procname);
232 $messageid = false;
236 //if messaging is disabled and they previously had forum notifications handled by the popup processor
237 //or any processor that puts a row in message_working then the notification will remain forever
238 //unread. To prevent this mark the message read if messaging is disabled
239 if (empty($CFG->messaging)) {
240 require_once($CFG->dirroot.'/message/lib.php');
241 $messageid = message_mark_message_read($savemessage, time());
242 } else if ( $DB->count_records('message_working', array('unreadmessageid' => $savemessage->id)) == 0){
243 //if there is no more processors that want to process this we can move message to message_read
244 require_once($CFG->dirroot.'/message/lib.php');
245 $messageid = message_mark_message_read($savemessage, time(), true);
250 // We may be sending a message from the 'noreply' address, which means we are not actually sending a
251 // message from a valid user. In this case, we will set the userid to 0.
252 // Check if the userid is valid.
253 if (core_user::is_real_user($eventdata->userfrom->id)) {
254 $userfromid = $eventdata->userfrom->id;
255 } else {
256 $userfromid = 0;
259 // Trigger event for sending a message.
260 $event = \core\event\message_sent::create(array(
261 'userid' => $userfromid,
262 'context' => context_system::instance(),
263 'relateduserid' => $eventdata->userto->id,
264 'other' => array(
265 'messageid' => $messageid // Can't use this as the objectid as it can either be the id in the 'message_read'
266 // or 'message' table.
269 $event->trigger();
271 return $messageid;
276 * Updates the message_providers table with the current set of message providers
278 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
279 * @return boolean True on success
281 function message_update_providers($component='moodle') {
282 global $DB;
284 // load message providers from files
285 $fileproviders = message_get_providers_from_file($component);
287 // load message providers from the database
288 $dbproviders = message_get_providers_from_db($component);
290 foreach ($fileproviders as $messagename => $fileprovider) {
292 if (!empty($dbproviders[$messagename])) { // Already exists in the database
293 // check if capability has changed
294 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
295 // exact same message provider already present in db, ignore this entry
296 unset($dbproviders[$messagename]);
297 continue;
299 } else { // Update existing one
300 $provider = new stdClass();
301 $provider->id = $dbproviders[$messagename]->id;
302 $provider->capability = $fileprovider['capability'];
303 $DB->update_record('message_providers', $provider);
304 unset($dbproviders[$messagename]);
305 continue;
308 } else { // New message provider, add it
310 $provider = new stdClass();
311 $provider->name = $messagename;
312 $provider->component = $component;
313 $provider->capability = $fileprovider['capability'];
315 $transaction = $DB->start_delegated_transaction();
316 $DB->insert_record('message_providers', $provider);
317 message_set_default_message_preference($component, $messagename, $fileprovider);
318 $transaction->allow_commit();
322 foreach ($dbproviders as $dbprovider) { // Delete old ones
323 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
324 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
325 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
326 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
329 return true;
333 * This function populates default message preferences for all existing providers
334 * when the new message processor is added.
336 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
337 * @throws invalid_parameter_exception if $processorname does not exist in the database
339 function message_update_processors($processorname) {
340 global $DB;
342 // validate if our processor exists
343 $processor = $DB->get_records('message_processors', array('name' => $processorname));
344 if (empty($processor)) {
345 throw new invalid_parameter_exception();
348 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
350 $transaction = $DB->start_delegated_transaction();
351 foreach ($providers as $provider) {
352 // load message providers from files
353 $fileproviders = message_get_providers_from_file($provider->component);
354 foreach ($fileproviders as $messagename => $fileprovider) {
355 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
358 $transaction->allow_commit();
362 * Setting default messaging preferences for particular message provider
364 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
365 * @param string $messagename The name of message provider
366 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
367 * @param string $processorname The optional name of message processor
369 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
370 global $DB;
372 // Fetch message processors
373 $condition = null;
374 // If we need to process a particular processor, set the select condition
375 if (!empty($processorname)) {
376 $condition = array('name' => $processorname);
378 $processors = $DB->get_records('message_processors', $condition);
380 // load default messaging preferences
381 $defaultpreferences = get_message_output_default_preferences();
383 // Setting default preference
384 $componentproviderbase = $component.'_'.$messagename;
385 $loggedinpref = array();
386 $loggedoffpref = array();
387 // set 'permitted' preference first for each messaging processor
388 foreach ($processors as $processor) {
389 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
390 // if we do not have this setting yet, set it
391 if (!isset($defaultpreferences->{$preferencename})) {
392 // determine plugin default settings
393 $plugindefault = 0;
394 if (isset($fileprovider['defaults'][$processor->name])) {
395 $plugindefault = $fileprovider['defaults'][$processor->name];
397 // get string values of the settings
398 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
399 // store default preferences for current processor
400 set_config($preferencename, $permitted, 'message');
401 // save loggedin/loggedoff settings
402 if ($loggedin) {
403 $loggedinpref[] = $processor->name;
405 if ($loggedoff) {
406 $loggedoffpref[] = $processor->name;
410 // now set loggedin/loggedoff preferences
411 if (!empty($loggedinpref)) {
412 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
413 if (isset($defaultpreferences->{$preferencename})) {
414 // We have the default preferences for this message provider, which
415 // likely means that we have been adding a new processor. Add defaults
416 // to exisitng preferences.
417 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
419 set_config($preferencename, join(',', $loggedinpref), 'message');
421 if (!empty($loggedoffpref)) {
422 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
423 if (isset($defaultpreferences->{$preferencename})) {
424 // We have the default preferences for this message provider, which
425 // likely means that we have been adding a new processor. Add defaults
426 // to exisitng preferences.
427 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
429 set_config($preferencename, join(',', $loggedoffpref), 'message');
434 * Returns the active providers for the user specified, based on capability
436 * @param int $userid id of user
437 * @return array An array of message providers
439 function message_get_providers_for_user($userid) {
440 global $DB, $CFG;
442 $providers = get_message_providers();
444 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
445 if (!$CFG->messaging) {
446 foreach ($providers as $providerid => $provider) {
447 if ($provider->name == 'instantmessage') {
448 unset($providers[$providerid]);
449 break;
454 // If the component is an enrolment plugin, check it is enabled
455 foreach ($providers as $providerid => $provider) {
456 list($type, $name) = core_component::normalize_component($provider->component);
457 if ($type == 'enrol' && !enrol_is_enabled($name)) {
458 unset($providers[$providerid]);
462 // Now we need to check capabilities. We need to eliminate the providers
463 // where the user does not have the corresponding capability anywhere.
464 // Here we deal with the common simple case of the user having the
465 // capability in the system context. That handles $CFG->defaultuserroleid.
466 // For the remaining providers/capabilities, we need to do a more complex
467 // query involving all overrides everywhere.
468 $unsureproviders = array();
469 $unsurecapabilities = array();
470 $systemcontext = context_system::instance();
471 foreach ($providers as $providerid => $provider) {
472 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
473 // The provider is relevant to this user.
474 continue;
477 $unsureproviders[$providerid] = $provider;
478 $unsurecapabilities[$provider->capability] = 1;
479 unset($providers[$providerid]);
482 if (empty($unsureproviders)) {
483 // More complex checks are not required.
484 return $providers;
487 // Now check the unsure capabilities.
488 list($capcondition, $params) = $DB->get_in_or_equal(
489 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
490 $params['userid'] = $userid;
492 $sql = "SELECT DISTINCT rc.capability, 1
494 FROM {role_assignments} ra
495 JOIN {context} actx ON actx.id = ra.contextid
496 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
497 JOIN {context} cctx ON cctx.id = rc.contextid
499 WHERE ra.userid = :userid
500 AND rc.capability $capcondition
501 AND rc.permission > 0
502 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
503 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
505 if (!empty($CFG->defaultfrontpageroleid)) {
506 $frontpagecontext = context_course::instance(SITEID);
508 list($capcondition2, $params2) = $DB->get_in_or_equal(
509 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
510 $params = array_merge($params, $params2);
511 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
512 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
514 $sql .= "
515 UNION
517 SELECT DISTINCT rc.capability, 1
519 FROM {role_capabilities} rc
520 JOIN {context} cctx ON cctx.id = rc.contextid
522 WHERE rc.roleid = :frontpageroleid
523 AND rc.capability $capcondition2
524 AND rc.permission > 0
525 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
528 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
530 // Add back any providers based on the detailed capability check.
531 foreach ($unsureproviders as $providerid => $provider) {
532 if (array_key_exists($provider->capability, $relevantcapabilities)) {
533 $providers[$providerid] = $provider;
537 return $providers;
541 * Gets the message providers that are in the database for this component.
543 * This is an internal function used within messagelib.php
545 * @see message_update_providers()
546 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
547 * @return array An array of message providers
549 function message_get_providers_from_db($component) {
550 global $DB;
552 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
556 * Loads the messages definitions for a component from file
558 * If no messages are defined for the component, return an empty array.
559 * This is an internal function used within messagelib.php
561 * @see message_update_providers()
562 * @see message_update_processors()
563 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
564 * @return array An array of message providers or empty array if not exists
566 function message_get_providers_from_file($component) {
567 $defpath = core_component::get_component_directory($component).'/db/messages.php';
569 $messageproviders = array();
571 if (file_exists($defpath)) {
572 require($defpath);
575 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
576 if (empty($messageprovider['capability'])) {
577 $messageproviders[$name]['capability'] = NULL;
579 if (empty($messageprovider['defaults'])) {
580 $messageproviders[$name]['defaults'] = array();
584 return $messageproviders;
588 * Remove all message providers for particular component and corresponding settings
590 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
591 * @return void
593 function message_provider_uninstall($component) {
594 global $DB;
596 $transaction = $DB->start_delegated_transaction();
597 $DB->delete_records('message_providers', array('component' => $component));
598 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
599 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
600 $transaction->allow_commit();
601 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
602 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
606 * Uninstall a message processor
608 * @param string $name A message processor name like 'email', 'jabber'
610 function message_processor_uninstall($name) {
611 global $DB;
613 $transaction = $DB->start_delegated_transaction();
614 $DB->delete_records('message_processors', array('name' => $name));
615 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
616 // delete permission preferences only, we do not care about loggedin/loggedoff
617 // defaults, they will be removed on the next attempt to update the preferences
618 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
619 $transaction->allow_commit();
620 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
621 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));