forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.php
3083 lines (2703 loc) · 131 KB
/
api.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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/>.
/**
* Contains class used to return information to display for the message area.
*
* @package core_message
* @copyright 2016 Mark Nelson <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message;
use core_favourites\local\entity\favourite;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/lib/messagelib.php');
/**
* Class used to return information to display for the message area.
*
* @copyright 2016 Mark Nelson <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class api {
/**
* The action for reading a message.
*/
const MESSAGE_ACTION_READ = 1;
/**
* The action for deleting a message.
*/
const MESSAGE_ACTION_DELETED = 2;
/**
* The action for reading a message.
*/
const CONVERSATION_ACTION_MUTED = 1;
/**
* The privacy setting for being messaged by anyone within courses user is member of.
*/
const MESSAGE_PRIVACY_COURSEMEMBER = 0;
/**
* The privacy setting for being messaged only by contacts.
*/
const MESSAGE_PRIVACY_ONLYCONTACTS = 1;
/**
* The privacy setting for being messaged by anyone on the site.
*/
const MESSAGE_PRIVACY_SITE = 2;
/**
* An individual conversation.
*/
const MESSAGE_CONVERSATION_TYPE_INDIVIDUAL = 1;
/**
* A group conversation.
*/
const MESSAGE_CONVERSATION_TYPE_GROUP = 2;
/**
* A self conversation.
*/
const MESSAGE_CONVERSATION_TYPE_SELF = 3;
/**
* The state for an enabled conversation area.
*/
const MESSAGE_CONVERSATION_ENABLED = 1;
/**
* The state for a disabled conversation area.
*/
const MESSAGE_CONVERSATION_DISABLED = 0;
/**
* The max message length.
*/
const MESSAGE_MAX_LENGTH = 4096;
/**
* Handles searching for messages in the message area.
*
* @param int $userid The user id doing the searching
* @param string $search The string the user is searching
* @param int $limitfrom
* @param int $limitnum
* @return array
*/
public static function search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
global $DB;
// Get the user fields we want.
$userfieldsapi = \core_user\fields::for_userpic()->including('lastaccess');
$ufields = $userfieldsapi->get_sql('u', false, 'userfrom_', '', false)->selects;
$ufields2 = $userfieldsapi->get_sql('u2', false, 'userto_', '', false)->selects;
// Add the uniqueid column to make each row unique and avoid SQL errors.
$uniqueidsql = $DB->sql_concat('m.id', "'_'", 'm.useridfrom', "'_'", 'mcm.userid');
$sql = "SELECT $uniqueidsql AS uniqueid, m.id, m.useridfrom, mcm.userid as useridto, m.subject, m.fullmessage,
m.fullmessagehtml, m.fullmessageformat, m.smallmessage, m.conversationid, m.timecreated, 0 as isread,
$ufields, mub.id as userfrom_blocked, $ufields2, mub2.id as userto_blocked
FROM {messages} m
INNER JOIN {user} u
ON u.id = m.useridfrom
INNER JOIN {message_conversations} mc
ON mc.id = m.conversationid
INNER JOIN {message_conversation_members} mcm
ON mcm.conversationid = m.conversationid
INNER JOIN {user} u2
ON u2.id = mcm.userid
LEFT JOIN {message_users_blocked} mub
ON (mub.blockeduserid = u.id AND mub.userid = ?)
LEFT JOIN {message_users_blocked} mub2
ON (mub2.blockeduserid = u2.id AND mub2.userid = ?)
LEFT JOIN {message_user_actions} mua
ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
WHERE (m.useridfrom = ? OR mcm.userid = ?)
AND (m.useridfrom != mcm.userid OR mc.type = ?)
AND u.deleted = 0
AND u2.deleted = 0
AND mua.id is NULL
AND " . $DB->sql_like('smallmessage', '?', false) . "
ORDER BY timecreated DESC";
$params = array($userid, $userid, $userid, self::MESSAGE_ACTION_DELETED, $userid, $userid,
self::MESSAGE_CONVERSATION_TYPE_SELF, '%' . $search . '%');
// Convert the messages into searchable contacts with their last message being the message that was searched.
$conversations = array();
if ($messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum)) {
foreach ($messages as $message) {
$prefix = 'userfrom_';
if ($userid == $message->useridfrom) {
$prefix = 'userto_';
// If it from the user, then mark it as read, even if it wasn't by the receiver.
$message->isread = true;
}
$blockedcol = $prefix . 'blocked';
$message->blocked = $message->$blockedcol ? 1 : 0;
$message->messageid = $message->id;
// To avoid duplicate messages, only add the message if it hasn't been added previously.
if (!array_key_exists($message->messageid, $conversations)) {
$conversations[$message->messageid] = helper::create_contact($message, $prefix);
}
}
// Remove the messageid keys (to preserve the expected type).
$conversations = array_values($conversations);
}
return $conversations;
}
/**
* @deprecated since 3.6
*/
public static function search_users_in_course() {
throw new \coding_exception('\core_message\api::search_users_in_course has been removed.');
}
/**
* @deprecated since 3.6
*/
public static function search_users() {
throw new \coding_exception('\core_message\api::search_users has been removed.');
}
/**
* Handles searching for user.
*
* @param int $userid The user id doing the searching
* @param string $search The string the user is searching
* @param int $limitfrom
* @param int $limitnum
* @return array
*/
public static function message_search_users(int $userid, string $search, int $limitfrom = 0, int $limitnum = 20) : array {
global $CFG, $DB;
// Check if messaging is enabled.
if (empty($CFG->messaging)) {
throw new \moodle_exception('disabled', 'message');
}
// Used to search for contacts.
$fullname = $DB->sql_fullname();
// Users not to include.
$excludeusers = array($CFG->siteguest);
if (!$selfconversation = self::get_self_conversation($userid)) {
// Userid should only be excluded when she hasn't a self-conversation.
$excludeusers[] = $userid;
}
list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);
$params = array('search' => '%' . $DB->sql_like_escape($search) . '%', 'userid1' => $userid, 'userid2' => $userid);
// Ok, let's search for contacts first.
$sql = "SELECT u.id
FROM {user} u
JOIN {message_contacts} mc
ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
WHERE u.deleted = 0
AND u.confirmed = 1
AND " . $DB->sql_like($fullname, ':search', false) . "
AND u.id $exclude
ORDER BY " . $DB->sql_fullname();
$foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);
$contacts = [];
if (!empty($foundusers)) {
$contacts = helper::get_member_info($userid, array_keys($foundusers));
foreach ($contacts as $memberuserid => $memberinfo) {
$contacts[$memberuserid]->conversations = self::get_conversations_between_users($userid, $memberuserid, 0, 1000);
}
}
// Let's get those non-contacts.
// Because we can't achieve all the required visibility checks in SQL, we'll iterate through the non-contact records
// and stop once we have enough matching the 'visible' criteria.
// Use a local generator to achieve this iteration.
$getnoncontactusers = function ($limitfrom = 0, $limitnum = 0) use (
$fullname,
$exclude,
$params,
$excludeparams,
$userid,
$selfconversation
) {
global $DB, $CFG;
$joinenrolled = '';
$enrolled = '';
$unionself = '';
$enrolledparams = [];
// Since we want to order a UNION we need to list out all the user fields individually this will
// allow us to reference the fullname correctly.
$userfields = implode(', u.', get_user_fieldnames());
$select = "u.id, " . $DB->sql_fullname() ." AS sortingname, u." . $userfields;
// When messageallusers is false valid non-contacts must be enrolled on one of the users courses.
if (empty($CFG->messagingallusers)) {
$joinenrolled = "JOIN {user_enrolments} ue ON ue.userid = u.id
JOIN {enrol} e ON e.id = ue.enrolid";
$enrolled = "AND e.courseid IN (
SELECT e.courseid
FROM {user_enrolments} ue
JOIN {enrol} e ON e.id = ue.enrolid
WHERE ue.userid = :enroluserid
)";
if ($selfconversation !== false) {
// We must include the user themselves, when they have a self conversation, even if they are not
// enrolled on any courses.
$unionself = "UNION SELECT u.id FROM {user} u
WHERE u.id = :self AND ". $DB->sql_like($fullname, ':selfsearch', false);
}
$enrolledparams = ['enroluserid' => $userid, 'self' => $userid, 'selfsearch' => $params['search']];
}
$sql = "SELECT $select
FROM (
SELECT DISTINCT u.id
FROM {user} u $joinenrolled
WHERE u.deleted = 0
AND u.confirmed = 1
AND " . $DB->sql_like($fullname, ':search', false) . "
AND u.id $exclude $enrolled
AND NOT EXISTS (SELECT mc.id
FROM {message_contacts} mc
WHERE (mc.userid = u.id AND mc.contactid = :userid1)
OR (mc.userid = :userid2 AND mc.contactid = u.id)) $unionself
) targetedusers
JOIN {user} u ON u.id = targetedusers.id
ORDER BY 2";
while ($records = $DB->get_records_sql($sql, $params + $excludeparams + $enrolledparams, $limitfrom, $limitnum)) {
yield $records;
$limitfrom += $limitnum;
}
};
// Fetch in batches of $limitnum * 2 to improve the chances of matching a user without going back to the DB.
// The generator cannot function without a sensible limiter, so set one if this is not set.
$batchlimit = ($limitnum == 0) ? 20 : $limitnum;
// We need to make the offset param work with the generator.
// Basically, if we want to get say 10 records starting at the 40th record, we need to see 50 records and return only
// those after the 40th record. We can never pass the method's offset param to the generator as we need to manage the
// position within those valid records ourselves.
// See MDL-63983 dealing with performance improvements to this area of code.
$noofvalidseenrecords = 0;
$returnedusers = [];
foreach ($getnoncontactusers(0, $batchlimit) as $users) {
foreach ($users as $id => $user) {
// User visibility checks: only return users who are visible to the user performing the search.
// Which visibility check to use depends on the 'messagingallusers' (site wide messaging) setting:
// - If enabled, return matched users whose profiles are visible to the current user anywhere (site or course).
// - If disabled, only return matched users whose course profiles are visible to the current user.
$userdetails = \core_message\helper::search_get_user_details($user);
// Return the user only if the searched field is returned.
// Otherwise it means that the $USER was not allowed to search the returned user.
if (!empty($userdetails) and !empty($userdetails['fullname'])) {
// We know we've matched, but only save the record if it's within the offset area we need.
if ($limitfrom == 0) {
// No offset specified, so just save.
$returnedusers[$id] = $user;
} else {
// There is an offset in play.
// If we've passed enough records already (> offset value), then we can save this one.
if ($noofvalidseenrecords >= $limitfrom) {
$returnedusers[$id] = $user;
}
}
if (count($returnedusers) == $limitnum) {
break 2;
}
$noofvalidseenrecords++;
}
}
}
$foundusers = $returnedusers;
$noncontacts = [];
if (!empty($foundusers)) {
$noncontacts = helper::get_member_info($userid, array_keys($foundusers));
foreach ($noncontacts as $memberuserid => $memberinfo) {
if ($memberuserid !== $userid) {
$noncontacts[$memberuserid]->conversations = self::get_conversations_between_users($userid, $memberuserid, 0,
1000);
} else {
$noncontacts[$memberuserid]->conversations[$selfconversation->id] = $selfconversation;
}
}
}
return array(array_values($contacts), array_values($noncontacts));
}
/**
* Gets extra fields, like image url and subname for any conversations linked to components.
*
* The subname is like a subtitle for the conversation, to compliment it's name.
* The imageurl is the location of the image for the conversation, as might be seen on a listing of conversations for a user.
*
* @param array $conversations a list of conversations records.
* @return array the array of subnames, index by conversation id.
* @throws \coding_exception
* @throws \dml_exception
*/
protected static function get_linked_conversation_extra_fields(array $conversations) : array {
global $DB, $PAGE;
$renderer = $PAGE->get_renderer('core');
$linkedconversations = [];
foreach ($conversations as $conversation) {
if (!is_null($conversation->component) && !is_null($conversation->itemtype)) {
$linkedconversations[$conversation->component][$conversation->itemtype][$conversation->id]
= $conversation->itemid;
}
}
if (empty($linkedconversations)) {
return [];
}
// TODO: MDL-63814: Working out the subname for linked conversations should be done in a generic way.
// Get the itemid, but only for course group linked conversation for now.
$extrafields = [];
if (!empty($linkeditems = $linkedconversations['core_group']['groups'])) { // Format: [conversationid => itemid].
// Get the name of the course to which the group belongs.
list ($groupidsql, $groupidparams) = $DB->get_in_or_equal(array_values($linkeditems), SQL_PARAMS_NAMED, 'groupid');
$sql = "SELECT g.*, c.shortname as courseshortname
FROM {groups} g
JOIN {course} c
ON g.courseid = c.id
WHERE g.id $groupidsql";
$courseinfo = $DB->get_records_sql($sql, $groupidparams);
foreach ($linkeditems as $convid => $groupid) {
if (array_key_exists($groupid, $courseinfo)) {
$group = $courseinfo[$groupid];
// Subname.
$extrafields[$convid]['subname'] = format_string($courseinfo[$groupid]->courseshortname);
// Imageurl.
$extrafields[$convid]['imageurl'] = $renderer->image_url('g/g1')->out(false); // default image.
if ($url = get_group_picture_url($group, $group->courseid, true)) {
$extrafields[$convid]['imageurl'] = $url->out(false);
}
}
}
}
return $extrafields;
}
/**
* Returns the contacts and their conversation to display in the contacts area.
*
* ** WARNING **
* It is HIGHLY recommended to use a sensible limit when calling this function. Trying
* to retrieve too much information in a single call will cause performance problems.
* ** WARNING **
*
* This function has specifically been altered to break each of the data sets it
* requires into separate database calls. This is to avoid the performance problems
* observed when attempting to join large data sets (e.g. the message tables and
* the user table).
*
* While it is possible to gather the data in a single query, and it may even be
* more efficient with a correctly tuned database, we have opted to trade off some of
* the benefits of a single query in order to ensure this function will work on
* most databases with default tunings and with large data sets.
*
* @param int $userid The user id
* @param int $limitfrom
* @param int $limitnum
* @param int $type the type of the conversation, if you wish to filter to a certain type (see api constants).
* @param bool $favourites whether to include NO favourites (false) or ONLY favourites (true), or null to ignore this setting.
* @param bool $mergeself whether to include self-conversations (true) or ONLY private conversations (false)
* when private conversations are requested.
* @return array the array of conversations
* @throws \moodle_exception
*/
public static function get_conversations($userid, $limitfrom = 0, $limitnum = 20, int $type = null,
bool $favourites = null, bool $mergeself = false) {
global $DB;
if (!is_null($type) && !in_array($type, [self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
self::MESSAGE_CONVERSATION_TYPE_GROUP, self::MESSAGE_CONVERSATION_TYPE_SELF])) {
throw new \moodle_exception("Invalid value ($type) for type param, please see api constants.");
}
self::lazy_create_self_conversation($userid);
// We need to know which conversations are favourites, so we can either:
// 1) Include the 'isfavourite' attribute on conversations (when $favourite = null and we're including all conversations)
// 2) Restrict the results to ONLY those conversations which are favourites (when $favourite = true)
// 3) Restrict the results to ONLY those conversations which are NOT favourites (when $favourite = false).
$service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
$favouriteconversations = $service->find_favourites_by_type('core_message', 'message_conversations');
$favouriteconversationids = array_column($favouriteconversations, 'itemid');
if ($favourites && empty($favouriteconversationids)) {
return []; // If we are aiming to return ONLY favourites, and we have none, there's nothing more to do.
}
// CONVERSATIONS AND MOST RECENT MESSAGE.
// Include those conversations with messages first (ordered by most recent message, desc), then add any conversations which
// don't have messages, such as newly created group conversations.
// Because we're sorting by message 'timecreated', those conversations without messages could be at either the start or the
// end of the results (behaviour for sorting of nulls differs between DB vendors), so we use the case to presort these.
// If we need to return ONLY favourites, or NO favourites, generate the SQL snippet.
$favouritesql = "";
$favouriteparams = [];
if (null !== $favourites && !empty($favouriteconversationids)) {
list ($insql, $favouriteparams) =
$DB->get_in_or_equal($favouriteconversationids, SQL_PARAMS_NAMED, 'favouriteids', $favourites);
$favouritesql = " AND mc.id {$insql} ";
}
// If we need to restrict type, generate the SQL snippet.
$typesql = "";
$typeparams = [];
if (!is_null($type)) {
if ($mergeself && $type == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
// When $megerself is set to true, the self-conversations are returned also with the private conversations.
$typesql = " AND (mc.type = :convtype1 OR mc.type = :convtype2) ";
$typeparams = ['convtype1' => $type, 'convtype2' => self::MESSAGE_CONVERSATION_TYPE_SELF];
} else {
$typesql = " AND mc.type = :convtype ";
$typeparams = ['convtype' => $type];
}
}
$sql = "SELECT m.id as messageid, mc.id as id, mc.name as conversationname, mc.type as conversationtype, m.useridfrom,
m.smallmessage, m.fullmessage, m.fullmessageformat, m.fullmessagetrust, m.fullmessagehtml, m.timecreated,
mc.component, mc.itemtype, mc.itemid, mc.contextid, mca.action as ismuted
FROM {message_conversations} mc
INNER JOIN {message_conversation_members} mcm
ON (mcm.conversationid = mc.id AND mcm.userid = :userid3)
LEFT JOIN (
SELECT m.conversationid, MAX(m.id) AS messageid
FROM {messages} m
INNER JOIN (
SELECT m.conversationid, MAX(m.timecreated) as maxtime
FROM {messages} m
INNER JOIN {message_conversation_members} mcm
ON mcm.conversationid = m.conversationid
LEFT JOIN {message_user_actions} mua
ON (mua.messageid = m.id AND mua.userid = :userid AND mua.action = :action)
WHERE mua.id is NULL
AND mcm.userid = :userid2
GROUP BY m.conversationid
) maxmessage
ON maxmessage.maxtime = m.timecreated AND maxmessage.conversationid = m.conversationid
GROUP BY m.conversationid
) lastmessage
ON lastmessage.conversationid = mc.id
LEFT JOIN {messages} m
ON m.id = lastmessage.messageid
LEFT JOIN {message_conversation_actions} mca
ON (mca.conversationid = mc.id AND mca.userid = :userid4 AND mca.action = :convaction)
WHERE mc.id IS NOT NULL
AND mc.enabled = 1 $typesql $favouritesql
ORDER BY (CASE WHEN m.timecreated IS NULL THEN 0 ELSE 1 END) DESC, m.timecreated DESC, id DESC";
$params = array_merge($favouriteparams, $typeparams, ['userid' => $userid, 'action' => self::MESSAGE_ACTION_DELETED,
'userid2' => $userid, 'userid3' => $userid, 'userid4' => $userid, 'convaction' => self::CONVERSATION_ACTION_MUTED]);
$conversationset = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
$conversations = [];
$selfconversations = []; // Used to track conversations with one's self.
$members = [];
$individualmembers = [];
$groupmembers = [];
$selfmembers = [];
foreach ($conversationset as $conversation) {
$conversations[$conversation->id] = $conversation;
$members[$conversation->id] = [];
}
$conversationset->close();
// If there are no conversations found, then return early.
if (empty($conversations)) {
return [];
}
// COMPONENT-LINKED CONVERSATION FIELDS.
// Conversations linked to components may have extra information, such as:
// - subname: Essentially a subtitle for the conversation. So you'd have "name: subname".
// - imageurl: A URL to the image for the linked conversation.
// For now, this is ONLY course groups.
$convextrafields = self::get_linked_conversation_extra_fields($conversations);
// MEMBERS.
// Ideally, we want to get 1 member for each conversation, but this depends on the type and whether there is a recent
// message or not.
//
// For 'individual' type conversations between 2 users, regardless of who sent the last message,
// we want the details of the other member in the conversation (i.e. not the current user).
//
// For 'group' type conversations, we want the details of the member who sent the last message, if there is one.
// This can be the current user or another group member, but for groups without messages, this will be empty.
//
// For 'self' type conversations, we want the details of the current user.
//
// This also means that if type filtering is specified and only group conversations are returned, we don't need this extra
// query to get the 'other' user as we already have that information.
// Work out which members we have already, and which ones we might need to fetch.
// If all the last messages were from another user, then we don't need to fetch anything further.
foreach ($conversations as $conversation) {
if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
if (!is_null($conversation->useridfrom) && $conversation->useridfrom != $userid) {
$members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
$individualmembers[$conversation->useridfrom] = $conversation->useridfrom;
} else {
$individualconversations[] = $conversation->id;
}
} else if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
// If we have a recent message, the sender is our member.
if (!is_null($conversation->useridfrom)) {
$members[$conversation->id][$conversation->useridfrom] = $conversation->useridfrom;
$groupmembers[$conversation->useridfrom] = $conversation->useridfrom;
}
} else if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_SELF) {
$selfconversations[$conversation->id] = $conversation->id;
$members[$conversation->id][$userid] = $userid;
$selfmembers[$userid] = $userid;
}
}
// If we need to fetch any member information for any of the individual conversations.
// This is the case if any of the individual conversations have a recent message sent by the current user.
if (!empty($individualconversations)) {
list ($icidinsql, $icidinparams) = $DB->get_in_or_equal($individualconversations, SQL_PARAMS_NAMED, 'convid');
$indmembersql = "SELECT mcm.id, mcm.conversationid, mcm.userid
FROM {message_conversation_members} mcm
WHERE mcm.conversationid $icidinsql
AND mcm.userid != :userid
ORDER BY mcm.id";
$indmemberparams = array_merge($icidinparams, ['userid' => $userid]);
$conversationmembers = $DB->get_records_sql($indmembersql, $indmemberparams);
foreach ($conversationmembers as $mid => $member) {
$members[$member->conversationid][$member->userid] = $member->userid;
$individualmembers[$member->userid] = $member->userid;
}
}
// We could fail early here if we're sure that:
// a) we have no otherusers for all the conversations (users may have been deleted)
// b) we're sure that all conversations are individual (1:1).
// We need to pull out the list of users info corresponding to the memberids in the conversations.This
// needs to be done in a separate query to avoid doing a join on the messages tables and the user
// tables because on large sites these tables are massive which results in extremely slow
// performance (typically due to join buffer exhaustion).
if (!empty($individualmembers) || !empty($groupmembers) || !empty($selfmembers)) {
// Now, we want to remove any duplicates from the group members array. For individual members we will
// be doing a more extensive call as we want their contact requests as well as privacy information,
// which is not necessary for group conversations.
$diffgroupmembers = array_diff($groupmembers, $individualmembers);
$individualmemberinfo = helper::get_member_info($userid, $individualmembers, true, true);
$groupmemberinfo = helper::get_member_info($userid, $diffgroupmembers);
$selfmemberinfo = helper::get_member_info($userid, $selfmembers);
// Don't use array_merge, as we lose array keys.
$memberinfo = $individualmemberinfo + $groupmemberinfo + $selfmemberinfo;
if (empty($memberinfo)) {
return [];
}
// Update the members array with the member information.
$deletedmembers = [];
foreach ($members as $convid => $memberarr) {
foreach ($memberarr as $key => $memberid) {
if (array_key_exists($memberid, $memberinfo)) {
// If the user is deleted, remember that.
if ($memberinfo[$memberid]->isdeleted) {
$deletedmembers[$convid][] = $memberid;
}
$members[$convid][$key] = clone $memberinfo[$memberid];
if ($conversations[$convid]->conversationtype == self::MESSAGE_CONVERSATION_TYPE_GROUP) {
// Remove data we don't need for group.
$members[$convid][$key]->requirescontact = null;
$members[$convid][$key]->canmessage = null;
$members[$convid][$key]->contactrequests = [];
}
} else { // Remove all members and individual conversations where we could not get the member's information.
unset($members[$convid][$key]);
// If the conversation is an individual conversation, then we should remove it from the list.
if ($conversations[$convid]->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
unset($conversations[$convid]);
}
}
}
}
}
// MEMBER COUNT.
$cids = array_column($conversations, 'id');
list ($cidinsql, $cidinparams) = $DB->get_in_or_equal($cids, SQL_PARAMS_NAMED, 'convid');
$membercountsql = "SELECT conversationid, count(DISTINCT userid) AS membercount
FROM {message_conversation_members} mcm
WHERE mcm.conversationid $cidinsql
GROUP BY mcm.conversationid";
$membercounts = $DB->get_records_sql($membercountsql, $cidinparams);
// UNREAD MESSAGE COUNT.
// Finally, let's get the unread messages count for this user so that we can add it
// to the conversation. Remember we need to ignore the messages the user sent.
$unreadcountssql = 'SELECT m.conversationid, count(m.id) as unreadcount
FROM {messages} m
INNER JOIN {message_conversations} mc
ON mc.id = m.conversationid
INNER JOIN {message_conversation_members} mcm
ON m.conversationid = mcm.conversationid
LEFT JOIN {message_user_actions} mua
ON (mua.messageid = m.id AND mua.userid = ? AND
(mua.action = ? OR mua.action = ?))
WHERE mcm.userid = ?
AND m.useridfrom != ?
AND mua.id is NULL
GROUP BY m.conversationid';
$unreadcounts = $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, self::MESSAGE_ACTION_DELETED,
$userid, $userid]);
// For the self-conversations, get the total number of messages (to know if the conversation is new or it has been emptied).
$selfmessagessql = "SELECT COUNT(m.id)
FROM {messages} m
INNER JOIN {message_conversations} mc
ON mc.id = m.conversationid
WHERE mc.type = ? AND convhash = ?";
$selfmessagestotal = $DB->count_records_sql(
$selfmessagessql,
[self::MESSAGE_CONVERSATION_TYPE_SELF, helper::get_conversation_hash([$userid])]
);
// Because we'll be calling format_string on each conversation name and passing contexts, we preload them here.
// This warms the cache and saves potentially hitting the DB once for each context fetch below.
\context_helper::preload_contexts_by_id(array_column($conversations, 'contextid'));
// Now, create the final return structure.
$arrconversations = [];
foreach ($conversations as $conversation) {
// Do not include any individual which do not contain a recent message for the user.
// This happens if the user has deleted all messages.
// Exclude the self-conversations with messages but without a recent message because the user has deleted all them.
// Self-conversations without any message should be included, to display them first time they are created.
// Group conversations with deleted users or no messages are always returned.
if ($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL && empty($conversation->messageid) ||
($conversation->conversationtype == self::MESSAGE_CONVERSATION_TYPE_SELF && empty($conversation->messageid)
&& $selfmessagestotal > 0)) {
continue;
}
$conv = new \stdClass();
$conv->id = $conversation->id;
// Name should be formatted and depends on the context the conversation resides in.
// If not set, the context is always context_user.
if (is_null($conversation->contextid)) {
$convcontext = \context_user::instance($userid);
// We'll need to check the capability to delete messages for all users in context system when contextid is null.
$contexttodeletemessageforall = \context_system::instance();
} else {
$convcontext = \context::instance_by_id($conversation->contextid);
$contexttodeletemessageforall = $convcontext;
}
$conv->name = format_string($conversation->conversationname, true, ['context' => $convcontext]);
$conv->subname = $convextrafields[$conv->id]['subname'] ?? null;
$conv->imageurl = $convextrafields[$conv->id]['imageurl'] ?? null;
$conv->type = $conversation->conversationtype;
$conv->membercount = $membercounts[$conv->id]->membercount;
$conv->isfavourite = in_array($conv->id, $favouriteconversationids);
$conv->isread = isset($unreadcounts[$conv->id]) ? false : true;
$conv->unreadcount = isset($unreadcounts[$conv->id]) ? $unreadcounts[$conv->id]->unreadcount : null;
$conv->ismuted = $conversation->ismuted ? true : false;
$conv->members = $members[$conv->id];
// Add the most recent message information.
$conv->messages = [];
// Add if the user has to allow delete messages for all users in the conversation.
$conv->candeletemessagesforallusers = has_capability('moodle/site:deleteanymessage', $contexttodeletemessageforall);
if ($conversation->smallmessage) {
$msg = new \stdClass();
$msg->id = $conversation->messageid;
$msg->text = message_format_message_text($conversation);
$msg->useridfrom = $conversation->useridfrom;
$msg->timecreated = $conversation->timecreated;
$conv->messages[] = $msg;
}
$arrconversations[] = $conv;
}
return $arrconversations;
}
/**
* Returns all conversations between two users
*
* @param int $userid1 One of the user's id
* @param int $userid2 The other user's id
* @param int $limitfrom
* @param int $limitnum
* @return array
* @throws \dml_exception
*/
public static function get_conversations_between_users(int $userid1, int $userid2,
int $limitfrom = 0, int $limitnum = 20) : array {
global $DB;
if ($userid1 == $userid2) {
return array();
}
// Get all conversation where both user1 and user2 are members.
// TODO: Add subname value. Waiting for definite table structure.
$sql = "SELECT mc.id, mc.type, mc.name, mc.timecreated
FROM {message_conversations} mc
INNER JOIN {message_conversation_members} mcm1
ON mc.id = mcm1.conversationid
INNER JOIN {message_conversation_members} mcm2
ON mc.id = mcm2.conversationid
WHERE mcm1.userid = :userid1
AND mcm2.userid = :userid2
AND mc.enabled != 0
ORDER BY mc.timecreated DESC";
return $DB->get_records_sql($sql, array('userid1' => $userid1, 'userid2' => $userid2), $limitfrom, $limitnum);
}
/**
* Return a conversation.
*
* @param int $userid The user id to get the conversation for
* @param int $conversationid The id of the conversation to fetch
* @param bool $includecontactrequests Should contact requests be included between members
* @param bool $includeprivacyinfo Should privacy info be included between members
* @param int $memberlimit Limit number of members to load
* @param int $memberoffset Offset members by this amount
* @param int $messagelimit Limit number of messages to load
* @param int $messageoffset Offset the messages
* @param bool $newestmessagesfirst Order messages by newest first
* @return \stdClass
*/
public static function get_conversation(
int $userid,
int $conversationid,
bool $includecontactrequests = false,
bool $includeprivacyinfo = false,
int $memberlimit = 0,
int $memberoffset = 0,
int $messagelimit = 0,
int $messageoffset = 0,
bool $newestmessagesfirst = true
) {
global $USER, $DB;
$systemcontext = \context_system::instance();
$canreadallmessages = has_capability('moodle/site:readallmessages', $systemcontext);
if (($USER->id != $userid) && !$canreadallmessages) {
throw new \moodle_exception('You do not have permission to perform this action.');
}
$conversation = $DB->get_record('message_conversations', ['id' => $conversationid]);
if (!$conversation) {
return null;
}
// Get the context of the conversation. This will be used to check whether the conversation is a favourite.
// This will be either 'user' (for individual conversations) or, in the case of linked conversations,
// the context stored in the record.
$userctx = \context_user::instance($userid);
$conversationctx = empty($conversation->contextid) ? $userctx : \context::instance_by_id($conversation->contextid);
$isconversationmember = $DB->record_exists(
'message_conversation_members',
[
'conversationid' => $conversationid,
'userid' => $userid
]
);
if (!$isconversationmember && !$canreadallmessages) {
throw new \moodle_exception('You do not have permission to view this conversation.');
}
$members = self::get_conversation_members(
$userid,
$conversationid,
$includecontactrequests,
$includeprivacyinfo,
$memberoffset,
$memberlimit
);
if ($conversation->type != self::MESSAGE_CONVERSATION_TYPE_SELF) {
// Strip out the requesting user to match what get_conversations does, except for self-conversations.
$members = array_filter($members, function($member) use ($userid) {
return $member->id != $userid;
});
}
$messages = self::get_conversation_messages(
$userid,
$conversationid,
$messageoffset,
$messagelimit,
$newestmessagesfirst ? 'timecreated DESC' : 'timecreated ASC'
);
$service = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
$isfavourite = $service->favourite_exists('core_message', 'message_conversations', $conversationid, $conversationctx);
$convextrafields = self::get_linked_conversation_extra_fields([$conversation]);
$subname = isset($convextrafields[$conversationid]) ? $convextrafields[$conversationid]['subname'] : null;
$imageurl = isset($convextrafields[$conversationid]) ? $convextrafields[$conversationid]['imageurl'] : null;
$unreadcountssql = 'SELECT count(m.id)
FROM {messages} m
INNER JOIN {message_conversations} mc
ON mc.id = m.conversationid
LEFT JOIN {message_user_actions} mua
ON (mua.messageid = m.id AND mua.userid = ? AND
(mua.action = ? OR mua.action = ?))
WHERE m.conversationid = ?
AND m.useridfrom != ?
AND mua.id is NULL';
$unreadcount = $DB->count_records_sql(
$unreadcountssql,
[
$userid,
self::MESSAGE_ACTION_READ,
self::MESSAGE_ACTION_DELETED,
$conversationid,
$userid
]
);
$membercount = $DB->count_records('message_conversation_members', ['conversationid' => $conversationid]);
$ismuted = false;
if ($DB->record_exists('message_conversation_actions', ['userid' => $userid,
'conversationid' => $conversationid, 'action' => self::CONVERSATION_ACTION_MUTED])) {
$ismuted = true;
}
// Get the context of the conversation. This will be used to check if the user can delete all messages in the conversation.
$deleteallcontext = empty($conversation->contextid) ? $systemcontext : \context::instance_by_id($conversation->contextid);
return (object) [
'id' => $conversation->id,
'name' => $conversation->name,
'subname' => $subname,
'imageurl' => $imageurl,
'type' => $conversation->type,
'membercount' => $membercount,
'isfavourite' => $isfavourite,
'isread' => empty($unreadcount),
'unreadcount' => $unreadcount,
'ismuted' => $ismuted,
'members' => $members,
'messages' => $messages['messages'],
'candeletemessagesforallusers' => has_capability('moodle/site:deleteanymessage', $deleteallcontext)
];
}
/**
* Mark a conversation as a favourite for the given user.
*
* @param int $conversationid the id of the conversation to mark as a favourite.
* @param int $userid the id of the user to whom the favourite belongs.
* @return favourite the favourite object.
* @throws \moodle_exception if the user or conversation don't exist.
*/
public static function set_favourite_conversation(int $conversationid, int $userid) : favourite {
global $DB;
if (!self::is_user_in_conversation($userid, $conversationid)) {
throw new \moodle_exception("Conversation doesn't exist or user is not a member");
}
// Get the context for this conversation.
$conversation = $DB->get_record('message_conversations', ['id' => $conversationid]);
$userctx = \context_user::instance($userid);
if (empty($conversation->contextid)) {
// When the conversation hasn't any contextid value defined, the favourite will be added to the user context.
$conversationctx = $userctx;
} else {
// If the contextid is defined, the favourite will be added there.
$conversationctx = \context::instance_by_id($conversation->contextid);
}
$ufservice = \core_favourites\service_factory::get_service_for_user_context($userctx);
if ($favourite = $ufservice->get_favourite('core_message', 'message_conversations', $conversationid, $conversationctx)) {
return $favourite;
} else {
return $ufservice->create_favourite('core_message', 'message_conversations', $conversationid, $conversationctx);
}
}
/**
* Unset a conversation as a favourite for the given user.
*
* @param int $conversationid the id of the conversation to unset as a favourite.
* @param int $userid the id to whom the favourite belongs.
* @throws \moodle_exception if the favourite does not exist for the user.
*/
public static function unset_favourite_conversation(int $conversationid, int $userid) {
global $DB;
// Get the context for this conversation.
$conversation = $DB->get_record('message_conversations', ['id' => $conversationid]);
$userctx = \context_user::instance($userid);
if (empty($conversation->contextid)) {
// When the conversation hasn't any contextid value defined, the favourite will be added to the user context.
$conversationctx = $userctx;
} else {
// If the contextid is defined, the favourite will be added there.
$conversationctx = \context::instance_by_id($conversation->contextid);
}
$ufservice = \core_favourites\service_factory::get_service_for_user_context($userctx);
$ufservice->delete_favourite('core_message', 'message_conversations', $conversationid, $conversationctx);
}
/**
* @deprecated since 3.6
*/