Merge branch 'MDL-35147_22' of git://github.com/timhunt/moodle into MOODLE_22_STABLE
[moodle.git] / lib / messagelib.php
blobcdb746d4f1b68c874629035d13179c07237a45ed
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * messagelib.php - Contains generic messaging functions for the message system
21 * @package core
22 * @subpackage message
23 * @copyright Luis Rodrigues and Martin Dougiamas
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 require_once(dirname(dirname(__FILE__)) . '/message/lib.php');
31 /**
32 * Called when a message provider wants to send a message.
33 * This functions checks the user's processor configuration to send the given type of message,
34 * then tries to send it.
36 * Required parameter $eventdata structure:
37 * component string component name. must exist in message_providers
38 * name string message type name. must exist in message_providers
39 * userfrom object|int the user sending the message
40 * userto object|int the message recipient
41 * subject string the message subject
42 * fullmessage - the full message in a given format
43 * fullmessageformat - the format if the full message (FORMAT_MOODLE, FORMAT_HTML, ..)
44 * fullmessagehtml - the full version (the message processor will choose with one to use)
45 * smallmessage - the small version of the message
46 * contexturl - 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.
47 * contexturlname - the display text for contexturl
49 * @param object $eventdata information about the message (component, userfrom, userto, ...)
50 * @return int|false the ID of the new message or false if there was a problem with a processor
52 function message_send($eventdata) {
53 global $CFG, $DB;
55 //new message ID to return
56 $messageid = false;
58 //TODO: we need to solve problems with database transactions here somehow, for now we just prevent transactions - sorry
59 $DB->transactions_forbidden();
61 if (is_number($eventdata->userto)) {
62 $eventdata->userto = $DB->get_record('user', array('id' => $eventdata->userto));
64 if (is_int($eventdata->userfrom)) {
65 $eventdata->userfrom = $DB->get_record('user', array('id' => $eventdata->userfrom));
67 if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended) or !isset($eventdata->userto->deleted)) {
68 $eventdata->userto = $DB->get_record('user', array('id' => $eventdata->userto->id));
71 //after how long inactive should the user be considered logged off?
72 if (isset($CFG->block_online_users_timetosee)) {
73 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
74 } else {
75 $timetoshowusers = 300;//5 minutes
78 // Work out if the user is logged in or not
79 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
80 $userstate = 'loggedin';
81 } else {
82 $userstate = 'loggedoff';
85 // Create the message object
86 $savemessage = new stdClass();
87 $savemessage->useridfrom = $eventdata->userfrom->id;
88 $savemessage->useridto = $eventdata->userto->id;
89 $savemessage->subject = $eventdata->subject;
90 $savemessage->fullmessage = $eventdata->fullmessage;
91 $savemessage->fullmessageformat = $eventdata->fullmessageformat;
92 $savemessage->fullmessagehtml = $eventdata->fullmessagehtml;
93 $savemessage->smallmessage = $eventdata->smallmessage;
95 if (!empty($eventdata->notification)) {
96 $savemessage->notification = $eventdata->notification;
97 } else {
98 $savemessage->notification = 0;
101 if (!empty($eventdata->contexturl)) {
102 $savemessage->contexturl = $eventdata->contexturl;
103 } else {
104 $savemessage->contexturl = null;
107 if (!empty($eventdata->contexturlname)) {
108 $savemessage->contexturlname = $eventdata->contexturlname;
109 } else {
110 $savemessage->contexturlname = null;
113 $savemessage->timecreated = time();
115 // Fetch enabled processors
116 $processors = get_message_processors(true);
117 // Fetch default (site) preferences
118 $defaultpreferences = get_message_output_default_preferences();
120 // Preset variables
121 $processorlist = array();
122 $preferencebase = $eventdata->component.'_'.$eventdata->name;
123 // Fill in the array of processors to be used based on default and user preferences
124 foreach ($processors as $processor) {
125 // First find out permissions
126 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
127 if (isset($defaultpreferences->{$defaultpreference})) {
128 $permitted = $defaultpreferences->{$defaultpreference};
129 } else {
130 //MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
131 //exist in the message_provider table (thus there is no default settings for them)
132 $preferrormsg = get_string('couldnotfindpreference', 'message', $defaultpreference);
133 throw new coding_exception($preferrormsg,'blah');
136 // Find out if user has configured this output
137 // Some processors cannot function without settings from the user
138 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
140 // DEBUG: notify if we are forcing unconfigured output
141 if ($permitted == 'forced' && !$userisconfigured) {
142 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
145 // Warn developers that necessary data is missing regardless of how the processors are configured
146 if (!isset($eventdata->userto->emailstop)) {
147 debugging('userto->emailstop is not set. Retrieving it from the user table');
148 $eventdata->userto->emailstop = $DB->get_field('user', 'emailstop', array('id'=>$eventdata->userto->id));
151 // Populate the list of processors we will be using
152 if ($permitted == 'forced' && $userisconfigured) {
153 // An admin is forcing users to use this message processor. Use this processor unconditionally.
154 $processorlist[] = $processor->name;
155 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
156 // User has not disabled notifications
157 // See if user set any notification preferences, otherwise use site default ones
158 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
159 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto->id)) {
160 if (in_array($processor->name, explode(',', $userpreference))) {
161 $processorlist[] = $processor->name;
163 } else if (isset($defaultpreferences->{$userpreferencename})) {
164 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
165 $processorlist[] = $processor->name;
171 if (empty($processorlist) && $savemessage->notification) {
172 //if they have deselected all processors and its a notification mark it read. The user doesnt want to be bothered
173 $savemessage->timeread = time();
174 $messageid = $DB->insert_record('message_read', $savemessage);
175 } else { // Process the message
176 // Store unread message just in case we can not send it
177 $messageid = $savemessage->id = $DB->insert_record('message', $savemessage);
178 $eventdata->savedmessageid = $savemessage->id;
180 // Try to deliver the message to each processor
181 if (!empty($processorlist)) {
182 foreach ($processorlist as $procname) {
183 if (!$processors[$procname]->object->send_message($eventdata)) {
184 debugging('Error calling message processor '.$procname);
185 $messageid = false;
189 //if messaging is disabled and they previously had forum notifications handled by the popup processor
190 //or any processor that puts a row in message_working then the notification will remain forever
191 //unread. To prevent this mark the message read if messaging is disabled
192 if (empty($CFG->messaging)) {
193 require_once($CFG->dirroot.'/message/lib.php');
194 $messageid = message_mark_message_read($savemessage, time());
195 } else if ( $DB->count_records('message_working', array('unreadmessageid' => $savemessage->id)) == 0){
196 //if there is no more processors that want to process this we can move message to message_read
197 require_once($CFG->dirroot.'/message/lib.php');
198 $messageid = message_mark_message_read($savemessage, time(), true);
203 return $messageid;
208 * This code updates the message_providers table with the current set of providers
210 * @param $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
211 * @return boolean
213 function message_update_providers($component='moodle') {
214 global $DB;
216 // load message providers from files
217 $fileproviders = message_get_providers_from_file($component);
219 // load message providers from the database
220 $dbproviders = message_get_providers_from_db($component);
222 foreach ($fileproviders as $messagename => $fileprovider) {
224 if (!empty($dbproviders[$messagename])) { // Already exists in the database
225 // check if capability has changed
226 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
227 // exact same message provider already present in db, ignore this entry
228 unset($dbproviders[$messagename]);
229 continue;
231 } else { // Update existing one
232 $provider = new stdClass();
233 $provider->id = $dbproviders[$messagename]->id;
234 $provider->capability = $fileprovider['capability'];
235 $DB->update_record('message_providers', $provider);
236 unset($dbproviders[$messagename]);
237 continue;
240 } else { // New message provider, add it
242 $provider = new stdClass();
243 $provider->name = $messagename;
244 $provider->component = $component;
245 $provider->capability = $fileprovider['capability'];
247 $transaction = $DB->start_delegated_transaction();
248 $DB->insert_record('message_providers', $provider);
249 message_set_default_message_preference($component, $messagename, $fileprovider);
250 $transaction->allow_commit();
254 foreach ($dbproviders as $dbprovider) { // Delete old ones
255 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
256 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
257 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
260 return true;
264 * This function populates default message preferences for all existing providers
265 * when the new message processor is added.
267 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
268 * @return void
269 * @throws invalid_parameter_exception if $processorname does not exist
271 function message_update_processors($processorname) {
272 global $DB;
274 // validate if our processor exists
275 $processor = $DB->get_records('message_processors', array('name' => $processorname));
276 if (empty($processor)) {
277 throw new invalid_parameter_exception();
280 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
282 $transaction = $DB->start_delegated_transaction();
283 foreach ($providers as $provider) {
284 // load message providers from files
285 $fileproviders = message_get_providers_from_file($provider->component);
286 foreach ($fileproviders as $messagename => $fileprovider) {
287 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
290 $transaction->allow_commit();
294 * Setting default messaging preference for particular message provider
296 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
297 * @param string $messagename The name of message provider
298 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
299 * @param string $processorname The optinal name of message processor
300 * @return void
302 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
303 global $DB;
305 // Fetch message processors
306 $condition = null;
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
326 $plugindefault = 0;
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
335 if ($loggedin) {
336 $loggedinpref[] = $processor->name;
338 if ($loggedoff) {
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 * Returns the active providers for the current user, based on capability
369 * This function has been deprecated please use {@see message_get_providers_for_user()} instead.
371 * @deprecated since 2.1
372 * @todo Remove in 2.2
373 * @return array of message providers
375 function message_get_my_providers() {
376 global $USER;
377 return message_get_providers_for_user($USER->id);
381 * Returns the active providers for the user specified, based on capability
383 * @param int $userid id of user
384 * @return array of message providers
386 function message_get_providers_for_user($userid) {
387 global $DB, $CFG;
389 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
391 $providers = $DB->get_records('message_providers', null, 'name');
393 // Remove all the providers we aren't allowed to see now
394 foreach ($providers as $providerid => $provider) {
395 if (!empty($provider->capability)) {
396 if (!has_capability($provider->capability, $systemcontext, $userid)) {
397 unset($providers[$providerid]); // Not allowed to see this
398 continue;
402 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
403 if (!$CFG->messaging && $provider->name == 'instantmessage') {
404 unset($providers[$providerid]);
405 continue;
408 // If the component is an enrolment plugin, check it is enabled
409 list($type, $name) = normalize_component($provider->component);
410 if ($type == 'enrol') {
411 if (!enrol_is_enabled($name)) {
412 unset($providers[$providerid]);
413 continue;
418 return $providers;
422 * Gets the message providers that are in the database for this component.
424 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
425 * @return array of message providers
427 * INTERNAL - to be used from messagelib only
429 function message_get_providers_from_db($component) {
430 global $DB;
432 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
436 * Loads the messages definitions for the component (from file). If no
437 * messages are defined for the component, we simply return an empty array.
439 * @param $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
440 * @return array of message providerss or empty array if not exists
442 * INTERNAL - to be used from messagelib only
444 function message_get_providers_from_file($component) {
445 $defpath = get_component_directory($component).'/db/messages.php';
447 $messageproviders = array();
449 if (file_exists($defpath)) {
450 require($defpath);
453 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
454 if (empty($messageprovider['capability'])) {
455 $messageproviders[$name]['capability'] = NULL;
457 if (empty($messageprovider['defaults'])) {
458 $messageproviders[$name]['defaults'] = array();
462 return $messageproviders;
466 * Remove all message providers for particular plugin and corresponding settings
468 * @param string $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
469 * @return void
471 function message_provider_uninstall($component) {
472 global $DB;
474 $transaction = $DB->start_delegated_transaction();
475 $DB->delete_records('message_providers', array('component' => $component));
476 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
477 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
478 $transaction->allow_commit();
482 * Remove message processor
484 * @param string $name - examples: 'email', 'jabber'
485 * @return void
487 function message_processor_uninstall($name) {
488 global $DB;
490 $transaction = $DB->start_delegated_transaction();
491 $DB->delete_records('message_processors', array('name' => $name));
492 // delete permission preferences only, we do not care about loggedin/loggedoff
493 // defaults, they will be removed on the next attempt to update the preferences
494 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
495 $transaction->allow_commit();