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 // Fetch enabled processors
118 $processors = get_message_processors(true);
119 // Fetch default (site) preferences
120 $defaultpreferences = get_message_output_default_preferences();
123 $processorlist = array();
124 $preferencebase = $eventdata->component
.'_'.$eventdata->name
;
125 // Fill in the array of processors to be used based on default and user preferences
126 foreach ($processors as $processor) {
127 // First find out permissions
128 $defaultpreference = $processor->name
.'_provider_'.$preferencebase.'_permitted';
129 if (isset($defaultpreferences->{$defaultpreference})) {
130 $permitted = $defaultpreferences->{$defaultpreference};
132 //MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
133 //exist in the message_provider table (thus there is no default settings for them)
134 $preferrormsg = get_string('couldnotfindpreference', 'message', $defaultpreference);
135 throw new coding_exception($preferrormsg,'blah');
138 // Find out if user has configured this output
139 // Some processors cannot function without settings from the user
140 $userisconfigured = $processor->object->is_user_configured($eventdata->userto
);
142 // DEBUG: notify if we are forcing unconfigured output
143 if ($permitted == 'forced' && !$userisconfigured) {
144 debugging('Attempt to force message delivery to user who has "'.$processor->name
.'" output unconfigured', DEBUG_NORMAL
);
147 // Warn developers that necessary data is missing regardless of how the processors are configured
148 if (!isset($eventdata->userto
->emailstop
)) {
149 debugging('userto->emailstop is not set. Retrieving it from the user table');
150 $eventdata->userto
->emailstop
= $DB->get_field('user', 'emailstop', array('id'=>$eventdata->userto
->id
));
153 // Populate the list of processors we will be using
154 if ($permitted == 'forced' && $userisconfigured) {
155 // An admin is forcing users to use this message processor. Use this processor unconditionally.
156 $processorlist[] = $processor->name
;
157 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto
->emailstop
) {
158 // User has not disabled notifications
159 // See if user set any notification preferences, otherwise use site default ones
160 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
161 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto
->id
)) {
162 if (in_array($processor->name
, explode(',', $userpreference))) {
163 $processorlist[] = $processor->name
;
165 } else if (isset($defaultpreferences->{$userpreferencename})) {
166 if (in_array($processor->name
, explode(',', $defaultpreferences->{$userpreferencename}))) {
167 $processorlist[] = $processor->name
;
173 if (empty($processorlist) && $savemessage->notification
) {
174 //if they have deselected all processors and its a notification mark it read. The user doesnt want to be bothered
175 $savemessage->timeread
= time();
176 $messageid = $DB->insert_record('message_read', $savemessage);
177 } else { // Process the message
178 // Store unread message just in case we can not send it
179 $messageid = $savemessage->id
= $DB->insert_record('message', $savemessage);
180 $eventdata->savedmessageid
= $savemessage->id
;
182 // Try to deliver the message to each processor
183 if (!empty($processorlist)) {
184 foreach ($processorlist as $procname) {
185 if (!$processors[$procname]->object->send_message($eventdata)) {
186 debugging('Error calling message processor '.$procname);
191 //if messaging is disabled and they previously had forum notifications handled by the popup processor
192 //or any processor that puts a row in message_working then the notification will remain forever
193 //unread. To prevent this mark the message read if messaging is disabled
194 if (empty($CFG->messaging
)) {
195 require_once($CFG->dirroot
.'/message/lib.php');
196 $messageid = message_mark_message_read($savemessage, time());
197 } else if ( $DB->count_records('message_working', array('unreadmessageid' => $savemessage->id
)) == 0){
198 //if there is no more processors that want to process this we can move message to message_read
199 require_once($CFG->dirroot
.'/message/lib.php');
200 $messageid = message_mark_message_read($savemessage, time(), true);
210 * Updates the message_providers table with the current set of message providers
212 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
213 * @return boolean True on success
215 function message_update_providers($component='moodle') {
218 // load message providers from files
219 $fileproviders = message_get_providers_from_file($component);
221 // load message providers from the database
222 $dbproviders = message_get_providers_from_db($component);
224 foreach ($fileproviders as $messagename => $fileprovider) {
226 if (!empty($dbproviders[$messagename])) { // Already exists in the database
227 // check if capability has changed
228 if ($dbproviders[$messagename]->capability
== $fileprovider['capability']) { // Same, so ignore
229 // exact same message provider already present in db, ignore this entry
230 unset($dbproviders[$messagename]);
233 } else { // Update existing one
234 $provider = new stdClass();
235 $provider->id
= $dbproviders[$messagename]->id
;
236 $provider->capability
= $fileprovider['capability'];
237 $DB->update_record('message_providers', $provider);
238 unset($dbproviders[$messagename]);
242 } else { // New message provider, add it
244 $provider = new stdClass();
245 $provider->name
= $messagename;
246 $provider->component
= $component;
247 $provider->capability
= $fileprovider['capability'];
249 $transaction = $DB->start_delegated_transaction();
250 $DB->insert_record('message_providers', $provider);
251 message_set_default_message_preference($component, $messagename, $fileprovider);
252 $transaction->allow_commit();
256 foreach ($dbproviders as $dbprovider) { // Delete old ones
257 $DB->delete_records('message_providers', array('id' => $dbprovider->id
));
258 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
259 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
266 * This function populates default message preferences for all existing providers
267 * when the new message processor is added.
269 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
270 * @throws invalid_parameter_exception if $processorname does not exist in the database
272 function message_update_processors($processorname) {
275 // validate if our processor exists
276 $processor = $DB->get_records('message_processors', array('name' => $processorname));
277 if (empty($processor)) {
278 throw new invalid_parameter_exception();
281 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
283 $transaction = $DB->start_delegated_transaction();
284 foreach ($providers as $provider) {
285 // load message providers from files
286 $fileproviders = message_get_providers_from_file($provider->component
);
287 foreach ($fileproviders as $messagename => $fileprovider) {
288 message_set_default_message_preference($provider->component
, $messagename, $fileprovider, $processorname);
291 $transaction->allow_commit();
295 * Setting default messaging preferences for particular message provider
297 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
298 * @param string $messagename The name of message provider
299 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
300 * @param string $processorname The optional name of message processor
302 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
305 // Fetch message processors
307 // If we need to process a particular processor, set the select condition
308 if (!empty($processorname)) {
309 $condition = array('name' => $processorname);
311 $processors = $DB->get_records('message_processors', $condition);
313 // load default messaging preferences
314 $defaultpreferences = get_message_output_default_preferences();
316 // Setting default preference
317 $componentproviderbase = $component.'_'.$messagename;
318 $loggedinpref = array();
319 $loggedoffpref = array();
320 // set 'permitted' preference first for each messaging processor
321 foreach ($processors as $processor) {
322 $preferencename = $processor->name
.'_provider_'.$componentproviderbase.'_permitted';
323 // if we do not have this setting yet, set it
324 if (!isset($defaultpreferences->{$preferencename})) {
325 // determine plugin default settings
327 if (isset($fileprovider['defaults'][$processor->name
])) {
328 $plugindefault = $fileprovider['defaults'][$processor->name
];
330 // get string values of the settings
331 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name
);
332 // store default preferences for current processor
333 set_config($preferencename, $permitted, 'message');
334 // save loggedin/loggedoff settings
336 $loggedinpref[] = $processor->name
;
339 $loggedoffpref[] = $processor->name
;
343 // now set loggedin/loggedoff preferences
344 if (!empty($loggedinpref)) {
345 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
346 if (isset($defaultpreferences->{$preferencename})) {
347 // We have the default preferences for this message provider, which
348 // likely means that we have been adding a new processor. Add defaults
349 // to exisitng preferences.
350 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
352 set_config($preferencename, join(',', $loggedinpref), 'message');
354 if (!empty($loggedoffpref)) {
355 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
356 if (isset($defaultpreferences->{$preferencename})) {
357 // We have the default preferences for this message provider, which
358 // likely means that we have been adding a new processor. Add defaults
359 // to exisitng preferences.
360 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
362 set_config($preferencename, join(',', $loggedoffpref), 'message');
367 * This function has been deprecated please use {@link message_get_providers_for_user()} instead.
369 * Returns the active providers for the current user, based on capability
371 * @see message_get_providers_for_user()
372 * @deprecated since 2.1
373 * @todo Remove in 2.2 (MDL-31031)
374 * @return array An array of message providers
376 function message_get_my_providers() {
378 return message_get_providers_for_user($USER->id
);
382 * Returns the active providers for the user specified, based on capability
384 * @param int $userid id of user
385 * @return array An array of message providers
387 function message_get_providers_for_user($userid) {
390 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
392 $providers = get_message_providers();
394 // Remove all the providers we aren't allowed to see now
395 foreach ($providers as $providerid => $provider) {
396 if (!empty($provider->capability
)) {
397 if (!has_capability($provider->capability
, $systemcontext, $userid)) {
398 unset($providers[$providerid]); // Not allowed to see this
403 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
404 if (!$CFG->messaging
&& $provider->name
== 'instantmessage') {
405 unset($providers[$providerid]);
409 // If the component is an enrolment plugin, check it is enabled
410 list($type, $name) = normalize_component($provider->component
);
411 if ($type == 'enrol') {
412 if (!enrol_is_enabled($name)) {
413 unset($providers[$providerid]);
423 * Gets the message providers that are in the database for this component.
425 * This is an internal function used within messagelib.php
427 * @see message_update_providers()
428 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
429 * @return array An array of message providers
431 function message_get_providers_from_db($component) {
434 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
438 * Loads the messages definitions for a component from file
440 * If no messages are defined for the component, return an empty array.
441 * This is an internal function used within messagelib.php
443 * @see message_update_providers()
444 * @see message_update_processors()
445 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
446 * @return array An array of message providers or empty array if not exists
448 function message_get_providers_from_file($component) {
449 $defpath = get_component_directory($component).'/db/messages.php';
451 $messageproviders = array();
453 if (file_exists($defpath)) {
457 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
458 if (empty($messageprovider['capability'])) {
459 $messageproviders[$name]['capability'] = NULL;
461 if (empty($messageprovider['defaults'])) {
462 $messageproviders[$name]['defaults'] = array();
466 return $messageproviders;
470 * Remove all message providers for particular component and corresponding settings
472 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
475 function message_provider_uninstall($component) {
478 $transaction = $DB->start_delegated_transaction();
479 $DB->delete_records('message_providers', array('component' => $component));
480 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
481 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
482 $transaction->allow_commit();
486 * Uninstall a message processor
488 * @param string $name A message processor name like 'email', 'jabber'
490 function message_processor_uninstall($name) {
493 $transaction = $DB->start_delegated_transaction();
494 $DB->delete_records('message_processors', array('name' => $name));
495 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
496 // delete permission preferences only, we do not care about loggedin/loggedoff
497 // defaults, they will be removed on the next attempt to update the preferences
498 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
499 $transaction->allow_commit();