Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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.
13
//
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/>.
16
 
17
/**
18
 * Functions for interacting with the message system
19
 *
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
23
 */
24
 
1441 ariadna 25
use core\url;
26
 
1 efrain 27
defined('MOODLE_INTERNAL') || die();
28
 
29
require_once(__DIR__ . '/../message/lib.php');
30
 
31
/**
32
 * Called when a message provider wants to send a message.
33
 * This functions checks the message recipient's message processor configuration then
34
 * sends the message to the configured processors
35
 *
36
 * Required parameters of the $eventdata object:
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 string the full message in a given format
43
 *  fullmessageformat int the format if the full message (FORMAT_MOODLE, FORMAT_HTML, ..)
44
 *  fullmessagehtml string the full version (the message processor will choose with one to use)
45
 *  smallmessage string the small version of the message
46
 *
47
 * Optional parameters of the $eventdata object:
48
 *  notification bool should the message be considered as a notification rather than a personal message
1441 ariadna 49
 *  contexturl string|url if this is a notification then you can specify a url to view the event.
50
 *                    For example the forum post the user is being notified of.
1 efrain 51
 *  contexturlname string the display text for contexturl
52
 *
53
 * Note: processor failure will not reported as false return value in all scenarios,
54
 *       for example when it is called while a database transaction is open,
55
 *       earlier versions did not do it consistently either.
56
 *
57
 * @category message
58
 * @param \core\message\message $eventdata information about the message (component, userfrom, userto, ...)
59
 * @return mixed the integer ID of the new message or false if there was a problem (with submitted data or sending the message to the message processor)
60
 */
61
function message_send(\core\message\message $eventdata) {
62
    global $CFG, $DB, $SITE;
63
 
64
    //new message ID to return
65
    $messageid = false;
66
 
67
    // Fetch default (site) preferences
68
    $defaultpreferences = get_message_output_default_preferences();
69
    $preferencebase = $eventdata->component.'_'.$eventdata->name;
70
 
71
    // If the message provider is disabled via preferences, then don't send the message.
72
    if (!empty($defaultpreferences->{$preferencebase.'_disable'})) {
73
        return $messageid;
74
    }
75
 
76
    // By default a message is a notification. Only personal/private messages aren't notifications.
77
    if (!isset($eventdata->notification)) {
78
        $eventdata->notification = 1;
79
    }
80
 
81
    if (!is_object($eventdata->userfrom)) {
82
        $eventdata->userfrom = core_user::get_user($eventdata->userfrom);
83
    }
84
    if (!$eventdata->userfrom) {
85
        debugging('Attempt to send msg from unknown user', DEBUG_NORMAL);
86
        return false;
87
    }
88
 
1441 ariadna 89
    // Cast context URL and name.
90
    if (!empty($eventdata->contexturl)) {
91
        $eventdata->contexturl = (string) $eventdata->contexturl;
92
    }
93
    if (!empty($eventdata->contexturlname)) {
94
        $eventdata->contexturlname = (string) $eventdata->contexturlname;
95
    }
96
 
1 efrain 97
    // Legacy messages (FROM a single user TO a single user) must be converted into conversation messages.
98
    // Then, these will be passed through the conversation messages code below.
99
    if (!$eventdata->notification && !$eventdata->convid) {
100
        // If messaging is disabled at the site level, then the 'instantmessage' provider is always disabled.
101
        // Given this is the only 'message' type message provider, we can exit now if this is the case.
102
        // Don't waste processing time trying to work out the other conversation member, if it's an individual
103
        // conversation, just throw a generic debugging notice and return.
104
        if (empty($CFG->messaging) || $eventdata->component !== 'moodle' || $eventdata->name !== 'instantmessage') {
105
            debugging('Attempt to send msg from a provider '.$eventdata->component.'/'.$eventdata->name.
106
                ' that is inactive or not allowed for the user id='.$eventdata->userto->id, DEBUG_NORMAL);
107
            return false;
108
        }
109
 
110
        if (!is_object($eventdata->userto)) {
111
            $eventdata->userto = core_user::get_user($eventdata->userto);
112
        }
113
        if (!$eventdata->userto) {
114
            debugging('Attempt to send msg to unknown user', DEBUG_NORMAL);
115
            return false;
116
        }
117
 
118
        // Verify all necessary data fields are present.
119
        if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended)
120
            or !isset($eventdata->userto->deleted) or !isset($eventdata->userto->emailstop)) {
121
 
122
            debugging('Necessary properties missing in userto object, fetching full record', DEBUG_DEVELOPER);
123
            $eventdata->userto = core_user::get_user($eventdata->userto->id);
124
        }
