MDL-40119 Forms: Remove cursor style override for calendar button
[moodle.git] / lib / messagelib.php
blob426c593070703f2c2520a9d775043b7c03ec67e2
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 = core_user::get_user($eventdata->userto);
66 if (is_int($eventdata->userfrom)) {
67 $eventdata->userfrom = core_user::get_user($eventdata->userfrom);
70 $usertoisrealuser = (core_user::is_real_user($eventdata->userto->id) != false);
71 // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
72 if (!$usertoisrealuser && !empty($eventdata->userto->emailstop)) {
73 debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
74 return false;
77 if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended) or !isset($eventdata->userto->deleted)) {
78 $eventdata->userto = core_user::get_user($eventdata->userto->id);
81 //after how long inactive should the user be considered logged off?
82 if (isset($CFG->block_online_users_timetosee)) {
83 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
84 } else {
85 $timetoshowusers = 300;//5 minutes
88 // Work out if the user is logged in or not
89 if (!empty($eventdata->userto->lastaccess) && (time()-$timetoshowusers) < $eventdata->userto->lastaccess) {
90 $userstate = 'loggedin';
91 } else {
92 $userstate = 'loggedoff';
95 // Create the message object
96 $savemessage = new stdClass();
97 $savemessage->useridfrom = $eventdata->userfrom->id;
98 $savemessage->useridto = $eventdata->userto->id;
99 $savemessage->subject = $eventdata->subject;
100 $savemessage->fullmessage = $eventdata->fullmessage;
101 $savemessage->fullmessageformat = $eventdata->fullmessageformat;
102 $savemessage->fullmessagehtml = $eventdata->fullmessagehtml;
103 $savemessage->smallmessage = $eventdata->smallmessage;
105 if (!empty($eventdata->notification)) {
106 $savemessage->notification = $eventdata->notification;
107 } else {
108 $savemessage->notification = 0;
111 if (!empty($eventdata->contexturl)) {
112 $savemessage->contexturl = $eventdata->contexturl;
113 } else {
114 $savemessage->contexturl = null;
117 if (!empty($eventdata->contexturlname)) {
118 $savemessage->contexturlname = $eventdata->contexturlname;
119 } else {
120 $savemessage->contexturlname = null;
123 $savemessage->timecreated = time();
125 if (PHPUNIT_TEST and class_exists('phpunit_util')) {
126 // Add some more tests to make sure the normal code can actually work.
127 $componentdir = core_component::get_component_directory($eventdata->component);
128 if (!$componentdir or !is_dir($componentdir)) {
129 throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component);
131 if (!file_exists("$componentdir/db/messages.php")) {
132 throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
134 $messageproviders = null;
135 include("$componentdir/db/messages.php");
136 if (!isset($messageproviders[$eventdata->name])) {
137 throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' messages.php file");
139 unset($componentdir);
140 unset($messageproviders);
141 // Now ask phpunit if it wants to catch this message.
142 if (phpunit_util::is_redirecting_messages()) {
143 $savemessage->timeread = time();
144 $messageid = $DB->insert_record('message_read', $savemessage);
145 $message = $DB->get_record('message_read', array('id'=>$messageid));
146 phpunit_util::message_sent($message);
147 return $messageid;
151 // Fetch enabled processors
152 $processors = get_message_processors(true);
153 // Fetch default (site) preferences
154 $defaultpreferences = get_message_output_default_preferences();
156 // Preset variables
157 $processorlist = array();
158 $preferencebase = $eventdata->component.'_'.$eventdata->name;
159 // Fill in the array of processors to be used based on default and user preferences
160 foreach ($processors as $processor) {
161 // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
162 if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
163 continue;
166 // First find out permissions
167 $defaultpreference = $processor->name.'_provider_'.$preferencebase.'_permitted';
168 if (isset($defaultpreferences->{$defaultpreference})) {
169 $permitted = $defaultpreferences->{$defaultpreference};
170 } else {
171 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
172 // exist in the message_provider table (thus there is no default settings for them).
173 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
174 to message_send() are valid.";
175 throw new coding_exception($preferrormsg);
178 // Find out if user has configured this output
179 // Some processors cannot function without settings from the user
180 $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
182 // DEBUG: notify if we are forcing unconfigured output
183 if ($permitted == 'forced' && !$userisconfigured) {
184 debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
187 // Warn developers that necessary data is missing regardless of how the processors are configured
188 if (!isset($eventdata->userto->emailstop)) {
189 debugging('userto->emailstop is not set. Retrieving it from the user table');
190 $eventdata->userto->emailstop = $DB->get_field('user', 'emailstop', array('id'=>$eventdata->userto->id));
193 // Populate the list of processors we will be using
194 if ($permitted == 'forced' && $userisconfigured) {
195 // An admin is forcing users to use this message processor. Use this processor unconditionally.
196 $processorlist[] = $processor->name;
197 } else if ($permitted == 'permitted' && $userisconfigured && !$eventdata->userto->emailstop) {
198 // User has not disabled notifications
199 // See if user set any notification preferences, otherwise use site default ones
200 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
201 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto->id)) {
202 if (in_array($processor->name, explode(',', $userpreference))) {
203 $processorlist[] = $processor->name;
205 } else if (isset($defaultpreferences->{$userpreferencename})) {
206 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
207 $processorlist[] = $processor->name;
213 if (empty($processorlist) && $savemessage->notification) {
214 //if they have deselected all processors and its a notification mark it read. The user doesnt want to be bothered
215 $savemessage->timeread = time();
216 $messageid = $DB->insert_record('message_read', $savemessage);
217 } else { // Process the message
218 // Store unread message just in case we can not send it
219 $messageid = $savemessage->id = $DB->insert_record('message', $savemessage);
220 $eventdata->savedmessageid = $savemessage->id;
222 // Try to deliver the message to each processor
223 if (!empty($processorlist)) {
224 foreach ($processorlist as $procname) {
225 if (!$processors[$procname]->object->send_message($eventdata)) {
226 debugging('Error calling message processor '.$procname);
227 $messageid = false;
231 //if messaging is disabled and they previously had forum notifications handled by the popup processor
232 //or any processor that puts a row in message_working then the notification will remain forever
233 //unread. To prevent this mark the message read if messaging is disabled
234 if (empty($CFG->messaging)) {
235 require_once($CFG->dirroot.'/message/lib.php');
236 $messageid = message_mark_message_read($savemessage, time());
237 } else if ( $DB->count_records('message_working', array('unreadmessageid' => $savemessage->id)) == 0){
238 //if there is no more processors that want to process this we can move message to message_read
239 require_once($CFG->dirroot.'/message/lib.php');
240 $messageid = message_mark_message_read($savemessage, time(), true);
245 return $messageid;
250 * Updates the message_providers table with the current set of message providers
252 * @param string $component For example 'moodle', 'mod_forum' or 'block_quiz_results'
253 * @return boolean True on success
255 function message_update_providers($component='moodle') {
256 global $DB;
258 // load message providers from files
259 $fileproviders = message_get_providers_from_file($component);
261 // load message providers from the database
262 $dbproviders = message_get_providers_from_db($component);
264 foreach ($fileproviders as $messagename => $fileprovider) {
266 if (!empty($dbproviders[$messagename])) { // Already exists in the database
267 // check if capability has changed
268 if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
269 // exact same message provider already present in db, ignore this entry
270 unset($dbproviders[$messagename]);
271 continue;
273 } else { // Update existing one
274 $provider = new stdClass();
275 $provider->id = $dbproviders[$messagename]->id;
276 $provider->capability = $fileprovider['capability'];
277 $DB->update_record('message_providers', $provider);
278 unset($dbproviders[$messagename]);
279 continue;
282 } else { // New message provider, add it
284 $provider = new stdClass();
285 $provider->name = $messagename;
286 $provider->component = $component;
287 $provider->capability = $fileprovider['capability'];
289 $transaction = $DB->start_delegated_transaction();
290 $DB->insert_record('message_providers', $provider);
291 message_set_default_message_preference($component, $messagename, $fileprovider);
292 $transaction->allow_commit();
296 foreach ($dbproviders as $dbprovider) { // Delete old ones
297 $DB->delete_records('message_providers', array('id' => $dbprovider->id));
298 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
299 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
300 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
303 return true;
307 * This function populates default message preferences for all existing providers
308 * when the new message processor is added.
310 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
311 * @throws invalid_parameter_exception if $processorname does not exist in the database
313 function message_update_processors($processorname) {
314 global $DB;
316 // validate if our processor exists
317 $processor = $DB->get_records('message_processors', array('name' => $processorname));
318 if (empty($processor)) {
319 throw new invalid_parameter_exception();
322 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
324 $transaction = $DB->start_delegated_transaction();
325 foreach ($providers as $provider) {
326 // load message providers from files
327 $fileproviders = message_get_providers_from_file($provider->component);
328 foreach ($fileproviders as $messagename => $fileprovider) {
329 message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
332 $transaction->allow_commit();
336 * Setting default messaging preferences for particular message provider
338 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
339 * @param string $messagename The name of message provider
340 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
341 * @param string $processorname The optional name of message processor
343 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
344 global $DB;
346 // Fetch message processors
347 $condition = null;
348 // If we need to process a particular processor, set the select condition
349 if (!empty($processorname)) {
350 $condition = array('name' => $processorname);
352 $processors = $DB->get_records('message_processors', $condition);
354 // load default messaging preferences
355 $defaultpreferences = get_message_output_default_preferences();
357 // Setting default preference
358 $componentproviderbase = $component.'_'.$messagename;
359 $loggedinpref = array();
360 $loggedoffpref = array();
361 // set 'permitted' preference first for each messaging processor
362 foreach ($processors as $processor) {
363 $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_permitted';
364 // if we do not have this setting yet, set it
365 if (!isset($defaultpreferences->{$preferencename})) {
366 // determine plugin default settings
367 $plugindefault = 0;
368 if (isset($fileprovider['defaults'][$processor->name])) {
369 $plugindefault = $fileprovider['defaults'][$processor->name];
371 // get string values of the settings
372 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name);
373 // store default preferences for current processor
374 set_config($preferencename, $permitted, 'message');
375 // save loggedin/loggedoff settings
376 if ($loggedin) {
377 $loggedinpref[] = $processor->name;
379 if ($loggedoff) {
380 $loggedoffpref[] = $processor->name;
384 // now set loggedin/loggedoff preferences
385 if (!empty($loggedinpref)) {
386 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
387 if (isset($defaultpreferences->{$preferencename})) {
388 // We have the default preferences for this message provider, which
389 // likely means that we have been adding a new processor. Add defaults
390 // to exisitng preferences.
391 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
393 set_config($preferencename, join(',', $loggedinpref), 'message');
395 if (!empty($loggedoffpref)) {
396 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
397 if (isset($defaultpreferences->{$preferencename})) {
398 // We have the default preferences for this message provider, which
399 // likely means that we have been adding a new processor. Add defaults
400 // to exisitng preferences.
401 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
403 set_config($preferencename, join(',', $loggedoffpref), 'message');
408 * Returns the active providers for the user specified, based on capability
410 * @param int $userid id of user
411 * @return array An array of message providers
413 function message_get_providers_for_user($userid) {
414 global $DB, $CFG;
416 $providers = get_message_providers();
418 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
419 if (!$CFG->messaging) {
420 foreach ($providers as $providerid => $provider) {
421 if ($provider->name == 'instantmessage') {
422 unset($providers[$providerid]);
423 break;
428 // If the component is an enrolment plugin, check it is enabled
429 foreach ($providers as $providerid => $provider) {
430 list($type, $name) = core_component::normalize_component($provider->component);
431 if ($type == 'enrol' && !enrol_is_enabled($name)) {
432 unset($providers[$providerid]);
436 // Now we need to check capabilities. We need to eliminate the providers
437 // where the user does not have the corresponding capability anywhere.
438 // Here we deal with the common simple case of the user having the
439 // capability in the system context. That handles $CFG->defaultuserroleid.
440 // For the remaining providers/capabilities, we need to do a more complex
441 // query involving all overrides everywhere.
442 $unsureproviders = array();
443 $unsurecapabilities = array();
444 $systemcontext = context_system::instance();
445 foreach ($providers as $providerid => $provider) {
446 if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
447 // The provider is relevant to this user.
448 continue;
451 $unsureproviders[$providerid] = $provider;
452 $unsurecapabilities[$provider->capability] = 1;
453 unset($providers[$providerid]);
456 if (empty($unsureproviders)) {
457 // More complex checks are not required.
458 return $providers;
461 // Now check the unsure capabilities.
462 list($capcondition, $params) = $DB->get_in_or_equal(
463 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
464 $params['userid'] = $userid;
466 $sql = "SELECT DISTINCT rc.capability, 1
468 FROM {role_assignments} ra
469 JOIN {context} actx ON actx.id = ra.contextid
470 JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
471 JOIN {context} cctx ON cctx.id = rc.contextid
473 WHERE ra.userid = :userid
474 AND rc.capability $capcondition
475 AND rc.permission > 0
476 AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
477 " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
479 if (!empty($CFG->defaultfrontpageroleid)) {
480 $frontpagecontext = context_course::instance(SITEID);
482 list($capcondition2, $params2) = $DB->get_in_or_equal(
483 array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
484 $params = array_merge($params, $params2);
485 $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
486 $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
488 $sql .= "
489 UNION
491 SELECT DISTINCT rc.capability, 1
493 FROM {role_capabilities} rc
494 JOIN {context} cctx ON cctx.id = rc.contextid
496 WHERE rc.roleid = :frontpageroleid
497 AND rc.capability $capcondition2
498 AND rc.permission > 0
499 AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
502 $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
504 // Add back any providers based on the detailed capability check.
505 foreach ($unsureproviders as $providerid => $provider) {
506 if (array_key_exists($provider->capability, $relevantcapabilities)) {
507 $providers[$providerid] = $provider;
511 return $providers;
515 * Gets the message providers that are in the database for this component.
517 * This is an internal function used within messagelib.php
519 * @see message_update_providers()
520 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
521 * @return array An array of message providers
523 function message_get_providers_from_db($component) {
524 global $DB;
526 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
530 * Loads the messages definitions for a component from file
532 * If no messages are defined for the component, return an empty array.
533 * This is an internal function used within messagelib.php
535 * @see message_update_providers()
536 * @see message_update_processors()
537 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
538 * @return array An array of message providers or empty array if not exists
540 function message_get_providers_from_file($component) {
541 $defpath = core_component::get_component_directory($component).'/db/messages.php';
543 $messageproviders = array();
545 if (file_exists($defpath)) {
546 require($defpath);
549 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
550 if (empty($messageprovider['capability'])) {
551 $messageproviders[$name]['capability'] = NULL;
553 if (empty($messageprovider['defaults'])) {
554 $messageproviders[$name]['defaults'] = array();
558 return $messageproviders;
562 * Remove all message providers for particular component and corresponding settings
564 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_quiz_results'
565 * @return void
567 function message_provider_uninstall($component) {
568 global $DB;
570 $transaction = $DB->start_delegated_transaction();
571 $DB->delete_records('message_providers', array('component' => $component));
572 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
573 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
574 $transaction->allow_commit();
575 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
576 cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
580 * Uninstall a message processor
582 * @param string $name A message processor name like 'email', 'jabber'
584 function message_processor_uninstall($name) {
585 global $DB;
587 $transaction = $DB->start_delegated_transaction();
588 $DB->delete_records('message_processors', array('name' => $name));
589 $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
590 // delete permission preferences only, we do not care about loggedin/loggedoff
591 // defaults, they will be removed on the next attempt to update the preferences
592 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
593 $transaction->allow_commit();
594 // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
595 cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));