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
 * Library functions for messaging
19
 *
20
 * @package   core_message
21
 * @copyright 2008 Luis Rodrigues
22
 * @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
define('MESSAGE_SEARCH_MAX_RESULTS', 200);
30
 
31
define('MESSAGE_TYPE_NOTIFICATION', 'notification');
32
define('MESSAGE_TYPE_MESSAGE', 'message');
33
 
34
/**
35
 * Define contants for messaging default settings population. For unambiguity of
36
 * plugin developer intentions we use 4-bit value (LSB numbering):
37
 * bit 0 - whether to send message (MESSAGE_DEFAULT_ENABLED)
1441 ariadna 38
 * bit 1 - not used
1 efrain 39
 * bit 2..3 - messaging permission (MESSAGE_DISALLOWED|MESSAGE_PERMITTED|MESSAGE_FORCED)
40
 *
41
 * MESSAGE_PERMITTED_MASK contains the mask we use to distinguish permission setting.
42
 */
43
 
44
define('MESSAGE_DEFAULT_ENABLED', 0x01); // 0001.
45
 
46
define('MESSAGE_DISALLOWED', 0x04); // 0100.
47
define('MESSAGE_PERMITTED', 0x08); // 1000.
48
define('MESSAGE_FORCED', 0x0c); // 1100.
49
 
50
define('MESSAGE_PERMITTED_MASK', 0x0c); // 1100.
51
 
52
/**
53
 * Set default values for polling.
54
 */
55
define('MESSAGE_DEFAULT_MIN_POLL_IN_SECONDS', 10);
56
define('MESSAGE_DEFAULT_MAX_POLL_IN_SECONDS', 2 * MINSECS);
57
define('MESSAGE_DEFAULT_TIMEOUT_POLL_IN_SECONDS', 5 * MINSECS);
58
 
59
/**
60
 * To get only read, unread or both messages or notifications.
61
 */
62
define('MESSAGE_GET_UNREAD', 0);
63
define('MESSAGE_GET_READ', 1);
64
define('MESSAGE_GET_READ_AND_UNREAD', 2);
65
 
66
/**
67
 * Try to guess how to convert the message to html.
68
 *
69
 * @access private
70
 *
71
 * @param stdClass $message
72
 * @param bool $forcetexttohtml
73
 * @return string html fragment
74
 */
75
function message_format_message_text($message, $forcetexttohtml = false) {
76
    // Note: this is a very nasty hack that tries to work around the weird messaging rules and design.
77
 
78
    $options = new stdClass();
79
    $options->para = false;
80
    $options->blanktarget = true;
81
    $options->trusted = isset($message->fullmessagetrust) ? $message->fullmessagetrust : false;
82
 
83
    $format = $message->fullmessageformat;
84
 
85
    if (strval($message->smallmessage) !== '') {
86
        if (!empty($message->notification)) {
87
            if (strval($message->fullmessagehtml) !== '' or strval($message->fullmessage) !== '') {
88
                $format = FORMAT_PLAIN;
89
            }
90
        }
91
        $messagetext = $message->smallmessage;
92
 
93
    } else if ($message->fullmessageformat == FORMAT_HTML) {
94
        if (strval($message->fullmessagehtml) !== '') {
95
            $messagetext = $message->fullmessagehtml;
96
        } else {
97
            $messagetext = $message->fullmessage;
98
            $format = FORMAT_MOODLE;
99
        }
100
 
101
    } else {
102
        if (strval($message->fullmessage) !== '') {
103
            $messagetext = $message->fullmessage;
104
        } else {
105
            $messagetext = $message->fullmessagehtml;
106
            $format = FORMAT_HTML;
107
        }
108
    }
109
 
110
    if ($forcetexttohtml) {
111
        // This is a crazy hack, why not set proper format when creating the notifications?
112
        if ($format === FORMAT_PLAIN) {
113
            $format = FORMAT_MOODLE;
114
        }
115
    }
116
    return format_text($messagetext, $format, $options);
117
}
118
 