125
 
126
        $usertoisrealuser = (core_user::is_real_user($eventdata->userto->id) != false);
127
        // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
128
        if (!$usertoisrealuser && !empty($eventdata->userto->emailstop)) {
129
            debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
130
            return false;
131
        }
132
 
133
        if ($eventdata->userfrom->id == $eventdata->userto->id) {
134
            // It's a self conversation.
135
            $conversation = \core_message\api::get_self_conversation($eventdata->userfrom->id);
136
            if (empty($conversation)) {
137
                $conversation = \core_message\api::create_conversation(
138
                    \core_message\api::MESSAGE_CONVERSATION_TYPE_SELF,
139
                    [$eventdata->userfrom->id]
140
                );
141
            }
142
        } else {
143
            if (!$conversationid = \core_message\api::get_conversation_between_users([$eventdata->userfrom->id,
144
                                                                                      $eventdata->userto->id])) {
145
                // It's a private conversation between users.
146
                $conversation = \core_message\api::create_conversation(
147
                    \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
148
                    [
149
                        $eventdata->userfrom->id,
150
                        $eventdata->userto->id
151
                    ]
152
                );
153
            }
154
        }
155
        // We either have found a conversation, or created one.
156
        $conversationid = !empty($conversationid) ? $conversationid : $conversation->id;
157
        $eventdata->convid = $conversationid;
158
    }
159
 
160
    // This is a message directed to a conversation, not a specific user as was the way in legacy messaging.
161
    // The above code has adapted the legacy messages into conversation messages.
162
    // We must call send_message_to_conversation(), which handles per-member processor iteration and triggers
163
    // a per-conversation event.
164
    // All eventdata for messages should now have a convid, as we fixed this above.
165
    if (!$eventdata->notification) {
166
 
167
        // Only one message will be saved to the DB.
168
        $conversationid = $eventdata->convid;
169
        $table = 'messages';
170
        $tabledata = new stdClass();
171
        $tabledata->courseid = $eventdata->courseid;
172
        $tabledata->useridfrom = $eventdata->userfrom->id;
173
        $tabledata->conversationid = $conversationid;
174
        $tabledata->subject = $eventdata->subject;
175
        $tabledata->fullmessage = $eventdata->fullmessage;
176
        $tabledata->fullmessageformat = $eventdata->fullmessageformat;
177
        $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
178
        $tabledata->smallmessage = $eventdata->smallmessage;
179
        $tabledata->timecreated = time();
180
        $tabledata->customdata = $eventdata->customdata;
181
 
182
        // The Trusted Content system.
183
        // Texts created or uploaded by such users will be marked as trusted and will not be cleaned before display.
184
        if (trusttext_active()) {
185
            // Individual conversations are always in system context.
186
            $messagecontext = \context_system::instance();
187
            // We need to know the type of conversation and the contextid if it is a group conversation.
188
            if ($conv = $DB->get_record('message_conversations', ['id' => $conversationid], 'id, type, contextid')) {
189
                if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP && $conv->contextid) {
190
                    $messagecontext = \context::instance_by_id($conv->contextid);
191
                }
192
            }
193
            $tabledata->fullmessagetrust = trusttext_trusted($messagecontext);
194
        } else {
195
            $tabledata->fullmessagetrust = false;
196
        }
