lib.php 31.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Library functions for messaging
 *
20
21
22
 * @package   core_message
 * @copyright 2008 Luis Rodrigues
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24

25
define('MESSAGE_SHORTLENGTH', 300);
26

27
define('MESSAGE_HISTORY_ALL', 1);
28

29
30
define('MESSAGE_SEARCH_MAX_RESULTS', 200);

31
32
define('MESSAGE_TYPE_NOTIFICATION', 'notification');
define('MESSAGE_TYPE_MESSAGE', 'message');
33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * Define contants for messaging default settings population. For unambiguity of
 * plugin developer intentions we use 4-bit value (LSB numbering):
 * bit 0 - whether to send message when user is loggedin (MESSAGE_DEFAULT_LOGGEDIN)
 * bit 1 - whether to send message when user is loggedoff (MESSAGE_DEFAULT_LOGGEDOFF)
 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
 *
 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting
 */

define('MESSAGE_DEFAULT_LOGGEDIN', 0x01); // 0001
define('MESSAGE_DEFAULT_LOGGEDOFF', 0x02); // 0010

define('MESSAGE_DISALLOWED', 0x04); // 0100
define('MESSAGE_PERMITTED', 0x08); // 1000
define('MESSAGE_FORCED', 0x0c); // 1100

define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100

53
54
55
/**
 * Set default value for default outputs permitted setting
 */
56
define('MESSAGE_DEFAULT_PERMITTED', 'permitted');
57

58
59
60
61
62
63
64
/**
 * Set default values for polling.
 */
define('MESSAGE_DEFAULT_MIN_POLL_IN_SECONDS', 10);
define('MESSAGE_DEFAULT_MAX_POLL_IN_SECONDS', 2 * MINSECS);
define('MESSAGE_DEFAULT_TIMEOUT_POLL_IN_SECONDS', 5 * MINSECS);

65
66
/**
 * Returns the count of unread messages for user. Either from a specific user or from all users.
67
 *
68
69
 * @deprecated since 3.10
 * TODO: MDL-69643
70
71
72
73
74
75
 * @param object $user1 the first user. Defaults to $USER
 * @param object $user2 the second user. If null this function will count all of user 1's unread messages.
 * @return int the count of $user1's unread messages
 */
function message_count_unread_messages($user1=null, $user2=null) {
    global $USER, $DB;
moodler's avatar
moodler committed
76

77
78
79
    debugging('message_count_unread_messages is deprecated and no longer used',
        DEBUG_DEVELOPER);

80
81
82
83
    if (empty($user1)) {
        $user1 = $USER;
    }

84
85
86
87
88
89
90
91
92
93
    $sql = "SELECT COUNT(m.id)
              FROM {messages} m
        INNER JOIN {message_conversations} mc
                ON mc.id = m.conversationid
        INNER JOIN {message_conversation_members} mcm
                ON mcm.conversationid = mc.id
         LEFT JOIN {message_user_actions} mua
                ON (mua.messageid = m.id AND mua.userid = ? AND (mua.action = ? OR mua.action = ?))
             WHERE mua.id is NULL
               AND mcm.userid = ?";
94
    $params = [$user1->id, \core_message\api::MESSAGE_ACTION_DELETED, \core_message\api::MESSAGE_ACTION_READ, $user1->id];
95

96
    if (!empty($user2)) {
97
98
        $sql .= " AND m.useridfrom = ?";
        $params[] = $user2->id;
99
100
101
    } else {
        $sql .= " AND m.useridfrom <> ?";
        $params[] = $user1->id;
102
    }
103
104

    return $DB->count_records_sql($sql, $params);
105
106
}

107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
 * Try to guess how to convert the message to html.
 *
 * @access private
 *
 * @param stdClass $message
 * @param bool $forcetexttohtml
 * @return string html fragment
 */
