Merge branch 'MDL-37781-workshop-schedule_23' of git://github.com/mudrd8mz/moodle...
[moodle.git] / lib / messagelib.php
blobe2ffd297cabdab2215efc0f5fd47e7f4ad503c70
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 // Fetch enabled processors
118 $processors = get_message_processors(true);
119 // Fetch default (site) preferences
120 $defaultpreferences = get_message_output_default_preferences();
122 // Preset variables
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};
131 } else {
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 = "Could not load preference $defaultpreference. Make sure the component and name you supplied
135 to message_send() are valid.";
136 throw new coding_exception($preferrormsg);
139 // Find out if user has configured this output
140 // Some processors cannot function without settings from the user
141 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
143 // DEBUG: notify if we are forcing unconfigured output
144 if ($permitted == 'forced' && !$userisconfigured) {
145 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
148 // Warn developers that necessary data is missing regardless of how the processors are configured
149 if (!isset($eventdata->userto->emailstop)) {
150 debugging('userto->emailstop is not set. Retrieving it from the user table');
151 $eventdata->userto->emailstop = $DB->get_field('user', 'emailstop', array('id'=>$eventdata->userto->id));
154 // Populate the list of processors we will be using
155 if ($permitted == 'forced' && $userisconfigured) {
156 // An admin is forcing users to use this message processor. Use this processor unconditionally.
157 $processorlist[] = $processor->name;
158 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
159 // User has not disabled notifications
160 // See if user set any notification preferences, otherwise use site default ones
161 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
162 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto->id)) {
163 if (in_array($processor->name, explode(',', $userpreference))) {
164 $processorlist[] = $processor->name;
166 } else if (isset($defaultpreferences->{$userpreferencename})) {
167 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
168 $processorlist[] = $processor->name;
174 if (empty($processorlist) && $savemessage->notification) {
175 //if they have deselected all processors and its a notification mark it read. The user doesnt want to be bothered
176 $savemessage->timeread = time();
177 $messageid = $DB->insert_record('message_read', $savemessage);
178 } else { // Process the message
179 // Store unread message just in case we can not send it
180 $messageid = $savemessage->id = $DB->insert_record('message', $savemessage);
181 $eventdata->savedmessageid = $savemessage->id;
183 // Try to deliver the message to each processor
184 if (!empty($processorlist)) {
185 foreach ($processorlist as $procname) {
186 if (!$processors[$procname]->object->send_message($eventdata)) {
187 debugging('Error calling message processor '.$procname);
188 $messageid = false;
192 //if messaging is disabled and they previously had forum notifications handled by the popup processor
193 //or any processor that puts a row in message_working then the notification will remain forever
194 //unread. To prevent this mark the message read if messaging is disabled
195 if (empty($CFG->messaging)) {
196 require_once($CFG->dirroot.'/message/lib.php');
197 $messageid = message_mark_message_read($savemessage, time());
198 } else if ( $DB->count_records('message_working', array('unreadmessageid' => $savemessage->id)) == 0){
199 //if there is no more processors that want to process this we can move message to message_read
200 require_once($CFG->dirroot.'/message/lib.php');
201 $messageid = message_mark_message_read($savemessage, time(), true);
206 return $messageid;
211 * Updates the message_providers table with the current set of message providers
213 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
214 * @return boolean True on success
216 function message_update_providers($component='moodle') {
217 global $DB;
219 // load message providers from files
220 $fileproviders = message_get_providers_from_file($component);
222 // load message providers from the database
223 $dbproviders = message_get_providers_from_db($component);
225 foreach ($fileproviders as $messagename => $fileprovider) {
227 if (!empty($dbproviders[$messagename])) { // Already exists in the database
228 // check if capability has changed
229 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
230 // exact same message provider already present in db, ignore this entry
231 unset($dbproviders[$messagename]);
232 continue;
234 } else { // Update existing one
235 $provider = new stdClass();
236 $provider->id = $dbproviders[$messagename]->id;
237 $provider->capability = $fileprovider['capability'];
238 $DB->update_record('message_providers', $provider);
239 unset($dbproviders[$messagename]);
240 continue;
243 } else { // New message provider, add it
245 $provider = new stdClass();
246 $provider->name = $messagename;
247 $provider->component = $component;
248 $provider->capability = $fileprovider['capability'];
250 $transaction = $DB->start_delegated_transaction();
251 $DB->insert_record('message_providers', $provider);
252 message_set_default_message_preference($component, $messagename, $fileprovider);
253 $transaction->allow_commit();
257 foreach ($dbproviders as $dbprovider) { // Delete old ones
258 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
259 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
260 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
263 return true;
267 * This function populates default message preferences for all existing providers
268 * when the new message processor is added.
270 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
271 * @throws invalid_parameter_exception if $processorname does not exist in the database
273 function message_update_processors($processorname) {
274 global $DB;
276 // validate if our processor exists
277 $processor = $DB->get_records('message_processors', array('name' => $processorname));
278 if (empty($processor)) {
279 throw new invalid_parameter_exception();
282 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
284 $transaction = $DB->start_delegated_transaction();
285 foreach ($providers as $provider) {
286 // load message providers from files
287 $fileproviders = message_get_providers_from_file($provider->component);
288 foreach ($fileproviders as $messagename => $fileprovider) {
289 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
292 $transaction->allow_commit();
296 * Setting default messaging preferences for particular message provider
298 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
299 * @param string $messagename The name of message provider
300 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
301 * @param string $processorname The optional name of message processor
303 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
304 global $DB;
306 // Fetch message processors
307 $condition = null;
308 // If we need to process a particular processor, set the select condition
309 if (!empty($processorname)) {
310 $condition = array('name' => $processorname);
312 $processors = $DB->get_records('message_processors', $condition);
314 // load default messaging preferences
315 $defaultpreferences = get_message_output_default_preferences();
317 // Setting default preference
318 $componentproviderbase = $component.'_'.$messagename;
319 $loggedinpref = array();
320 $loggedoffpref = array();
321 // set 'permitted' preference first for each messaging processor
322 foreach ($processors as $processor) {
323 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
324 // if we do not have this setting yet, set it
325 if (!isset($defaultpreferences->{$preferencename})) {
326 // determine plugin default settings
327 $plugindefault = 0;
328 if (isset($fileprovider['defaults'][$processor->name])) {
329 $plugindefault = $fileprovider['defaults'][$processor->name];
331 // get string values of the settings
332 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
333 // store default preferences for current processor
334 set_config($preferencename, $permitted, 'message');
335 // save loggedin/loggedoff settings
336 if ($loggedin) {
337 $loggedinpref[] = $processor->name;
339 if ($loggedoff) {
340 $loggedoffpref[] = $processor->name;
344 // now set loggedin/loggedoff preferences
345 if (!empty($loggedinpref)) {
346 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
347 if (isset($defaultpreferences->{$preferencename})) {
348 // We have the default preferences for this message provider, which
349 // likely means that we have been adding a new processor. Add defaults
350 // to exisitng preferences.
351 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
353 set_config($preferencename, join(',', $loggedinpref), 'message');
355 if (!empty($loggedoffpref)) {
356 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
357 if (isset($defaultpreferences->{$preferencename})) {
358 // We have the default preferences for this message provider, which
359 // likely means that we have been adding a new processor. Add defaults
360 // to exisitng preferences.
361 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
363 set_config($preferencename, join(',', $loggedoffpref), 'message');
368 * This function has been deprecated please use {@link message_get_providers_for_user()} instead.
370 * Returns the active providers for the current user, based on capability
372 * @see message_get_providers_for_user()
373 * @deprecated since 2.1
374 * @todo Remove in 2.2 (MDL-31031)
375 * @return array An array of message providers
377 function message_get_my_providers() {
378 global $USER;
379 return message_get_providers_for_user($USER->id);
383 * Returns the active providers for the user specified, based on capability
385 * @param int $userid id of user
386 * @return array An array of message providers
388 function message_get_providers_for_user($userid) {
389 global $DB, $CFG;
391 $providers = get_message_providers();
393 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
394 if (!$CFG->messaging) {
395 foreach ($providers as $providerid => $provider) {
396 if ($provider->name == 'instantmessage') {
397 unset($providers[$providerid]);
398 break;
403 // If the component is an enrolment plugin, check it is enabled
404 foreach ($providers as $providerid => $provider) {
405 list($type, $name) = normalize_component($provider->component);
406 if ($type == 'enrol' && !enrol_is_enabled($name)) {
407 unset($providers[$providerid]);
411 // Now we need to check capabilities. We need to eliminate the providers
412 // where the user does not have the corresponding capability anywhere.
413 // Here we deal with the common simple case of the user having the
414 // capability in the system context. That handles $CFG->defaultuserroleid.
415 // For the remaining providers/capabilities, we need to do a more complex
416 // query involving all overrides everywhere.
417 $unsureproviders = array();
418 $unsurecapabilities = array();
419 $systemcontext = context_system::instance();
420 foreach ($providers as $providerid => $provider) {
421 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
422 // The provider is relevant to this user.
423 continue;
426 $unsureproviders[$providerid] = $provider;
427 $unsurecapabilities[$provider->capability] = 1;
428 unset($providers[$providerid]);
431 if (empty($unsureproviders)) {
432 // More complex checks are not required.
433 return $providers;
436 // Now check the unsure capabilities.
437 list($capcondition, $params) = $DB->get_in_or_equal(
438 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
439 $params['userid'] = $userid;
441 $sql = "SELECT DISTINCT rc.capability, 1
443 FROM {role_assignments} ra
444 JOIN {context} actx ON actx.id = ra.contextid
445 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
446 JOIN {context} cctx ON cctx.id = rc.contextid
448 WHERE ra.userid = :userid
449 AND rc.capability $capcondition
450 AND rc.permission > 0
451 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
452 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
454 if (!empty($CFG->defaultfrontpageroleid)) {
455 $frontpagecontext = context_course::instance(SITEID);
457 list($capcondition2, $params2) = $DB->get_in_or_equal(
458 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
459 $params = array_merge($params, $params2);
460 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
461 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
463 $sql .= "
464 UNION
466 SELECT DISTINCT rc.capability, 1
468 FROM {role_capabilities} rc
469 JOIN {context} cctx ON cctx.id = rc.contextid
471 WHERE rc.roleid = :frontpageroleid
472 AND rc.capability $capcondition2
473 AND rc.permission > 0
474 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
477 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
479 // Add back any providers based on the detailed capability check.
480 foreach ($unsureproviders as $providerid => $provider) {
481 if (array_key_exists($provider->capability, $relevantcapabilities)) {
482 $providers[$providerid] = $provider;
486 return $providers;
490 * Gets the message providers that are in the database for this component.
492 * This is an internal function used within messagelib.php
494 * @see message_update_providers()
495 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
496 * @return array An array of message providers
498 function message_get_providers_from_db($component) {
499 global $DB;
501 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
505 * Loads the messages definitions for a component from file
507 * If no messages are defined for the component, return an empty array.
508 * This is an internal function used within messagelib.php
510 * @see message_update_providers()
511 * @see message_update_processors()
512 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
513 * @return array An array of message providers or empty array if not exists
515 function message_get_providers_from_file($component) {
516 $defpath = get_component_directory($component).'/db/messages.php';
518 $messageproviders = array();
520 if (file_exists($defpath)) {
521 require($defpath);
524 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
525 if (empty($messageprovider['capability'])) {
526 $messageproviders[$name]['capability'] = NULL;
528 if (empty($messageprovider['defaults'])) {
529 $messageproviders[$name]['defaults'] = array();
533 return $messageproviders;
537 * Remove all message providers for particular component and corresponding settings
539 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
540 * @return void
542 function message_provider_uninstall($component) {
543 global $DB;
545 $transaction = $DB->start_delegated_transaction();
546 $DB->delete_records('message_providers', array('component' => $component));
547 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
548 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
549 $transaction->allow_commit();
553 * Uninstall a message processor
555 * @param string $name A message processor name like 'email', 'jabber'
557 function message_processor_uninstall($name) {
558 global $DB;
560 $transaction = $DB->start_delegated_transaction();
561 $DB->delete_records('message_processors', array('name' => $name));
562 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
563 // delete permission preferences only, we do not care about loggedin/loggedoff
564 // defaults, they will be removed on the next attempt to update the preferences
565 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
566 $transaction->allow_commit();