197
 
198
        if ($messageid = message_handle_phpunit_redirection($eventdata, $table, $tabledata)) {
199
            return $messageid;
200
        }
201
 
202
        // Cache messages.
203
        if (!empty($eventdata->convid)) {
204
            // Cache the timecreated value of the last message in this conversation.
205
            $cache = cache::make('core', 'message_time_last_message_between_users');
206
            $key = \core_message\helper::get_last_message_time_created_cache_key($eventdata->convid);
207
            $cache->set($key, $tabledata->timecreated);
208
        }
209
 
210
        // Store unread message just in case we get a fatal error any time later.
211
        $tabledata->id = $DB->insert_record($table, $tabledata);
212
        $eventdata->savedmessageid = $tabledata->id;
213
 
214
        return \core\message\manager::send_message_to_conversation($eventdata, $tabledata);
215
    }
216
 
217
    // Else the message is a notification.
218
    if (!is_object($eventdata->userto)) {
219
        $eventdata->userto = core_user::get_user($eventdata->userto);
220
    }
221
    if (!$eventdata->userto) {
222
        debugging('Attempt to send msg to unknown user', DEBUG_NORMAL);
223
        return false;
224
    }
225
 
226
    // If the provider's component is disabled or the user can't receive messages from it, don't send the message.
227
    $isproviderallowed = false;
228
    foreach (message_get_providers_for_user($eventdata->userto->id) as $provider) {
229
        if ($provider->component === $eventdata->component && $provider->name === $eventdata->name) {
230
            $isproviderallowed = true;
231
            break;
232
        }
233
    }
234
    if (!$isproviderallowed) {
235
        debugging('Attempt to send msg from a provider '.$eventdata->component.'/'.$eventdata->name.
236
            ' that is inactive or not allowed for the user id='.$eventdata->userto->id, DEBUG_NORMAL);
237
        return false;
238
    }
239
 
240
    // Verify all necessary data fields are present.
241
    if (!isset($eventdata->userto->auth) or !isset($eventdata->userto->suspended)
242
            or !isset($eventdata->userto->deleted) or !isset($eventdata->userto->emailstop)) {
243
 
244
        debugging('Necessary properties missing in userto object, fetching full record', DEBUG_DEVELOPER);
245
        $eventdata->userto = core_user::get_user($eventdata->userto->id);
246
    }
247
 
248
    $usertoisrealuser = (core_user::is_real_user($eventdata->userto->id) != false);
249
    // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
250
    if (!$usertoisrealuser && !empty($eventdata->userto->emailstop)) {
251
        debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
252
        return false;
253
    }
254
 
255
    // Check if we are creating a notification or message.
256
    $table = 'notifications';
257
 
258
    $tabledata = new stdClass();
259
    $tabledata->useridfrom = $eventdata->userfrom->id;
260
    $tabledata->useridto = $eventdata->userto->id;
261
    $tabledata->subject = $eventdata->subject;
262
    $tabledata->fullmessage = $eventdata->fullmessage;
263
    $tabledata->fullmessageformat = $eventdata->fullmessageformat;
264
    $tabledata->fullmessagehtml = $eventdata->fullmessagehtml;
265
    $tabledata->smallmessage = $eventdata->smallmessage;
266
    $tabledata->eventtype = $eventdata->name;
267
    $tabledata->component = $eventdata->component;
268
    $tabledata->timecreated = time();
269
    $tabledata->customdata = $eventdata->customdata;
1441 ariadna 270
    $tabledata->contexturl = $eventdata->contexturl ?? null;
271
    $tabledata->contexturlname = $eventdata->contexturlname ?? null;
1 efrain 272
 