function message_format_message_text($message, $forcetexttohtml = false) {
    // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.

    $options = new stdClass();
    $options->para = false;
121
    $options->blanktarget = true;
122
    $options->trusted = isset($message->fullmessagetrust) ? $message->fullmessagetrust : false;
123
124
125

    $format = $message->fullmessageformat;

126
    if (strval($message->smallmessage) !== '') {
127
        if (!empty($message->notification)) {
128
            if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') {
129
130
131
132
133
134
                $format = FORMAT_PLAIN;
            }
        }
        $messagetext = $message->smallmessage;

    } else if ($message->fullmessageformat == FORMAT_HTML) {
135
        if (strval($message->fullmessagehtml) !== '') {
136
137
138
139
140
141
142
            $messagetext = $message->fullmessagehtml;
        } else {
            $messagetext = $message->fullmessage;
            $format = FORMAT_MOODLE;
        }

    } else {
143
        if (strval($message->fullmessage) !== '') {
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
            $messagetext = $message->fullmessage;
        } else {
            $messagetext = $message->fullmessagehtml;
            $format = FORMAT_HTML;
        }
    }

    if ($forcetexttohtml) {
        // This is a crazy hack, why not set proper format when creating the notifications?
        if ($format === FORMAT_PLAIN) {
            $format = FORMAT_MOODLE;
        }
    }
    return format_text($messagetext, $format, $options);
}

moodler's avatar
moodler committed
160
/**
161
162
163
164
 * Search through course users.
 *
 * If $courseids contains the site course then this function searches
 * through all undeleted and confirmed users.
moodler's avatar
moodler committed
165
 *
166
167
168
 * @param int|array $courseids Course ID or array of course IDs.
 * @param string $searchtext the text to search for.
 * @param string $sort the column name to order by.
169
 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
170
 * @return array An array of {@link $USER} records.
moodler's avatar
moodler committed
171
 */
172
function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
173
    global $CFG, $USER, $DB;
moodler's avatar
moodler committed
174

175
176
177
178
179
180
181
182
183
184
    // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
    if (!$courseids) {
        $courseids = array(SITEID);
    }

    // Allow an integer to be passed.
    if (!is_array($courseids)) {
        $courseids = array($courseids);
    }

185
    $fullname = $DB->sql_fullname();
186
    $userfieldsapi = \core_user\fields::for_userpic();
187
    $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
moodler's avatar
moodler committed
188
189
190
191
192
193
194

    if (!empty($sort)) {
        $order = ' ORDER BY '. $sort;
    } else {
        $order = '';
    }

195
196
    $params = array(
        'userid' => $USER->id,
197
        'userid2' => $USER->id,
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        'query' => "%$searchtext%"
    );

    if (empty($exceptions)) {
        $exceptions = array();
    } else if (!empty($exceptions) && is_string($exceptions)) {
        $exceptions = explode(',', $exceptions);
    }

    // Ignore self and guest account.
    $exceptions[] = $USER->id;
    $exceptions[] = $CFG->siteguest;

    // Exclude exceptions from the search result.
    list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
    $except = ' AND u.id ' . $except;
    $params = array_merge($params_except, $params);
215
216
217

    if (in_array(SITEID, $courseids)) {
        // Search on site level.
218
        return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mub.id as userblockedid
219
                                       FROM {user} u
220
                                       LEFT JOIN {message_contacts} mc
221
                                            ON mc.contactid = u.id AND mc.userid = :userid
222
223
                                       LEFT JOIN {message_users_blocked} mub
                                            ON mub.userid = :userid2 AND mub.blockeduserid = u.id
224
                                      WHERE u.deleted = '0' AND u.confirmed = '1'
225
                                            AND (".$DB->sql_like($fullname, ':query', false).")
226
227
                                            $except
                                     $order", $params);
moodler's avatar
moodler committed
228
    } else {
229
230
231
232
233
234
235
236
        // Search in courses.

        // Getting the context IDs or each course.
        $contextids = array();
        foreach ($courseids as $courseid) {
            $context = context_course::instance($courseid);
            $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
        }
237
        list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
238
239
240
241
        $params = array_merge($params, $contextparams);

        // Everyone who has a role assignment in this course or higher.
        // TODO: add enabled enrolment join here (skodak)
242
        $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mub.id as userblockedid
243
                                         FROM {user} u
244
245
                                         JOIN {role_assignments} ra ON ra.userid = u.id
                                         LEFT JOIN {message_contacts} mc
246
                                              ON mc.contactid = u.id AND mc.userid = :userid
247
248
                                         LEFT JOIN {message_users_blocked} mub
                                              ON mub.userid = :userid2 AND mub.blockeduserid = u.id
249
                                        WHERE u.deleted = '0' AND u.confirmed = '1'
250
                                              AND (".$DB->sql_like($fullname, ':query', false).")
251
                                              AND ra.contextid $contextwhere
252
253
                                              $except
                                       $order", $params);
254
255

        return $users;
moodler's avatar
moodler committed
256
257
258
    }
}

