Merge branch 'wip-MDL-21097-m25' of git://github.com/marinaglancy/moodle into MOODLE_...
[moodle.git] / lib / messagelib.php
blob194e08e8a2b2f1257022ece583a3c22a17c68b91
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 //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;
76 } else {
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';
83 } else {
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;
99 } else {
100 $savemessage->notification = 0;
103 if (!empty($eventdata->contexturl)) {
104 $savemessage->contexturl = $eventdata->contexturl;
105 } else {
106 $savemessage->contexturl = null;
109 if (!empty($eventdata->contexturlname)) {
110 $savemessage->contexturlname = $eventdata->contexturlname;
111 } else {
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);
139 return $messageid;
143 // Fetch enabled processors
144 $processors = get_message_processors(true);
145 // Fetch default (site) preferences
146 $defaultpreferences = get_message_output_default_preferences();
148 // Preset variables
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};
157 } else {
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);
214 $messageid = false;
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);
232 return $messageid;
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') {
243 global $DB;
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]);
258 continue;
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]);
266 continue;
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}_%"));
287 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
290 return true;
294 * This function populates default message preferences for all existing providers
295 * when the new message processor is added.
297 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
298 * @throws invalid_parameter_exception if $processorname does not exist in the database
300 function message_update_processors($processorname) {
301 global $DB;
303 // validate if our processor exists
304 $processor = $DB->get_records('message_processors', array('name' => $processorname));
305 if (empty($processor)) {
306 throw new invalid_parameter_exception();
309 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
311 $transaction = $DB->start_delegated_transaction();
312 foreach ($providers as $provider) {
313 // load message providers from files
314 $fileproviders = message_get_providers_from_file($provider->component);
315 foreach ($fileproviders as $messagename => $fileprovider) {
316 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
319 $transaction->allow_commit();
323 * Setting default messaging preferences for particular message provider
325 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
326 * @param string $messagename The name of message provider
327 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
328 * @param string $processorname The optional name of message processor
330 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
331 global $DB;
333 // Fetch message processors
334 $condition = null;
335 // If we need to process a particular processor, set the select condition
336 if (!empty($processorname)) {
337 $condition = array('name' => $processorname);
339 $processors = $DB->get_records('message_processors', $condition);
341 // load default messaging preferences
342 $defaultpreferences = get_message_output_default_preferences();
344 // Setting default preference
345 $componentproviderbase = $component.'_'.$messagename;
346 $loggedinpref = array();
347 $loggedoffpref = array();
348 // set 'permitted' preference first for each messaging processor
349 foreach ($processors as $processor) {
350 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
351 // if we do not have this setting yet, set it
352 if (!isset($defaultpreferences->{$preferencename})) {
353 // determine plugin default settings
354 $plugindefault = 0;
355 if (isset($fileprovider['defaults'][$processor->name])) {
356 $plugindefault = $fileprovider['defaults'][$processor->name];
358 // get string values of the settings
359 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
360 // store default preferences for current processor
361 set_config($preferencename, $permitted, 'message');
362 // save loggedin/loggedoff settings
363 if ($loggedin) {
364 $loggedinpref[] = $processor->name;
366 if ($loggedoff) {
367 $loggedoffpref[] = $processor->name;
371 // now set loggedin/loggedoff preferences
372 if (!empty($loggedinpref)) {
373 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
374 if (isset($defaultpreferences->{$preferencename})) {
375 // We have the default preferences for this message provider, which
376 // likely means that we have been adding a new processor. Add defaults
377 // to exisitng preferences.
378 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
380 set_config($preferencename, join(',', $loggedinpref), 'message');
382 if (!empty($loggedoffpref)) {
383 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
384 if (isset($defaultpreferences->{$preferencename})) {
385 // We have the default preferences for this message provider, which
386 // likely means that we have been adding a new processor. Add defaults
387 // to exisitng preferences.
388 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
390 set_config($preferencename, join(',', $loggedoffpref), 'message');
395 * This function has been deprecated please use {@link message_get_providers_for_user()} instead.
397 * Returns the active providers for the current user, based on capability
399 * @see message_get_providers_for_user()
400 * @deprecated since 2.1
401 * @todo Remove in 2.5 (MDL-34454)
402 * @return array An array of message providers
404 function message_get_my_providers() {
405 global $USER;
406 debugging('message_get_my_providers is deprecated please update your code', DEBUG_DEVELOPER);
407 return message_get_providers_for_user($USER->id);
411 * Returns the active providers for the user specified, based on capability
413 * @param int $userid id of user
414 * @return array An array of message providers
416 function message_get_providers_for_user($userid) {
417 global $DB, $CFG;
419 $providers = get_message_providers();
421 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
422 if (!$CFG->messaging) {
423 foreach ($providers as $providerid => $provider) {
424 if ($provider->name == 'instantmessage') {
425 unset($providers[$providerid]);
426 break;
431 // If the component is an enrolment plugin, check it is enabled
432 foreach ($providers as $providerid => $provider) {
433 list($type, $name) = normalize_component($provider->component);
434 if ($type == 'enrol' && !enrol_is_enabled($name)) {
435 unset($providers[$providerid]);
439 // Now we need to check capabilities. We need to eliminate the providers
440 // where the user does not have the corresponding capability anywhere.
441 // Here we deal with the common simple case of the user having the
442 // capability in the system context. That handles $CFG->defaultuserroleid.
443 // For the remaining providers/capabilities, we need to do a more complex
444 // query involving all overrides everywhere.
445 $unsureproviders = array();
446 $unsurecapabilities = array();
447 $systemcontext = context_system::instance();
448 foreach ($providers as $providerid => $provider) {
449 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
450 // The provider is relevant to this user.
451 continue;
454 $unsureproviders[$providerid] = $provider;
455 $unsurecapabilities[$provider->capability] = 1;
456 unset($providers[$providerid]);
459 if (empty($unsureproviders)) {
460 // More complex checks are not required.
461 return $providers;
464 // Now check the unsure capabilities.
465 list($capcondition, $params) = $DB->get_in_or_equal(
466 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
467 $params['userid'] = $userid;
469 $sql = "SELECT DISTINCT rc.capability, 1
471 FROM {role_assignments} ra
472 JOIN {context} actx ON actx.id = ra.contextid
473 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
474 JOIN {context} cctx ON cctx.id = rc.contextid
476 WHERE ra.userid = :userid
477 AND rc.capability $capcondition
478 AND rc.permission > 0
479 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
480 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
482 if (!empty($CFG->defaultfrontpageroleid)) {
483 $frontpagecontext = context_course::instance(SITEID);
485 list($capcondition2, $params2) = $DB->get_in_or_equal(
486 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
487 $params = array_merge($params, $params2);
488 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
489 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
491 $sql .= "
492 UNION
494 SELECT DISTINCT rc.capability, 1
496 FROM {role_capabilities} rc
497 JOIN {context} cctx ON cctx.id = rc.contextid
499 WHERE rc.roleid = :frontpageroleid
500 AND rc.capability $capcondition2
501 AND rc.permission > 0
502 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
505 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
507 // Add back any providers based on the detailed capability check.
508 foreach ($unsureproviders as $providerid => $provider) {
509 if (array_key_exists($provider->capability, $relevantcapabilities)) {
510 $providers[$providerid] = $provider;
514 return $providers;
518 * Gets the message providers that are in the database for this component.
520 * This is an internal function used within messagelib.php
522 * @see message_update_providers()
523 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
524 * @return array An array of message providers
526 function message_get_providers_from_db($component) {
527 global $DB;
529 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
533 * Loads the messages definitions for a component from file
535 * If no messages are defined for the component, return an empty array.
536 * This is an internal function used within messagelib.php
538 * @see message_update_providers()
539 * @see message_update_processors()
540 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
541 * @return array An array of message providers or empty array if not exists
543 function message_get_providers_from_file($component) {
544 $defpath = get_component_directory($component).'/db/messages.php';
546 $messageproviders = array();
548 if (file_exists($defpath)) {
549 require($defpath);
552 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
553 if (empty($messageprovider['capability'])) {
554 $messageproviders[$name]['capability'] = NULL;
556 if (empty($messageprovider['defaults'])) {
557 $messageproviders[$name]['defaults'] = array();
561 return $messageproviders;
565 * Remove all message providers for particular component and corresponding settings
567 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
568 * @return void
570 function message_provider_uninstall($component) {
571 global $DB;
573 $transaction = $DB->start_delegated_transaction();
574 $DB->delete_records('message_providers', array('component' => $component));
575 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
576 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
577 $transaction->allow_commit();
578 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
579 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
583 * Uninstall a message processor
585 * @param string $name A message processor name like 'email', 'jabber'
587 function message_processor_uninstall($name) {
588 global $DB;
590 $transaction = $DB->start_delegated_transaction();
591 $DB->delete_records('message_processors', array('name' => $name));
592 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
593 // delete permission preferences only, we do not care about loggedin/loggedoff
594 // defaults, they will be removed on the next attempt to update the preferences
595 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
596 $transaction->allow_commit();
597 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
598 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));