273
    if ($messageid = message_handle_phpunit_redirection($eventdata, $table, $tabledata)) {
274
        return $messageid;
275
    }
276
 
277
    // Fetch enabled processors.
278
    $processors = get_message_processors(true);
279
 
280
    // Preset variables
281
    $processorlist = array();
282
    // Fill in the array of processors to be used based on default and user preferences
283
    foreach ($processors as $processor) {
284
        // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
285
        if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
286
            continue;
287
        }
288
 
289
        // First find out permissions
290
        $defaultlockedpreference = $processor->name . '_provider_' . $preferencebase . '_locked';
291
        $locked = false;
292
        if (isset($defaultpreferences->{$defaultlockedpreference})) {
293
            $locked = $defaultpreferences->{$defaultlockedpreference};
294
        } else {
295
            // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
296
            // exist in the message_provider table (thus there is no default settings for them).
297
            $preferrormsg = "Could not load preference $defaultlockedpreference. Make sure the component and name you supplied
298
                    to message_send() are valid.";
299
            throw new coding_exception($preferrormsg);
300
        }
301
 
302
        $preferencename = 'message_provider_'.$preferencebase.'_enabled';
303
        $forced = false;
304
        if ($locked && isset($defaultpreferences->{$preferencename})) {
305
            $userpreference = $defaultpreferences->{$preferencename};
306
            $forced = in_array($processor->name, explode(',', $userpreference));
307
        }
308
 
309
        // Find out if user has configured this output
310
        // Some processors cannot function without settings from the user
311
        $userisconfigured = $processor->object->is_user_configured($eventdata->userto);
312
 
313
        // DEBUG: notify if we are forcing unconfigured output
314
        if ($forced && !$userisconfigured) {
315
            debugging('Attempt to force message delivery to user who has "'.$processor->name.'" output unconfigured', DEBUG_NORMAL);
316
        }
317
 
318
        // Populate the list of processors we will be using
319
        if ($forced && $userisconfigured) {
320
            // An admin is forcing users to use this message processor. Use this processor unconditionally.
321
            $processorlist[] = $processor->name;
322
        } else if (!$forced && !$locked && $userisconfigured && !$eventdata->userto->emailstop) {
323
            // User has not disabled notifications
324
            // See if user set any notification preferences, otherwise use site default ones
325
            if ($userpreference = get_user_preferences($preferencename, null, $eventdata->userto)) {
326
                if (in_array($processor->name, explode(',', $userpreference))) {
327
                    $processorlist[] = $processor->name;
328
                }
329
            } else if (isset($defaultpreferences->{$preferencename})) {
330
                if (in_array($processor->name, explode(',', $defaultpreferences->{$preferencename}))) {
331
                    $processorlist[] = $processor->name;
332
                }
333
            }
334
        }
335
    }
336
 
337
    // Store unread message just in case we get a fatal error any time later.
338
    $tabledata->id = $DB->insert_record($table, $tabledata);
339
    $eventdata->savedmessageid = $tabledata->id;
340
 
341
    // Let the manager do the sending or buffering when db transaction in progress.
342
    try {
343
        return \core\message\manager::send_message($eventdata, $tabledata, $processorlist);
344
    } catch (\moodle_exception $exception) {
345
        return false;
346
    }
347
}
348
 
349
/**
350
 * Helper method containing the PHPUnit specific code, used to redirect and capture messages/notifications.
351
 *
352
 * @param \core\message\message $eventdata the message object
353
 * @param string $table the table to store the tabledata in, either messages or notifications.
354
 * @param stdClass $tabledata the data to be stored when creating the message/notification.
355
 * @return int the id of the stored message.
356
 */