119
/**
120
 * Search through course users.
121
 *
122
 * If $courseids contains the site course then this function searches
123
 * through all undeleted and confirmed users.
124
 *
125
 * @param int|array $courseids Course ID or array of course IDs.
126
 * @param string $searchtext the text to search for.
127
 * @param string $sort the column name to order by.
128
 * @param string|array $exceptions comma separated list or array of user IDs to exclude.
129
 * @return array An array of {@link $USER} records.
130
 */
131
function message_search_users($courseids, $searchtext, $sort='', $exceptions='') {
132
    global $CFG, $USER, $DB;
133
 
134
    // Basic validation to ensure that the parameter $courseids is not an empty array or an empty value.
135
    if (!$courseids) {
136
        $courseids = array(SITEID);
137
    }
138
 
139
    // Allow an integer to be passed.
140
    if (!is_array($courseids)) {
141
        $courseids = array($courseids);
142
    }
143
 
144
    $fullname = $DB->sql_fullname();
145
    $userfieldsapi = \core_user\fields::for_userpic();
146
    $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
147
 
148
    if (!empty($sort)) {
149
        $order = ' ORDER BY '. $sort;
150
    } else {
151
        $order = '';
152
    }
153
 
154
    $params = array(
155
        'userid' => $USER->id,
156
        'userid2' => $USER->id,
157
        'query' => "%$searchtext%"
158
    );
159
 
160
    if (empty($exceptions)) {
161
        $exceptions = array();
162
    } else if (!empty($exceptions) && is_string($exceptions)) {
163
        $exceptions = explode(',', $exceptions);
164
    }
165
 
166
    // Ignore self and guest account.
167
    $exceptions[] = $USER->id;
168
    $exceptions[] = $CFG->siteguest;
169
 
170
    // Exclude exceptions from the search result.
171
    list($except, $params_except) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'param', false);
172
    $except = ' AND u.id ' . $except;
173
    $params = array_merge($params_except, $params);
174
 
