2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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');
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
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) {
57 //new message ID to return
60 //TODO: we need to solve problems with database transactions here somehow, for now we just prevent transactions - sorry
61 $DB->transactions_forbidden();
63 if (is_number($eventdata->userto
)) {
64 $eventdata->userto
= $DB->get_record('user', array('id' => $eventdata->userto
));
66 if (is_int($eventdata->userfrom
)) {
67 $eventdata->userfrom
= $DB->get_record('user', array('id' => $eventdata->userfrom
));
69 if (!isset($eventdata->userto
->auth
) or !isset($eventdata->userto
->suspended
) or !isset($eventdata->userto
->deleted
)) {
70 $eventdata->userto
= $DB->get_record('user', array('id' => $eventdata->userto
->id
));
73 //after how long inactive should the user be considered logged off?
74 if (isset($CFG->block_online_users_timetosee
)) {
75 $timetoshowusers = $CFG->block_online_users_timetosee
* 60;
77 $timetoshowusers = 300;//5 minutes
80 // Work out if the user is logged in or not
81 if (!empty($eventdata->userto
->lastaccess
) && (time()-$timetoshowusers) < $eventdata->userto
->lastaccess
) {
82 $userstate = 'loggedin';
84 $userstate = 'loggedoff';
87 // Create the message object
88 $savemessage = new stdClass();
89 $savemessage->useridfrom
= $eventdata->userfrom
->id
;
90 $savemessage->useridto
= $eventdata->userto
->id
;
91 $savemessage->subject
= $eventdata->subject
;
92 $savemessage->fullmessage
= $eventdata->fullmessage
;
93 $savemessage->fullmessageformat
= $eventdata->fullmessageformat
;
94 $savemessage->fullmessagehtml
= $eventdata->fullmessagehtml
;
95 $savemessage->smallmessage
= $eventdata->smallmessage
;
97 if (!empty($eventdata->notification
)) {
98 $savemessage->notification
= $eventdata->notification
;
100 $savemessage->notification
= 0;
103 if (!empty($eventdata->contexturl
)) {
104 $savemessage->contexturl
= $eventdata->contexturl
;
106 $savemessage->contexturl
= null;
109 if (!empty($eventdata->contexturlname
)) {
110 $savemessage->contexturlname
= $eventdata->contexturlname
;
112 $savemessage->contexturlname
= null;
115 $savemessage->timecreated
= time();
117 if (PHPUNIT_TEST
and class_exists('phpunit_util')) {
118 // Add some more tests to make sure the normal code can actually work.
119 $componentdir = get_component_directory($eventdata->component
);
120 if (!$componentdir or !is_dir($componentdir)) {
121 throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component
);
123 if (!file_exists("$componentdir/db/messages.php")) {
124 throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
126 $messageproviders = null;
127 include("$componentdir/db/messages.php");
128 if (!isset($messageproviders[$eventdata->name
])) {
129 throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' messages.php file");
131 unset($componentdir);
132 unset($messageproviders);
133 // Now ask phpunit if it wants to catch this message.
134 if (phpunit_util
::is_redirecting_messages()) {
135 $savemessage->timeread
= time();
136 $messageid = $DB->insert_record('message_read', $savemessage);
137 $message = $DB->get_record('message_read', array('id'=>$messageid));
138 phpunit_util
::message_sent($message);
143 // Fetch enabled processors
144 $processors = get_message_processors(true);
145 // Fetch default (site) preferences
146 $defaultpreferences = get_message_output_default_preferences();
149 $processorlist = array();
150 $preferencebase = $eventdata->component
.'_'.$eventdata->name
;
151 // Fill in the array of processors to be used based on default and user preferences
152 foreach ($processors as $processor) {
153 // First find out permissions
154 $defaultpreference = $processor->name
.'_provider_'.$preferencebase.'_permitted';
155 if (isset($defaultpreferences->{$defaultpreference})) {
156 $permitted = $defaultpreferences->{$defaultpreference};
158 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
159 // exist in the message_provider table (thus there is no default settings for them).
160 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
161 to message_send() are valid.";
162 throw new coding_exception($preferrormsg);
165 // Find out if user has configured this output
166 // Some processors cannot function without settings from the user
167 $userisconfigured = $processor->object->is_user_configured($eventdata->userto
);
169 // DEBUG: notify if we are forcing unconfigured output
170 if ($permitted == 'forced' && !$userisconfigured) {
171 debugging('Attempt to force message delivery to user who has "'.$processor->name
.'" output unconfigured', DEBUG_NORMAL
);
174 // Warn developers that necessary data is missing regardless of how the processors are configured
175 if (!isset($eventdata->userto
->emailstop
)) {
176 debugging('userto->emailstop is not set. Retrieving it from the user table');
177 $eventdata->userto
->emailstop
= $DB->get_field('user', 'emailstop', array('id'=>$eventdata->userto
->id
));
180 // Populate the list of processors we will be using
181 if ($permitted == 'forced' && $userisconfigured) {
182 // An admin is forcing users to use this message processor. Use this processor unconditionally.
183 $processorlist[] = $processor->name
;
184 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto
->emailstop
) {
185 // User has not disabled notifications
186 // See if user set any notification preferences, otherwise use site default ones
187 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
188 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto
->id
)) {
189 if (in_array($processor->name
, explode(',', $userpreference))) {
190 $processorlist[] = $processor->name
;
192 } else if (isset($defaultpreferences->{$userpreferencename})) {
193 if (in_array($processor->name
, explode(',', $defaultpreferences->{$userpreferencename}))) {
194 $processorlist[] = $processor->name
;
200 if (empty($processorlist) && $savemessage->notification
) {
201 //if they have deselected all processors and its a notification mark it read. The user doesnt want to be bothered
202 $savemessage->timeread
= time();
203 $messageid = $DB->insert_record('message_read', $savemessage);
204 } else { // Process the message
205 // Store unread message just in case we can not send it
206 $messageid = $savemessage->id
= $DB->insert_record('message', $savemessage);
207 $eventdata->savedmessageid
= $savemessage->id
;
209 // Try to deliver the message to each processor
210 if (!empty($processorlist)) {
211 foreach ($processorlist as $procname) {
212 if (!$processors[$procname]->object->send_message($eventdata)) {
213 debugging('Error calling message processor '.$procname);
218 //if messaging is disabled and they previously had forum notifications handled by the popup processor
219 //or any processor that puts a row in message_working then the notification will remain forever
220 //unread. To prevent this mark the message read if messaging is disabled
221 if (empty($CFG->messaging
)) {
222 require_once($CFG->dirroot
.'/message/lib.php');
223 $messageid = message_mark_message_read($savemessage, time());
224 } else if ( $DB->count_records('message_working', array('unreadmessageid' => $savemessage->id
)) == 0){
225 //if there is no more processors that want to process this we can move message to message_read
226 require_once($CFG->dirroot
.'/message/lib.php');
227 $messageid = message_mark_message_read($savemessage, time(), true);
237 * Updates the message_providers table with the current set of message providers
239 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
240 * @return boolean True on success
242 function message_update_providers($component='moodle') {
245 // load message providers from files
246 $fileproviders = message_get_providers_from_file($component);
248 // load message providers from the database
249 $dbproviders = message_get_providers_from_db($component);
251 foreach ($fileproviders as $messagename => $fileprovider) {
253 if (!empty($dbproviders[$messagename])) { // Already exists in the database
254 // check if capability has changed
255 if ($dbproviders[$messagename]->capability
== $fileprovider['capability']) { // Same, so ignore
256 // exact same message provider already present in db, ignore this entry
257 unset($dbproviders[$messagename]);
260 } else { // Update existing one
261 $provider = new stdClass();
262 $provider->id
= $dbproviders[$messagename]->id
;
263 $provider->capability
= $fileprovider['capability'];
264 $DB->update_record('message_providers', $provider);
265 unset($dbproviders[$messagename]);
269 } else { // New message provider, add it
271 $provider = new stdClass();
272 $provider->name
= $messagename;
273 $provider->component
= $component;
274 $provider->capability
= $fileprovider['capability'];
276 $transaction = $DB->start_delegated_transaction();
277 $DB->insert_record('message_providers', $provider);
278 message_set_default_message_preference($component, $messagename, $fileprovider);
279 $transaction->allow_commit();
283 foreach ($dbproviders as $dbprovider) { // Delete old ones
284 $DB->delete_records('message_providers', array('id' => $dbprovider->id
));
285 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
286 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
293 * This function populates default message preferences for all existing providers
294 * when the new message processor is added.
296 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
297 * @throws invalid_parameter_exception if $processorname does not exist in the database
299 function message_update_processors($processorname) {
302 // validate if our processor exists
303 $processor = $DB->get_records('message_processors', array('name' => $processorname));
304 if (empty($processor)) {
305 throw new invalid_parameter_exception();
308 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
310 $transaction = $DB->start_delegated_transaction();
311 foreach ($providers as $provider) {
312 // load message providers from files
313 $fileproviders = message_get_providers_from_file($provider->component
);
314 foreach ($fileproviders as $messagename => $fileprovider) {
315 message_set_default_message_preference($provider->component
, $messagename, $fileprovider, $processorname);
318 $transaction->allow_commit();
322 * Setting default messaging preferences for particular message provider
324 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
325 * @param string $messagename The name of message provider
326 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
327 * @param string $processorname The optional name of message processor
329 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
332 // Fetch message processors
334 // If we need to process a particular processor, set the select condition
335 if (!empty($processorname)) {
336 $condition = array('name' => $processorname);
338 $processors = $DB->get_records('message_processors', $condition);
340 // load default messaging preferences
341 $defaultpreferences = get_message_output_default_preferences();
343 // Setting default preference
344 $componentproviderbase = $component.'_'.$messagename;
345 $loggedinpref = array();
346 $loggedoffpref = array();
347 // set 'permitted' preference first for each messaging processor
348 foreach ($processors as $processor) {
349 $preferencename = $processor->name
.'_provider_'.$componentproviderbase.'_permitted';
350 // if we do not have this setting yet, set it
351 if (!isset($defaultpreferences->{$preferencename})) {
352 // determine plugin default settings
354 if (isset($fileprovider['defaults'][$processor->name
])) {
355 $plugindefault = $fileprovider['defaults'][$processor->name
];
357 // get string values of the settings
358 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name
);
359 // store default preferences for current processor
360 set_config($preferencename, $permitted, 'message');
361 // save loggedin/loggedoff settings
363 $loggedinpref[] = $processor->name
;
366 $loggedoffpref[] = $processor->name
;
370 // now set loggedin/loggedoff preferences
371 if (!empty($loggedinpref)) {
372 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
373 if (isset($defaultpreferences->{$preferencename})) {
374 // We have the default preferences for this message provider, which
375 // likely means that we have been adding a new processor. Add defaults
376 // to exisitng preferences.
377 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
379 set_config($preferencename, join(',', $loggedinpref), 'message');
381 if (!empty($loggedoffpref)) {
382 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
383 if (isset($defaultpreferences->{$preferencename})) {
384 // We have the default preferences for this message provider, which
385 // likely means that we have been adding a new processor. Add defaults
386 // to exisitng preferences.
387 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
389 set_config($preferencename, join(',', $loggedoffpref), 'message');
394 * This function has been deprecated please use {@link message_get_providers_for_user()} instead.
396 * Returns the active providers for the current user, based on capability
398 * @see message_get_providers_for_user()
399 * @deprecated since 2.1
400 * @todo Remove in 2.5 (MDL-34454)
401 * @return array An array of message providers
403 function message_get_my_providers() {
405 debugging('message_get_my_providers is deprecated please update your code', DEBUG_DEVELOPER
);
406 return message_get_providers_for_user($USER->id
);
410 * Returns the active providers for the user specified, based on capability
412 * @param int $userid id of user
413 * @return array An array of message providers
415 function message_get_providers_for_user($userid) {
418 $providers = get_message_providers();
420 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
421 if (!$CFG->messaging
) {
422 foreach ($providers as $providerid => $provider) {
423 if ($provider->name
== 'instantmessage') {
424 unset($providers[$providerid]);
430 // If the component is an enrolment plugin, check it is enabled
431 foreach ($providers as $providerid => $provider) {
432 list($type, $name) = normalize_component($provider->component
);
433 if ($type == 'enrol' && !enrol_is_enabled($name)) {
434 unset($providers[$providerid]);
438 // Now we need to check capabilities. We need to eliminate the providers
439 // where the user does not have the corresponding capability anywhere.
440 // Here we deal with the common simple case of the user having the
441 // capability in the system context. That handles $CFG->defaultuserroleid.
442 // For the remaining providers/capabilities, we need to do a more complex
443 // query involving all overrides everywhere.
444 $unsureproviders = array();
445 $unsurecapabilities = array();
446 $systemcontext = context_system
::instance();
447 foreach ($providers as $providerid => $provider) {
448 if (empty($provider->capability
) ||
has_capability($provider->capability
, $systemcontext, $userid)) {
449 // The provider is relevant to this user.
453 $unsureproviders[$providerid] = $provider;
454 $unsurecapabilities[$provider->capability
] = 1;
455 unset($providers[$providerid]);
458 if (empty($unsureproviders)) {
459 // More complex checks are not required.
463 // Now check the unsure capabilities.
464 list($capcondition, $params) = $DB->get_in_or_equal(
465 array_keys($unsurecapabilities), SQL_PARAMS_NAMED
);
466 $params['userid'] = $userid;
468 $sql = "SELECT DISTINCT rc.capability, 1
470 FROM {role_assignments} ra
471 JOIN {context} actx ON actx.id = ra.contextid
472 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
473 JOIN {context} cctx ON cctx.id = rc.contextid
475 WHERE ra.userid = :userid
476 AND rc.capability $capcondition
477 AND rc.permission > 0
478 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
479 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
481 if (!empty($CFG->defaultfrontpageroleid
)) {
482 $frontpagecontext = context_course
::instance(SITEID
);
484 list($capcondition2, $params2) = $DB->get_in_or_equal(
485 array_keys($unsurecapabilities), SQL_PARAMS_NAMED
);
486 $params = array_merge($params, $params2);
487 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid
;
488 $params['frontpagepathpattern'] = $frontpagecontext->path
. '/';
493 SELECT DISTINCT rc.capability, 1
495 FROM {role_capabilities} rc
496 JOIN {context} cctx ON cctx.id = rc.contextid
498 WHERE rc.roleid = :frontpageroleid
499 AND rc.capability $capcondition2
500 AND rc.permission > 0
501 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
504 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
506 // Add back any providers based on the detailed capability check.
507 foreach ($unsureproviders as $providerid => $provider) {
508 if (array_key_exists($provider->capability
, $relevantcapabilities)) {
509 $providers[$providerid] = $provider;
517 * Gets the message providers that are in the database for this component.
519 * This is an internal function used within messagelib.php
521 * @see message_update_providers()
522 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
523 * @return array An array of message providers
525 function message_get_providers_from_db($component) {
528 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
532 * Loads the messages definitions for a component from file
534 * If no messages are defined for the component, return an empty array.
535 * This is an internal function used within messagelib.php
537 * @see message_update_providers()
538 * @see message_update_processors()
539 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
540 * @return array An array of message providers or empty array if not exists
542 function message_get_providers_from_file($component) {
543 $defpath = get_component_directory($component).'/db/messages.php';
545 $messageproviders = array();
547 if (file_exists($defpath)) {
551 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
552 if (empty($messageprovider['capability'])) {
553 $messageproviders[$name]['capability'] = NULL;
555 if (empty($messageprovider['defaults'])) {
556 $messageproviders[$name]['defaults'] = array();
560 return $messageproviders;
564 * Remove all message providers for particular component and corresponding settings
566 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
569 function message_provider_uninstall($component) {
572 $transaction = $DB->start_delegated_transaction();
573 $DB->delete_records('message_providers', array('component' => $component));
574 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
575 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
576 $transaction->allow_commit();
580 * Uninstall a message processor
582 * @param string $name A message processor name like 'email', 'jabber'
584 function message_processor_uninstall($name) {
587 $transaction = $DB->start_delegated_transaction();
588 $DB->delete_records('message_processors', array('name' => $name));
589 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
590 // delete permission preferences only, we do not care about loggedin/loggedoff
591 // defaults, they will be removed on the next attempt to update the preferences
592 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
593 $transaction->allow_commit();