259
260
/**
 * Format a message for display in the message history
261
 *
262
263
264
265
266
267
268
 * @param object $message the message object
 * @param string $format optional date format
 * @param string $keywords keywords to highlight
 * @param string $class CSS class to apply to the div around the message
 * @return string the formatted message
 */
function message_format_message($message, $format='', $keywords='', $class='other') {
269
270
271

    static $dateformat;

272
273
    //if we haven't previously set the date format or they've supplied a new one
    if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
274
275
276
        if ($format) {
            $dateformat = $format;
        } else {
277
            $dateformat = get_string('strftimedatetimeshort');
278
        }
moodler's avatar
moodler committed
279
    }
280
    $time = userdate($message->timecreated, $dateformat);
281

282
    $messagetext = message_format_message_text($message, false);
283
284
285
286
287

    if ($keywords) {
        $messagetext = highlight($keywords, $messagetext);
    }

288
289
    $messagetext .= message_format_contexturl($message);

Petr Škoda's avatar
Petr Škoda committed
290
291
    $messagetext = clean_text($messagetext, FORMAT_HTML);

292
293
    return <<<TEMPLATE
<div class='message $class'>
294
    <a name="m{$message->id}"></a>
295
296
297
    <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
</div>
TEMPLATE;
298
299
300
301
}

/**
 * Format a the context url and context url name of a message for display
302
 *
303
304
305
306
307
308
 * @param object $message the message object
 * @return string the formatted string
 */
function message_format_contexturl($message) {
    $s = null;

309
310
311
312
313
314
315
    if (!empty($message->contexturl)) {
        $displaytext = null;
        if (!empty($message->contexturlname)) {
            $displaytext= $message->contexturlname;
        } else {
            $displaytext= $message->contexturl;
        }
316
317
318
        $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
            $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
        $s .= html_writer::end_tag('div');
319
    }
320

321
    return $s;
moodler's avatar
moodler committed
322
}
moodler's avatar
moodler committed
323

324
/**
325
 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
326
 *
327
328
329
330
 * @param object $userfrom the message sender
 * @param object $userto the message recipient
 * @param string $message the message
 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
331
 * @return int|false the ID of the new message or false
332
 */
333
function message_post_message($userfrom, $userto, $message, $format) {
334
    global $PAGE;
335

336
337
    $eventdata = new \core\message\message();
    $eventdata->courseid         = 1;
338
    $eventdata->component        = 'moodle';
339
    $eventdata->name             = 'instantmessage';
340
341
    $eventdata->userfrom         = $userfrom;
    $eventdata->userto           = $userto;
342
343
344
345

    //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
    $eventdata->subject          = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);

346
    if ($format == FORMAT_HTML) {
347
        $eventdata->fullmessagehtml  = $message;
348
349
350
        //some message processors may revert to sending plain text even if html is supplied
        //so we keep both plain and html versions if we're intending to send html
        $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
351
352
353
354
    } else {
        $eventdata->fullmessage      = $message;
        $eventdata->fullmessagehtml  = '';
    }
355

356
    $eventdata->fullmessageformat = $format;
357
    $eventdata->smallmessage     = $message;//store the message unfiltered. Clean up on output.
358
    $eventdata->timecreated     = time();
359
    $eventdata->notification    = 0;
360
361
    // User image.
    $userpicture = new user_picture($userfrom);