175
    if (in_array(SITEID, $courseids)) {
176
        // Search on site level.
177
        return $DB->get_records_sql("SELECT $ufields, mc.id as contactlistid, mub.id as userblockedid
178
                                       FROM {user} u
179
                                       LEFT JOIN {message_contacts} mc
180
                                            ON mc.contactid = u.id AND mc.userid = :userid
181
                                       LEFT JOIN {message_users_blocked} mub
182
                                            ON mub.userid = :userid2 AND mub.blockeduserid = u.id
183
                                      WHERE u.deleted = '0' AND u.confirmed = '1'
184
                                            AND (".$DB->sql_like($fullname, ':query', false).")
185
                                            $except
186
                                     $order", $params);
187
    } else {
188
        // Search in courses.
189
 
190
        // Getting the context IDs or each course.
191
        $contextids = array();
192
        foreach ($courseids as $courseid) {
193
            $context = context_course::instance($courseid);
194
            $contextids = array_merge($contextids, $context->get_parent_context_ids(true));
195
        }
196
        list($contextwhere, $contextparams) = $DB->get_in_or_equal(array_unique($contextids), SQL_PARAMS_NAMED, 'context');
197
        $params = array_merge($params, $contextparams);
198
 
199
        // Everyone who has a role assignment in this course or higher.
200
        // TODO: add enabled enrolment join here (skodak)
201
        $users = $DB->get_records_sql("SELECT DISTINCT $ufields, mc.id as contactlistid, mub.id as userblockedid
202
                                         FROM {user} u
203
                                         JOIN {role_assignments} ra ON ra.userid = u.id
204
                                         LEFT JOIN {message_contacts} mc
205
                                              ON mc.contactid = u.id AND mc.userid = :userid
206
                                         LEFT JOIN {message_users_blocked} mub
207
                                              ON mub.userid = :userid2 AND mub.blockeduserid = u.id
208
                                        WHERE u.deleted = '0' AND u.confirmed = '1'
209
                                              AND (".$DB->sql_like($fullname, ':query', false).")
210
                                              AND ra.contextid $contextwhere
211
                                              $except
212
                                       $order", $params);
213
 
214
        return $users;
215
    }
216
}
217
 
218
/**
219
 * Format a message for display in the message history
220
 *
221
 * @param object $message the message object
222
 * @param string $format optional date format
223
 * @param string $keywords keywords to highlight
224
 * @param string $class CSS class to apply to the div around the message
225
 * @return string the formatted message
226
 */
227
function message_format_message($message, $format='', $keywords='', $class='other') {
228
 
229
    static $dateformat;
230
 
231
    //if we haven't previously set the date format or they've supplied a new one
232
    if ( empty($dateformat) || (!empty($format) && $dateformat != $format) ) {
233
        if ($format) {
234
            $dateformat = $format;
235
        } else {
236
            $dateformat = get_string('strftimedatetimeshort');
237
        }
238
    }
239
    $time = userdate($message->timecreated, $dateformat);
240
 
241
    $messagetext = message_format_message_text($message, false);
242
 
243
    if ($keywords) {
244
        $messagetext = highlight($keywords, $messagetext);
245
    }
246
 
247
    $messagetext .= message_format_contexturl($message);
248
 
249
    $messagetext = clean_text($messagetext, FORMAT_HTML);
250
 
251
    return <<<TEMPLATE
252
<div class='message $class'>
253
    <a name="m{$message->id}"></a>
254
    <span class="message-meta"><span class="time">$time</span></span>: <span class="text">$messagetext</span>
255
</div>
256
TEMPLATE;
257
}
258
 
259
/**
260
 * Format a the context url and context url name of a message for display
261
 *
262
 * @param object $message the message object
263
 * @return string the formatted string
264
 */
265
function message_format_contexturl($message) {
266
    $s = null;
267
 
268
    if (!empty($message->contexturl)) {
269
        $displaytext = null;
270
        if (!empty($message->contexturlname)) {
271
            $displaytext= $message->contexturlname;
272
        } else {
273
            $displaytext= $message->contexturl;
274
        }
275
        $s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
276
            $s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
277
        $s .= html_writer::end_tag('div');
278
    }
279
 
280
    return $s;
281
}
282
 
283
/**
284
 * Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
285
 *
286
 * @param object $userfrom the message sender
287
 * @param object $userto the message recipient
288
 * @param string $message the message
289
 * @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
290
 * @return int|false the ID of the new message or false
291
 */
292
function message_post_message($userfrom, $userto, $message, $format) {
293
    global $PAGE;
294
 
295
    $eventdata = new \core\message\message();
296
    $eventdata->courseid         = 1;
297
    $eventdata->component        = 'moodle';
298
    $eventdata->name             = 'instantmessage';
299
    $eventdata->userfrom         = $userfrom;
300
    $eventdata->userto           = $userto;
301
 
302
    //using string manager directly so that strings in the message will be in the message recipients language rather than the senders
303
    $eventdata->subject          = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
304
 
305
    if ($format == FORMAT_HTML) {
306
        $eventdata->fullmessagehtml  = $message;
307
        //some message processors may revert to sending plain text even if html is supplied
308
        //so we keep both plain and html versions if we're intending to send html
309
        $eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
310
    } else {
311
        $eventdata->fullmessage      = $message;
312
        $eventdata->fullmessagehtml  = '';
313
    }
314
 
315
    $eventdata->fullmessageformat = $format;
316
    $eventdata->smallmessage     = $message;//store the message unfiltered. Clean up on output.
317
    $eventdata->timecreated     = time();
318
    $eventdata->notification    = 0;
319
    // User image.
320
    $userpicture = new user_picture($userfrom);
321
    $userpicture->size = 1; // Use f1 size.
322
    $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
323
    $eventdata->customdata = [
324
        'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
325
        'actionbuttons' => [
326
            'send' => get_string_manager()->get_string('send', 'message', null, $eventdata->userto->lang),
327
        ],
328
        'placeholders' => [
329
            'send' => get_string_manager()->get_string('writeamessage', 'message', null, $eventdata->userto->lang),
330
        ],
331
    ];
332
    return message_send($eventdata);
333
}
334
 
335
/**
336
 * Get all message processors, validate corresponding plugin existance and
337
 * system configuration
338
 *
339
 * @param bool $ready only return ready-to-use processors
340
 * @param bool $reset Reset list of message processors (used in unit tests)
341
 * @param bool $resetonly Just reset, then exit
342
 * @return mixed $processors array of objects containing information on message processors
343
 */
344
function get_message_processors($ready = false, $reset = false, $resetonly = false) {
345
    global $DB, $CFG;
346
 
347
    static $processors;
348
    if ($reset) {
349
        $processors = array();
350
 
351
        if ($resetonly) {
352
            return $processors;
353
        }
354
    }
355
 
356
    if (empty($processors)) {
357
        // Get all processors, ensure the name column is the first so it will be the array key
358
        $processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
359
        foreach ($processors as &$processor){
360
            $processor = \core_message\api::get_processed_processor_object($processor);
361
        }
362
    }
363
    if ($ready) {
364
        // Filter out enabled and system_configured processors
365
        $readyprocessors = $processors;
366
        foreach ($readyprocessors as $readyprocessor) {
367
            if (!($readyprocessor->enabled && $readyprocessor->configured)) {
368
                unset($readyprocessors[$readyprocessor->name]);
369
            }
370
        }
371
        return $readyprocessors;
372
    }
373
 
374
    return $processors;
375
}
376
 
377
/**
378
 * Get all message providers, validate their plugin existance and
379
 * system configuration
380
 *
381
 * @return mixed $processors array of objects containing information on message processors
382
 */
383
function get_message_providers() {
384
    global $CFG, $DB;
385
 
386
    $pluginman = core_plugin_manager::instance();
387
 
388
    $providers = $DB->get_records('message_providers', null, 'name');
389
 
390
    // Remove all the providers whose plugins are disabled or don't exist
391
    foreach ($providers as $providerid => $provider) {
392
        $plugin = $pluginman->get_plugin_info($provider->component);
393
        if ($plugin) {
394
            if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
395
                unset($providers[$providerid]);   // Plugins does not exist
396
                continue;
397
            }
398
            if ($plugin->is_enabled() === false) {
399
                unset($providers[$providerid]);   // Plugin disabled
400
                continue;
401
            }
402
        }
403
    }
404
    return $providers;
405
}
406
 
