3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * messagelib.php - Contains generic messaging functions for the message system
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');
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) {
55 //new message ID to return
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;
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';
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
;
95 $savemessage->notification
= 0;
98 if (!empty($eventdata->contexturl
)) {
99 $savemessage->contexturl
= $eventdata->contexturl
;
101 $savemessage->contexturl
= null;
104 if (!empty($eventdata->contexturlname
)) {
105 $savemessage->contexturlname
= $eventdata->contexturlname
;
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();
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};
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 $userisconfigured = $processor->object->is_user_configured($eventdata->userto
);
136 // DEBUG: notify if we are forcing unconfigured output
137 if ($permitted == 'forced' && !$userisconfigured) {
138 debugging('Attempt to force message delivery to user who has "'.$processor->name
.'" output unconfigured', DEBUG_NORMAL
);
141 // Populate the list of processors we will be using
142 if ($permitted == 'forced' && $userisconfigured) {
143 // We force messages for this processor, so use this processor unconditionally if user has configured it
144 $processorlist[] = $processor->name
;
145 } else if ($permitted == 'permitted' && $userisconfigured) {
146 // User settings are permitted, see if user set any, otherwise use site default ones
147 $userpreferencename = 'message_provider_'.$preferencebase.'_'.$userstate;
148 if ($userpreference = get_user_preferences($userpreferencename, null, $eventdata->userto
->id
)) {
149 if (in_array($processor->name
, explode(',', $userpreference))) {
150 $processorlist[] = $processor->name
;
152 } else if (isset($defaultpreferences->{$userpreferencename})) {
153 if (in_array($processor->name
, explode(',', $defaultpreferences->{$userpreferencename}))) {
154 $processorlist[] = $processor->name
;
160 if (empty($processorlist) && $savemessage->notification
) {
161 //if they have deselected all processors and its a notification mark it read. The user doesnt want to be bothered
162 $savemessage->timeread
= time();
163 $messageid = $DB->insert_record('message_read', $savemessage);
164 } else { // Process the message
165 // Store unread message just in case we can not send it
166 $messageid = $savemessage->id
= $DB->insert_record('message', $savemessage);
167 $eventdata->savedmessageid
= $savemessage->id
;
169 // Try to deliver the message to each processor
170 if (!empty($processorlist)) {
171 foreach ($processorlist as $procname) {
172 if (!$processors[$procname]->object->send_message($eventdata)) {
173 debugging('Error calling message processor '.$procname);
178 //if messaging is disabled and they previously had forum notifications handled by the popup processor
179 //or any processor that puts a row in message_working then the notification will remain forever
180 //unread. To prevent this mark the message read if messaging is disabled
181 if (empty($CFG->messaging
)) {
182 require_once($CFG->dirroot
.'/message/lib.php');
183 $messageid = message_mark_message_read($savemessage, time());
184 } else if ( $DB->count_records('message_working', array('unreadmessageid' => $savemessage->id
)) == 0){
185 //if there is no more processors that want to process this we can move message to message_read
186 require_once($CFG->dirroot
.'/message/lib.php');
187 $messageid = message_mark_message_read($savemessage, time(), true);
197 * This code updates the message_providers table with the current set of providers
199 * @param $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
202 function message_update_providers($component='moodle') {
205 // load message providers from files
206 $fileproviders = message_get_providers_from_file($component);
208 // load message providers from the database
209 $dbproviders = message_get_providers_from_db($component);
211 foreach ($fileproviders as $messagename => $fileprovider) {
213 if (!empty($dbproviders[$messagename])) { // Already exists in the database
214 // check if capability has changed
215 if ($dbproviders[$messagename]->capability
== $fileprovider['capability']) { // Same, so ignore
216 // exact same message provider already present in db, ignore this entry
217 unset($dbproviders[$messagename]);
220 } else { // Update existing one
221 $provider = new stdClass();
222 $provider->id
= $dbproviders[$messagename]->id
;
223 $provider->capability
= $fileprovider['capability'];
224 $DB->update_record('message_providers', $provider);
225 unset($dbproviders[$messagename]);
229 } else { // New message provider, add it
231 $provider = new stdClass();
232 $provider->name
= $messagename;
233 $provider->component
= $component;
234 $provider->capability
= $fileprovider['capability'];
236 $transaction = $DB->start_delegated_transaction();
237 $DB->insert_record('message_providers', $provider);
238 message_set_default_message_preference($component, $messagename, $fileprovider);
239 $transaction->allow_commit();
243 foreach ($dbproviders as $dbprovider) { // Delete old ones
244 $DB->delete_records('message_providers', array('id' => $dbprovider->id
));
245 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
246 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
253 * This function populates default message preferences for all existing providers
254 * when the new message processor is added.
256 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
258 * @throws invalid_parameter_exception if $processorname does not exist
260 function message_update_processors($processorname) {
263 // validate if our processor exists
264 $processor = $DB->get_records('message_processors', array('name' => $processorname));
265 if (empty($processor)) {
266 throw new invalid_parameter_exception();
269 $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
271 $transaction = $DB->start_delegated_transaction();
272 foreach ($providers as $provider) {
273 // load message providers from files
274 $fileproviders = message_get_providers_from_file($provider->component
);
275 foreach ($fileproviders as $messagename => $fileprovider) {
276 message_set_default_message_preference($provider->component
, $messagename, $fileprovider, $processorname);
279 $transaction->allow_commit();
283 * Setting default messaging preference for particular message provider
285 * @param string $component The name of component (e.g. moodle, mod_forum, etc.)
286 * @param string $messagename The name of message provider
287 * @param array $fileprovider The value of $messagename key in the array defined in plugin messages.php
288 * @param string $processorname The optinal name of message processor
291 function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
294 // Fetch message processors
296 // If we need to process a particular processor, set the select condition
297 if (!empty($processorname)) {
298 $condition = array('name' => $processorname);
300 $processors = $DB->get_records('message_processors', $condition);
302 // load default messaging preferences
303 $defaultpreferences = get_message_output_default_preferences();
305 // Setting default preference
306 $componentproviderbase = $component.'_'.$messagename;
307 $loggedinpref = array();
308 $loggedoffpref = array();
309 // set 'permitted' preference first for each messaging processor
310 foreach ($processors as $processor) {
311 $preferencename = $processor->name
.'_provider_'.$componentproviderbase.'_permitted';
312 // if we do not have this setting yet, set it
313 if (!isset($defaultpreferences->{$preferencename})) {
314 // determine plugin default settings
316 if (isset($fileprovider['defaults'][$processor->name
])) {
317 $plugindefault = $fileprovider['defaults'][$processor->name
];
319 // get string values of the settings
320 list($permitted, $loggedin, $loggedoff) = translate_message_default_setting($plugindefault, $processor->name
);
321 // store default preferences for current processor
322 set_config($preferencename, $permitted, 'message');
323 // save loggedin/loggedoff settings
325 $loggedinpref[] = $processor->name
;
328 $loggedoffpref[] = $processor->name
;
332 // now set loggedin/loggedoff preferences
333 if (!empty($loggedinpref)) {
334 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedin';
335 if (isset($defaultpreferences->{$preferencename})) {
336 // We have the default preferences for this message provider, which
337 // likely means that we have been adding a new processor. Add defaults
338 // to exisitng preferences.
339 $loggedinpref = array_merge($loggedinpref, explode(',', $defaultpreferences->{$preferencename}));
341 set_config($preferencename, join(',', $loggedinpref), 'message');
343 if (!empty($loggedoffpref)) {
344 $preferencename = 'message_provider_'.$componentproviderbase.'_loggedoff';
345 if (isset($defaultpreferences->{$preferencename})) {
346 // We have the default preferences for this message provider, which
347 // likely means that we have been adding a new processor. Add defaults
348 // to exisitng preferences.
349 $loggedoffpref = array_merge($loggedoffpref, explode(',', $defaultpreferences->{$preferencename}));
351 set_config($preferencename, join(',', $loggedoffpref), 'message');
356 * Returns the active providers for the current user, based on capability
358 * This function has been deprecated please use {@see message_get_providers_for_user()} instead.
360 * @deprecated since 2.1
361 * @todo Remove in 2.2
362 * @return array of message providers
364 function message_get_my_providers() {
366 return message_get_providers_for_user($USER->id
);
370 * Returns the active providers for the user specified, based on capability
372 * @param int $userid id of user
373 * @return array of message providers
375 function message_get_providers_for_user($userid) {
378 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
380 $providers = $DB->get_records('message_providers', null, 'name');
382 // Remove all the providers we aren't allowed to see now
383 foreach ($providers as $providerid => $provider) {
384 if (!empty($provider->capability
)) {
385 if (!has_capability($provider->capability
, $systemcontext, $userid)) {
386 unset($providers[$providerid]); // Not allowed to see this
389 // Ensure user is not allowed to configure instantmessage if it is globally disabled.
390 if (!$CFG->messaging
&& $provider->name
== 'instantmessage') {
391 unset($providers[$providerid]);
399 * Gets the message providers that are in the database for this component.
401 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
402 * @return array of message providers
404 * INTERNAL - to be used from messagelib only
406 function message_get_providers_from_db($component) {
409 return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability'); // Name is unique per component
413 * Loads the messages definitions for the component (from file). If no
414 * messages are defined for the component, we simply return an empty array.
416 * @param $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
417 * @return array of message providerss or empty array if not exists
419 * INTERNAL - to be used from messagelib only
421 function message_get_providers_from_file($component) {
422 $defpath = get_component_directory($component).'/db/messages.php';
424 $messageproviders = array();
426 if (file_exists($defpath)) {
430 foreach ($messageproviders as $name => $messageprovider) { // Fix up missing values if required
431 if (empty($messageprovider['capability'])) {
432 $messageproviders[$name]['capability'] = NULL;
434 if (empty($messageprovider['defaults'])) {
435 $messageproviders[$name]['defaults'] = array();
439 return $messageproviders;
443 * Remove all message providers for particular plugin and corresponding settings
445 * @param string $component - examples: 'moodle', 'mod_forum', 'block_quiz_results'
448 function message_provider_uninstall($component) {
451 $transaction = $DB->start_delegated_transaction();
452 $DB->delete_records('message_providers', array('component' => $component));
453 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
454 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_%"));
455 $transaction->allow_commit();
459 * Remove message processor
461 * @param string $name - examples: 'email', 'jabber'
464 function message_processor_uninstall($name) {
467 $transaction = $DB->start_delegated_transaction();
468 $DB->delete_records('message_processors', array('name' => $name));
469 // delete permission preferences only, we do not care about loggedin/loggedoff
470 // defaults, they will be removed on the next attempt to update the preferences
471 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
472 $transaction->allow_commit();