362
    $userpicture->size = 1; // Use f1 size.
363
364
365
    $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
    $eventdata->customdata = [
        'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
366
367
368
369
370
371
        'actionbuttons' => [
            'send' => get_string_manager()->get_string('send', 'message', null, $eventdata->userto->lang),
        ],
        'placeholders' => [
            'send' => get_string_manager()->get_string('writeamessage', 'message', null, $eventdata->userto->lang),
        ],
372
    ];
373
    return message_send($eventdata);
374
}
moodler's avatar
moodler committed
375

376
/**
377
378
 * Get all message processors, validate corresponding plugin existance and
 * system configuration
379
 *
380
 * @param bool $ready only return ready-to-use processors
381
 * @param bool $reset Reset list of message processors (used in unit tests)
382
 * @param bool $resetonly Just reset, then exit
383
 * @return mixed $processors array of objects containing information on message processors
384
 */
385
function get_message_processors($ready = false, $reset = false, $resetonly = false) {
386
387
    global $DB, $CFG;

388
    static $processors;
389
390
    if ($reset) {
        $processors = array();
391
392
393
394

        if ($resetonly) {
            return $processors;
        }
395
    }
396
397

    if (empty($processors)) {
398
399
        // Get all processors, ensure the name column is the first so it will be the array key
        $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
400
        foreach ($processors as &$processor){
401
            $processor = \core_message\api::get_processed_processor_object($processor);
402
403
        }
    }
404
    if ($ready) {
405
406
407
408
409
410
411
412
        // Filter out enabled and system_configured processors
        $readyprocessors = $processors;
        foreach ($readyprocessors as $readyprocessor) {
            if (!($readyprocessor->enabled && $readyprocessor->configured)) {
                unset($readyprocessors[$readyprocessor->name]);
            }
        }
        return $readyprocessors;
413
414
    }

415
416
    return $processors;
}
417

418
419
420
421
422
423
424
425
/**
 * Get all message providers, validate their plugin existance and
 * system configuration
 *
 * @return mixed $processors array of objects containing information on message processors
 */
function get_message_providers() {
    global $CFG, $DB;
426
427

    $pluginman = core_plugin_manager::instance();
428
429
430
431
432
433
434

    $providers = $DB->get_records('message_providers', null, 'name');

    // Remove all the providers whose plugins are disabled or don't exist
    foreach ($providers as $providerid => $provider) {
        $plugin = $pluginman->get_plugin_info($provider->component);
        if ($plugin) {
435
            if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
436
437
438
439
440
441
442
443
444
445
446
447
                unset($providers[$providerid]);   // Plugins does not exist
                continue;
            }
            if ($plugin->is_enabled() === false) {
                unset($providers[$providerid]);   // Plugin disabled
                continue;
            }
        }
    }
    return $providers;
}

448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/**
 * Get an instance of the message_output class for one of the output plugins.
 * @param string $type the message output type. E.g. 'email' or 'jabber'.
 * @return message_output message_output the requested class.
 */
function get_message_processor($type) {
    global $CFG;

    // Note, we cannot use the get_message_processors function here, becaues this
    // code is called during install after installing each messaging plugin, and
    // get_message_processors caches the list of installed plugins.

    $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
    if (!is_readable($processorfile)) {
        throw new coding_exception('Unknown message processor type ' . $type);
    }

    include_once($processorfile);

    $processclass = 'message_output_' . $type;
    if (!class_exists($processclass)) {
        throw new coding_exception('Message processor ' . $type .
                ' does not define the right class');
    }

    return new $processclass();
}

476
477
/**
 * Get messaging outputs default (site) preferences
478
 *
479
480
481
 * @return object $processors object containing information on message processors
 */
function get_message_output_default_preferences() {
482
    return get_config('message');
483
}
484
485
486
487
488

/**
 * Translate message default settings from binary value to the array of string
 * representing the settings to be stored. Also validate the provided value and
 * use default if it is malformed.
489
 *
490
491
492
493
494
495
496
 * @param  int    $plugindefault Default setting suggested by plugin
 * @param  string $processorname The name of processor
 * @return array  $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
 */