357
function message_handle_phpunit_redirection(\core\message\message $eventdata, string $table, \stdClass $tabledata) {
358
    global $DB;
359
    if (PHPUNIT_TEST and class_exists('phpunit_util')) {
360
        // Add some more tests to make sure the normal code can actually work.
361
        $componentdir = core_component::get_component_directory($eventdata->component);
362
        if (!$componentdir or !is_dir($componentdir)) {
363
            throw new coding_exception('Invalid component specified in message-send(): '.$eventdata->component);
364
        }
365
        if (!file_exists("$componentdir/db/messages.php")) {
366
            throw new coding_exception("$eventdata->component does not contain db/messages.php necessary for message_send()");
367
        }
368
        $messageproviders = null;
369
        include("$componentdir/db/messages.php");
370
        if (!isset($messageproviders[$eventdata->name])) {
371
            throw new coding_exception("Missing messaging defaults for event '$eventdata->name' in '$eventdata->component' " .
372
                "messages.php file");
373
        }
374
        unset($componentdir);
375
        unset($messageproviders);
376
        // Now ask phpunit if it wants to catch this message.
377
        if (phpunit_util::is_redirecting_messages()) {
378
            $messageid = $DB->insert_record($table, $tabledata);
379
            $message = $DB->get_record($table, array('id' => $messageid));
380
 
381
            if ($eventdata->notification) {
382
                // Add the useridto attribute for BC.
383
                $message->useridto = $eventdata->userto->id;
384
 
385
                // Mark the notification as read.
386
                \core_message\api::mark_notification_as_read($message);
387
            } else {
388
                // Add the useridto attribute for BC.
389
                if (isset($eventdata->userto)) {
390
                    $message->useridto = $eventdata->userto->id;
391
                }
392
                // Mark the message as read for each of the other users.
393
                $sql = "SELECT u.*
394
                  FROM {message_conversation_members} mcm
395
                  JOIN {user} u
396
                    ON (mcm.conversationid = :convid AND u.id = mcm.userid AND u.id != :userid)";
397
                $otherusers = $DB->get_records_sql($sql, ['convid' => $eventdata->convid, 'userid' => $eventdata->userfrom->id]);
398
                foreach ($otherusers as $othermember) {
399
                    \core_message\api::mark_message_as_read($othermember->id, $message);
400
                }
401
            }
402
 
403
            // Unit tests need this detail.
404
            $message->notification = $eventdata->notification;
405
            phpunit_util::message_sent($message);
406
            return $messageid;
407
        }
408
    }
409
}
410
 
411
/**
412
 * Updates the message_providers table with the current set of message providers
413
 *
414
 * @param string $component For example 'moodle', 'mod_forum' or 'block_activity_results'
415
 * @return boolean True on success
416
 */
417
function message_update_providers($component='moodle') {
418
    global $DB;
419
 
420
    // load message providers from files
421
    $fileproviders = message_get_providers_from_file($component);
422
 
423
    // load message providers from the database
424
    $dbproviders = message_get_providers_from_db($component);
425
 
426
    foreach ($fileproviders as $messagename => $fileprovider) {
427
 
428
        if (!empty($dbproviders[$messagename])) {   // Already exists in the database
429
            // check if capability has changed
430
            if ($dbproviders[$messagename]->capability == $fileprovider['capability']) {  // Same, so ignore
431
                // exact same message provider already present in db, ignore this entry
432
                unset($dbproviders[$messagename]);
433
                continue;
434
 
435
            } else {                                // Update existing one
436
                $provider = new stdClass();
437
                $provider->id         = $dbproviders[$messagename]->id;
438
                $provider->capability = $fileprovider['capability'];
439
                $DB->update_record('message_providers', $provider);
440
                unset($dbproviders[$messagename]);
441
                continue;
442
            }
443
 
444
        } else {             // New message provider, add it
445
 
446
            $provider = new stdClass();
447
            $provider->name       = $messagename;
448
            $provider->component  = $component;
449
            $provider->capability = $fileprovider['capability'];
450
 
451
            $transaction = $DB->start_delegated_transaction();
452
            $DB->insert_record('message_providers', $provider);
453
            message_set_default_message_preference($component, $messagename, $fileprovider);
454
            $transaction->allow_commit();
455
        }
456
    }
457
 
458
    foreach ($dbproviders as $dbprovider) {  // Delete old ones
459
        $DB->delete_records('message_providers', array('id' => $dbprovider->id));
460
        $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_{$dbprovider->name}_%"));
461
        $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_{$component}_{$dbprovider->name}_%"));
462
        cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
463
    }
464
 
465
    return true;
466
}
467
 
