Merge branch '43675-27' of git://github.com/samhemelryk/moodle
[moodle.git] / lib / messagelib.php
blob51c71c4f321414d9d18f654504216acee4ec8eb6
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 if (is_number($eventdata->userto)) {
72 $eventdata->userto = core_user::get_user($eventdata->userto);
74 if (is_int($eventdata->userfrom)) {
75 $eventdata->userfrom = core_user::get_user($eventdata->userfrom);
78 $usertoisrealuser = (core_user::is_real_user($eventdata->userto->id) != false);
79 // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
80 if (!$usertoisrealuser && !empty($eventdata->userto->emailstop)) {
81 debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
82 return false;
85 if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended) or !isset($eventdata->userto->deleted)) {
86 $eventdata->userto = core_user::get_user($eventdata->userto->id);
89 //after how long inactive should the user be considered logged off?
90 if (isset($CFG->block_online_users_timetosee)) {
91 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
92 } else {
93 $timetoshowusers = 300;//5 minutes
96 // Work out if the user is logged in or not
97 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
98 $userstate = 'loggedin';
99 } else {
100 $userstate = 'loggedoff';
103 // Create the message object
104 $savemessage = new stdClass();
105 $savemessage->useridfrom = $eventdata->userfrom->id;
106 $savemessage->useridto = $eventdata->userto->id;
107 $savemessage->subject = $eventdata->subject;
108 $savemessage->fullmessage = $eventdata->fullmessage;
109 $savemessage->fullmessageformat = $eventdata->fullmessageformat;
110 $savemessage->fullmessagehtml = $eventdata->fullmessagehtml;
111 $savemessage->smallmessage = $eventdata->smallmessage;
113 if (!empty($eventdata->notification)) {
114 $savemessage->notification = $eventdata->notification;
115 } else {
116 $savemessage->notification = 0;
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 return $messageid;
255 * Updates the message_providers table with the current set of message providers
257 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
258 * @return boolean True on success
260 function message_update_providers($component='moodle') {
261 global $DB;
263 // load message providers from files
264 $fileproviders = message_get_providers_from_file($component);
266 // load message providers from the database
267 $dbproviders = message_get_providers_from_db($component);
269 foreach ($fileproviders as $messagename => $fileprovider) {
271 if (!empty($dbproviders[$messagename])) { // Already exists in the database
272 // check if capability has changed
273 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
274 // exact same message provider already present in db, ignore this entry
275 unset($dbproviders[$messagename]);
276 continue;
278 } else { // Update existing one
279 $provider = new stdClass();
280 $provider->id = $dbproviders[$messagename]->id;
281 $provider->capability = $fileprovider['capability'];
282 $DB->update_record('message_providers', $provider);
283 unset($dbproviders[$messagename]);
284 continue;
287 } else { // New message provider, add it
289 $provider = new stdClass();
290 $provider->name = $messagename;
291 $provider->component = $component;
292 $provider->capability = $fileprovider['capability'];
294 $transaction = $DB->start_delegated_transaction();
295 $DB->insert_record('message_providers', $provider);
296 message_set_default_message_preference($component, $messagename, $fileprovider);
297 $transaction->allow_commit();
301 foreach ($dbproviders as $dbprovider) { // Delete old ones
302 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
303 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
304 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
305 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
308 return true;
312 * This function populates default message preferences for all existing providers
313 * when the new message processor is added.
315 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
316 * @throws invalid_parameter_exception if $processorname does not exist in the database
318 function message_update_processors($processorname) {
319 global $DB;
321 // validate if our processor exists
322 $processor = $DB->get_records('message_processors', array('name' => $processorname));
323 if (empty($processor)) {
324 throw new invalid_parameter_exception();
327 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
329 $transaction = $DB->start_delegated_transaction();
330 foreach ($providers as $provider) {
331 // load message providers from files
332 $fileproviders = message_get_providers_from_file($provider->component);
333 foreach ($fileproviders as $messagename => $fileprovider) {
334 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
337 $transaction->allow_commit();
341 * Setting default messaging preferences for particular message provider
343 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
344 * @param string $messagename The name of message provider
345 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
346 * @param string $processorname The optional name of message processor
348 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
349 global $DB;
351 // Fetch message processors
352 $condition = null;
353 // If we need to process a particular processor, set the select condition
354 if (!empty($processorname)) {
355 $condition = array('name' => $processorname);
357 $processors = $DB->get_records('message_processors', $condition);
359 // load default messaging preferences
360 $defaultpreferences = get_message_output_default_preferences();
362 // Setting default preference
363 $componentproviderbase = $component.'_'.$messagename;
364 $loggedinpref = array();
365 $loggedoffpref = array();
366 // set 'permitted' preference first for each messaging processor
367 foreach ($processors as $processor) {
368 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
369 // if we do not have this setting yet, set it
370 if (!isset($defaultpreferences->{$preferencename})) {
371 // determine plugin default settings
372 $plugindefault = 0;
373 if (isset($fileprovider['defaults'][$processor->name])) {
374 $plugindefault = $fileprovider['defaults'][$processor->name];
376 // get string values of the settings
377 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
378 // store default preferences for current processor
379 set_config($preferencename, $permitted, 'message');
380 // save loggedin/loggedoff settings
381 if ($loggedin) {
382 $loggedinpref[] = $processor->name;
384 if ($loggedoff) {
385 $loggedoffpref[] = $processor->name;
389 // now set loggedin/loggedoff preferences
390 if (!empty($loggedinpref)) {
391 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
392 if (isset($defaultpreferences->{$preferencename})) {
393 // We have the default preferences for this message provider, which
394 // likely means that we have been adding a new processor. Add defaults
395 // to exisitng preferences.
396 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
398 set_config($preferencename, join(',', $loggedinpref), 'message');
400 if (!empty($loggedoffpref)) {
401 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
402 if (isset($defaultpreferences->{$preferencename})) {
403 // We have the default preferences for this message provider, which
404 // likely means that we have been adding a new processor. Add defaults
405 // to exisitng preferences.
406 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
408 set_config($preferencename, join(',', $loggedoffpref), 'message');
413 * Returns the active providers for the user specified, based on capability
415 * @param int $userid id of user
416 * @return array An array of message providers
418 function message_get_providers_for_user($userid) {
419 global $DB, $CFG;
421 $providers = get_message_providers();
423 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
424 if (!$CFG->messaging) {
425 foreach ($providers as $providerid => $provider) {
426 if ($provider->name == 'instantmessage') {
427 unset($providers[$providerid]);
428 break;
433 // If the component is an enrolment plugin, check it is enabled
434 foreach ($providers as $providerid => $provider) {
435 list($type, $name) = core_component::normalize_component($provider->component);
436 if ($type == 'enrol' && !enrol_is_enabled($name)) {
437 unset($providers[$providerid]);
441 // Now we need to check capabilities. We need to eliminate the providers
442 // where the user does not have the corresponding capability anywhere.
443 // Here we deal with the common simple case of the user having the
444 // capability in the system context. That handles $CFG->defaultuserroleid.
445 // For the remaining providers/capabilities, we need to do a more complex
446 // query involving all overrides everywhere.
447 $unsureproviders = array();
448 $unsurecapabilities = array();
449 $systemcontext = context_system::instance();
450 foreach ($providers as $providerid => $provider) {
451 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
452 // The provider is relevant to this user.
453 continue;
456 $unsureproviders[$providerid] = $provider;
457 $unsurecapabilities[$provider->capability] = 1;
458 unset($providers[$providerid]);
461 if (empty($unsureproviders)) {
462 // More complex checks are not required.
463 return $providers;
466 // Now check the unsure capabilities.
467 list($capcondition, $params) = $DB->get_in_or_equal(
468 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
469 $params['userid'] = $userid;
471 $sql = "SELECT DISTINCT rc.capability, 1
473 FROM {role_assignments} ra
474 JOIN {context} actx ON actx.id = ra.contextid
475 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
476 JOIN {context} cctx ON cctx.id = rc.contextid
478 WHERE ra.userid = :userid
479 AND rc.capability $capcondition
480 AND rc.permission > 0
481 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
482 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
484 if (!empty($CFG->defaultfrontpageroleid)) {
485 $frontpagecontext = context_course::instance(SITEID);
487 list($capcondition2, $params2) = $DB->get_in_or_equal(
488 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
489 $params = array_merge($params, $params2);
490 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
491 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
493 $sql .= "
494 UNION
496 SELECT DISTINCT rc.capability, 1
498 FROM {role_capabilities} rc
499 JOIN {context} cctx ON cctx.id = rc.contextid
501 WHERE rc.roleid = :frontpageroleid
502 AND rc.capability $capcondition2
503 AND rc.permission > 0
504 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
507 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
509 // Add back any providers based on the detailed capability check.
510 foreach ($unsureproviders as $providerid => $provider) {
511 if (array_key_exists($provider->capability, $relevantcapabilities)) {
512 $providers[$providerid] = $provider;
516 return $providers;
520 * Gets the message providers that are in the database for this component.
522 * This is an internal function used within messagelib.php
524 * @see message_update_providers()
525 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
526 * @return array An array of message providers
528 function message_get_providers_from_db($component) {
529 global $DB;
531 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
535 * Loads the messages definitions for a component from file
537 * If no messages are defined for the component, return an empty array.
538 * This is an internal function used within messagelib.php
540 * @see message_update_providers()
541 * @see message_update_processors()
542 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
543 * @return array An array of message providers or empty array if not exists
545 function message_get_providers_from_file($component) {
546 $defpath = core_component::get_component_directory($component).'/db/messages.php';
548 $messageproviders = array();
550 if (file_exists($defpath)) {
551 require($defpath);
554 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
555 if (empty($messageprovider['capability'])) {
556 $messageproviders[$name]['capability'] = NULL;
558 if (empty($messageprovider['defaults'])) {
559 $messageproviders[$name]['defaults'] = array();
563 return $messageproviders;
567 * Remove all message providers for particular component and corresponding settings
569 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
570 * @return void
572 function message_provider_uninstall($component) {
573 global $DB;
575 $transaction = $DB->start_delegated_transaction();
576 $DB->delete_records('message_providers', array('component' => $component));
577 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
578 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
579 $transaction->allow_commit();
580 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
581 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
585 * Uninstall a message processor
587 * @param string $name A message processor name like 'email', 'jabber'
589 function message_processor_uninstall($name) {
590 global $DB;
592 $transaction = $DB->start_delegated_transaction();
593 $DB->delete_records('message_processors', array('name' => $name));
594 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
595 // delete permission preferences only, we do not care about loggedin/loggedoff
596 // defaults, they will be removed on the next attempt to update the preferences
597 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
598 $transaction->allow_commit();
599 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
600 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));