function translate_message_default_setting($plugindefault, $processorname) {
    // Preset translation arrays
    $permittedvalues = array(
497
498
499
        MESSAGE_DISALLOWED => 'disallowed',
        MESSAGE_PERMITTED  => 'permitted',
        MESSAGE_FORCED     => 'forced',
500
501
502
503
    );

    $loggedinstatusvalues = array(
        0x00 => null, // use null if loggedin/loggedoff is not defined
504
505
        MESSAGE_DEFAULT_LOGGEDIN  => 'loggedin',
        MESSAGE_DEFAULT_LOGGEDOFF => 'loggedoff',
506
507
508
    );

    // define the default setting
509
510
    $processor = get_message_processor($processorname);
    $default = $processor->get_default_messaging_settings();
511
512
513

    // Validate the value. It should not exceed the maximum size
    if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
514
        debugging(get_string('errortranslatingdefault', 'message'));
515
516
517
518
519
520
521
522
        $plugindefault = $default;
    }
    // Use plugin default setting of 'permitted' is 0
    if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
        $plugindefault = $default;
    }

    $permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
523
    $loggedin = $loggedoff = null;
524
525

    if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
526
527
        $loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
        $loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
528
529
530
531
    }

    return array($permitted, $loggedin, $loggedoff);
}
532

533
534
535
536
537
538
539
540
541
542
543
544
545
546
/**
 * Return a list of page types
 *
 * @param string $pagetype current page type
 * @param context|null $parentcontext Block's parent context
 * @param context|null $currentcontext Current context of block
 * @return array
 */
function message_page_type_list(string $pagetype, ?context $parentcontext, ?context $currentcontext): array {
    return [
        'message-*' => get_string('page-message-x', 'message'),
    ];
}

547
/**
548
 * Get messages sent or/and received by the specified users.
549
550
 * Please note that this function return deleted messages too. Besides, only individual conversation messages
 * are returned to maintain backwards compatibility.
551
552
 *
 * @param  int      $useridto       the user id who received the message
553
 * @param  int      $useridfrom     the user id who sent the message. -10 or -20 for no-reply or support user
554
 * @param  int      $notifications  1 for retrieving notifications, 0 for messages, -1 for both
555
 * @param  bool     $read           true for retrieving read messages, false for unread
556
557
558
559
560
561
562
563
564
565
 * @param  string   $sort           the column name to order by including optionally direction
 * @param  int      $limitfrom      limit from
 * @param  int      $limitnum       limit num
 * @return external_description
 * @since  2.8
 */
function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
                                $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
    global $DB;

566
    // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
567
    $userfieldsapi = \core_user\fields::for_name();
568
    if (empty($useridto)) {
569
        $userfields = $userfieldsapi->get_sql('u', false, 'userto', '', false)->selects;
570
        $messageuseridtosql = 'u.id as useridto';
571
    } else {
572
        $userfields = $userfieldsapi->get_sql('u', false, 'userfrom', '', false)->selects;
573
        $messageuseridtosql = "$useridto as useridto";
574
575
576
577
578
    }

    // Create the SQL we will be using.
    $messagesql = "SELECT mr.*, $userfields, 0 as notification, '' as contexturl, '' as contexturlname,
                          mua.timecreated as timeusertodeleted, mua2.timecreated as timeread,