407
/**
408
 * Get an instance of the message_output class for one of the output plugins.
409
 * @param string $type the message output type. E.g. 'email' or 'jabber'.
410
 * @return message_output message_output the requested class.
411
 */
412
function get_message_processor($type) {
413
    global $CFG;
414
 
415
    // Note, we cannot use the get_message_processors function here, becaues this
416
    // code is called during install after installing each messaging plugin, and
417
    // get_message_processors caches the list of installed plugins.
418
 
419
    $processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
420
    if (!is_readable($processorfile)) {
421
        throw new coding_exception('Unknown message processor type ' . $type);
422
    }
423
 
424
    include_once($processorfile);
425
 
426
    $processclass = 'message_output_' . $type;
427
    if (!class_exists($processclass)) {
428
        throw new coding_exception('Message processor ' . $type .
429
                ' does not define the right class');
430
    }
431
 
432
    return new $processclass();
433
}
434
 
435
/**
436
 * Get messaging outputs default (site) preferences
437
 *
438
 * @return object $processors object containing information on message processors
439
 */
440
function get_message_output_default_preferences() {
441
    return get_config('message');
442
}
443
 
444
/**
445
 * Translate message default settings from binary value to the array of string
446
 * representing the settings to be stored. Also validate the provided value and
447
 * use default if it is malformed.
448
 *
449
 * @param  int    $plugindefault Default setting suggested by plugin
450
 * @param  string $processorname The name of processor
451
 * @return array  $settings array of strings in the order: $locked, $enabled.
452
 */
453
function translate_message_default_setting($plugindefault, $processorname) {
454
 
455
    // Define the default setting.
456
    $processor = get_message_processor($processorname);
457
    $default = $processor->get_default_messaging_settings();
458
 
459
    // Validate the value. It should not exceed the maximum size
460
    if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
461
        debugging(get_string('errortranslatingdefault', 'message'));
462
        $plugindefault = $default;
463
    }
464
    // Use plugin default setting of 'permitted' is 0
465
    if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
466
        $plugindefault = $default;
467
    }
468
 
469
    $locked = false;
470
    $enabled = false;
471
 
472
    $permitted = $plugindefault & MESSAGE_PERMITTED_MASK;
