Merge branch 'MDL-29276' of git://github.com/mouneyrac/moodle
[moodle.git] / lib / messagelib.php
blobec2970c753a034ce949cf1cfb01c49d4b76615a4
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_int($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));
68 //after how long inactive should the user be considered logged off?
69 if (isset($CFG->block_online_users_timetosee)) {
70 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
71 } else {
72 $timetoshowusers = 300;//5 minutes
75 // Work out if the user is logged in or not
76 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
77 $userstate = 'loggedin';
78 } else {
79 $userstate = 'loggedoff';
82 // Create the message object
83 $savemessage = new stdClass();
84 $savemessage->useridfrom = $eventdata->userfrom->id;
85 $savemessage->useridto = $eventdata->userto->id;
86 $savemessage->subject = $eventdata->subject;
87 $savemessage->fullmessage = $eventdata->fullmessage;
88 $savemessage->fullmessageformat = $eventdata->fullmessageformat;
89 $savemessage->fullmessagehtml = $eventdata->fullmessagehtml;
90 $savemessage->smallmessage = $eventdata->smallmessage;
92 if (!empty($eventdata->notification)) {
93 $savemessage->notification = $eventdata->notification;
94 } else {
95 $savemessage->notification = 0;
98 if (!empty($eventdata->contexturl)) {
99 $savemessage->contexturl = $eventdata->contexturl;
100 } else {
101 $savemessage->contexturl = null;
104 if (!empty($eventdata->contexturlname)) {
105 $savemessage->contexturlname = $eventdata->contexturlname;
106 } else {
107 $savemessage->contexturlname = null;
110 $savemessage->timecreated = time();
112 // Fetch enabled processors
113 $processors = get_message_processors(true);
114 // Fetch default (site) preferences
115 $defaultpreferences = get_message_output_default_preferences();
117 // Preset variables
118 $processorlist = array();
119 $preferencebase = $eventdata->component.'_'.$eventdata->name;
120 // Fill in the array of processors to be used based on default and user preferences
121 foreach ($processors as $processor) {
122 // First find out permissions
123 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
124 if (isset($defaultpreferences->{$defaultpreference})) {
125 $permitted = $defaultpreferences->{$defaultpreference};
126 } else {
127 //MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
128 //exist in the message_provider table (thus there is no default settings for them)
129 $preferrormsg = get_string('couldnotfindpreference', 'message', $preferencename);
130 throw new coding_exception($preferrormsg,'blah');
133 // Find out if user has configured this output
134 // Some processors cannot function without settings from the user
135 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
137 // DEBUG: notify if we are forcing unconfigured output
138 if ($permitted == 'forced' && !$userisconfigured) {
139 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
142 // Populate the list of processors we will be using
143 if ($permitted == 'forced' && $userisconfigured) {
144 // We force messages for this processor, so use this processor unconditionally if user has configured it
145 $processorlist[] = $processor->name;
146 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
147 // User settings are permitted, see if user set any, otherwise use site default ones
148 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
149 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto->id)) {
150 if (in_array($processor->name, explode(',', $userpreference))) {
151 $processorlist[] = $processor->name;
153 } else if (isset($defaultpreferences->{$userpreferencename})) {
154 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
155 $processorlist[] = $processor->name;
161 if (empty($processorlist) && $savemessage->notification) {
162 //if they have deselected all processors and its a notification mark it read. The user doesnt want to be bothered
163 $savemessage->timeread = time();
164 $messageid = $DB->insert_record('message_read', $savemessage);
165 } else { // Process the message
166 // Store unread message just in case we can not send it
167 $messageid = $savemessage->id = $DB->insert_record('message', $savemessage);
168 $eventdata->savedmessageid = $savemessage->id;
170 // Try to deliver the message to each processor
171 if (!empty($processorlist)) {
172 foreach ($processorlist as $procname) {
173 if (!$processors[$procname]->object->send_message($eventdata)) {
174 debugging('Error calling message processor '.$procname);
175 $messageid = false;
179 //if messaging is disabled and they previously had forum notifications handled by the popup processor
180 //or any processor that puts a row in message_working then the notification will remain forever
181 //unread. To prevent this mark the message read if messaging is disabled
182 if (empty($CFG->messaging)) {
183 require_once($CFG->dirroot.'/message/lib.php');
184 $messageid = message_mark_message_read($savemessage, time());
185 } else if ( $DB->count_records('message_working', array('unreadmessageid' => $savemessage->id)) == 0){
186 //if there is no more processors that want to process this we can move message to message_read
187 require_once($CFG->dirroot.'/message/lib.php');
188 $messageid = message_mark_message_read($savemessage, time(), true);
193 return $messageid;
198 * This code updates the message_providers table with the current set of providers
200 * @param $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
201 * @return boolean
203 function message_update_providers($component='moodle') {
204 global $DB;
206 // load message providers from files
207 $fileproviders = message_get_providers_from_file($component);
209 // load message providers from the database
210 $dbproviders = message_get_providers_from_db($component);
212 foreach ($fileproviders as $messagename => $fileprovider) {
214 if (!empty($dbproviders[$messagename])) { // Already exists in the database
215 // check if capability has changed
216 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
217 // exact same message provider already present in db, ignore this entry
218 unset($dbproviders[$messagename]);
219 continue;
221 } else { // Update existing one
222 $provider = new stdClass();
223 $provider->id = $dbproviders[$messagename]->id;
224 $provider->capability = $fileprovider['capability'];
225 $DB->update_record('message_providers', $provider);
226 unset($dbproviders[$messagename]);
227 continue;
230 } else { // New message provider, add it
232 $provider = new stdClass();
233 $provider->name = $messagename;
234 $provider->component = $component;
235 $provider->capability = $fileprovider['capability'];
237 $transaction = $DB->start_delegated_transaction();
238 $DB->insert_record('message_providers', $provider);
239 message_set_default_message_preference($component, $messagename, $fileprovider);
240 $transaction->allow_commit();
244 foreach ($dbproviders as $dbprovider) { // Delete old ones
245 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
246 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
247 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
250 return true;
254 * This function populates default message preferences for all existing providers
255 * when the new message processor is added.
257 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
258 * @return void
259 * @throws invalid_parameter_exception if $processorname does not exist
261 function message_update_processors($processorname) {
262 global $DB;
264 // validate if our processor exists
265 $processor = $DB->get_records('message_processors', array('name' => $processorname));
266 if (empty($processor)) {
267 throw new invalid_parameter_exception();
270 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
272 $transaction = $DB->start_delegated_transaction();
273 foreach ($providers as $provider) {
274 // load message providers from files
275 $fileproviders = message_get_providers_from_file($provider->component);
276 foreach ($fileproviders as $messagename => $fileprovider) {
277 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
280 $transaction->allow_commit();
284 * Setting default messaging preference for particular message provider
286 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
287 * @param string $messagename The name of message provider
288 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
289 * @param string $processorname The optinal name of message processor
290 * @return void
292 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
293 global $DB;
295 // Fetch message processors
296 $condition = null;
297 // If we need to process a particular processor, set the select condition
298 if (!empty($processorname)) {
299 $condition = array('name' => $processorname);
301 $processors = $DB->get_records('message_processors', $condition);
303 // load default messaging preferences
304 $defaultpreferences = get_message_output_default_preferences();
306 // Setting default preference
307 $componentproviderbase = $component.'_'.$messagename;
308 $loggedinpref = array();
309 $loggedoffpref = array();
310 // set 'permitted' preference first for each messaging processor
311 foreach ($processors as $processor) {
312 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
313 // if we do not have this setting yet, set it
314 if (!isset($defaultpreferences->{$preferencename})) {
315 // determine plugin default settings
316 $plugindefault = 0;
317 if (isset($fileprovider['defaults'][$processor->name])) {
318 $plugindefault = $fileprovider['defaults'][$processor->name];
320 // get string values of the settings
321 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
322 // store default preferences for current processor
323 set_config($preferencename, $permitted, 'message');
324 // save loggedin/loggedoff settings
325 if ($loggedin) {
326 $loggedinpref[] = $processor->name;
328 if ($loggedoff) {
329 $loggedoffpref[] = $processor->name;
333 // now set loggedin/loggedoff preferences
334 if (!empty($loggedinpref)) {
335 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
336 if (isset($defaultpreferences->{$preferencename})) {
337 // We have the default preferences for this message provider, which
338 // likely means that we have been adding a new processor. Add defaults
339 // to exisitng preferences.
340 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
342 set_config($preferencename, join(',', $loggedinpref), 'message');
344 if (!empty($loggedoffpref)) {
345 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
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 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
352 set_config($preferencename, join(',', $loggedoffpref), 'message');
357 * Returns the active providers for the current user, based on capability
359 * This function has been deprecated please use {@see message_get_providers_for_user()} instead.
361 * @deprecated since 2.1
362 * @todo Remove in 2.2
363 * @return array of message providers
365 function message_get_my_providers() {
366 global $USER;
367 return message_get_providers_for_user($USER->id);
371 * Returns the active providers for the user specified, based on capability
373 * @param int $userid id of user
374 * @return array of message providers
376 function message_get_providers_for_user($userid) {
377 global $DB, $CFG;
379 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
381 $providers = $DB->get_records('message_providers', null, 'name');
383 // Remove all the providers we aren't allowed to see now
384 foreach ($providers as $providerid => $provider) {
385 if (!empty($provider->capability)) {
386 if (!has_capability($provider->capability, $systemcontext, $userid)) {
387 unset($providers[$providerid]); // Not allowed to see this
390 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
391 if (!$CFG->messaging && $provider->name == 'instantmessage') {
392 unset($providers[$providerid]);
396 return $providers;
400 * Gets the message providers that are in the database for this component.
402 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
403 * @return array of message providers
405 * INTERNAL - to be used from messagelib only
407 function message_get_providers_from_db($component) {
408 global $DB;
410 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
414 * Loads the messages definitions for the component (from file). If no
415 * messages are defined for the component, we simply return an empty array.
417 * @param $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
418 * @return array of message providerss or empty array if not exists
420 * INTERNAL - to be used from messagelib only
422 function message_get_providers_from_file($component) {
423 $defpath = get_component_directory($component).'/db/messages.php';
425 $messageproviders = array();
427 if (file_exists($defpath)) {
428 require($defpath);
431 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
432 if (empty($messageprovider['capability'])) {
433 $messageproviders[$name]['capability'] = NULL;
435 if (empty($messageprovider['defaults'])) {
436 $messageproviders[$name]['defaults'] = array();
440 return $messageproviders;
444 * Remove all message providers for particular plugin and corresponding settings
446 * @param string $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
447 * @return void
449 function message_provider_uninstall($component) {
450 global $DB;
452 $transaction = $DB->start_delegated_transaction();
453 $DB->delete_records('message_providers', array('component' => $component));
454 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
455 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
456 $transaction->allow_commit();
460 * Remove message processor
462 * @param string $name - examples: 'email', 'jabber'
463 * @return void
465 function message_processor_uninstall($name) {
466 global $DB;
468 $transaction = $DB->start_delegated_transaction();
469 $DB->delete_records('message_processors', array('name' => $name));
470 // delete permission preferences only, we do not care about loggedin/loggedoff
471 // defaults, they will be removed on the next attempt to update the preferences
472 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
473 $transaction->allow_commit();