579
                          mua3.timecreated as timeuserfromdeleted, $messageuseridtosql
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
                     FROM {messages} mr
               INNER JOIN {message_conversations} mc
                       ON mc.id = mr.conversationid
               INNER JOIN {message_conversation_members} mcm
                       ON mcm.conversationid = mc.id ";

    $notificationsql = "SELECT mr.*, $userfields, 1 as notification
                          FROM {notifications} mr ";

    $messagejoinsql = "LEFT JOIN {message_user_actions} mua
                              ON (mua.messageid = mr.id AND mua.userid = mcm.userid AND mua.action = ?)
                       LEFT JOIN {message_user_actions} mua2
                              ON (mua2.messageid = mr.id AND mua2.userid = mcm.userid AND mua2.action = ?)
                       LEFT JOIN {message_user_actions} mua3
                              ON (mua3.messageid = mr.id AND mua3.userid = mr.useridfrom AND mua3.action = ?)";
    $messagejoinparams = [\core_message\api::MESSAGE_ACTION_DELETED, \core_message\api::MESSAGE_ACTION_READ,
        \core_message\api::MESSAGE_ACTION_DELETED];
    $notificationsparams = [];

    // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
    if (empty($useridto)) {
        // Create the messaging query and params.
        $messagesql .= "INNER JOIN {user} u
                                ON u.id = mcm.userid
                                $messagejoinsql
                             WHERE mr.useridfrom = ?
                               AND mr.useridfrom != mcm.userid
607
608
609
                               AND u.deleted = 0
                               AND mc.type = ? ";
        $messageparams = array_merge($messagejoinparams, [$useridfrom, \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL]);
610
611
612
613
614
615
616
617
618

        // Create the notifications query and params.
        $notificationsql .= "INNER JOIN {user} u
                                     ON u.id = mr.useridto
                                  WHERE mr.useridfrom = ?
                                    AND u.deleted = 0 ";
        $notificationsparams[] = $useridfrom;
    } else {
        // Create the messaging query and params.
619
        // Left join because useridfrom may be -10 or -20 (no-reply and support users).
620
621
622
623
624
        $messagesql .= "LEFT JOIN {user} u
                               ON u.id = mr.useridfrom
                               $messagejoinsql
                            WHERE mcm.userid = ?
                              AND mr.useridfrom != mcm.userid
625
626
627
628
629
630
631
                              AND u.deleted = 0
                              AND mc.type = ? ";
        $messageparams = array_merge($messagejoinparams, [$useridto, \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL]);

        // If we're dealing with messages only and both useridto and useridfrom are set,
        // try to get a conversation between the users. Break early if we can't find one.
        if (!empty($useridfrom) && $notifications == 0) {
632
633
            $messagesql .= " AND mr.useridfrom = ? ";
            $messageparams[] = $useridfrom;
634
635
636
637
638
639
640
641

            // There should be an individual conversation between the users. If not, we can return early.
            $conversationid = \core_message\api::get_conversation_between_users([$useridto, $useridfrom]);
            if (empty($conversationid)) {
                return [];
            }
            $messagesql .= " AND mc.id = ? ";
            $messageparams[] = $conversationid;
642
643
644
645
646
647
648
649
650
651
652
        }

        // Create the notifications query and params.
        // Left join because useridfrom may be -10 or -20 (no-reply and support users).
        $notificationsql .= "LEFT JOIN {user} u
                                    ON (u.id = mr.useridfrom AND u.deleted = 0)
                                 WHERE mr.useridto = ? ";
        $notificationsparams[] = $useridto;
        if (!empty($useridfrom)) {
            $notificationsql .= " AND mr.useridfrom = ? ";
            $notificationsparams[] = $useridfrom;
653
654
        }
    }
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
    if ($read) {
        $notificationsql .= "AND mr.timeread IS NOT NULL ";
    } else {
        $notificationsql .= "AND mr.timeread IS NULL ";
    }
    $messagesql .= "ORDER BY $sort";
    $notificationsql .= "ORDER BY $sort";

    // Handle messages if needed.
    if ($notifications === -1 || $notifications === 0) {
        $messages = $DB->get_records_sql($messagesql, $messageparams, $limitfrom, $limitnum);
        // Get rid of the messages that have either been read or not read depending on the value of $read.
        $messages = array_filter($messages, function ($message) use ($read) {
            if ($read) {
                return !is_null($message->timeread);
            }
671

672
673
            return is_null($message->timeread);
        });
674
675
    }

676
677
678
679
680
681
    // All.
    if ($notifications === -1) {
        return array_merge($messages, $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum));
    } else if ($notifications === 1) { // Just notifications.
        return $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum);
    }
682

683
    // Just messages.
684
685
    return $messages;
}
686