473
    switch ($permitted) {
474
        case MESSAGE_FORCED:
475
            $locked = true;
476
            $enabled = true;
477
            break;
478
        case MESSAGE_DISALLOWED:
479
            $locked = true;
480
            $enabled = false;
481
            break;
482
        default:
483
            $locked = false;
484
            // It's equivalent to logged in.
485
            $enabled = $plugindefault & MESSAGE_DEFAULT_ENABLED == MESSAGE_DEFAULT_ENABLED;
486
            break;
487
    }
488
 
489
    return array($locked, $enabled);
490
}
491
 
492
/**
493
 * Return a list of page types
494
 *
495
 * @param string $pagetype current page type
496
 * @param context|null $parentcontext Block's parent context
497
 * @param context|null $currentcontext Current context of block
498
 * @return array
499
 */
500
function message_page_type_list(string $pagetype, ?context $parentcontext, ?context $currentcontext): array {
501
    return [
502
        'message-*' => get_string('page-message-x', 'message'),
503
    ];
504
}
505
 
506
/**
507
 * Get messages sent or/and received by the specified users.
508
 * Please note that this function return deleted messages too. Besides, only individual conversation messages
509
 * are returned to maintain backwards compatibility.
510
 *
511
 * @param  int      $useridto       the user id who received the message
512
 * @param  int      $useridfrom     the user id who sent the message. -10 or -20 for no-reply or support user
513
 * @param  int      $notifications  1 for retrieving notifications, 0 for messages, -1 for both
514
 * @param  int      $read           Either MESSAGE_GET_READ, MESSAGE_GET_UNREAD or MESSAGE_GET_READ_AND_UNREAD.
515
 * @param  string   $sort           the column name to order by including optionally direction
516
 * @param  int      $limitfrom      limit from
517
 * @param  int      $limitnum       limit num
518
 * @return external_description
519
 * @since  2.8
520
 */
521
function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = MESSAGE_GET_READ,
522
                                $sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
523
    global $DB;
524
 
525
    if (is_bool($read)) {
526
        // Backwards compatibility, this parameter was a bool before 4.0.
527
        $read = (int) $read;
528
    }
529
 
530
    // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
531
    $userfieldsapi = \core_user\fields::for_name();
532
    if (empty($useridto)) {
533
        $userfields = $userfieldsapi->get_sql('u', false, 'userto', '', false)->selects;
534
        $messageuseridtosql = 'u.id as useridto';
535
    } else {
536
        $userfields = $userfieldsapi->get_sql('u', false, 'userfrom', '', false)->selects;
537
        $messageuseridtosql = "$useridto as useridto";
538
    }
539
 
540
    // Create the SQL we will be using.
541
    $messagesql = "SELECT mr.*, $userfields, 0 as notification, '' as contexturl, '' as contexturlname,
542
                          mua.timecreated as timeusertodeleted, mua2.timecreated as timeread,
543
                          mua3.timecreated as timeuserfromdeleted, $messageuseridtosql
544
                     FROM {messages} mr
545
               INNER JOIN {message_conversations} mc
546
                       ON mc.id = mr.conversationid
547
               INNER JOIN {message_conversation_members} mcm
548
                       ON mcm.conversationid = mc.id ";
549
 
550
    $notificationsql = "SELECT mr.*, $userfields, 1 as notification
551
                          FROM {notifications} mr ";
552
 
553
    $messagejoinsql = "LEFT JOIN {message_user_actions} mua
554
                              ON (mua.messageid = mr.id AND mua.userid = mcm.userid AND mua.action = ?)
555
                       LEFT JOIN {message_user_actions} mua2
556
                              ON (mua2.messageid = mr.id AND mua2.userid = mcm.userid AND mua2.action = ?)
557
                       LEFT JOIN {message_user_actions} mua3
558
                              ON (mua3.messageid = mr.id AND mua3.userid = mr.useridfrom AND mua3.action = ?)";
559
    $messagejoinparams = [\core_message\api::MESSAGE_ACTION_DELETED, \core_message\api::MESSAGE_ACTION_READ,
560
        \core_message\api::MESSAGE_ACTION_DELETED];
561
    $notificationsparams = [];
562
 
563
    // If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