468
/**
469
 * This function populates default message preferences for all existing providers
470
 * when the new message processor is added.
471
 *
472
 * @param string $processorname The name of message processor plugin (e.g. 'email', 'jabber')
473
 * @throws invalid_parameter_exception if $processorname does not exist in the database
474
 */
475
function message_update_processors($processorname) {
476
    global $DB;
477
 
478
    // validate if our processor exists
479
    $processor = $DB->get_records('message_processors', array('name' => $processorname));
480
    if (empty($processor)) {
481
        throw new invalid_parameter_exception();
482
    }
483
 
484
    $providers = $DB->get_records_sql('SELECT DISTINCT component FROM {message_providers}');
485
 
486
    $transaction = $DB->start_delegated_transaction();
487
    foreach ($providers as $provider) {
488
        // load message providers from files
489
        $fileproviders = message_get_providers_from_file($provider->component);
490
        foreach ($fileproviders as $messagename => $fileprovider) {
491
            message_set_default_message_preference($provider->component, $messagename, $fileprovider, $processorname);
492
        }
493
    }
494
    $transaction->allow_commit();
495
}
496
 
497
/**
498
 * Setting default messaging preferences for particular message provider
499
 *
500
 * @param  string $component   The name of component (e.g. moodle, mod_forum, etc.)
501
 * @param  string $messagename The name of message provider
502
 * @param  array  $fileprovider The value of $messagename key in the array defined in plugin messages.php
503
 * @param  string $processorname The optional name of message processor
504
 */
505
function message_set_default_message_preference($component, $messagename, $fileprovider, $processorname='') {
506
    global $DB;
507
 
508
    // Fetch message processors
509
    $condition = null;
510
    // If we need to process a particular processor, set the select condition
511
    if (!empty($processorname)) {
512
       $condition = array('name' => $processorname);
513
    }
514
    $processors = $DB->get_records('message_processors', $condition);
515
 
516
    // load default messaging preferences
517
    $defaultpreferences = get_message_output_default_preferences();
518
 
519
    // Setting default preference
520
    $componentproviderbase = $component.'_'.$messagename;
521
    $enabledpref = [];
522
    // Set 'locked' preference first for each messaging processor.
523
    foreach ($processors as $processor) {
524
        $preferencename = $processor->name.'_provider_'.$componentproviderbase.'_locked';
525
        // If we do not have this setting yet, set it.
526
        if (!isset($defaultpreferences->{$preferencename})) {
527
            // Determine plugin default settings.
528
            $plugindefault = 0;
529
            if (isset($fileprovider['defaults'][$processor->name])) {
530
                $plugindefault = $fileprovider['defaults'][$processor->name];
531
            }
532
            // Get string values of the settings.
533
            list($locked, $enabled) = translate_message_default_setting($plugindefault, $processor->name);
534
            // Store default preferences for current processor.
535
            set_config($preferencename, $locked, 'message');
536
            // Save enabled settings.
537
            if ($enabled) {
538
                $enabledpref[] = $processor->name;
539
            }
540
        }
541
    }
542
    // Now set enabled preferences.
543
    if (!empty($enabledpref)) {
544
        $preferencename = 'message_provider_'.$componentproviderbase.'_enabled';
545
        if (isset($defaultpreferences->{$preferencename})) {
546
            // We have the default preferences for this message provider, which
547
            // likely means that we have been adding a new processor. Add defaults
548
            // to exisitng preferences.
549
            $enabledpref = array_merge($enabledpref, explode(',', $defaultpreferences->{$preferencename}));
550
        }
551
        set_config($preferencename, join(',', $enabledpref), 'message');
552
    }
553
}
554
 