687
688
689
690
691
692
693
/**
 * Handles displaying processor settings in a fragment.
 *
 * @param array $args
 * @return bool|string
 * @throws moodle_exception
 */
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
function message_output_fragment_processor_settings($args = []) {
    global $PAGE;

    if (!isset($args['type'])) {
        throw new moodle_exception('Must provide a processor type');
    }

    if (!isset($args['userid'])) {
        throw new moodle_exception('Must provide a userid');
    }

    $type = $args['type'];
    $userid = $args['userid'];

    $user = core_user::get_user($userid, '*', MUST_EXIST);
    $processor = get_message_processor($type);
    $providers = message_get_providers_for_user($userid);
711
712
    $processorwrapper = new stdClass();
    $processorwrapper->object = $processor;
713
    $preferences = \core_message\api::get_all_message_preferences([$processorwrapper], $providers, $user);
714
715
716
717
718
719

    $processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type);
    $renderer = $PAGE->get_renderer('core', 'message');

    return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));
}
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747

/**
 * Checks if current user is allowed to edit messaging preferences of another user
 *
 * @param stdClass $user user whose preferences we are updating
 * @return bool
 */
function core_message_can_edit_message_profile($user) {
    global $USER;
    if ($user->id == $USER->id) {
        return has_capability('moodle/user:editownmessageprofile', context_system::instance());
    } else {
        $personalcontext = context_user::instance($user->id);
        if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
            return false;
        }
        if (isguestuser($user)) {
            return false;
        }
        // No editing of admins by non-admins.
        if (is_siteadmin($user) and !is_siteadmin($USER)) {
            return false;
        }
        return true;
    }
}

/**
748
 * Implements callback user_preferences, lists preferences that users are allowed to update directly
749
750
751
752
753
754
755
 *
 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
 *
 * @return array
 */
function core_message_user_preferences() {
    $preferences = [];
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
    $preferences['message_blocknoncontacts'] = array(
        'type' => PARAM_INT,
        'null' => NULL_NOT_ALLOWED,
        'default' => 0,
        'choices' => array(
            \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
            \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
            \core_message\api::MESSAGE_PRIVACY_SITE
        ),
        'cleancallback' => function ($value) {
            global $CFG;

            // When site-wide messaging between users is disabled, MESSAGE_PRIVACY_SITE should be converted.
            if (empty($CFG->messagingallusers) && $value === \core_message\api::MESSAGE_PRIVACY_SITE) {
                return \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER;
            }
            return $value;
        }
    );
775
776
777
778
779
    $preferences['message_entertosend'] = array(
        'type' => PARAM_BOOL,
        'null' => NULL_NOT_ALLOWED,
        'default' => false
    );
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
    $preferences['/^message_provider_([\w\d_]*)_logged(in|off)$/'] = array('isregex' => true, 'type' => PARAM_NOTAGS,
        'null' => NULL_NOT_ALLOWED, 'default' => 'none',
        'permissioncallback' => function ($user, $preferencename) {
            global $CFG;
            require_once($CFG->libdir.'/messagelib.php');
            if (core_message_can_edit_message_profile($user) &&
                    preg_match('/^message_provider_([\w\d_]*)_logged(in|off)$/', $preferencename, $matches)) {
                $providers = message_get_providers_for_user($user->id);
                foreach ($providers as $provider) {
                    if ($matches[1] === $provider->component . '_' . $provider->name) {
                       return true;
                    }
                }
            }
            return false;
        },
        'cleancallback' => function ($value, $preferencename) {
            if ($value === 'none' || empty($value)) {
                return 'none';
            }
            $parts = explode('/,/', $value);
            $processors = array_keys(get_message_processors());
            array_filter($parts, function($v) use ($processors) {return in_array($v, $processors);});
            return $parts ? join(',', $parts) : 'none';
        });
    return $preferences;
}
807
808

/**
809
 * Render the message drawer to be included in the top of the body of each page.
810
811
812
 *
 * @return string HTML
 */
813
function core_message_standard_after_main_region_html() {
814
    return \core_message\helper::render_messaging_widget(true, null, null);
815
}