564
    if (empty($useridto)) {
565
        // Create the messaging query and params.
566
        $messagesql .= "INNER JOIN {user} u
567
                                ON u.id = mcm.userid
568
                                $messagejoinsql
569
                             WHERE mr.useridfrom = ?
570
                               AND mr.useridfrom != mcm.userid
571
                               AND u.deleted = 0
572
                               AND mc.type = ? ";
573
        $messageparams = array_merge($messagejoinparams, [$useridfrom, \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL]);
574
 
575
        // Create the notifications query and params.
576
        $notificationsql .= "INNER JOIN {user} u
577
                                     ON u.id = mr.useridto
578
                                  WHERE mr.useridfrom = ?
579
                                    AND u.deleted = 0 ";
580
        $notificationsparams[] = $useridfrom;
581
    } else {
582
        // Create the messaging query and params.
583
        // Left join because useridfrom may be -10 or -20 (no-reply and support users).
584
        $messagesql .= "LEFT JOIN {user} u
585
                               ON u.id = mr.useridfrom
586
                               $messagejoinsql
587
                            WHERE mcm.userid = ?
588
                              AND mr.useridfrom != mcm.userid
589
                              AND u.deleted = 0
590
                              AND mc.type = ? ";
591
        $messageparams = array_merge($messagejoinparams, [$useridto, \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL]);
592
 
593
        // If we're dealing with messages only and both useridto and useridfrom are set,
594
        // try to get a conversation between the users. Break early if we can't find one.
595
        if (!empty($useridfrom) && $notifications == 0) {
596
            $messagesql .= " AND mr.useridfrom = ? ";
597
            $messageparams[] = $useridfrom;
598
 
599
            // There should be an individual conversation between the users. If not, we can return early.
600
            $conversationid = \core_message\api::get_conversation_between_users([$useridto, $useridfrom]);
601
            if (empty($conversationid)) {
602
                return [];
603
            }
604
            $messagesql .= " AND mc.id = ? ";
605
            $messageparams[] = $conversationid;
606
        }
607
 
608
        // Create the notifications query and params.
609
        // Left join because useridfrom may be -10 or -20 (no-reply and support users).
610
        $notificationsql .= "LEFT JOIN {user} u
611
                                    ON (u.id = mr.useridfrom AND u.deleted = 0)
612
                                 WHERE mr.useridto = ? ";
613
        $notificationsparams[] = $useridto;
614
        if (!empty($useridfrom)) {
615
            $notificationsql .= " AND mr.useridfrom = ? ";
616
            $notificationsparams[] = $useridfrom;
617
        }
618
    }
619
    if ($read === MESSAGE_GET_READ) {
620
        $notificationsql .= "AND mr.timeread IS NOT NULL ";
621
    } else if ($read === MESSAGE_GET_UNREAD) {
622
        $notificationsql .= "AND mr.timeread IS NULL ";
623
    }
624
    $messagesql .= "ORDER BY $sort";
625
    $notificationsql .= "ORDER BY $sort";
626
 
627
    // Handle messages if needed.
628
    if ($notifications === -1 || $notifications === 0) {
629
        $messages = $DB->get_records_sql($messagesql, $messageparams, $limitfrom, $limitnum);
630
        if ($read !== MESSAGE_GET_READ_AND_UNREAD) {
631
            // Get rid of the messages that have either been read or not read depending on the value of $read.
632
            $messages = array_filter($messages, function ($message) use ($read) {
633
                if ($read === MESSAGE_GET_READ) {
634
                    return !is_null($message->timeread);
635
                }
636
 
637
                return is_null($message->timeread);
638
            });
639
        }
640
    }
641
 
642
    // All.
643
    if ($notifications === -1) {
644
        return array_merge($messages, $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum));
645
    } else if ($notifications === 1) { // Just notifications.
646
        return $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum);
647
    }
648
 
649
    // Just messages.
650
    return $messages;
651
}
652
 
653
/**
654
 * Handles displaying processor settings in a fragment.
655
 *
656
 * @param array $args
657
 * @return bool|string
658
 * @throws moodle_exception
659
 */