555
/**
556
 * Returns the active providers for the user specified, based on capability
557
 *
558
 * @param int $userid id of user
559
 * @return array An array of message providers
560
 */
561
function message_get_providers_for_user($userid) {
562
    global $DB, $CFG;
563
 
564
    $providers = get_message_providers();
565
 
566
    // Ensure user is not allowed to configure instantmessage if it is globally disabled.
567
    if (!$CFG->messaging) {
568
        foreach ($providers as $providerid => $provider) {
569
            if ($provider->name == 'instantmessage') {
570
                unset($providers[$providerid]);
571
                break;
572
            }
573
        }
574
    }
575
 
576
    // If the component is an enrolment plugin, check it is enabled
577
    foreach ($providers as $providerid => $provider) {
578
        list($type, $name) = core_component::normalize_component($provider->component);
579
        if ($type == 'enrol' && !enrol_is_enabled($name)) {
580
            unset($providers[$providerid]);
581
        }
582
    }
583
 
584
    // Now we need to check capabilities. We need to eliminate the providers
585
    // where the user does not have the corresponding capability anywhere.
586
    // Here we deal with the common simple case of the user having the
587
    // capability in the system context. That handles $CFG->defaultuserroleid.
588
    // For the remaining providers/capabilities, we need to do a more complex
589
    // query involving all overrides everywhere.
590
    $unsureproviders = array();
591
    $unsurecapabilities = array();
592
    $systemcontext = context_system::instance();
593
    foreach ($providers as $providerid => $provider) {
594
        if (empty($provider->capability) || has_capability($provider->capability, $systemcontext, $userid)) {
595
            // The provider is relevant to this user.
596
            continue;
597
        }
598
 
599
        $unsureproviders[$providerid] = $provider;
600
        $unsurecapabilities[$provider->capability] = 1;
601
        unset($providers[$providerid]);
602
    }
603
 
604
    if (empty($unsureproviders)) {
605
        // More complex checks are not required.
606
        return $providers;
607
    }
608
 
609
    // Now check the unsure capabilities.
610
    list($capcondition, $params) = $DB->get_in_or_equal(
611
            array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
612
    $params['userid'] = $userid;
613
 
614
    $sql = "SELECT DISTINCT rc.capability, 1
615
 
616
              FROM {role_assignments} ra
617
              JOIN {context} actx ON actx.id = ra.contextid
618
              JOIN {role_capabilities} rc ON rc.roleid = ra.roleid
619
              JOIN {context} cctx ON cctx.id = rc.contextid
620
 
621
             WHERE ra.userid = :userid
622
               AND rc.capability $capcondition
623
               AND rc.permission > 0
624
               AND (".$DB->sql_concat('actx.path', "'/'")." LIKE ".$DB->sql_concat('cctx.path', "'/%'").
625
               " OR ".$DB->sql_concat('cctx.path', "'/'")." LIKE ".$DB->sql_concat('actx.path', "'/%'").")";
626
 
627
    if (!empty($CFG->defaultfrontpageroleid)) {
628
        $frontpagecontext = context_course::instance(SITEID);
629
 
630
        list($capcondition2, $params2) = $DB->get_in_or_equal(
631
                array_keys($unsurecapabilities), SQL_PARAMS_NAMED);
632
        $params = array_merge($params, $params2);
633
        $params['frontpageroleid'] = $CFG->defaultfrontpageroleid;
634
        $params['frontpagepathpattern'] = $frontpagecontext->path . '/';
635
 
636
        $sql .= "
637
             UNION
638
 
639
            SELECT DISTINCT rc.capability, 1
640
 
641
              FROM {role_capabilities} rc
642
              JOIN {context} cctx ON cctx.id = rc.contextid
643
 
644
             WHERE rc.roleid = :frontpageroleid
645
               AND rc.capability $capcondition2
646
               AND rc.permission > 0
647
               AND ".$DB->sql_concat('cctx.path', "'/'")." LIKE :frontpagepathpattern";
648
    }
649
 
650
    $relevantcapabilities = $DB->get_records_sql_menu($sql, $params);
651
 
652
    // Add back any providers based on the detailed capability check.
653
    foreach ($unsureproviders as $providerid => $provider) {
654
        if (array_key_exists($provider->capability, $relevantcapabilities)) {
655
            $providers[$providerid] = $provider;
656
        }
657
    }
658
 
659
    return $providers;
660
}
661
 
662
/**
663
 * Gets the message providers that are in the database for this component.
664
 *
665
 * This is an internal function used within messagelib.php
666
 *
667
 * @see message_update_providers()
668
 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_activity_results'
669
 * @return array An array of message providers
670
 */
671
function message_get_providers_from_db($component) {
672
    global $DB;
673
 
674
    return $DB->get_records('message_providers', array('component'=>$component), '', 'name, id, component, capability');  // Name is unique per component
675
}
676
 
677
/**
678
 * Loads the messages definitions for a component from file
679
 *
680
 * If no messages are defined for the component, return an empty array.
681
 * This is an internal function used within messagelib.php
682
 *
683
 * @see message_update_providers()
684
 * @see message_update_processors()
685
 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_activity_results'
686
 * @return array An array of message providers or empty array if not exists
687
 */
688
function message_get_providers_from_file($component) {
689
    $defpath = core_component::get_component_directory($component).'/db/messages.php';
690
 
691
    $messageproviders = array();
692
 
693
    if (file_exists($defpath)) {
694
        require($defpath);
695
    }
696
 
697
    foreach ($messageproviders as $name => $messageprovider) {   // Fix up missing values if required
698
        if (empty($messageprovider['capability'])) {
699
            $messageproviders[$name]['capability'] = NULL;
700
        }
701
        if (empty($messageprovider['defaults'])) {
702
            $messageproviders[$name]['defaults'] = array();
703
        }
704
    }
705
 
706
    return $messageproviders;
707
}
708
 
709
/**
710
 * Remove all message providers for particular component and corresponding settings
711
 *
712
 * @param string $component A moodle component like 'moodle', 'mod_forum', 'block_activity_results'
713
 * @return void
714
 */
715
function message_provider_uninstall($component) {
716
    global $DB;
717
 
718
    $transaction = $DB->start_delegated_transaction();
719
    $DB->delete_records('message_providers', array('component' => $component));
720
    $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_{$component}_%"));
1441 ariadna 721
    $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?'), ["message_provider_{$component}_%"]);
1 efrain 722
    $transaction->allow_commit();
723
    // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
724
    cache_helper::invalidate_by_definition('core', 'config', array(), 'message');
725
}
726
 
727
/**
728
 * Uninstall a message processor
729
 *
730
 * @param string $name A message processor name like 'email', 'jabber'
731
 */
732
function message_processor_uninstall($name) {
733
    global $DB;
734
 
735
    $transaction = $DB->start_delegated_transaction();
736
    $DB->delete_records('message_processors', array('name' => $name));
737
    $DB->delete_records_select('config_plugins', "plugin = ?", array("message_{$name}"));
738
    // Delete permission preferences only, we do not care about enabled defaults,
739
    // they will be removed on the next attempt to update the preferences.
740
    $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("{$name}_provider_%"));
741
    $transaction->allow_commit();
742
    // Purge all messaging settings from the caches. They are stored by plugin so we have to clear all message settings.
743
    cache_helper::invalidate_by_definition('core', 'config', array(), array('message', "message_{$name}"));
744
}