660
function message_output_fragment_processor_settings($args = []) {
661
    global $PAGE;
662
 
663
    if (!isset($args['type'])) {
664
        throw new moodle_exception('Must provide a processor type');
665
    }
666
 
667
    if (!isset($args['userid'])) {
668
        throw new moodle_exception('Must provide a userid');
669
    }
670
 
671
    $type = clean_param($args['type'], PARAM_SAFEDIR);
672
    $userid = clean_param($args['userid'], PARAM_INT);
673
 
674
    $user = core_user::get_user($userid, '*', MUST_EXIST);
675
    if (!core_message_can_edit_message_profile($user)) {
676
        throw new moodle_exception('Cannot edit message profile');
677
    }
678
 
679
    $processor = get_message_processor($type);
680
    $providers = message_get_providers_for_user($userid);
681
    $processorwrapper = new stdClass();
682
    $processorwrapper->object = $processor;
683
    $preferences = \core_message\api::get_all_message_preferences([$processorwrapper], $providers, $user);
684
 
685
    $processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type);
686
    $renderer = $PAGE->get_renderer('core', 'message');
687
 
688
    return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));
689
}
690
 
691
/**
692
 * Checks if current user is allowed to edit messaging preferences of another user
693
 *
694
 * @param stdClass $user user whose preferences we are updating
695
 * @return bool
696
 */
697
function core_message_can_edit_message_profile($user) {
698
    global $USER;
699
    if ($user->id == $USER->id) {
700
        return has_capability('moodle/user:editownmessageprofile', context_system::instance());
701
    } else {
702
        $personalcontext = context_user::instance($user->id);
703
        if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
704
            return false;
705
        }
706
        if (isguestuser($user)) {
707
            return false;
708
        }
709
        // No editing of admins by non-admins.
710
        if (is_siteadmin($user) and !is_siteadmin($USER)) {
711
            return false;
712
        }
713
        return true;
714
    }
715
}
716
 
717
/**
718
 * Implements callback user_preferences, lists preferences that users are allowed to update directly
719
 *
720
 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
721
 *
722
 * @return array
723
 */
724
function core_message_user_preferences() {
725
    $preferences = [];
726
    $preferences['message_blocknoncontacts'] = array(
727
        'type' => PARAM_INT,
728
        'null' => NULL_NOT_ALLOWED,
729
        'default' => 0,
730
        'choices' => array(
731
            \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
732
            \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
733
            \core_message\api::MESSAGE_PRIVACY_SITE
734
        ),
735
        'cleancallback' => function ($value) {
736
            global $CFG;
737
 
738
            // When site-wide messaging between users is disabled, MESSAGE_PRIVACY_SITE should be converted.
739
            if (empty($CFG->messagingallusers) && $value === \core_message\api::MESSAGE_PRIVACY_SITE) {
740
                return \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER;
741
            }
742
            return $value;
743
        }
744
    );
745
    $preferences['message_entertosend'] = array(
746
        'type' => PARAM_BOOL,
747
        'null' => NULL_NOT_ALLOWED,
748
        'default' => false
749
    );
750
    $preferences['/^message_provider_([\w\d_]*)_enabled$/'] = array('isregex' => true, 'type' => PARAM_NOTAGS,
751
        'null' => NULL_NOT_ALLOWED, 'default' => 'none',
752
        'permissioncallback' => function ($user, $preferencename) {
753
            global $CFG;
754
            require_once($CFG->libdir.'/messagelib.php');
755
            if (core_message_can_edit_message_profile($user) &&
756
                    preg_match('/^message_provider_([\w\d_]*)_enabled$/', $preferencename, $matches)) {
757
                $providers = message_get_providers_for_user($user->id);
758
                foreach ($providers as $provider) {
759
                    if ($matches[1] === $provider->component . '_' . $provider->name) {
760
                       return true;
761
                    }
762
                }
763
            }
764
            return false;
765
        },
766
        'cleancallback' => function ($value, $preferencename) {
767
            if ($value === 'none' || empty($value)) {
768
                return 'none';
769
            }
770
            $parts = explode('/,/', $value);
771
            $processors = array_keys(get_message_processors());
772
            array_filter($parts, function($v) use ($processors) {return in_array($v, $processors);});
773
            return $parts ? join(',', $parts) : 'none';
774
        });
775
    return $preferences;
776
}