MDL-64632 core_message: fixed PHP error when users are deleted from DB
[moodle.git] / message / tests / externallib_test.php
CommitLineData
e6432668
JM
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 * External message functions unit tests
19 *
20 * @package core_message
21 * @category external
22 * @copyright 2012 Jerome Mouneyrac
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28global $CFG;
29
30require_once($CFG->dirroot . '/webservice/tests/helpers.php');
31require_once($CFG->dirroot . '/message/externallib.php');
32
fb04293b
SA
33use \core_message\tests\helper as testhelper;
34
8252b7c2 35class core_message_externallib_testcase extends externallib_advanced_testcase {
e6432668 36
6ff4464b
JL
37 /**
38 * Tests set up
39 */
40 protected function setUp() {
41 global $CFG;
42
43 require_once($CFG->dirroot . '/message/lib.php');
44 }
45
d6731600
FM
46 /**
47 * Send a fake message.
48 *
49 * {@link message_send()} does not support transaction, this function will simulate a message
50 * sent from a user to another. We should stop using it once {@link message_send()} will support
51 * transactions. This is not clean at all, this is just used to add rows to the table.
52 *
53 * @param stdClass $userfrom user object of the one sending the message.
54 * @param stdClass $userto user object of the one receiving the message.
55 * @param string $message message to send.
7d69958e 56 * @param int $notification is the message a notification.
6aa01968 57 * @param int $time the time the message was sent
d6731600 58 */
6aa01968 59 protected function send_message($userfrom, $userto, $message = 'Hello world!', $notification = 0, $time = 0) {
d6731600 60 global $DB;
6aa01968
MN
61
62 if (empty($time)) {
63 $time = time();
64 }
65
883ce421
MN
66 if ($notification) {
67 $record = new stdClass();
68 $record->useridfrom = $userfrom->id;
69 $record->useridto = $userto->id;
70 $record->subject = 'No subject';
71 $record->fullmessage = $message;
72 $record->smallmessage = $message;
73 $record->timecreated = $time;
74
75 return $DB->insert_record('notifications', $record);
76 }
77
b2cd17e6 78 if (!$conversationid = \core_message\api::get_conversation_between_users([$userfrom->id, $userto->id])) {
f2ac0a3e
MN
79 $conversation = \core_message\api::create_conversation(
80 \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
81 [
82 $userfrom->id,
83 $userto->id
84 ]
85 );
86 $conversationid = $conversation->id;
883ce421
MN
87 }
88
89 // Ok, send the message.
d6731600
FM
90 $record = new stdClass();
91 $record->useridfrom = $userfrom->id;
883ce421 92 $record->conversationid = $conversationid;
d6731600
FM
93 $record->subject = 'No subject';
94 $record->fullmessage = $message;
883ce421 95 $record->smallmessage = $message;
6aa01968 96 $record->timecreated = $time;
4d146f1a 97
883ce421 98 return $DB->insert_record('messages', $record);
d6731600
FM
99 }
100
e6432668 101 /**
f219eac7 102 * Test send_instant_messages.
e6432668
JM
103 */
104 public function test_send_instant_messages() {
f219eac7 105 global $DB, $USER;
e6432668 106
f219eac7 107 $this->resetAfterTest();
e6432668 108
7356e732
EL
109 // Transactions used in tests, tell phpunit use alternative reset method.
110 $this->preventResetByRollback();
e6432668 111
f219eac7
MN
112 $user1 = self::getDataGenerator()->create_user();
113 $user2 = self::getDataGenerator()->create_user();
e6432668 114
f219eac7
MN
115 $this->setUser($user1);
116
117 // Create test message data.
118 $message1 = array();
119 $message1['touserid'] = $user2->id;
120 $message1['text'] = 'the message.';
121 $message1['clientmsgid'] = 4;
122 $messages = array($message1);
123
124 $sentmessages = core_message_external::send_instant_messages($messages);
125 $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
f7dfa9ba
SA
126 $this->assertEquals(
127 get_string('usercantbemessaged', 'message', fullname(\core_user::get_user($message1['touserid']))),
128 array_pop($sentmessages)['errormessage']
129 );
130
131 // Add the user1 as a contact.
132 \core_message\api::add_contact($user1->id, $user2->id);
133
134 // Send message again. Now it should work properly.
135 $sentmessages = core_message_external::send_instant_messages($messages);
136 // We need to execute the return values cleaning process to simulate the web service server.
137 $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
f219eac7
MN
138
139 $sentmessage = reset($sentmessages);
140
141 $sql = "SELECT m.*, mcm.userid as useridto
142 FROM {messages} m
143 INNER JOIN {message_conversations} mc
144 ON m.conversationid = mc.id
145 INNER JOIN {message_conversation_members} mcm
146 ON mcm.conversationid = mc.id
147 WHERE mcm.userid != ?
148 AND m.id = ?";
149 $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
150
151 // Confirm that the message was inserted correctly.
152 $this->assertEquals($themessage->useridfrom, $user1->id);
153 $this->assertEquals($themessage->useridto, $message1['touserid']);
154 $this->assertEquals($themessage->smallmessage, $message1['text']);
155 $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
156 }
157
158 /**
159 * Test send_instant_messages to a user who has blocked you.
160 */
161 public function test_send_instant_messages_blocked_user() {
162 global $DB;
163
164 $this->resetAfterTest();
165
166 // Transactions used in tests, tell phpunit use alternative reset method.
167 $this->preventResetByRollback();
e6432668
JM
168
169 $user1 = self::getDataGenerator()->create_user();
f219eac7
MN
170 $user2 = self::getDataGenerator()->create_user();
171
172 $this->setUser($user1);
173
174 \core_message\api::block_user($user2->id, $user1->id);
e6432668
JM
175
176 // Create test message data.
177 $message1 = array();
f219eac7 178 $message1['touserid'] = $user2->id;
e6432668
JM
179 $message1['text'] = 'the message.';
180 $message1['clientmsgid'] = 4;
181 $messages = array($message1);
182
183 $sentmessages = core_message_external::send_instant_messages($messages);
f219eac7 184 $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
e6432668 185
f219eac7
MN
186 $sentmessage = reset($sentmessages);
187
f7dfa9ba 188 $this->assertEquals(get_string('usercantbemessaged', 'message', fullname($user2)), $sentmessage['errormessage']);
f219eac7
MN
189
190 $this->assertEquals(0, $DB->count_records('messages'));
191 }
192
193 /**
194 * Test send_instant_messages when sending a message to a non-contact who has blocked non-contacts.
195 */
196 public function test_send_instant_messages_block_non_contacts() {
197 global $DB;
198
199 $this->resetAfterTest(true);
200
201 // Transactions used in tests, tell phpunit use alternative reset method.
202 $this->preventResetByRollback();
203
204 $user1 = self::getDataGenerator()->create_user();
205 $user2 = self::getDataGenerator()->create_user();
206
207 $this->setUser($user1);
208
209 // Set the user preference so user 2 does not accept messages from non-contacts.
f7dfa9ba 210 set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2);
f219eac7
MN
211
212 // Create test message data.
213 $message1 = array();
214 $message1['touserid'] = $user2->id;
215 $message1['text'] = 'the message.';
216 $message1['clientmsgid'] = 4;
217 $messages = array($message1);
218
219 $sentmessages = core_message_external::send_instant_messages($messages);
220 $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
221
222 $sentmessage = reset($sentmessages);
223
f7dfa9ba 224 $this->assertEquals(get_string('usercantbemessaged', 'message', fullname($user2)), $sentmessage['errormessage']);
f219eac7
MN
225
226 $this->assertEquals(0, $DB->count_records('messages'));
227 }
228
229 /**
230 * Test send_instant_messages when sending a message to a contact who has blocked non-contacts.
231 */
232 public function test_send_instant_messages_block_non_contacts_but_am_contact() {
233 global $DB, $USER;
234
235 $this->resetAfterTest(true);
236
237 // Transactions used in tests, tell phpunit use alternative reset method.
238 $this->preventResetByRollback();
239
240 $user1 = self::getDataGenerator()->create_user();
241 $user2 = self::getDataGenerator()->create_user();
242
243 $this->setUser($user1);
244
245 // Set the user preference so user 2 does not accept messages from non-contacts.
f7dfa9ba 246 set_user_preference('message_blocknoncontacts', \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS, $user2);
f219eac7
MN
247
248 \core_message\api::add_contact($user1->id, $user2->id);
249
250 // Create test message data.
251 $message1 = array();
252 $message1['touserid'] = $user2->id;
253 $message1['text'] = 'the message.';
254 $message1['clientmsgid'] = 4;
255 $messages = array($message1);
256
257 $sentmessages = core_message_external::send_instant_messages($messages);
fb695f6e
JM
258 $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);
259
f219eac7
MN
260 $sentmessage = reset($sentmessages);
261
883ce421
MN
262 $sql = "SELECT m.*, mcm.userid as useridto
263 FROM {messages} m
264 INNER JOIN {message_conversations} mc
265 ON m.conversationid = mc.id
266 INNER JOIN {message_conversation_members} mcm
267 ON mcm.conversationid = mc.id
268 WHERE mcm.userid != ?
269 AND m.id = ?";
f219eac7 270 $themessage = $DB->get_record_sql($sql, [$USER->id, $sentmessage['msgid']]);
e6432668
JM
271
272 // Confirm that the message was inserted correctly.
f219eac7 273 $this->assertEquals($themessage->useridfrom, $user1->id);
e6432668
JM
274 $this->assertEquals($themessage->useridto, $message1['touserid']);
275 $this->assertEquals($themessage->smallmessage, $message1['text']);
f219eac7
MN
276 $this->assertEquals($sentmessage['clientmsgid'], $message1['clientmsgid']);
277 }
278
279 /**
280 * Test send_instant_messages with no capabilities
281 */
282 public function test_send_instant_messages_no_capability() {
283 global $DB;
284
285 $this->resetAfterTest(true);
286
287 // Transactions used in tests, tell phpunit use alternative reset method.
288 $this->preventResetByRollback();
289
290 $user1 = self::getDataGenerator()->create_user();
291 $user2 = self::getDataGenerator()->create_user();
292
293 $this->setUser($user1);
294
295 // Unset the required capabilities by the external function.
296 $contextid = context_system::instance()->id;
297 $userrole = $DB->get_record('role', array('shortname' => 'user'));
298 $this->unassignUserCapability('moodle/site:sendmessage', $contextid, $userrole->id);
299
300 // Create test message data.
301 $message1 = array();
302 $message1['touserid'] = $user2->id;
303 $message1['text'] = 'the message.';
304 $message1['clientmsgid'] = 4;
305 $messages = array($message1);
306
307 $this->expectException('required_capability_exception');
308 core_message_external::send_instant_messages($messages);
309 }
310
311 /**
312 * Test send_instant_messages when messaging is disabled.
313 */
314 public function test_send_instant_messages_messaging_disabled() {
315 global $CFG;
316
317 $this->resetAfterTest(true);
318
319 // Transactions used in tests, tell phpunit use alternative reset method.
320 $this->preventResetByRollback();
321
322 $user1 = self::getDataGenerator()->create_user();
323 $user2 = self::getDataGenerator()->create_user();
324
325 $this->setUser($user1);
326
327 // Disable messaging.
328 $CFG->messaging = 0;
329
330 // Create test message data.
331 $message1 = array();
332 $message1['touserid'] = $user2->id;
333 $message1['text'] = 'the message.';
334 $message1['clientmsgid'] = 4;
335 $messages = array($message1);
336
337 $this->expectException('moodle_exception');
338 core_message_external::send_instant_messages($messages);
e6432668 339 }
d6731600
FM
340
341 /**
342 * Test create_contacts.
343 */
344 public function test_create_contacts() {
345 $this->resetAfterTest(true);
346
347 $user1 = self::getDataGenerator()->create_user();
348 $user2 = self::getDataGenerator()->create_user();
349 $user3 = self::getDataGenerator()->create_user();
350 $user4 = self::getDataGenerator()->create_user();
351 $user5 = self::getDataGenerator()->create_user();
352 $this->setUser($user1);
353
354 // Adding a contact.
355 $return = core_message_external::create_contacts(array($user2->id));
f219eac7 356 $this->assertDebuggingCalled();
d6731600
FM
357 $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
358 $this->assertEquals(array(), $return);
359
360 // Adding a contact who is already a contact.
361 $return = core_message_external::create_contacts(array($user2->id));
f219eac7 362 $this->assertDebuggingCalled();
d6731600
FM
363 $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
364 $this->assertEquals(array(), $return);
365
366 // Adding multiple contacts.
367 $return = core_message_external::create_contacts(array($user3->id, $user4->id));
f219eac7 368 $this->assertDebuggingCalledCount(2);
d6731600
FM
369 $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
370 $this->assertEquals(array(), $return);
371
372 // Adding a non-existing user.
373 $return = core_message_external::create_contacts(array(99999));
f219eac7 374 $this->assertDebuggingCalled();
d6731600
FM
375 $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
376 $this->assertCount(1, $return);
377 $return = array_pop($return);
378 $this->assertEquals($return['warningcode'], 'contactnotcreated');
379 $this->assertEquals($return['itemid'], 99999);
380
381 // Adding contacts with valid and invalid parameters.
382 $return = core_message_external::create_contacts(array($user5->id, 99999));
f219eac7 383 $this->assertDebuggingCalledCount(2);
d6731600
FM
384 $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
385 $this->assertCount(1, $return);
386 $return = array_pop($return);
387 $this->assertEquals($return['warningcode'], 'contactnotcreated');
388 $this->assertEquals($return['itemid'], 99999);
343ba16c
SL
389
390 // Try to add a contact to another user, should throw an exception.
391 // All assertions must be added before this point.
392 $this->expectException('required_capability_exception');
393 core_message_external::create_contacts(array($user2->id), $user3->id);
d6731600
FM
394 }
395
396 /**
397 * Test delete_contacts.
398 */
399 public function test_delete_contacts() {
400 $this->resetAfterTest(true);
401
402 $user1 = self::getDataGenerator()->create_user();
403 $user2 = self::getDataGenerator()->create_user();
404 $user3 = self::getDataGenerator()->create_user();
405 $user4 = self::getDataGenerator()->create_user();
406 $user5 = self::getDataGenerator()->create_user();
407 $user6 = self::getDataGenerator()->create_user();
408 $this->setUser($user1);
f219eac7
MN
409
410 \core_message\api::add_contact($user1->id, $user3->id);
411 \core_message\api::add_contact($user1->id, $user4->id);
412 \core_message\api::add_contact($user1->id, $user5->id);
413 \core_message\api::add_contact($user1->id, $user6->id);
d6731600
FM
414
415 // Removing a non-contact.
416 $return = core_message_external::delete_contacts(array($user2->id));
417 $this->assertNull($return);
418
419 // Removing one contact.
420 $return = core_message_external::delete_contacts(array($user3->id));
421 $this->assertNull($return);
422
423 // Removing multiple contacts.
424 $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
425 $this->assertNull($return);
426
427 // Removing contact from unexisting user.
428 $return = core_message_external::delete_contacts(array(99999));
429 $this->assertNull($return);
430
431 // Removing mixed valid and invalid data.
432 $return = core_message_external::delete_contacts(array($user6->id, 99999));
433 $this->assertNull($return);
343ba16c
SL
434
435 // Try to delete a contact of another user contact list, should throw an exception.
436 // All assertions must be added before this point.
437 $this->expectException('required_capability_exception');
438 core_message_external::delete_contacts(array($user2->id), $user3->id);
d6731600
FM
439 }
440
441 /**
442 * Test block_contacts.
443 */
444 public function test_block_contacts() {
445 $this->resetAfterTest(true);
446
447 $user1 = self::getDataGenerator()->create_user();
448 $user2 = self::getDataGenerator()->create_user();
449 $user3 = self::getDataGenerator()->create_user();
450 $user4 = self::getDataGenerator()->create_user();
451 $user5 = self::getDataGenerator()->create_user();
452 $this->setUser($user1);
f219eac7
MN
453
454 \core_message\api::add_contact($user1->id, $user3->id);
455 \core_message\api::add_contact($user1->id, $user4->id);
456 \core_message\api::add_contact($user1->id, $user5->id);
d6731600
FM
457
458 // Blocking a contact.
459 $return = core_message_external::block_contacts(array($user2->id));
f219eac7 460 $this->assertDebuggingCalled();
d6731600
FM
461 $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
462 $this->assertEquals(array(), $return);
463
464 // Blocking a contact who is already a contact.
465 $return = core_message_external::block_contacts(array($user2->id));
f219eac7 466 $this->assertDebuggingCalled();
d6731600
FM
467 $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
468 $this->assertEquals(array(), $return);
469
470 // Blocking multiple contacts.
471 $return = core_message_external::block_contacts(array($user3->id, $user4->id));
f219eac7 472 $this->assertDebuggingCalledCount(2);
d6731600
FM
473 $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
474 $this->assertEquals(array(), $return);
475
476 // Blocking a non-existing user.
477 $return = core_message_external::block_contacts(array(99999));
f219eac7 478 $this->assertDebuggingCalled();
d6731600
FM
479 $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
480 $this->assertCount(1, $return);
481 $return = array_pop($return);
482 $this->assertEquals($return['warningcode'], 'contactnotblocked');
483 $this->assertEquals($return['itemid'], 99999);
484
485 // Blocking contacts with valid and invalid parameters.
486 $return = core_message_external::block_contacts(array($user5->id, 99999));
f219eac7 487 $this->assertDebuggingCalledCount(2);
d6731600
FM
488 $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
489 $this->assertCount(1, $return);
490 $return = array_pop($return);
491 $this->assertEquals($return['warningcode'], 'contactnotblocked');
492 $this->assertEquals($return['itemid'], 99999);
343ba16c
SL
493
494 // Try to block a contact of another user contact list, should throw an exception.
495 // All assertions must be added before this point.
496 $this->expectException('required_capability_exception');
497 core_message_external::block_contacts(array($user2->id), $user3->id);
d6731600
FM
498 }
499
500 /**
501 * Test unblock_contacts.
502 */
503 public function test_unblock_contacts() {
504 $this->resetAfterTest(true);
505
506 $user1 = self::getDataGenerator()->create_user();
507 $user2 = self::getDataGenerator()->create_user();
508 $user3 = self::getDataGenerator()->create_user();
509 $user4 = self::getDataGenerator()->create_user();
510 $user5 = self::getDataGenerator()->create_user();
511 $user6 = self::getDataGenerator()->create_user();
512 $this->setUser($user1);
f219eac7
MN
513
514 \core_message\api::add_contact($user1->id, $user3->id);
515 \core_message\api::add_contact($user1->id, $user4->id);
516 \core_message\api::add_contact($user1->id, $user5->id);
517 \core_message\api::add_contact($user1->id, $user6->id);
d6731600
FM
518
519 // Removing a non-contact.
520 $return = core_message_external::unblock_contacts(array($user2->id));
f219eac7 521 $this->assertDebuggingCalled();
d6731600
FM
522 $this->assertNull($return);
523
524 // Removing one contact.
525 $return = core_message_external::unblock_contacts(array($user3->id));
f219eac7 526 $this->assertDebuggingCalled();
d6731600
FM
527 $this->assertNull($return);
528
529 // Removing multiple contacts.
530 $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
f219eac7 531 $this->assertDebuggingCalledCount(2);
d6731600
FM
532 $this->assertNull($return);
533
534 // Removing contact from unexisting user.
535 $return = core_message_external::unblock_contacts(array(99999));
f219eac7 536 $this->assertDebuggingCalled();
d6731600
FM
537 $this->assertNull($return);
538
539 // Removing mixed valid and invalid data.
540 $return = core_message_external::unblock_contacts(array($user6->id, 99999));
f219eac7 541 $this->assertDebuggingCalledCount(2);
d6731600
FM
542 $this->assertNull($return);
543
343ba16c
SL
544 // Try to unblock a contact of another user contact list, should throw an exception.
545 // All assertions must be added before this point.
546 $this->expectException('required_capability_exception');
547 core_message_external::unblock_contacts(array($user2->id), $user3->id);
f219eac7 548 $this->assertDebuggingCalled();
d6731600
FM
549 }
550
52284186
MN
551 /**
552 * Test getting contact requests.
553 */
554 public function test_get_contact_requests() {
0866b336
RW
555 global $PAGE;
556
52284186
MN
557 $this->resetAfterTest();
558
559 $user1 = self::getDataGenerator()->create_user();
560 $user2 = self::getDataGenerator()->create_user();
561 $user3 = self::getDataGenerator()->create_user();
562
563 $this->setUser($user1);
564
565 // Block one user, their request should not show up.
566 \core_message\api::block_user($user1->id, $user3->id);
567
568 \core_message\api::create_contact_request($user2->id, $user1->id);
569 \core_message\api::create_contact_request($user3->id, $user1->id);
570
571 $requests = core_message_external::get_contact_requests($user1->id);
572 $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
573
574 $this->assertCount(1, $requests);
575
576 $request = reset($requests);
0866b336
RW
577 $userpicture = new \user_picture($user2);
578 $profileimageurl = $userpicture->get_url($PAGE)->out(false);
52284186
MN
579
580 $this->assertEquals($user2->id, $request['id']);
daa33803
MN
581 $this->assertEquals(fullname($user2), $request['fullname']);
582 $this->assertArrayHasKey('profileimageurl', $request);
583 $this->assertArrayHasKey('profileimageurlsmall', $request);
584 $this->assertArrayHasKey('isonline', $request);
585 $this->assertArrayHasKey('showonlinestatus', $request);
586 $this->assertArrayHasKey('isblocked', $request);
587 $this->assertArrayHasKey('iscontact', $request);
52284186
MN
588 }
589
e4088b75
JD
590 /**
591 * Test the get_contact_requests() function when the user has blocked the sender of the request.
592 */
593 public function test_get_contact_requests_blocked_sender() {
594 $this->resetAfterTest();
595 $user1 = self::getDataGenerator()->create_user();
596 $user2 = self::getDataGenerator()->create_user();
597
598 // User1 blocks User2.
599 \core_message\api::block_user($user1->id, $user2->id);
600
601 // User2 tries to add User1 as a contact.
602 \core_message\api::create_contact_request($user2->id, $user1->id);
603
604 // Verify we don't see the contact request from the blocked user User2 in the requests for User1.
605 $this->setUser($user1);
606 $requests = core_message_external::get_contact_requests($user1->id);
607 $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
608
609 $this->assertCount(0, $requests);
610 }
611
b3ce575e
MN
612 /**
613 * Test getting contact requests when there are none.
614 */
615 public function test_get_contact_requests_no_requests() {
616 $this->resetAfterTest();
617
618 $user1 = self::getDataGenerator()->create_user();
619
620 $this->setUser($user1);
621
622 $requests = core_message_external::get_contact_requests($user1->id);
623 $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
624
625 $this->assertEmpty($requests);
626 }
627
628 /**
629 * Test getting contact requests with limits.
630 */
631 public function test_get_contact_requests_with_limits() {
632 $this->resetAfterTest();
633
634 $user1 = self::getDataGenerator()->create_user();
635 $user2 = self::getDataGenerator()->create_user();
636 $user3 = self::getDataGenerator()->create_user();
637
638 $this->setUser($user1);
639
640 \core_message\api::create_contact_request($user2->id, $user1->id);
641 \core_message\api::create_contact_request($user3->id, $user1->id);
642
643 $requests = core_message_external::get_contact_requests($user1->id, 0, 1);
644 $requests = external_api::clean_returnvalue(core_message_external::get_contact_requests_returns(), $requests);
645
646 $this->assertCount(1, $requests);
52284186
MN
647 }
648
649 /**
650 * Test getting contact requests with messaging disabled.
651 */
652 public function test_get_contact_requests_messaging_disabled() {
653 global $CFG;
654
655 $this->resetAfterTest();
656
657 // Create some skeleton data just so we can call the WS.
658 $user1 = self::getDataGenerator()->create_user();
659
660 $this->setUser($user1);
661
662 // Disable messaging.
663 $CFG->messaging = 0;
664
665 // Ensure an exception is thrown.
666 $this->expectException('moodle_exception');
667 core_message_external::get_contact_requests($user1->id);
668 }
669
670 /**
671 * Test getting contact requests with no permission.
672 */
673 public function test_get_contact_requests_no_permission() {
674 $this->resetAfterTest();
675
676 // Create some skeleton data just so we can call the WS.
677 $user1 = self::getDataGenerator()->create_user();
678 $user2 = self::getDataGenerator()->create_user();
679 $user3 = self::getDataGenerator()->create_user();
680
681 $this->setUser($user3);
682
683 // Ensure an exception is thrown.
684 $this->expectException('required_capability_exception');
685 core_message_external::create_contact_request($user1->id, $user2->id);
686 }
687
7d678923
MN
688 /**
689 * Test getting the number of received contact requests.
690 */
691 public function test_get_received_contact_requests_count() {
692 $this->resetAfterTest();
693
694 $user1 = self::getDataGenerator()->create_user();
695 $user2 = self::getDataGenerator()->create_user();
696 $user3 = self::getDataGenerator()->create_user();
697 $user4 = self::getDataGenerator()->create_user();
698
699 $this->setUser($user1);
700
701 $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
702 $contactrequestnumber = external_api::clean_returnvalue(
703 core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
704 $this->assertEquals(0, $contactrequestnumber);
705
706 \core_message\api::create_contact_request($user2->id, $user1->id);
707
708 $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
709 $contactrequestnumber = external_api::clean_returnvalue(
710 core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
711 $this->assertEquals(1, $contactrequestnumber);
712
713 \core_message\api::create_contact_request($user3->id, $user1->id);
714
715 $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
716 $contactrequestnumber = external_api::clean_returnvalue(
717 core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
718 $this->assertEquals(2, $contactrequestnumber);
719
720 \core_message\api::create_contact_request($user1->id, $user4->id);
721
722 // Web service should ignore sent requests.
723 $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
724 $contactrequestnumber = external_api::clean_returnvalue(
725 core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
726 $this->assertEquals(2, $contactrequestnumber);
727 }
728
e492a554
JD
729 /**
730 * Test the get_received_contact_requests_count() function when the user has blocked the sender of the request.
731 */
732 public function test_get_received_contact_requests_count_blocked_sender() {
733 $this->resetAfterTest();
734 $user1 = self::getDataGenerator()->create_user();
735 $user2 = self::getDataGenerator()->create_user();
736
737 // User1 blocks User2.
738 \core_message\api::block_user($user1->id, $user2->id);
739
740 // User2 tries to add User1 as a contact.
741 \core_message\api::create_contact_request($user2->id, $user1->id);
742
743 // Verify we don't see the contact request from the blocked user User2 in the count for User1.
744 $this->setUser($user1);
745 $contactrequestnumber = core_message_external::get_received_contact_requests_count($user1->id);
746 $contactrequestnumber = external_api::clean_returnvalue(
747 core_message_external::get_received_contact_requests_count_returns(), $contactrequestnumber);
748 $this->assertEquals(0, $contactrequestnumber);
749 }
750
7d678923
MN
751 /**
752 * Test getting the number of received contact requests with no permissions.
753 */
754 public function test_get_received_contact_requests_count_no_permission() {
755 $this->resetAfterTest();
756
757 // Create some skeleton data just so we can call the WS.
758 $user1 = self::getDataGenerator()->create_user();
759 $user2 = self::getDataGenerator()->create_user();
760
761 $this->setUser($user2);
762
763 // Ensure an exception is thrown.
764 $this->expectException('required_capability_exception');
765 core_message_external::get_received_contact_requests_count($user1->id);
766 }
767
768 /**
769 * Test getting the number of received contact requests with messaging disabled.
770 */
771 public function test_get_received_contact_requests_count_messaging_disabled() {
772 global $CFG;
773
774 $this->resetAfterTest();
775
776 // Create some skeleton data just so we can call the WS.
777 $user1 = self::getDataGenerator()->create_user();
778
779 $this->setUser($user1);
780
781 // Disable messaging.
782 $CFG->messaging = 0;
783
784 // Ensure an exception is thrown.
785 $this->expectException('moodle_exception');
786 core_message_external::get_received_contact_requests_count($user1->id);
787 }
788
52284186
MN
789 /**
790 * Test creating a contact request.
791 */
792 public function test_create_contact_request() {
0d203bbf 793 global $CFG, $DB;
52284186
MN
794
795 $this->resetAfterTest();
796
797 $user1 = self::getDataGenerator()->create_user();
798 $user2 = self::getDataGenerator()->create_user();
799
800 $this->setUser($user1);
801
0d203bbf
MN
802 // Allow users to message anyone site-wide.
803 $CFG->messagingallusers = 1;
804
52284186
MN
805 $return = core_message_external::create_contact_request($user1->id, $user2->id);
806 $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
0866b336 807 $this->assertEquals([], $return['warnings']);
52284186
MN
808
809 $request = $DB->get_records('message_contact_requests');
810
811 $this->assertCount(1, $request);
812
813 $request = reset($request);
814
0866b336
RW
815 $this->assertEquals($request->id, $return['request']['id']);
816 $this->assertEquals($request->userid, $return['request']['userid']);
817 $this->assertEquals($request->requesteduserid, $return['request']['requesteduserid']);
818 $this->assertEquals($request->timecreated, $return['request']['timecreated']);
52284186
MN
819 }
820
0d203bbf
MN
821 /**
822 * Test creating a contact request when not allowed.
823 */
824 public function test_create_contact_request_not_allowed() {
825 global $CFG;
826
827 $this->resetAfterTest();
828
829 $user1 = self::getDataGenerator()->create_user();
830 $user2 = self::getDataGenerator()->create_user();
831
832 $this->setUser($user1);
833
834 $CFG->messagingallusers = 0;
835
836 $return = core_message_external::create_contact_request($user1->id, $user2->id);
837 $return = external_api::clean_returnvalue(core_message_external::create_contact_request_returns(), $return);
838
0866b336 839 $warning = reset($return['warnings']);
0d203bbf
MN
840
841 $this->assertEquals('user', $warning['item']);
842 $this->assertEquals($user2->id, $warning['itemid']);
843 $this->assertEquals('cannotcreatecontactrequest', $warning['warningcode']);
844 $this->assertEquals('You are unable to create a contact request for this user', $warning['message']);
845 }
846
52284186
MN
847 /**
848 * Test creating a contact request with messaging disabled.
849 */
850 public function test_create_contact_request_messaging_disabled() {
851 global $CFG;
852
853 $this->resetAfterTest();
854
855 // Create some skeleton data just so we can call the WS.
856 $user1 = self::getDataGenerator()->create_user();
857 $user2 = self::getDataGenerator()->create_user();
858
859 $this->setUser($user1);
860
861 // Disable messaging.
862 $CFG->messaging = 0;
863
864 // Ensure an exception is thrown.
865 $this->expectException('moodle_exception');
866 core_message_external::create_contact_request($user1->id, $user2->id);
867 }
868
869 /**
870 * Test creating a contact request with no permission.
871 */
872 public function test_create_contact_request_no_permission() {
873 $this->resetAfterTest();
874
875 // Create some skeleton data just so we can call the WS.
876 $user1 = self::getDataGenerator()->create_user();
877 $user2 = self::getDataGenerator()->create_user();
878 $user3 = self::getDataGenerator()->create_user();
879
880 $this->setUser($user3);
881
882 // Ensure an exception is thrown.
883 $this->expectException('required_capability_exception');
884 core_message_external::create_contact_request($user1->id, $user2->id);
885 }
886
887 /**
888 * Test confirming a contact request.
889 */
890 public function test_confirm_contact_request() {
891 global $DB;
892
893 $this->resetAfterTest();
894
895 $user1 = self::getDataGenerator()->create_user();
896 $user2 = self::getDataGenerator()->create_user();
897
898 $this->setUser($user1);
899
900 \core_message\api::create_contact_request($user1->id, $user2->id);
901
902 $this->setUser($user2);
903
904 $return = core_message_external::confirm_contact_request($user1->id, $user2->id);
905 $return = external_api::clean_returnvalue(core_message_external::confirm_contact_request_returns(), $return);
906 $this->assertEquals(array(), $return);
907
908 $this->assertEquals(0, $DB->count_records('message_contact_requests'));
909
910 $contact = $DB->get_records('message_contacts');
911
912 $this->assertCount(1, $contact);
913
914 $contact = reset($contact);
915
916 $this->assertEquals($user1->id, $contact->userid);
917 $this->assertEquals($user2->id, $contact->contactid);
918 }
919
920 /**
921 * Test confirming a contact request with messaging disabled.
922 */
923 public function test_confirm_contact_request_messaging_disabled() {
924 global $CFG;
925
926 $this->resetAfterTest();
927
928 // Create some skeleton data just so we can call the WS.
929 $user1 = self::getDataGenerator()->create_user();
930 $user2 = self::getDataGenerator()->create_user();
931
932 $this->setUser($user1);
933
934 // Disable messaging.
935 $CFG->messaging = 0;
936
937 // Ensure an exception is thrown.
938 $this->expectException('moodle_exception');
939 core_message_external::confirm_contact_request($user1->id, $user2->id);
940 }
941
942 /**
943 * Test confirming a contact request with no permission.
944 */
945 public function test_confirm_contact_request_no_permission() {
946 $this->resetAfterTest();
947
948 // Create some skeleton data just so we can call the WS.
949 $user1 = self::getDataGenerator()->create_user();
950 $user2 = self::getDataGenerator()->create_user();
951 $user3 = self::getDataGenerator()->create_user();
952
953 $this->setUser($user3);
954
955 // Ensure an exception is thrown.
956 $this->expectException('required_capability_exception');
957 core_message_external::confirm_contact_request($user1->id, $user2->id);
958 }
959
960 /**
961 * Test declining a contact request.
962 */
963 public function test_decline_contact_request() {
964 global $DB;
965
966 $this->resetAfterTest();
967
968 $user1 = self::getDataGenerator()->create_user();
969 $user2 = self::getDataGenerator()->create_user();
970
971 $this->setUser($user1);
972
973 \core_message\api::create_contact_request($user1->id, $user2->id);
974
975 $this->setUser($user2);
976
977 $return = core_message_external::decline_contact_request($user1->id, $user2->id);
978 $return = external_api::clean_returnvalue(core_message_external::decline_contact_request_returns(), $return);
979 $this->assertEquals(array(), $return);
980
981 $this->assertEquals(0, $DB->count_records('message_contact_requests'));
982 $this->assertEquals(0, $DB->count_records('message_contacts'));
983 }
984
985 /**
986 * Test declining a contact request with messaging disabled.
987 */
988 public function test_decline_contact_request_messaging_disabled() {
989 global $CFG;
990
991 $this->resetAfterTest();
992
993 // Create some skeleton data just so we can call the WS.
994 $user1 = self::getDataGenerator()->create_user();
995 $user2 = self::getDataGenerator()->create_user();
996
997 $this->setUser($user1);
998
999 // Disable messaging.
1000 $CFG->messaging = 0;
1001
1002 // Ensure an exception is thrown.
1003 $this->expectException('moodle_exception');
1004 core_message_external::decline_contact_request($user1->id, $user2->id);
1005 }
1006
1007 /**
1008 * Test declining a contact request with no permission.
1009 */
1010 public function test_decline_contact_request_no_permission() {
1011 $this->resetAfterTest();
1012
1013 // Create some skeleton data just so we can call the WS.
1014 $user1 = self::getDataGenerator()->create_user();
1015 $user2 = self::getDataGenerator()->create_user();
1016 $user3 = self::getDataGenerator()->create_user();
1017
1018 $this->setUser($user3);
1019
1020 // Ensure an exception is thrown.
1021 $this->expectException('required_capability_exception');
1022 core_message_external::decline_contact_request($user1->id, $user2->id);
1023 }
1024
1025 /**
1026 * Test blocking a user.
1027 */
1028 public function test_block_user() {
1029 global $DB;
1030
1031 $this->resetAfterTest(true);
1032
1033 $user1 = self::getDataGenerator()->create_user();
1034 $user2 = self::getDataGenerator()->create_user();
1035
1036 $this->setUser($user1);
1037
1038 // Blocking a user.
1039 $return = core_message_external::block_user($user1->id, $user2->id);
1040 $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
1041 $this->assertEquals(array(), $return);
1042
1043 // Get list of blocked users.
1044 $record = $DB->get_record('message_users_blocked', []);
1045
1046 $this->assertEquals($user1->id, $record->userid);
1047 $this->assertEquals($user2->id, $record->blockeduserid);
1048
1049 // Blocking a user who is already blocked.
1050 $return = core_message_external::block_user($user1->id, $user2->id);
1051 $return = external_api::clean_returnvalue(core_message_external::block_user_returns(), $return);
1052 $this->assertEquals(array(), $return);
1053
1054 $this->assertEquals(1, $DB->count_records('message_users_blocked'));
1055 }
1056
1057 /**
1058 * Test blocking a user with messaging disabled.
1059 */
1060 public function test_block_user_messaging_disabled() {
1061 global $CFG;
1062
1063 $this->resetAfterTest();
1064
1065 // Create some skeleton data just so we can call the WS.
1066 $user1 = self::getDataGenerator()->create_user();
1067 $user2 = self::getDataGenerator()->create_user();
1068
1069 $this->setUser($user1);
1070
1071 // Disable messaging.
1072 $CFG->messaging = 0;
1073
1074 // Ensure an exception is thrown.
1075 $this->expectException('moodle_exception');
1076 core_message_external::block_user($user1->id, $user2->id);
1077 }
1078
1079 /**
1080 * Test blocking a user with no permission.
1081 */
1082 public function test_block_user_no_permission() {
1083 $this->resetAfterTest();
1084
1085 // Create some skeleton data just so we can call the WS.
1086 $user1 = self::getDataGenerator()->create_user();
1087 $user2 = self::getDataGenerator()->create_user();
1088 $user3 = self::getDataGenerator()->create_user();
1089
1090 $this->setUser($user3);
1091
1092 // Ensure an exception is thrown.
1093 $this->expectException('required_capability_exception');
1094 core_message_external::block_user($user1->id, $user2->id);
1095 }
1096
1097 /**
1098 * Test unblocking a user.
1099 */
1100 public function test_unblock_user() {
1101 global $DB;
1102
1103 $this->resetAfterTest(true);
1104
1105 $user1 = self::getDataGenerator()->create_user();
1106 $user2 = self::getDataGenerator()->create_user();
1107
1108 $this->setUser($user1);
1109
1110 // Block the user.
1111 \core_message\api::block_user($user1->id, $user2->id);
1112
1113 // Unblocking a user.
1114 $return = core_message_external::unblock_user($user1->id, $user2->id);
1115 $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
1116 $this->assertEquals(array(), $return);
1117
1118 $this->assertEquals(0, $DB->count_records('message_users_blocked'));
1119
1120 // Unblocking a user who is already unblocked.
1121 $return = core_message_external::unblock_user($user1->id, $user2->id);
1122 $return = external_api::clean_returnvalue(core_message_external::unblock_user_returns(), $return);
1123 $this->assertEquals(array(), $return);
1124
1125 $this->assertEquals(0, $DB->count_records('message_users_blocked'));
1126 }
1127
1128 /**
1129 * Test unblocking a user with messaging disabled.
1130 */
1131 public function test_unblock_user_messaging_disabled() {
1132 global $CFG;
1133
1134 $this->resetAfterTest();
1135
1136 // Create some skeleton data just so we can call the WS.
1137 $user1 = self::getDataGenerator()->create_user();
1138 $user2 = self::getDataGenerator()->create_user();
1139
1140 $this->setUser($user1);
1141
1142 // Disable messaging.
1143 $CFG->messaging = 0;
1144
1145 // Ensure an exception is thrown.
1146 $this->expectException('moodle_exception');
1147 core_message_external::unblock_user($user1->id, $user2->id);
1148 }
1149
1150 /**
1151 * Test unblocking a user with no permission.
1152 */
1153 public function test_unblock_user_no_permission() {
1154 $this->resetAfterTest();
1155
1156 // Create some skeleton data just so we can call the WS.
1157 $user1 = self::getDataGenerator()->create_user();
1158 $user2 = self::getDataGenerator()->create_user();
1159 $user3 = self::getDataGenerator()->create_user();
1160
1161 $this->setUser($user3);
1162
1163 // Ensure an exception is thrown.
1164 $this->expectException('required_capability_exception');
1165 core_message_external::unblock_user($user1->id, $user2->id);
1166 }
1167
d6731600
FM
1168 /**
1169 * Test get_contacts.
1170 */
1171 public function test_get_contacts() {
1172 $this->resetAfterTest(true);
1173
1174 $user1 = self::getDataGenerator()->create_user();
1175 $user_stranger = self::getDataGenerator()->create_user();
1176 $user_offline1 = self::getDataGenerator()->create_user();
1177 $user_offline2 = self::getDataGenerator()->create_user();
1178 $user_offline3 = self::getDataGenerator()->create_user();
1179 $user_online = new stdClass();
1180 $user_online->lastaccess = time();
1181 $user_online = self::getDataGenerator()->create_user($user_online);
1182 $user_blocked = self::getDataGenerator()->create_user();
0b074e88 1183 $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
d6731600
FM
1184
1185 // Login as user1.
1186 $this->setUser($user1);
f219eac7
MN
1187 \core_message\api::add_contact($user1->id, $user_offline1->id);
1188 \core_message\api::add_contact($user1->id, $user_offline2->id);
1189 \core_message\api::add_contact($user1->id, $user_offline3->id);
1190 \core_message\api::add_contact($user1->id, $user_online->id);
d6731600
FM
1191
1192 // User_stranger sends a couple of messages to user1.
1193 $this->send_message($user_stranger, $user1, 'Hello there!');
1194 $this->send_message($user_stranger, $user1, 'How you goin?');
1195 $this->send_message($user_stranger, $user1, 'Cya!');
0b074e88 1196 $this->send_message($noreplyuser, $user1, 'I am not a real user');
d6731600
FM
1197
1198 // User_blocked sends a message to user1.
1199 $this->send_message($user_blocked, $user1, 'Here, have some spam.');
1200
1201 // Retrieve the contacts of the user.
1202 $this->setUser($user1);
1203 $contacts = core_message_external::get_contacts();
1204 $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1205 $this->assertCount(3, $contacts['offline']);
1206 $this->assertCount(1, $contacts['online']);
0b074e88 1207 $this->assertCount(3, $contacts['strangers']);
d6731600 1208 core_message_external::block_contacts(array($user_blocked->id));
f219eac7 1209 $this->assertDebuggingCalled();
d6731600
FM
1210 $contacts = core_message_external::get_contacts();
1211 $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1212 $this->assertCount(3, $contacts['offline']);
1213 $this->assertCount(1, $contacts['online']);
0b074e88 1214 $this->assertCount(2, $contacts['strangers']);
d6731600
FM
1215
1216 // Checking some of the fields returned.
1217 $stranger = array_pop($contacts['strangers']);
01393790 1218
0b074e88
JL
1219 $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
1220 $this->assertEquals(1, $stranger['unread']);
01393790
JL
1221
1222 // Check that deleted users are not returned.
1223 delete_user($user_offline1);
1224 delete_user($user_stranger);
1225 delete_user($user_online);
1226 $contacts = core_message_external::get_contacts();
1227 $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
1228 $this->assertCount(2, $contacts['offline']);
1229 $this->assertCount(0, $contacts['online']);
1230 $this->assertCount(1, $contacts['strangers']);
d6731600
FM
1231 }
1232
1233 /**
1234 * Test search_contacts.
52f3e060 1235 * @expectedException moodle_exception
d6731600
FM
1236 */
1237 public function test_search_contacts() {
1238 global $DB;
1239 $this->resetAfterTest(true);
1240
1241 $course1 = $this->getDataGenerator()->create_course();
1242 $course2 = $this->getDataGenerator()->create_course();
1243
1244 $user1 = new stdClass();
1245 $user1->firstname = 'X';
1246 $user1->lastname = 'X';
1247 $user1 = $this->getDataGenerator()->create_user($user1);
1248 $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
1249 $this->getDataGenerator()->enrol_user($user1->id, $course2->id);
1250
1251 $user2 = new stdClass();
1252 $user2->firstname = 'Eric';
1253 $user2->lastname = 'Cartman';
1254 $user2 = self::getDataGenerator()->create_user($user2);
1255 $user3 = new stdClass();
1256 $user3->firstname = 'Stan';
1257 $user3->lastname = 'Marsh';
1258 $user3 = self::getDataGenerator()->create_user($user3);
1259 self::getDataGenerator()->enrol_user($user3->id, $course1->id);
1260 $user4 = new stdClass();
1261 $user4->firstname = 'Kyle';
1262 $user4->lastname = 'Broflovski';
1263 $user4 = self::getDataGenerator()->create_user($user4);
1264 $user5 = new stdClass();
1265 $user5->firstname = 'Kenny';
1266 $user5->lastname = 'McCormick';
1267 $user5 = self::getDataGenerator()->create_user($user5);
1268 self::getDataGenerator()->enrol_user($user5->id, $course2->id);
1269
d6731600 1270 $this->setUser($user1);
2e2d1977 1271
d6731600
FM
1272 $results = core_message_external::search_contacts('r');
1273 $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
2e2d1977
AD
1274 $this->assertCount(5, $results); // Users 2 through 5 + admin
1275
d6731600
FM
1276 $results = core_message_external::search_contacts('r', true);
1277 $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1278 $this->assertCount(2, $results);
2e2d1977 1279
d6731600
FM
1280 $results = core_message_external::search_contacts('Kyle', false);
1281 $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1282 $this->assertCount(1, $results);
1283 $result = reset($results);
1284 $this->assertEquals($user4->id, $result['id']);
2e2d1977 1285
d6731600
FM
1286 $results = core_message_external::search_contacts('y', false);
1287 $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1288 $this->assertCount(2, $results);
2e2d1977 1289
d6731600
FM
1290 $results = core_message_external::search_contacts('y', true);
1291 $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
1292 $this->assertCount(1, $results);
1293 $result = reset($results);
1294 $this->assertEquals($user5->id, $result['id']);
1295
1296 // Empty query, will throw an exception.
d6731600
FM
1297 $results = core_message_external::search_contacts('');
1298 }
6ff4464b
JL
1299
1300 /**
1301 * Test get_messages.
1302 */
1303 public function test_get_messages() {
ea21d637 1304 global $CFG, $DB;
6ff4464b
JL
1305 $this->resetAfterTest(true);
1306
1307 $this->preventResetByRollback();
1308 // This mark the messages as read!.
1309 $sink = $this->redirectMessages();
1310
1311 $user1 = self::getDataGenerator()->create_user();
1312 $user2 = self::getDataGenerator()->create_user();
1313 $user3 = self::getDataGenerator()->create_user();
1314
1315 $course = self::getDataGenerator()->create_course();
1316
1317 // Send a message from one user to another.
1318 message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1319 message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
1320 message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1321 message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1322 message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);
1323
1324 $this->setUser($user1);
1325 // Get read conversations from user1 to user2.
1326 $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1327 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1328 $this->assertCount(1, $messages['messages']);
1329
ea21d637
JL
1330 // Delete the message.
1331 $message = array_shift($messages['messages']);
883ce421 1332 \core_message\api::delete_message($user1->id, $message['id']);
ea21d637
JL
1333
1334 $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
1335 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1336 $this->assertCount(0, $messages['messages']);
1337
6ff4464b
JL
1338 // Get unread conversations from user1 to user2.
1339 $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
1340 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1341 $this->assertCount(0, $messages['messages']);
1342
1343 // Get read messages send from user1.
1344 $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1345 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
ea21d637 1346 $this->assertCount(1, $messages['messages']);
6ff4464b
JL
1347
1348 $this->setUser($user2);
1349 // Get read conversations from any user to user2.
1350 $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
1351 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1352 $this->assertCount(2, $messages['messages']);
1353
ea21d637
JL
1354 // Conversations from user3 to user2.
1355 $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1356 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1357 $this->assertCount(1, $messages['messages']);
1358
1359 // Delete the message.
1360 $message = array_shift($messages['messages']);
883ce421 1361 \core_message\api::delete_message($user2->id, $message['id']);
ea21d637
JL
1362
1363 $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
1364 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1365 $this->assertCount(0, $messages['messages']);
1366
6ff4464b
JL
1367 $this->setUser($user3);
1368 // Get read notifications received by user3.
1369 $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
1370 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1371 $this->assertCount(0, $messages['messages']);
1372
1373 // Now, create some notifications...
1374 // We are creating fake notifications but based on real ones.
1375
39d2c688 1376 // This one comes from a disabled plugin's provider and therefore is not sent.
cc350fd9
AD
1377 $eventdata = new \core\message\message();
1378 $eventdata->courseid = $course->id;
39d2c688 1379 $eventdata->notification = 1;
6ff4464b
JL
1380 $eventdata->modulename = 'moodle';
1381 $eventdata->component = 'enrol_paypal';
1382 $eventdata->name = 'paypal_enrolment';
1383 $eventdata->userfrom = get_admin();
1384 $eventdata->userto = $user1;
1385 $eventdata->subject = "Moodle: PayPal payment";
1386 $eventdata->fullmessage = "Your PayPal payment is pending.";
1387 $eventdata->fullmessageformat = FORMAT_PLAIN;
1388 $eventdata->fullmessagehtml = '';
1389 $eventdata->smallmessage = '';
1390 message_send($eventdata);
39d2c688
DM
1391 $this->assertDebuggingCalled('Attempt to send msg from a provider enrol_paypal/paypal_enrolment '.
1392 'that is inactive or not allowed for the user id='.$user1->id);
1393
1394 // This one omits notification = 1.
1395 $message = new \core\message\message();
1396 $message->courseid = $course->id;
1397 $message->component = 'enrol_manual';
1398 $message->name = 'expiry_notification';
1399 $message->userfrom = $user2;
1400 $message->userto = $user1;
1401 $message->subject = 'Test: This is not a notification but otherwise is valid';
1402 $message->fullmessage = 'Test: Full message';
1403 $message->fullmessageformat = FORMAT_MARKDOWN;
1404 $message->fullmessagehtml = markdown_to_html($message->fullmessage);
1405 $message->smallmessage = $message->subject;
1406 $message->contexturlname = $course->fullname;
1407 $message->contexturl = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1408 message_send($message);
6ff4464b 1409
cc350fd9 1410 $message = new \core\message\message();
880fc15b 1411 $message->courseid = $course->id;
6ff4464b
JL
1412 $message->notification = 1;
1413 $message->component = 'enrol_manual';
1414 $message->name = 'expiry_notification';
1415 $message->userfrom = $user2;
1416 $message->userto = $user1;
1417 $message->subject = 'Enrolment expired';
1418 $message->fullmessage = 'Enrolment expired blah blah blah';
1419 $message->fullmessageformat = FORMAT_MARKDOWN;
1420 $message->fullmessagehtml = markdown_to_html($message->fullmessage);
1421 $message->smallmessage = $message->subject;
1422 $message->contexturlname = $course->fullname;
1423 $message->contexturl = (string)new moodle_url('/course/view.php', array('id' => $course->id));
1424 message_send($message);
1425
1426 $userfrom = core_user::get_noreply_user();
1427 $userfrom->maildisplay = true;
0e8b5160
EM
1428 $eventdata = new \core\message\message();
1429 $eventdata->courseid = $course->id;
6ff4464b
JL
1430 $eventdata->component = 'moodle';
1431 $eventdata->name = 'badgecreatornotice';
1432 $eventdata->userfrom = $userfrom;
1433 $eventdata->userto = $user1;
1434 $eventdata->notification = 1;
1435 $eventdata->subject = 'New badge';
1436 $eventdata->fullmessage = format_text_email($eventdata->subject, FORMAT_HTML);
1437 $eventdata->fullmessageformat = FORMAT_PLAIN;
1438 $eventdata->fullmessagehtml = $eventdata->subject;
1439 $eventdata->smallmessage = $eventdata->subject;
1440 message_send($eventdata);
1441
cc350fd9
AD
1442 $eventdata = new \core\message\message();
1443 $eventdata->courseid = $course->id;
6ff4464b
JL
1444 $eventdata->name = 'submission';
1445 $eventdata->component = 'mod_feedback';
1446 $eventdata->userfrom = $user1;
1447 $eventdata->userto = $user2;
1448 $eventdata->subject = 'Feedback submitted';
1449 $eventdata->fullmessage = 'Feedback submitted from an user';
1450 $eventdata->fullmessageformat = FORMAT_PLAIN;
1451 $eventdata->fullmessagehtml = '<strong>Feedback submitted</strong>';
1452 $eventdata->smallmessage = '';
1453 message_send($eventdata);
1454
1455 $this->setUser($user1);
1456 // Get read notifications from any user to user1.
1457 $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
1458 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1459 $this->assertCount(3, $messages['messages']);
1460
1461 // Get one read notifications from any user to user1.
1462 $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
1463 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1464 $this->assertCount(1, $messages['messages']);
1465
1466 // Get unread notifications from any user to user1.
1467 $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
1468 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1469 $this->assertCount(0, $messages['messages']);
1470
1471 // Get read both type of messages from any user to user1.
1472 $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
1473 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1474 $this->assertCount(4, $messages['messages']);
1475
1476 // Get read notifications from no-reply-user to user1.
1477 $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
1478 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1479 $this->assertCount(1, $messages['messages']);
1480
1481 // Get notifications send by user1 to any user.
1482 $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
1483 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1484 $this->assertCount(1, $messages['messages']);
1485
1486 // Test warnings.
1487 $CFG->messaging = 0;
1488
1489 $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
1490 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1491 $this->assertCount(1, $messages['warnings']);
1492
1493 // Test exceptions.
1494
1495 // Messaging disabled.
1496 try {
1497 $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1498 $this->fail('Exception expected due messaging disabled.');
1499 } catch (moodle_exception $e) {
1500 $this->assertEquals('disabled', $e->errorcode);
1501 }
1502
1503 $CFG->messaging = 1;
1504
1505 // Invalid users.
1506 try {
1507 $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
1508 $this->fail('Exception expected due invalid users.');
1509 } catch (moodle_exception $e) {
1510 $this->assertEquals('accessdenied', $e->errorcode);
1511 }
1512
1513 // Invalid user ids.
1514 try {
1515 $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
1516 $this->fail('Exception expected due invalid users.');
1517 } catch (moodle_exception $e) {
1518 $this->assertEquals('invaliduser', $e->errorcode);
1519 }
1520
1521 // Invalid users (permissions).
1522 $this->setUser($user2);
1523 try {
1524 $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
1525 $this->fail('Exception expected due invalid user.');
1526 } catch (moodle_exception $e) {
1527 $this->assertEquals('accessdenied', $e->errorcode);
1528 }
1529
1530 }
ff1f3739 1531
c57fadcc
MN
1532 /**
1533 * Test get_messages where we want all messages from a user, sent to any user.
1534 */
1535 public function test_get_messages_useridto_all() {
1536 $this->resetAfterTest(true);
1537
1538 $user1 = self::getDataGenerator()->create_user();
1539 $user2 = self::getDataGenerator()->create_user();
1540 $user3 = self::getDataGenerator()->create_user();
1541
1542 $this->setUser($user1);
1543
1544 // Send a message from user 1 to two other users.
1545 $this->send_message($user1, $user2, 'some random text 1', 0, 1);
1546 $this->send_message($user1, $user3, 'some random text 2', 0, 2);
1547
1548 // Get messages sent from user 1.
1549 $messages = core_message_external::get_messages(0, $user1->id, 'conversations', false, false, 0, 0);
1550 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1551
1552 // Confirm the data is correct.
1553 $messages = $messages['messages'];
1554 $this->assertCount(2, $messages);
1555
1556 $message1 = array_shift($messages);
1557 $message2 = array_shift($messages);
1558
1559 $this->assertEquals($user1->id, $message1['useridfrom']);
1560 $this->assertEquals($user2->id, $message1['useridto']);
1561
1562 $this->assertEquals($user1->id, $message2['useridfrom']);
1563 $this->assertEquals($user3->id, $message2['useridto']);
1564 }
1565
1566 /**
1567 * Test get_messages where we want all messages to a user, sent by any user.
1568 */
1569 public function test_get_messages_useridfrom_all() {
1570 $this->resetAfterTest();
1571
1572 $user1 = self::getDataGenerator()->create_user();
1573 $user2 = self::getDataGenerator()->create_user();
1574 $user3 = self::getDataGenerator()->create_user();
1575
1576 $this->setUser($user1);
1577
1578 // Send a message to user 1 from two other users.
1579 $this->send_message($user2, $user1, 'some random text 1', 0, 1);
1580 $this->send_message($user3, $user1, 'some random text 2', 0, 2);
1581
1582 // Get messages sent to user 1.
1583 $messages = core_message_external::get_messages($user1->id, 0, 'conversations', false, false, 0, 0);
1584 $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
1585
1586 // Confirm the data is correct.
1587 $messages = $messages['messages'];
1588 $this->assertCount(2, $messages);
1589
1590 $message1 = array_shift($messages);
1591 $message2 = array_shift($messages);
1592
1593 $this->assertEquals($user2->id, $message1['useridfrom']);
1594 $this->assertEquals($user1->id, $message1['useridto']);
1595
1596 $this->assertEquals($user3->id, $message2['useridfrom']);
1597 $this->assertEquals($user1->id, $message2['useridto']);
1598 }
1599
ff1f3739
JL
1600 /**
1601 * Test get_blocked_users.
1602 */
1603 public function test_get_blocked_users() {
1604 $this->resetAfterTest(true);
1605
1606 $user1 = self::getDataGenerator()->create_user();
1607 $userstranger = self::getDataGenerator()->create_user();
1608 $useroffline1 = self::getDataGenerator()->create_user();
1609 $useroffline2 = self::getDataGenerator()->create_user();
1610 $userblocked = self::getDataGenerator()->create_user();
1611
1612 // Login as user1.
1613 $this->setUser($user1);
f219eac7
MN
1614
1615 \core_message\api::add_contact($user1->id, $useroffline1->id);
1616 \core_message\api::add_contact($user1->id, $useroffline2->id);
ff1f3739
JL
1617
1618 // The userstranger sends a couple of messages to user1.
1619 $this->send_message($userstranger, $user1, 'Hello there!');
1620 $this->send_message($userstranger, $user1, 'How you goin?');
1621
1622 // The userblocked sends a message to user1.
1623 // Note that this user is not blocked at this point.
1624 $this->send_message($userblocked, $user1, 'Here, have some spam.');
1625
1626 // Retrieve the list of blocked users.
1627 $this->setUser($user1);
1628 $blockedusers = core_message_external::get_blocked_users($user1->id);
1629 $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1630 $this->assertCount(0, $blockedusers['users']);
1631
1632 // Block the $userblocked and retrieve again the list.
1633 core_message_external::block_contacts(array($userblocked->id));
f219eac7 1634 $this->assertDebuggingCalled();
ff1f3739
JL
1635 $blockedusers = core_message_external::get_blocked_users($user1->id);
1636 $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1637 $this->assertCount(1, $blockedusers['users']);
1638
01393790
JL
1639 // Remove the $userblocked and check that the list now is empty.
1640 delete_user($userblocked);
1641 $blockedusers = core_message_external::get_blocked_users($user1->id);
1642 $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
1643 $this->assertCount(0, $blockedusers['users']);
ff1f3739
JL
1644 }
1645
b6795827
JL
1646 /**
1647 * Test mark_message_read.
1648 */
1649 public function test_mark_message_read() {
1650 $this->resetAfterTest(true);
1651
1652 $user1 = self::getDataGenerator()->create_user();
1653 $user2 = self::getDataGenerator()->create_user();
1654 $user3 = self::getDataGenerator()->create_user();
1655
1656 // Login as user1.
1657 $this->setUser($user1);
f219eac7
MN
1658 \core_message\api::add_contact($user1->id, $user2->id);
1659 \core_message\api::add_contact($user1->id, $user3->id);
b6795827
JL
1660
1661 // The user2 sends a couple of messages to user1.
1662 $this->send_message($user2, $user1, 'Hello there!');
1663 $this->send_message($user2, $user1, 'How you goin?');
1664 $this->send_message($user3, $user1, 'How you goin?');
1665 $this->send_message($user3, $user2, 'How you goin?');
1666
1667 // Retrieve all messages sent by user2 (they are currently unread).
1668 $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1669
1670 $messageids = array();
1671 foreach ($lastmessages as $m) {
1672 $messageid = core_message_external::mark_message_read($m->id, time());
1673 $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
1674 }
1675
1676 // Retrieve all messages sent (they are currently read).
1677 $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
1678 $this->assertCount(2, $lastmessages);
1679 $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
1680 $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);
1681
1682 // Retrieve all messages sent by any user (that are currently unread).
1683 $lastmessages = message_get_messages($user1->id, 0, 0, false);
1684 $this->assertCount(1, $lastmessages);
1685
1686 // Invalid message ids.
1687 try {
883ce421 1688 $messageid = core_message_external::mark_message_read(1337, time());
b6795827
JL
1689 $this->fail('Exception expected due invalid messageid.');
1690 } catch (dml_missing_record_exception $e) {
883ce421 1691 $this->assertEquals('invalidrecordunknown', $e->errorcode);
b6795827
JL
1692 }
1693
1694 // A message to a different user.
1695 $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
1696 $messageid = array_pop($lastmessages)->id;
1697 try {
1698 $messageid = core_message_external::mark_message_read($messageid, time());
1699 $this->fail('Exception expected due invalid messageid.');
1700 } catch (invalid_parameter_exception $e) {
1701 $this->assertEquals('invalidparameter', $e->errorcode);
1702 }
2b595d96
MN
1703 }
1704
1705 /**
1706 * Test mark_notification_read.
1707 */
1708 public function test_mark_notification_read() {
1709 $this->resetAfterTest(true);
1710
1711 $user1 = self::getDataGenerator()->create_user();
1712 $user2 = self::getDataGenerator()->create_user();
1713 $user3 = self::getDataGenerator()->create_user();
1714
1715 // Login as user1.
1716 $this->setUser($user1);
f219eac7
MN
1717 \core_message\api::add_contact($user1->id, $user2->id);
1718 \core_message\api::add_contact($user1->id, $user3->id);
b6795827 1719
2b595d96
MN
1720 // The user2 sends a couple of notifications to user1.
1721 $this->send_message($user2, $user1, 'Hello there!', 1);
1722 $this->send_message($user2, $user1, 'How you goin?', 1);
1723 $this->send_message($user3, $user1, 'How you goin?', 1);
1724 $this->send_message($user3, $user2, 'How you goin?', 1);
1725
1726 // Retrieve all notifications sent by user2 (they are currently unread).
1727 $lastnotifications = message_get_messages($user1->id, $user2->id, 1, false);
1728
1729 $notificationids = array();
1730 foreach ($lastnotifications as $n) {
1731 $notificationid = core_message_external::mark_notification_read($n->id, time());
1732 $notificationids[] = external_api::clean_returnvalue(core_message_external::mark_notification_read_returns(),
1733 $notificationid);
1734 }
1735
1736 // Retrieve all notifications sent (they are currently read).
1737 $lastnotifications = message_get_messages($user1->id, $user2->id, 1, true);
1738 $this->assertCount(2, $lastnotifications);
1739 $this->assertArrayHasKey($notificationids[1]['notificationid'], $lastnotifications);
1740 $this->assertArrayHasKey($notificationids[0]['notificationid'], $lastnotifications);
1741
1742 // Retrieve all notifications sent by any user (that are currently unread).
1743 $lastnotifications = message_get_messages($user1->id, 0, 1, false);
1744 $this->assertCount(1, $lastnotifications);
1745
1746 // Invalid notification ids.
1747 try {
1748 $notificationid = core_message_external::mark_notification_read(1337, time());
1749 $this->fail('Exception expected due invalid notificationid.');
1750 } catch (dml_missing_record_exception $e) {
1751 $this->assertEquals('invalidrecord', $e->errorcode);
1752 }
1753
1754 // A notification to a different user.
1755 $lastnotifications = message_get_messages($user2->id, $user3->id, 1, false);
1756 $notificationid = array_pop($lastnotifications)->id;
1757 try {
1758 $notificationid = core_message_external::mark_notification_read($notificationid, time());
1759 $this->fail('Exception expected due invalid notificationid.');
1760 } catch (invalid_parameter_exception $e) {
1761 $this->assertEquals('invalidparameter', $e->errorcode);
1762 }
b6795827
JL
1763 }
1764
419b1128
JL
1765 /**
1766 * Test delete_message.
1767 */
1768 public function test_delete_message() {
1769 global $DB;
1770 $this->resetAfterTest(true);
1771
1772 $user1 = self::getDataGenerator()->create_user();
1773 $user2 = self::getDataGenerator()->create_user();
1774 $user3 = self::getDataGenerator()->create_user();
1775 $user4 = self::getDataGenerator()->create_user();
1776
1777 // Login as user1.
1778 $this->setUser($user1);
f219eac7
MN
1779 \core_message\api::add_contact($user1->id, $user2->id);
1780 \core_message\api::add_contact($user1->id, $user3->id);
419b1128
JL
1781
1782 // User user1 does not interchange messages with user3.
1783 $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
1784 $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
1785 $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
1786 $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);
1787
1788 // Retrieve all messages sent by user2 (they are currently unread).
1789 $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);
1790
1791 // Delete a message not read, as a user from.
1792 $result = core_message_external::delete_message($m1to2, $user1->id, false);
1793 $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1794 $this->assertTrue($result['status']);
1795 $this->assertCount(0, $result['warnings']);
883ce421
MN
1796 $mua = $DB->get_record('message_user_actions', array('messageid' => $m1to2, 'userid' => $user1->id));
1797 $this->assertEquals(\core_message\api::MESSAGE_ACTION_DELETED, $mua->action);
419b1128
JL
1798
1799 // Try to delete the same message again.
1800 $result = core_message_external::delete_message($m1to2, $user1->id, false);
1801 $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1802 $this->assertFalse($result['status']);
1803
1804 // Try to delete a message that does not belong to me.
1805 try {
1806 $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
1807 $this->fail('Exception expected due invalid messageid.');
1808 } catch (moodle_exception $e) {
1809 $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
1810 }
1811
1812 $this->setUser($user3);
1813 // Delete a message not read, as a user to.
1814 $result = core_message_external::delete_message($m2to3, $user3->id, false);
1815 $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1816 $this->assertTrue($result['status']);
1817 $this->assertCount(0, $result['warnings']);
883ce421
MN
1818 $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m2to3, 'userid' => $user3->id,
1819 'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
419b1128
JL
1820
1821 // Delete a message read.
548936a6
MN
1822 $message = $DB->get_record('messages', ['id' => $m3to2]);
1823 \core_message\api::mark_message_as_read($user3->id, $message, time());
883ce421 1824 $result = core_message_external::delete_message($m3to2, $user3->id);
419b1128
JL
1825 $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1826 $this->assertTrue($result['status']);
1827 $this->assertCount(0, $result['warnings']);
883ce421
MN
1828 $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to2, 'userid' => $user3->id,
1829 'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
419b1128
JL
1830
1831 // Invalid message ids.
1832 try {
1833 $result = core_message_external::delete_message(-1, $user1->id);
1834 $this->fail('Exception expected due invalid messageid.');
1835 } catch (dml_missing_record_exception $e) {
08cb8a34 1836 $this->assertEquals('invalidrecord', $e->errorcode);
419b1128
JL
1837 }
1838
1839 // Invalid user.
1840 try {
1841 $result = core_message_external::delete_message($m1to2, -1, false);
1842 $this->fail('Exception expected due invalid user.');
1843 } catch (moodle_exception $e) {
1844 $this->assertEquals('invaliduser', $e->errorcode);
1845 }
1846
1847 // Not active user.
1848 delete_user($user2);
1849 try {
1850 $result = core_message_external::delete_message($m1to2, $user2->id, false);
1851 $this->fail('Exception expected due invalid user.');
1852 } catch (moodle_exception $e) {
1853 $this->assertEquals('userdeleted', $e->errorcode);
1854 }
1855
1856 // Now, as an admin, try to delete any message.
1857 $this->setAdminUser();
1858 $result = core_message_external::delete_message($m3to4, $user4->id, false);
1859 $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
1860 $this->assertTrue($result['status']);
1861 $this->assertCount(0, $result['warnings']);
883ce421
MN
1862 $this->assertTrue($DB->record_exists('message_user_actions', array('messageid' => $m3to4, 'userid' => $user4->id,
1863 'action' => \core_message\api::MESSAGE_ACTION_DELETED)));
419b1128
JL
1864
1865 }
1866
3274d5ca
RW
1867 public function test_mark_all_notifications_as_read_invalid_user_exception() {
1868 $this->resetAfterTest(true);
1869
6aa01968
MN
1870 $this->expectException('moodle_exception');
1871 core_message_external::mark_all_notifications_as_read(-2132131, 0);
3274d5ca
RW
1872 }
1873
1874 public function test_mark_all_notifications_as_read_access_denied_exception() {
1875 $this->resetAfterTest(true);
1876
1877 $sender = $this->getDataGenerator()->create_user();
1878 $user = $this->getDataGenerator()->create_user();
1879
1880 $this->setUser($user);
6aa01968
MN
1881 $this->expectException('moodle_exception');
1882 core_message_external::mark_all_notifications_as_read($sender->id, 0);
3274d5ca
RW
1883 }
1884
1885 public function test_mark_all_notifications_as_read_missing_from_user_exception() {
1886 $this->resetAfterTest(true);
1887
1888 $sender = $this->getDataGenerator()->create_user();
1889
1890 $this->setUser($sender);
6aa01968
MN
1891 $this->expectException('moodle_exception');
1892 core_message_external::mark_all_notifications_as_read($sender->id, 99999);
3274d5ca
RW
1893 }
1894
1895 public function test_mark_all_notifications_as_read() {
7d69958e
RW
1896 global $DB;
1897
3274d5ca
RW
1898 $this->resetAfterTest(true);
1899
1900 $sender1 = $this->getDataGenerator()->create_user();
1901 $sender2 = $this->getDataGenerator()->create_user();
1902 $sender3 = $this->getDataGenerator()->create_user();
1903 $recipient = $this->getDataGenerator()->create_user();
1904
1905 $this->setUser($recipient);
1906
6aa01968
MN
1907 $this->send_message($sender1, $recipient, 'Notification', 1);
1908 $this->send_message($sender1, $recipient, 'Notification', 1);
1909 $this->send_message($sender2, $recipient, 'Notification', 1);
1910 $this->send_message($sender2, $recipient, 'Notification', 1);
1911 $this->send_message($sender3, $recipient, 'Notification', 1);
1912 $this->send_message($sender3, $recipient, 'Notification', 1);
3274d5ca
RW
1913
1914 core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
883ce421
MN
1915 $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1916 $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
3274d5ca 1917
7d69958e
RW
1918 $this->assertCount(2, $readnotifications);
1919 $this->assertCount(4, $unreadnotifications);
3274d5ca
RW
1920
1921 core_message_external::mark_all_notifications_as_read($recipient->id, 0);
883ce421
MN
1922 $readnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NOT NULL', [$recipient->id]);
1923 $unreadnotifications = $DB->get_records_select('notifications', 'useridto = ? AND timeread IS NULL', [$recipient->id]);
3274d5ca 1924
7d69958e
RW
1925 $this->assertCount(6, $readnotifications);
1926 $this->assertCount(0, $unreadnotifications);
3274d5ca 1927 }
e86f0cb4
JL
1928
1929 /**
1930 * Test get_user_notification_preferences
1931 */
1932 public function test_get_user_notification_preferences() {
1933 $this->resetAfterTest(true);
1934
1935 $user = self::getDataGenerator()->create_user();
1936 $this->setUser($user);
1937
1938 // Set a couple of preferences to test.
1939 set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
1940 set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
1941
1942 $prefs = core_message_external::get_user_notification_preferences();
1943 $prefs = external_api::clean_returnvalue(core_message_external::get_user_notification_preferences_returns(), $prefs);
1944 // Check processors.
46c5c883 1945 $this->assertGreaterThanOrEqual(2, count($prefs['preferences']['processors']));
e86f0cb4
JL
1946 $this->assertEquals($user->id, $prefs['preferences']['userid']);
1947
1948 // Check components.
46c5c883 1949 $this->assertGreaterThanOrEqual(8, count($prefs['preferences']['components']));
e86f0cb4
JL
1950
1951 // Check some preferences that we previously set.
1952 $found = 0;
1953 foreach ($prefs['preferences']['components'] as $component) {
1954 foreach ($component['notifications'] as $prefdata) {
1955 if ($prefdata['preferencekey'] != 'message_provider_mod_assign_assign_notification') {
1956 continue;
1957 }
1958 foreach ($prefdata['processors'] as $processor) {
1959 if ($processor['name'] == 'popup') {
1960 $this->assertTrue($processor['loggedin']['checked']);
1961 $found++;
1962 } else if ($processor['name'] == 'email') {
1963 $this->assertTrue($processor['loggedoff']['checked']);
1964 $found++;
1965 }
1966 }
1967 }
1968 }
1969 $this->assertEquals(2, $found);
1970 }
1971
1972 /**
1973 * Test get_user_notification_preferences permissions
1974 */
1975 public function test_get_user_notification_preferences_permissions() {
1976 $this->resetAfterTest(true);
1977
1978 $user = self::getDataGenerator()->create_user();
1979 $otheruser = self::getDataGenerator()->create_user();
1980 $this->setUser($user);
1981
1982 $this->expectException('moodle_exception');
1983 $prefs = core_message_external::get_user_notification_preferences($otheruser->id);
1984 }
6aa01968
MN
1985
1986 /**
1987 * Tests searching users in a course.
1988 */
548cac7d 1989 public function test_data_for_messagearea_search_users_in_course() {
6aa01968
MN
1990 $this->resetAfterTest(true);
1991
1992 // Create some users.
1993 $user1 = new stdClass();
1994 $user1->firstname = 'User';
1995 $user1->lastname = 'One';
1996 $user1 = self::getDataGenerator()->create_user($user1);
1997
1998 // The person doing the search.
1999 $this->setUser($user1);
2000
2001 // Set the second user's status to online by setting their last access to now.
2002 $user2 = new stdClass();
2003 $user2->firstname = 'User';
2004 $user2->lastname = 'Two';
2005 $user2->lastaccess = time();
2006 $user2 = self::getDataGenerator()->create_user($user2);
2007
2008 // Block the second user.
f219eac7 2009 \core_message\api::block_user($user1->id, $user2->id);
6aa01968
MN
2010
2011 $user3 = new stdClass();
2012 $user3->firstname = 'User';
2013 $user3->lastname = 'Three';
2014 $user3 = self::getDataGenerator()->create_user($user3);
2015
2016 // Create a course.
2017 $course1 = new stdClass();
2018 $course1->fullname = 'Course';
2019 $course1->shortname = 'One';
2020 $course1 = $this->getDataGenerator()->create_course();
2021
2022 // Enrol the user we are doing the search for and one user in the course.
2023 $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
2024 $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
2025
2026 // Perform a search.
2027 $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
2028
2029 // We need to execute the return values cleaning process to simulate the web service.
2030 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
2031 $result);
2032
2033 // Check that we only retrieved a user that was enrolled, and that the user performing the search was not returned.
2034 $users = $result['contacts'];
2035 $this->assertCount(1, $users);
2036
2037 $user = $users[0];
2038 $this->assertEquals($user2->id, $user['userid']);
2039 $this->assertEquals(fullname($user2), $user['fullname']);
2040 $this->assertFalse($user['ismessaging']);
2041 $this->assertFalse($user['sentfromcurrentuser']);
2042 $this->assertNull($user['lastmessage']);
2043 $this->assertNull($user['messageid']);
cb805753 2044 $this->assertNull($user['isonline']);
6aa01968
MN
2045 $this->assertFalse($user['isread']);
2046 $this->assertTrue($user['isblocked']);
2047 $this->assertNull($user['unreadcount']);
2048 }
2049
2050 /**
2051 * Tests searching users in course as another user.
2052 */
548cac7d 2053 public function test_data_for_messagearea_search_users_in_course_as_other_user() {
6aa01968
MN
2054 $this->resetAfterTest(true);
2055
2056 // The person doing the search for another user.
2057 $this->setAdminUser();
2058
2059 // Create some users.
2060 $user1 = new stdClass();
2061 $user1->firstname = 'User';
2062 $user1->lastname = 'One';
2063 $user1 = self::getDataGenerator()->create_user($user1);
2064
2065 $user2 = new stdClass();
2066 $user2->firstname = 'User';
2067 $user2->lastname = 'Two';
2068 $user2 = self::getDataGenerator()->create_user($user2);
2069
2070 $user3 = new stdClass();
2071 $user3->firstname = 'User';
2072 $user3->lastname = 'Three';
2073 $user3 = self::getDataGenerator()->create_user($user3);
2074
2075 // Create a course.
2076 $course1 = new stdClass();
2077 $course1->fullname = 'Course';
2078 $course1->shortname = 'One';
2079 $course1 = $this->getDataGenerator()->create_course();
2080
2081 // Enrol the user we are doing the search for and one user in the course.
2082 $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
2083 $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
2084
2085 // Perform a search.
2086 $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');
2087
2088 // We need to execute the return values cleaning process to simulate the web service server.
2089 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
2090 $result);
2091
2092 // Check that we got the user enrolled, and that the user we are performing the search on behalf of was not returned.
2093 $users = $result['contacts'];
2094 $this->assertCount(1, $users);
2095
2096 $user = $users[0];
2097 $this->assertEquals($user2->id, $user['userid']);
2098 $this->assertEquals(fullname($user2), $user['fullname']);
2099 $this->assertFalse($user['ismessaging']);
2100 $this->assertFalse($user['sentfromcurrentuser']);
2101 $this->assertNull($user['lastmessage']);
2102 $this->assertNull($user['messageid']);
2103 $this->assertFalse($user['isonline']);
2104 $this->assertFalse($user['isread']);
2105 $this->assertFalse($user['isblocked']);
2106 $this->assertNull($user['unreadcount']);
2107 }
2108
2109 /**
2110 * Tests searching users in course as another user without the proper capabilities.
2111 */
548cac7d 2112 public function test_data_for_messagearea_search_users_in_course_as_other_user_without_cap() {
6aa01968
MN
2113 $this->resetAfterTest(true);
2114
2115 // Create some users.
2116 $user1 = self::getDataGenerator()->create_user();
2117 $user2 = self::getDataGenerator()->create_user();
2118
2119 // The person doing the search for another user.
2120 $this->setUser($user1);
2121
2122 // Create a course.
2123 $course = $this->getDataGenerator()->create_course();
2124
2125 // Ensure an exception is thrown.
2126 $this->expectException('moodle_exception');
2127 core_message_external::data_for_messagearea_search_users_in_course($user2->id, $course->id, 'User');
548cac7d 2128 $this->assertDebuggingCalled();
6aa01968
MN
2129 }
2130
2131 /**
2132 * Tests searching users in course with messaging disabled.
2133 */
548cac7d 2134 public function test_data_for_messagearea_search_users_in_course_messaging_disabled() {
6aa01968
MN
2135 global $CFG;
2136
2137 $this->resetAfterTest(true);
2138
2139 // Create some skeleton data just so we can call the WS..
2140 $user = self::getDataGenerator()->create_user();
2141 $course = $this->getDataGenerator()->create_course();
2142
2143 // The person doing the search for another user.
2144 $this->setUser($user);
2145
2146 // Disable messaging.
2147 $CFG->messaging = 0;
2148
2149 // Ensure an exception is thrown.
2150 $this->expectException('moodle_exception');
2151 core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
548cac7d 2152 $this->assertDebuggingCalled();
6aa01968
MN
2153 }
2154
2155 /**
2156 * Tests searching users.
2157 */
548cac7d 2158 public function test_data_for_messagearea_search_users() {
6aa01968
MN
2159 $this->resetAfterTest(true);
2160
2161 // Create some users.
2162 $user1 = new stdClass();
2163 $user1->firstname = 'User';
2164 $user1->lastname = 'One';
2165 $user1 = self::getDataGenerator()->create_user($user1);
2166
2167 // Set as the user performing the search.
2168 $this->setUser($user1);
2169
2170 $user2 = new stdClass();
2171 $user2->firstname = 'User search';
2172 $user2->lastname = 'Two';
2173 $user2 = self::getDataGenerator()->create_user($user2);
2174
2175 $user3 = new stdClass();
2176 $user3->firstname = 'User search';
2177 $user3->lastname = 'Three';
2178 $user3 = self::getDataGenerator()->create_user($user3);
2179
2180 $user4 = new stdClass();
2181 $user4->firstname = 'User';
2182 $user4->lastname = 'Four';
2183 $user4 = self::getDataGenerator()->create_user($user4);
2184
2185 $user5 = new stdClass();
2186 $user5->firstname = 'User search';
2187 $user5->lastname = 'Five';
2188 $user5 = self::getDataGenerator()->create_user($user5);
2189
2190 $user6 = new stdClass();
2191 $user6->firstname = 'User';
2192 $user6->lastname = 'Six';
2193 $user6 = self::getDataGenerator()->create_user($user6);
2194
2195 // Create some courses.
2196 $course1 = new stdClass();
2197 $course1->fullname = 'Course search';
2198 $course1->shortname = 'One';
2199 $course1 = $this->getDataGenerator()->create_course($course1);
2200
2201 $course2 = new stdClass();
2202 $course2->fullname = 'Course';
2203 $course2->shortname = 'Two';
2204 $course2 = $this->getDataGenerator()->create_course($course2);
2205
2206 $course3 = new stdClass();
2207 $course3->fullname = 'Course';
2208 $course3->shortname = 'Three search';
2209 $course3 = $this->getDataGenerator()->create_course($course3);
2210
87d4ab65
AG
2211 $course4 = new stdClass();
2212 $course4->fullname = 'Course Four';
2213 $course4->shortname = 'CF100';
2214 $course4 = $this->getDataGenerator()->create_course($course4);
2215
2216 $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
2217 $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
2218 $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');
2219
6aa01968 2220 // Add some users as contacts.
f219eac7
MN
2221 \core_message\api::add_contact($user1->id, $user2->id);
2222 \core_message\api::add_contact($user1->id, $user3->id);
2223 \core_message\api::add_contact($user1->id, $user4->id);
6aa01968 2224
548cac7d
AA
2225 // Perform a search $CFG->messagingallusers setting enabled.
2226 set_config('messagingallusers', 1);
6aa01968
MN
2227 $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2228
2229 // We need to execute the return values cleaning process to simulate the web service server.
2230 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2231 $result);
2232
2233 // Confirm that we returns contacts, courses and non-contacts.
2234 $contacts = $result['contacts'];
2235 $courses = $result['courses'];
2236 $noncontacts = $result['noncontacts'];
2237
2238 // Check that we retrieved the correct contacts.
2239 $this->assertCount(2, $contacts);
2240 $this->assertEquals($user3->id, $contacts[0]['userid']);
2241 $this->assertEquals($user2->id, $contacts[1]['userid']);
2242
2243 // Check that we retrieved the correct courses.
2244 $this->assertCount(2, $courses);
2245 $this->assertEquals($course3->id, $courses[0]['id']);
2246 $this->assertEquals($course1->id, $courses[1]['id']);
2247
2248 // Check that we retrieved the correct non-contacts.
2249 $this->assertCount(1, $noncontacts);
2250 $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2251 }
2252
2253 /**
2254 * Tests searching users as another user.
2255 */
548cac7d 2256 public function test_data_for_messagearea_search_users_as_other_user() {
6aa01968
MN
2257 $this->resetAfterTest(true);
2258
2259 // The person doing the search.
2260 $this->setAdminUser();
2261
2262 // Create some users.
2263 $user1 = new stdClass();
2264 $user1->firstname = 'User';
2265 $user1->lastname = 'One';
2266 $user1 = self::getDataGenerator()->create_user($user1);
2267
2268 $user2 = new stdClass();
2269 $user2->firstname = 'User search';
2270 $user2->lastname = 'Two';
2271 $user2 = self::getDataGenerator()->create_user($user2);
2272
2273 $user3 = new stdClass();
2274 $user3->firstname = 'User search';
2275 $user3->lastname = 'Three';
2276 $user3 = self::getDataGenerator()->create_user($user3);
2277
2278 $user4 = new stdClass();
2279 $user4->firstname = 'User';
2280 $user4->lastname = 'Four';
2281 $user4 = self::getDataGenerator()->create_user($user4);
2282
2283 $user5 = new stdClass();
2284 $user5->firstname = 'User search';
2285 $user5->lastname = 'Five';
2286 $user5 = self::getDataGenerator()->create_user($user5);
2287
2288 $user6 = new stdClass();
2289 $user6->firstname = 'User';
2290 $user6->lastname = 'Six';
2291 $user6 = self::getDataGenerator()->create_user($user6);
2292
2293 // Create some courses.
2294 $course1 = new stdClass();
2295 $course1->fullname = 'Course search';
2296 $course1->shortname = 'One';
2297 $course1 = $this->getDataGenerator()->create_course($course1);
2298
2299 $course2 = new stdClass();
2300 $course2->fullname = 'Course';
2301 $course2->shortname = 'Two';
2302 $course2 = $this->getDataGenerator()->create_course($course2);
2303
2304 $course3 = new stdClass();
2305 $course3->fullname = 'Course';
2306 $course3->shortname = 'Three search';
2307 $course3 = $this->getDataGenerator()->create_course($course3);
2308
2309 // Add some users as contacts.
f219eac7
MN
2310 \core_message\api::add_contact($user1->id, $user2->id);
2311 \core_message\api::add_contact($user1->id, $user3->id);
2312 \core_message\api::add_contact($user1->id, $user4->id);
6aa01968 2313
548cac7d
AA
2314 // Perform a search $CFG->messagingallusers setting enabled.
2315 set_config('messagingallusers', 1);
6aa01968
MN
2316 $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');
2317
2318 // We need to execute the return values cleaning process to simulate the web service server.
2319 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
2320 $result);
2321
2322 // Confirm that we returns contacts, courses and non-contacts.
2323 $contacts = $result['contacts'];
2324 $courses = $result['courses'];
2325 $noncontacts = $result['noncontacts'];
2326
2327 // Check that we retrieved the correct contacts.
2328 $this->assertCount(2, $contacts);
2329 $this->assertEquals($user3->id, $contacts[0]['userid']);
2330 $this->assertEquals($user2->id, $contacts[1]['userid']);
2331
2332 // Check that we retrieved the correct courses.
87d4ab65 2333 $this->assertCount(0, $courses);
6aa01968
MN
2334
2335 // Check that we retrieved the correct non-contacts.
2336 $this->assertCount(1, $noncontacts);
2337 $this->assertEquals($user5->id, $noncontacts[0]['userid']);
2338 }
2339
2340 /**
2341 * Tests searching users as another user without the proper capabilities.
2342 */
548cac7d 2343 public function test_data_for_messagearea_search_users_as_other_user_without_cap() {
6aa01968
MN
2344 $this->resetAfterTest(true);
2345
2346 // Create some users.
2347 $user1 = self::getDataGenerator()->create_user();
2348 $user2 = self::getDataGenerator()->create_user();
2349
2350 // The person doing the search for another user.
2351 $this->setUser($user1);
2352
2353 // Ensure an exception is thrown.
2354 $this->expectException('moodle_exception');
2355 core_message_external::data_for_messagearea_search_users($user2->id, 'User');
548cac7d 2356 $this->assertDebuggingCalled();
6aa01968
MN
2357 }
2358
2359 /**
2360 * Tests searching users with messaging disabled.
2361 */
548cac7d 2362 public function test_data_for_messagearea_search_users_messaging_disabled() {
6aa01968
MN
2363 global $CFG;
2364
2365 $this->resetAfterTest(true);
2366
2367 // Create some skeleton data just so we can call the WS.
2368 $user = self::getDataGenerator()->create_user();
2369
2370 // The person doing the search.
2371 $this->setUser($user);
2372
2373 // Disable messaging.
2374 $CFG->messaging = 0;
2375
2376 // Ensure an exception is thrown.
2377 $this->expectException('moodle_exception');
2378 core_message_external::data_for_messagearea_search_users($user->id, 'User');
548cac7d
AA
2379 $this->assertDebuggingCalled();
2380 }
2381
2382 /**
41485be2
JD
2383 * Tests searching for users when site-wide messaging is disabled.
2384 *
2385 * This test verifies that any contacts are returned, as well as any non-contacts whose profile we can view.
2386 * If checks this by placing some users in the same course, where default caps would permit a user to view another user's
2387 * profile.
548cac7d 2388 */
41485be2
JD
2389 public function test_message_search_users_messagingallusers_disabled() {
2390 $this->resetAfterTest();
548cac7d
AA
2391
2392 // Create some users.
41485be2
JD
2393 $users = [];
2394 foreach (range(1, 7) as $i) {
2395 $user = new stdClass();
2396 $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
2397 $user->lastname = $i;
2398 $user = $this->getDataGenerator()->create_user($user);
2399 $users[$i] = $user;
2400 }
548cac7d 2401
41485be2
JD
2402 // Enrol a few users in the same course, but leave them as non-contacts.
2403 $course1 = $this->getDataGenerator()->create_course();
2404 $this->setAdminUser();
2405 $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
2406 $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
2407 $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
548cac7d 2408
41485be2
JD
2409 // Add some other users as contacts.
2410 \core_message\api::add_contact($users[1]->id, $users[2]->id);
2411 \core_message\api::add_contact($users[3]->id, $users[1]->id);
2412 \core_message\api::add_contact($users[1]->id, $users[4]->id);
548cac7d 2413
41485be2 2414 // Create individual conversations between some users, one contact and one non-contact.
548cac7d 2415 \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
41485be2 2416 [$users[1]->id, $users[2]->id]);
548cac7d 2417 \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
41485be2 2418 [$users[6]->id, $users[1]->id]);
548cac7d 2419
41485be2
JD
2420 // Create a group conversation between 4 users, including a contact and a non-contact.
2421 \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2422 [$users[1]->id, $users[2]->id, $users[4]->id, $users[7]->id], 'Project chat');
548cac7d 2423
41485be2
JD
2424 // Set as the user performing the search.
2425 $this->setUser($users[1]);
548cac7d 2426
41485be2 2427 // Perform a search with $CFG->messagingallusers disabled.
548cac7d 2428 set_config('messagingallusers', 0);
41485be2
JD
2429 $result = core_message_external::message_search_users($users[1]->id, 'search');
2430 $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
548cac7d
AA
2431
2432 // Confirm that we returns contacts and non-contacts.
41485be2
JD
2433 $this->assertArrayHasKey('contacts', $result);
2434 $this->assertArrayHasKey('noncontacts', $result);
548cac7d
AA
2435 $contacts = $result['contacts'];
2436 $noncontacts = $result['noncontacts'];
2437
2438 // Check that we retrieved the correct contacts.
2439 $this->assertCount(2, $contacts);
41485be2
JD
2440 $this->assertEquals($users[2]->id, $contacts[0]['id']);
2441 $this->assertEquals($users[3]->id, $contacts[1]['id']);
2442
2443 // Verify the correct conversations were returned for the contacts.
2444 $this->assertCount(2, $contacts[0]['conversations']);
2445 // We can't rely on the ordering of conversations within the results, so sort by id first.
2446 usort($contacts[0]['conversations'], function($a, $b) {
2447 return $a['id'] < $b['id'];
2448 });
2449 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $contacts[0]['conversations'][0]['type']);
2450 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $contacts[0]['conversations'][1]['type']);
2451
2452 $this->assertCount(0, $contacts[1]['conversations']);
548cac7d
AA
2453
2454 // Check that we retrieved the correct non-contacts.
41485be2 2455 // When site wide messaging is disabled, we expect to see only those users whose profiles we can view.
548cac7d 2456 $this->assertCount(2, $noncontacts);
41485be2
JD
2457 $this->assertEquals($users[6]->id, $noncontacts[0]['id']);
2458 $this->assertEquals($users[7]->id, $noncontacts[1]['id']);
2459
2460 // Verify the correct conversations were returned for the non-contacts.
2461 $this->assertCount(1, $noncontacts[0]['conversations']);
2462 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $noncontacts[0]['conversations'][0]['type']);
2463
2464 $this->assertCount(1, $noncontacts[1]['conversations']);
2465 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[1]['conversations'][0]['type']);
548cac7d
AA
2466 }
2467
2468 /**
41485be2
JD
2469 * Tests searching for users when site-wide messaging is enabled.
2470 *
2471 * This test verifies that any contacts are returned, as well as any non-contacts, regardless of whether the searching user
2472 * can view their respective profile.
548cac7d 2473 */
41485be2
JD
2474 public function test_message_search_users_messagingallusers_enabled() {
2475 $this->resetAfterTest();
548cac7d
AA
2476
2477 // Create some users.
41485be2
JD
2478 $users = [];
2479 foreach (range(1, 8) as $i) {
2480 $user = new stdClass();
2481 $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
2482 $user->lastname = $i;
2483 $user = $this->getDataGenerator()->create_user($user);
2484 $users[$i] = $user;
2485 }
548cac7d 2486
41485be2
JD
2487 // Enrol a few users in the same course, but leave them as non-contacts.
2488 $course1 = $this->getDataGenerator()->create_course();
2489 $this->setAdminUser();
2490 $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
2491 $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
2492 $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
548cac7d 2493
41485be2
JD
2494 // Add some other users as contacts.
2495 \core_message\api::add_contact($users[1]->id, $users[2]->id);
2496 \core_message\api::add_contact($users[3]->id, $users[1]->id);
2497 \core_message\api::add_contact($users[1]->id, $users[4]->id);
548cac7d 2498
41485be2 2499 // Create individual conversations between some users, one contact and one non-contact.
548cac7d 2500 \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
41485be2 2501 [$users[1]->id, $users[2]->id]);
548cac7d 2502 \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
41485be2 2503 [$users[6]->id, $users[1]->id]);
548cac7d 2504
41485be2
JD
2505 // Create a group conversation between 5 users, including a contact and a non-contact, and a user NOT in a shared course.
2506 \core_message\api::create_conversation(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
2507 [$users[1]->id, $users[2]->id, $users[4]->id, $users[7]->id, $users[8]->id], 'Project chat');
548cac7d 2508
41485be2
JD
2509 // Set as the user performing the search.
2510 $this->setUser($users[1]);
2511
2512 // Perform a search with $CFG->messagingallusers enabled.
2513 set_config('messagingallusers', 1);
2514 $result = core_message_external::message_search_users($users[1]->id, 'search');
2515 $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
548cac7d
AA
2516
2517 // Confirm that we returns contacts and non-contacts.
41485be2
JD
2518 $this->assertArrayHasKey('contacts', $result);
2519 $this->assertArrayHasKey('noncontacts', $result);
548cac7d
AA
2520 $contacts = $result['contacts'];
2521 $noncontacts = $result['noncontacts'];
2522
2523 // Check that we retrieved the correct contacts.
2524 $this->assertCount(2, $contacts);
41485be2
JD
2525 $this->assertEquals($users[2]->id, $contacts[0]['id']);
2526 $this->assertEquals($users[3]->id, $contacts[1]['id']);
548cac7d 2527
41485be2
JD
2528 // Verify the correct conversations were returned for the contacts.
2529 $this->assertCount(2, $contacts[0]['conversations']);
2530 // We can't rely on the ordering of conversations within the results, so sort by id first.
2531 usort($contacts[0]['conversations'], function($a, $b) {
2532 return $a['id'] < $b['id'];
2533 });
2534 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $contacts[0]['conversations'][0]['type']);
2535 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $contacts[0]['conversations'][1]['type']);
548cac7d 2536
41485be2 2537 $this->assertCount(0, $contacts[1]['conversations']);
548cac7d 2538
41485be2
JD
2539 // Check that we retrieved the correct non-contacts.
2540 // If site wide messaging is enabled, we expect to be able to search for any users.
2541 $this->assertCount(4, $noncontacts);
2542 $this->assertEquals($users[5]->id, $noncontacts[0]['id']);
2543 $this->assertEquals($users[6]->id, $noncontacts[1]['id']);
2544 $this->assertEquals($users[7]->id, $noncontacts[2]['id']);
2545 $this->assertEquals($users[8]->id, $noncontacts[3]['id']);
2546
2547 // Verify the correct conversations were returned for the non-contacts.
2548 $this->assertCount(0, $noncontacts[0]['conversations']);
548cac7d 2549
41485be2
JD
2550 $this->assertCount(1, $noncontacts[1]['conversations']);
2551 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL, $noncontacts[1]['conversations'][0]['type']);
548cac7d 2552
41485be2
JD
2553 $this->assertCount(1, $noncontacts[2]['conversations']);
2554 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[2]['conversations'][0]['type']);
548cac7d 2555
41485be2
JD
2556 $this->assertCount(1, $noncontacts[3]['conversations']);
2557 $this->assertEquals(\core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP, $noncontacts[3]['conversations'][0]['type']);
548cac7d
AA
2558 }
2559
2560 /**
41485be2 2561 * Verify searching for users works even if no matching users from either contacts, or non-contacts can be found.
548cac7d 2562 */
41485be2
JD
2563 public function test_message_search_users_with_empty_result() {
2564 $this->resetAfterTest();
548cac7d 2565
41485be2
JD
2566 // Create some users, but make sure neither will match the search term.
2567 $user1 = new stdClass();
2568 $user1->firstname = 'User';
2569 $user1->lastname = 'One';
2570 $user1 = $this->getDataGenerator()->create_user($user1);
2571 $user2 = new stdClass();
2572 $user2->firstname = 'User';
2573 $user2->lastname = 'Two';
2574 $user2 = $this->getDataGenerator()->create_user($user2);
548cac7d 2575
41485be2 2576 // Perform a search as user1.
548cac7d 2577 $this->setUser($user1);
41485be2
JD
2578 $result = core_message_external::message_search_users($user1->id, 'search');
2579 $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
548cac7d 2580
41485be2
JD
2581 // Check results are empty.
2582 $this->assertCount(0, $result['contacts']);
2583 $this->assertCount(0, $result['noncontacts']);
548cac7d
AA
2584 }
2585
2586 /**
41485be2 2587 * Test verifying that limits and offsets work for both the contacts and non-contacts return data.
548cac7d 2588 */
41485be2
JD
2589 public function test_message_search_users_limit_offset() {
2590 $this->resetAfterTest();
548cac7d 2591
41485be2
JD
2592 // Create 20 users.
2593 $users = [];
2594 foreach (range(1, 20) as $i) {
2595 $user = new stdClass();
2596 $user->firstname = "User search";
2597 $user->lastname = $i;
2598 $user = $this->getDataGenerator()->create_user($user);
2599 $users[$i] = $user;
2600 }
2601
2602 // Enrol the first 9 users in the same course, but leave them as non-contacts.
2603 $this->setAdminUser();
2604 $course1 = $this->getDataGenerator()->create_course();
2605 foreach (range(1, 9) as $i) {
2606 $this->getDataGenerator()->enrol_user($users[$i]->id, $course1->id);
2607 }
2608
2609 // Add 5 users, starting at the 11th user, as contacts for user1.
2610 foreach (range(11, 15) as $i) {
2611 \core_message\api::add_contact($users[1]->id, $users[$i]->id);
2612 }
548cac7d
AA
2613
2614 // Set as the user performing the search.
41485be2 2615 $this->setUser($users[1]);
548cac7d 2616
41485be2
JD
2617 // Search using a limit of 3.
2618 // This tests the case where we have more results than the limit for both contacts and non-contacts.
2619 $result = core_message_external::message_search_users($users[1]->id, 'search', 0, 3);
2620 $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2621 $contacts = $result['contacts'];
2622 $noncontacts = $result['noncontacts'];
548cac7d 2623
41485be2
JD
2624 // Check that we retrieved the correct contacts.
2625 $this->assertCount(3, $contacts);
2626 $this->assertEquals($users[11]->id, $contacts[0]['id']);
2627 $this->assertEquals($users[12]->id, $contacts[1]['id']);
2628 $this->assertEquals($users[13]->id, $contacts[2]['id']);
548cac7d 2629
41485be2
JD
2630 // Check that we retrieved the correct non-contacts.
2631 $this->assertCount(3, $noncontacts);
2632 $this->assertEquals($users[2]->id, $noncontacts[0]['id']);
2633 $this->assertEquals($users[3]->id, $noncontacts[1]['id']);
2634 $this->assertEquals($users[4]->id, $noncontacts[2]['id']);
2635
2636 // Now, offset to get the next batch of results.
2637 // We expect to see 2 contacts, and 3 non-contacts.
2638 $result = core_message_external::message_search_users($users[1]->id, 'search', 3, 3);
2639 $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2640 $contacts = $result['contacts'];
2641 $noncontacts = $result['noncontacts'];
2642 $this->assertCount(2, $contacts);
2643 $this->assertEquals($users[14]->id, $contacts[0]['id']);
2644 $this->assertEquals($users[15]->id, $contacts[1]['id']);
548cac7d 2645
41485be2
JD
2646 $this->assertCount(3, $noncontacts);
2647 $this->assertEquals($users[5]->id, $noncontacts[0]['id']);
2648 $this->assertEquals($users[6]->id, $noncontacts[1]['id']);
2649 $this->assertEquals($users[7]->id, $noncontacts[2]['id']);
2650
2651 // Now, offset to get the next batch of results.
2652 // We expect to see 0 contacts, and 2 non-contacts.
2653 $result = core_message_external::message_search_users($users[1]->id, 'search', 6, 3);
2654 $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
2655 $contacts = $result['contacts'];
2656 $noncontacts = $result['noncontacts'];
2657 $this->assertCount(0, $contacts);
548cac7d 2658
41485be2
JD
2659 $this->assertCount(2, $noncontacts);
2660 $this->assertEquals($users[8]->id, $noncontacts[0]['id']);
2661 $this->assertEquals($users[9]->id, $noncontacts[1]['id']);
2662 }
548cac7d 2663
41485be2
JD
2664 /**
2665 * Tests searching users as another user having the 'moodle/user:viewdetails' capability.
2666 */
2667 public function test_message_search_users_with_cap() {
2668 $this->resetAfterTest();
2669 global $DB;
548cac7d 2670
41485be2
JD
2671 // Create some users.
2672 $users = [];
2673 foreach (range(1, 8) as $i) {
2674 $user = new stdClass();
2675 $user->firstname = ($i == 4) ? 'User' : 'User search'; // Ensure the fourth user won't match the search term.
2676 $user->lastname = $i;
2677 $user = $this->getDataGenerator()->create_user($user);
2678 $users[$i] = $user;
2679 }
548cac7d 2680
41485be2
JD
2681 // Enrol a few users in the same course, but leave them as non-contacts.
2682 $course1 = $this->getDataGenerator()->create_course();
2683 $this->setAdminUser();
2684 $this->getDataGenerator()->enrol_user($users[1]->id, $course1->id);
2685 $this->getDataGenerator()->enrol_user($users[6]->id, $course1->id);
2686 $this->getDataGenerator()->enrol_user($users[7]->id, $course1->id);
548cac7d 2687
41485be2
JD
2688 // Add some other users as contacts.
2689 \core_message\api::add_contact($users[1]->id, $users[2]->id);
2690 \core_message\api::add_contact($users[3]->id, $users[1]->id);
2691 \core_message\api::add_contact($users[1]->id, $users[4]->id);
548cac7d 2692
41485be2
JD
2693 // Set as the user performing the search.
2694 $this->setUser($users[1]);
2695
2696 // Grant the authenticated user role the capability 'user:viewdetails' at site context.
2697 $authenticatedrole = $DB->get_record('role', ['shortname' => 'user'], '*', MUST_EXIST);
2698 assign_capability('moodle/user:viewdetails', CAP_ALLOW, $authenticatedrole->id, context_system::instance());
2699
2700 // Perform a search with $CFG->messagingallusers disabled.
2701 set_config('messagingallusers', 0);
2702 $result = core_message_external::message_search_users($users[1]->id, 'search');
2703 $result = external_api::clean_returnvalue(core_message_external::message_search_users_returns(), $result);
548cac7d
AA
2704 $contacts = $result['contacts'];
2705 $noncontacts = $result['noncontacts'];
2706
2707 // Check that we retrieved the correct contacts.
41485be2
JD
2708 $this->assertCount(2, $contacts);
2709 $this->assertEquals($users[2]->id, $contacts[0]['id']);
2710 $this->assertEquals($users[3]->id, $contacts[1]['id']);
548cac7d
AA
2711
2712 // Check that we retrieved the correct non-contacts.
41485be2
JD
2713 // Site-wide messaging is disabled, but since we can see all users, we expect to be able to search for any users.
2714 $this->assertCount(4, $noncontacts);
2715 $this->assertEquals($users[5]->id, $noncontacts[0]['id']);
2716 $this->assertEquals($users[6]->id, $noncontacts[1]['id']);
2717 $this->assertEquals($users[7]->id, $noncontacts[2]['id']);
2718 $this->assertEquals($users[8]->id, $noncontacts[3]['id']);
2719 }
548cac7d 2720
41485be2
JD
2721 /**
2722 * Tests searching users as another user without the 'moodle/user:viewdetails' capability.
2723 */
2724 public function test_message_search_users_without_cap() {
2725 $this->resetAfterTest();
2726
2727 // Create some users.
2728 $user1 = $this->getDataGenerator()->create_user();
2729 $user2 = $this->getDataGenerator()->create_user();
2730
2731 // The person doing the search for another user.
2732 $this->setUser($user1);
2733
2734 // Ensure an exception is thrown.
2735 $this->expectException('moodle_exception');
2736 core_message_external::message_search_users($user2->id, 'User');
2737 $this->assertDebuggingCalled();
548cac7d
AA
2738 }
2739
2740 /**
2741 * Tests searching users with messaging disabled.
2742 */
2743 public function test_message_search_users_messaging_disabled() {
41485be2 2744 $this->resetAfterTest();
548cac7d
AA
2745
2746 // Create some skeleton data just so we can call the WS.
41485be2 2747 $user = $this->getDataGenerator()->create_user();
548cac7d
AA
2748
2749 // The person doing the search.
2750 $this->setUser($user);
2751
2752 // Disable messaging.
2753 set_config('messaging', 0);
2754
2755 // Ensure an exception is thrown.
2756 $this->expectException('moodle_exception');
2757 core_message_external::message_search_users($user->id, 'User');
6aa01968
MN
2758 }
2759
2760 /**
2761 * Tests searching messages.
2762 */
2763 public function test_messagearea_search_messages() {
2764 $this->resetAfterTest(true);
2765
2766 // Create some users.
2767 $user1 = self::getDataGenerator()->create_user();
2768 $user2 = self::getDataGenerator()->create_user();
2769
2770 // The person doing the search.
2771 $this->setUser($user1);
2772
2773 // Send some messages back and forth.
2774 $time = time();
2775 $this->send_message($user1, $user2, 'Yo!', 0, $time);
2776 $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2777 $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2778 $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
d2708759 2779 $convid = \core_message\api::get_conversation_between_users([$user1->id, $user2->id]);
6aa01968
MN
2780
2781 // Perform a search.
2782 $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2783
2784 // We need to execute the return values cleaning process to simulate the web service server.
d2708759 2785 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(), $result);
6aa01968
MN
2786
2787 // Confirm the data is correct.
2788 $messages = $result['contacts'];
2789 $this->assertCount(2, $messages);
2790
2791 $message1 = $messages[0];
2792 $message2 = $messages[1];
2793
2794 $this->assertEquals($user2->id, $message1['userid']);
2795 $this->assertEquals(fullname($user2), $message1['fullname']);
2796 $this->assertTrue($message1['ismessaging']);
2797 $this->assertFalse($message1['sentfromcurrentuser']);
2798 $this->assertEquals('Word.', $message1['lastmessage']);
2799 $this->assertNotEmpty($message1['messageid']);
cb805753 2800 $this->assertNull($message1['isonline']);
6aa01968
MN
2801 $this->assertFalse($message1['isread']);
2802 $this->assertFalse($message1['isblocked']);
2803 $this->assertNull($message1['unreadcount']);
d2708759 2804 $this->assertEquals($convid, $message1['conversationid']);
6aa01968
MN
2805
2806 $this->assertEquals($user2->id, $message2['userid']);
2807 $this->assertEquals(fullname($user2), $message2['fullname']);
2808 $this->assertTrue($message2['ismessaging']);
2809 $this->assertTrue($message2['sentfromcurrentuser']);
2810 $this->assertEquals('Yo!', $message2['lastmessage']);
2811 $this->assertNotEmpty($message2['messageid']);
cb805753 2812 $this->assertNull($message2['isonline']);
6aa01968
MN
2813 $this->assertTrue($message2['isread']);
2814 $this->assertFalse($message2['isblocked']);
2815 $this->assertNull($message2['unreadcount']);
d2708759 2816 $this->assertEquals($convid, $message2['conversationid']);
6aa01968
MN
2817 }
2818
2819 /**
2820 * Tests searching messages as another user.
2821 */
2822 public function test_messagearea_search_messages_as_other_user() {
2823 $this->resetAfterTest(true);
2824
2825 // The person doing the search.
2826 $this->setAdminUser();
2827
2828 // Create some users.
2829 $user1 = self::getDataGenerator()->create_user();
2830 $user2 = self::getDataGenerator()->create_user();
2831
2832 // Send some messages back and forth.
2833 $time = time();
2834 $this->send_message($user1, $user2, 'Yo!', 0, $time);
2835 $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2836 $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
2837 $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
2838
2839 // Perform a search.
2840 $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');
2841
2842 // We need to execute the return values cleaning process to simulate the web service server.
2843 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
2844 $result);
2845
2846 // Confirm the data is correct.
2847 $messages = $result['contacts'];
2848 $this->assertCount(2, $messages);
2849
2850 $message1 = $messages[0];
2851 $message2 = $messages[1];
2852
2853 $this->assertEquals($user2->id, $message1['userid']);
2854 $this->assertEquals(fullname($user2), $message1['fullname']);
2855 $this->assertTrue($message1['ismessaging']);
2856 $this->assertFalse($message1['sentfromcurrentuser']);
2857 $this->assertEquals('Word.', $message1['lastmessage']);
2858 $this->assertNotEmpty($message1['messageid']);
2859 $this->assertFalse($message1['isonline']);
2860 $this->assertFalse($message1['isread']);
2861 $this->assertFalse($message1['isblocked']);
2862 $this->assertNull($message1['unreadcount']);
2863
2864 $this->assertEquals($user2->id, $message2['userid']);
2865 $this->assertEquals(fullname($user2), $message2['fullname']);
2866 $this->assertTrue($message2['ismessaging']);
2867 $this->assertTrue($message2['sentfromcurrentuser']);
2868 $this->assertEquals('Yo!', $message2['lastmessage']);
2869 $this->assertNotEmpty($message2['messageid']);
2870 $this->assertFalse($message2['isonline']);
2871 $this->assertTrue($message2['isread']);
2872 $this->assertFalse($message2['isblocked']);
2873 $this->assertNull($message2['unreadcount']);
2874 }
2875
2876 /**
2877 * Tests searching messages as another user without the proper capabilities.
2878 */
2879 public function test_messagearea_search_messages_as_other_user_without_cap() {
2880 $this->resetAfterTest(true);
2881
2882 // Create some users.
2883 $user1 = self::getDataGenerator()->create_user();
2884 $user2 = self::getDataGenerator()->create_user();
2885
2886 // The person doing the search for another user.
2887 $this->setUser($user1);
2888
2889 // Ensure an exception is thrown.
2890 $this->expectException('moodle_exception');
2891 core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
2892 }
2893
2894 /**
2895 * Tests searching messages with messaging disabled
2896 */
2897 public function test_messagearea_search_messages_messaging_disabled() {
2898 global $CFG;
2899
2900 $this->resetAfterTest(true);
2901
2902 // Create some skeleton data just so we can call the WS.
2903 $user = self::getDataGenerator()->create_user();
2904
2905 // The person doing the search .
2906 $this->setUser($user);
2907
2908 // Disable messaging.
2909 $CFG->messaging = 0;
2910
2911 // Ensure an exception is thrown.
2912 $this->expectException('moodle_exception');
2913 core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
2914 }
2915
2916 /**
2917 * Tests retrieving conversations.
2918 */
2919 public function test_messagearea_conversations() {
2920 $this->resetAfterTest(true);
2921
2922 // Create some users.
2923 $user1 = self::getDataGenerator()->create_user();
2924 $user2 = self::getDataGenerator()->create_user();
2925 $user3 = self::getDataGenerator()->create_user();
2926 $user4 = self::getDataGenerator()->create_user();
2927
2928 // The person retrieving the conversations.
2929 $this->setUser($user1);
2930
2931 // Send some messages back and forth, have some different conversations with different users.
2932 $time = time();
2933 $this->send_message($user1, $user2, 'Yo!', 0, $time);
2934 $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
2935 $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
4d146f1a 2936 $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
6aa01968
MN
2937
2938 $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
2939 $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
2940 $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
4d146f1a 2941 $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
6aa01968
MN
2942
2943 $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
2944 $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
4d146f1a 2945 $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
6aa01968
MN
2946
2947 // Retrieve the conversations.
2948 $result = core_message_external::data_for_messagearea_conversations($user1->id);
2949
2950 // We need to execute the return values cleaning process to simulate the web service server.
2951 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
2952 $result);
2953
2954 // Confirm the data is correct.
2955 $messages = $result['contacts'];
2956 $this->assertCount(3, $messages);
2957
2958 $message1 = $messages[0];
2959 $message2 = $messages[1];
2960 $message3 = $messages[2];
2961
2962 $this->assertEquals($user4->id, $message1['userid']);
2963 $this->assertTrue($message1['ismessaging']);
2964 $this->assertTrue($message1['sentfromcurrentuser']);
2965 $this->assertEquals('Dope.', $message1['lastmessage']);
4d146f1a 2966 $this->assertEquals($messageid3, $message1['messageid']);
cb805753 2967 $this->assertNull($message1['isonline']);
4d146f1a 2968 $this->assertFalse($message1['isread']);
6aa01968 2969 $this->assertFalse($message1['isblocked']);
4d146f1a 2970 $this->assertEquals(1, $message1['unreadcount']);
6aa01968
MN
2971
2972 $this->assertEquals($user3->id, $message2['userid']);
2973 $this->assertTrue($message2['ismessaging']);
2974 $this->assertFalse($message2['sentfromcurrentuser']);
2975 $this->assertEquals('Cool.', $message2['lastmessage']);
4d146f1a 2976 $this->assertEquals($messageid2, $message2['messageid']);
cb805753 2977 $this->assertNull($message2['isonline']);
6aa01968
MN
2978 $this->assertFalse($message2['isread']);
2979 $this->assertFalse($message2['isblocked']);
2980 $this->assertEquals(2, $message2['unreadcount']);
2981
2982 $this->assertEquals($user2->id, $message3['userid']);
2983 $this->assertTrue($message3['ismessaging']);
2984 $this->assertFalse($message3['sentfromcurrentuser']);
2985 $this->assertEquals('Word.', $message3['lastmessage']);
4d146f1a 2986 $this->assertEquals($messageid1, $message3['messageid']);
cb805753 2987 $this->assertNull($message3['isonline']);
6aa01968
MN
2988 $this->assertFalse($message3['isread']);
2989 $this->assertFalse($message3['isblocked']);
2990 $this->assertEquals(2, $message3['unreadcount']);
2991 }
2992
2993 /**
2994 * Tests retrieving conversations as another user.
2995 */
2996 public function test_messagearea_conversations_as_other_user() {
2997 $this->resetAfterTest(true);
2998
2999 // Set as admin.
3000 $this->setAdminUser();
3001
3002 // Create some users.
3003 $user1 = self::getDataGenerator()->create_user();
3004 $user2 = self::getDataGenerator()->create_user();
3005 $user3 = self::getDataGenerator()->create_user();
3006 $user4 = self::getDataGenerator()->create_user();
3007
3008 // Send some messages back and forth, have some different conversations with different users.
3009 $time = time();
3010 $this->send_message($user1, $user2, 'Yo!', 0, $time);
3011 $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
3012 $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
4d146f1a 3013 $messageid1 = $this->send_message($user2, $user1, 'Word.', 0, $time + 3);
6aa01968
MN
3014
3015 $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
3016 $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
3017 $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
4d146f1a 3018 $messageid2 = $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);
6aa01968
MN
3019
3020 $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
3021 $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
4d146f1a 3022 $messageid3 = $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);
6aa01968
MN
3023
3024 // Retrieve the conversations.
3025 $result = core_message_external::data_for_messagearea_conversations($user1->id);
3026
3027 // We need to execute the return values cleaning process to simulate the web service server.
3028 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
3029 $result);
3030
3031 // Confirm the data is correct.
3032 $messages = $result['contacts'];
3033 $this->assertCount(3, $messages);
3034
3035 $message1 = $messages[0];
3036 $message2 = $messages[1];
3037 $message3 = $messages[2];
3038
3039 $this->assertEquals($user4->id, $message1['userid']);
3040 $this->assertTrue($message1['ismessaging']);
3041 $this->assertTrue($message1['sentfromcurrentuser']);
3042 $this->assertEquals('Dope.', $message1['lastmessage']);
4d146f1a 3043 $this->assertEquals($messageid3, $message1['messageid']);
6aa01968 3044 $this->assertFalse($message1['isonline']);
4d146f1a 3045 $this->assertFalse($message1['isread']);
6aa01968 3046 $this->assertFalse($message1['isblocked']);
4d146f1a 3047 $this->assertEquals(1, $message1['unreadcount']);
6aa01968
MN
3048
3049 $this->assertEquals($user3->id, $message2['userid']);
3050 $this->assertTrue($message2['ismessaging']);
3051 $this->assertFalse($message2['sentfromcurrentuser']);
3052 $this->assertEquals('Cool.', $message2['lastmessage']);
4d146f1a 3053 $this->assertEquals($messageid2, $message2['messageid']);
6aa01968
MN
3054 $this->assertFalse($message2['isonline']);
3055 $this->assertFalse($message2['isread']);
3056 $this->assertFalse($message2['isblocked']);
3057 $this->assertEquals(2, $message2['unreadcount']);
3058
3059 $this->assertEquals($user2->id, $message3['userid']);
3060 $this->assertTrue($message3['ismessaging']);
3061 $this->assertFalse($message3['sentfromcurrentuser']);
3062 $this->assertEquals('Word.', $message3['lastmessage']);
4d146f1a 3063 $this->assertEquals($messageid1, $message3['messageid']);
6aa01968
MN
3064 $this->assertFalse($message3['isonline']);
3065 $this->assertFalse($message3['isread']);
3066 $this->assertFalse($message3['isblocked']);
3067 $this->assertEquals(2, $message3['unreadcount']);
3068 }
3069
3070 /**
3071 * Tests retrieving conversations as another user without the proper capabilities.
3072 */
3073 public function test_messagearea_conversations_as_other_user_without_cap() {
3074 $this->resetAfterTest(true);
3075
3076 // Create some users.
3077 $user1 = self::getDataGenerator()->create_user();
3078 $user2 = self::getDataGenerator()->create_user();
3079
3080 // The person retrieving the conversations for another user.
3081 $this->setUser($user1);
3082
3083 // Ensure an exception is thrown.
3084 $this->expectException('moodle_exception');
3085 core_message_external::data_for_messagearea_conversations($user2->id);
3086 }
3087
3088 /**
3089 * Tests retrieving conversations with messaging disabled.
3090 */
3091 public function test_messagearea_conversations_messaging_disabled() {
3092 global $CFG;
3093
3094 $this->resetAfterTest(true);
3095
3096 // Create some skeleton data just so we can call the WS.
3097 $user = self::getDataGenerator()->create_user();
3098
3099 // The person retrieving the conversations.
3100 $this->setUser($user);
3101
3102 // Disable messaging.
3103 $CFG->messaging = 0;
3104
3105 // Ensure an exception is thrown.
3106 $this->expectException('moodle_exception');
3107 core_message_external::data_for_messagearea_conversations($user->id);
3108 }
3109
3110 /**
3111 * Tests retrieving contacts.
3112 */
3113 public function test_messagearea_contacts() {
3114 $this->resetAfterTest(true);
3115
3116 // Create some users.
3117 $user1 = self::getDataGenerator()->create_user();
3118
3119 // Set as the user.
3120 $this->setUser($user1);
3121
3122 $user2 = new stdClass();
3123 $user2->firstname = 'User';
3124 $user2->lastname = 'A';
3125 $user2 = self::getDataGenerator()->create_user($user2);
3126
3127 $user3 = new stdClass();
3128 $user3->firstname = 'User';
3129 $user3->lastname = 'B';
3130 $user3 = self::getDataGenerator()->create_user($user3);
3131
3132 $user4 = new stdClass();
3133 $user4->firstname = 'User';
3134 $user4->lastname = 'C';
3135 $user4 = self::getDataGenerator()->create_user($user4);
3136
3137 $user5 = new stdClass();
3138 $user5->firstname = 'User';
3139 $user5->lastname = 'D';
3140 $user5 = self::getDataGenerator()->create_user($user5);
3141
3142 // Add some users as contacts.
f219eac7
MN
3143 \core_message\api::add_contact($user1->id, $user2->id);
3144 \core_message\api::add_contact($user1->id, $user3->id);
3145 \core_message\api::add_contact($user1->id, $user4->id);
6aa01968
MN
3146
3147 // Retrieve the contacts.
3148 $result = core_message_external::data_for_messagearea_contacts($user1->id);
3149
3150 // We need to execute the return values cleaning process to simulate the web service server.
3151 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
3152 $result);
3153
3154 // Confirm the data is correct.
3155 $contacts = $result['contacts'];
f219eac7 3156 usort($contacts, ['static', 'sort_contacts']);
6aa01968
MN
3157 $this->assertCount(3, $contacts);
3158
3159 $contact1 = $contacts[0];
3160 $contact2 = $contacts[1];
3161 $contact3 = $contacts[2];
3162
3163 $this->assertEquals($user2->id, $contact1['userid']);
3164 $this->assertFalse($contact1['ismessaging']);
3165 $this->assertFalse($contact1['sentfromcurrentuser']);
3166 $this->assertNull($contact1['lastmessage']);
3167 $this->assertNull($contact1['messageid']);
cb805753 3168 $this->assertNull($contact1['isonline']);
6aa01968
MN
3169 $this->assertFalse($contact1['isread']);
3170 $this->assertFalse($contact1['isblocked']);
3171 $this->assertNull($contact1['unreadcount']);
3172
3173 $this->assertEquals($user3->id, $contact2['userid']);
3174 $this->assertFalse($contact2['ismessaging']);
3175 $this->assertFalse($contact2['sentfromcurrentuser']);
3176 $this->assertNull($contact2['lastmessage']);
3177 $this->assertNull($contact2['messageid']);
cb805753 3178 $this->assertNull($contact2['isonline']);
6aa01968
MN
3179 $this->assertFalse($contact2['isread']);
3180 $this->assertFalse($contact2['isblocked']);
3181 $this->assertNull($contact2['unreadcount']);
3182
3183 $this->assertEquals($user4->id, $contact3['userid']);
3184 $this->assertFalse($contact3['ismessaging']);
3185 $this->assertFalse($contact3['sentfromcurrentuser']);
3186 $this->assertNull($contact3['lastmessage']);
3187 $this->assertNull($contact3['messageid']);
cb805753 3188 $this->assertNull($contact3['isonline']);
6aa01968
MN
3189 $this->assertFalse($contact3['isread']);
3190 $this->assertFalse($contact3['isblocked']);
3191 $this->assertNull($contact3['unreadcount']);
3192 }
3193
3194 /**
3195 * Tests retrieving contacts as another user.
3196 */
3197 public function test_messagearea_contacts_as_other_user() {
3198 $this->resetAfterTest(true);
3199
3200 $this->setAdminUser();
3201
3202 // Create some users.
3203 $user1 = self::getDataGenerator()->create_user();
3204
3205 $user2 = new stdClass();
3206 $user2->firstname = 'User';
3207 $user2->lastname = 'A';
3208 $user2 = self::getDataGenerator()->create_user($user2);
3209
3210 $user3 = new stdClass();
3211 $user3->firstname = 'User';
3212 $user3->lastname = 'B';
3213 $user3 = self::getDataGenerator()->create_user($user3);
3214
3215 $user4 = new stdClass();
3216 $user4->firstname = 'User';
3217 $user4->lastname = 'C';
3218 $user4 = self::getDataGenerator()->create_user($user4);
3219
3220 $user5 = new stdClass();
3221 $user5->firstname = 'User';
3222 $user5->lastname = 'D';
3223 $user5 = self::getDataGenerator()->create_user($user5);
3224
3225 // Add some users as contacts.
f219eac7
MN
3226 \core_message\api::add_contact($user1->id, $user2->id);
3227 \core_message\api::add_contact($user1->id, $user3->id);
3228 \core_message\api::add_contact($user1->id, $user4->id);
6aa01968
MN
3229
3230 // Retrieve the contacts.
3231 $result = core_message_external::data_for_messagearea_contacts($user1->id);
3232
3233 // We need to execute the return values cleaning process to simulate the web service server.
3234 $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
3235 $result);
3236
3237 // Confirm the data is correct.
3238 $contacts = $result['contacts'];
f219eac7 3239 usort($contacts, ['static', 'sort_contacts']);
6aa01968
MN
3240 $this->assertCount(3, $contacts);
3241
3242 $contact1 = $contacts[0];
3243 $contact2 = $contacts[1];
3244 $contact3 = $contacts[2];
3245
3246 $this->assertEquals($user2->id, $contact1['userid']);
3247 $this->assertFalse($contact1['ismessaging']);
3248 $this->assertFalse($contact1['sentfromcurrentuser']);
3249 $this->assertNull($contact1['lastmessage']);
3250 $this->assertNull($contact1['messageid']);
3251 $this->assertFalse($contact1['isonline']);
3252 $this->assertFalse($contact1['isread']);
3253 $this->assertFalse($contact1['isblocked']);
3254 $this->assertNull($contact1['unreadcount']);
3255
3256 $this->assertEquals($user3->id, $contact2['userid']);
3257 $this->assertFalse($contact2['ismessaging']);
3258 $this->assertFalse($contact2['sentfromcurrentuser']);
3259 $this->assertNull($contact2['lastmessage']);
3260 $this->assertNull($contact2['messageid']);
3261 $this->assertFalse($contact2['isonline']);
3262 $this->assertFalse($contact2['isread']);
3263 $this->assertFalse($contact2['isblocked']);
3264 $this->assertNull($contact2['unreadcount']);
3265
3266 $this->assertEquals($user4->id, $contact3['userid']);
3267 $this->assertFalse($contact3['ismessaging']);
3268 $this->assertFalse($contact3['sentfromcurrentuser']);
3269 $this->assertNull($contact3['lastmessage']);
3270 $this->assertNull($contact3['messageid']);
3271 $this->assertFalse($contact3['isonline']);
3272 $this->assertFalse($contact3['isread']);
3273 $this->assertFalse($contact3['isblocked']);
3274 $this->assertNull($contact3['unreadcount']);
3275 }
3276
3277 /**
3278 * Tests retrieving contacts as another user without the proper capabilities.
3279 */
3280 public function test_messagearea_contacts_as_other_user_without_cap() {
3281 $this->resetAfterTest(true);
3282
3283 // Create some users.
3284 $user1 = self::getDataGenerator()->create_user();
3285 $user2 = self::getDataGenerator()->create_user();
3286
3287 // The person retrieving the contacts for another user.
3288 $this->setUser($user1);
3289
3290 // Perform the WS call and ensure an exception is thrown.
3291 $this->expectException('moodle_exception');
3292 core_message_external::data_for_messagearea_contacts($user2->id);
3293 }
3294
3295 /**
3296 * Tests retrieving contacts with messaging disabled.
3297 */
3298 public function test_messagearea_contacts_messaging_disabled() {
3299 global $CFG;
3300
3301 $this->resetAfterTest(true);
3302
3303 // Create some skeleton data just so we can call the WS.
3304 $user = self::getDataGenerator()->create_user();
3305
3306 // The person retrieving the contacts.
3307 $this->setUser($user);
3308
3309 // Disable messaging.
3310 $CFG->messaging = 0;
3311
3312 // Perform the WS call and ensure we are shown that it is disabled.
3313 $this->expectException('moodle_exception');
3314 core_message_external::data_for_messagearea_contacts($user->id);
3315 }
3316
c9b0f33f
MN
3317 /**
3318 * Tests retrieving contacts.
3319 */
3320 public function test_get_user_contacts() {
3321 $this->resetAfterTest(true);
3322
3323 // Create some users.
3324 $user1 = self::getDataGenerator()->create_user();
3325
3326 // Set as the user.
3327 $this->setUser($user1);
3328
3329 $user2 = new stdClass();
3330 $user2->firstname = 'User';
3331 $user2->lastname = 'A';
3332 $user2 = self::getDataGenerator()->create_user($user2);
3333
3334 $user3 = new stdClass();
3335 $user3->firstname = 'User';
3336 $user3->lastname = 'B';
3337 $user3 = self::getDataGenerator()->create_user($user3);
3338
3339 $user4 = new stdClass();
3340 $user4->firstname = 'User';
3341 $user4->lastname = 'C';
3342 $user4 = self::getDataGenerator()->create_user($user4);
3343
3344 $user5 = new stdClass();
3345 $user5->firstname = 'User';
3346 $user5->lastname = 'D';
3347 $user5 = self::getDataGenerator()->create_user($user5);
3348
3349 // Add some users as contacts.
3350 \core_message\api::add_contact($user1->id, $user2->id);
3351 \core_message\api::add_contact($user1->id, $user3->id);
3352 \core_message\api::add_contact($user1->id, $user4->id);
3353
3354 // Retrieve the contacts.
3355 $result = core_message_external::get_user_contacts($user1->id);
3356
3357 // We need to execute the return values cleaning process to simulate the web service server.
3358 $result = external_api::clean_returnvalue(core_message_external::get_user_contacts_returns(),
3359 $result);
3360
3361 // Confirm the data is correct.
3362 $contacts = $result;
3363 usort($contacts, ['static', 'sort_contacts_id']);
3364 $this->assertCount(3, $contacts);
3365
3366 $contact1 = array_shift($contacts);
3367 $contact2 = array_shift($contacts);
3368 $contact3 = array_shift($contacts);
3369
3370 $this->assertEquals($user2->id, $contact1['id']);
3371 $this->assertEquals(fullname($user2), $contact1['fullname']);
3372 $this->assertTrue($contact1['iscontact']);
3373
3374 $this->assertEquals($user3->id, $contact2['id']);
3375 $this->assertEquals(fullname($user3), $contact2['fullname']);
3376 $this->assertTrue($contact2['iscontact']);
3377
3378 $this->assertEquals($user4->id, $contact3['id']);
3379 $this->assertEquals(fullname($user4), $contact3['fullname']);
3380 $this->assertTrue($contact3['iscontact']);
3381 }
3382
3383 /**
3384 * Tests retrieving contacts as another user.
3385 */
3386 public function test_get_user_contacts_as_other_user() {
3387 $this->resetAfterTest(true);
3388
3389 $this->setAdminUser();
3390
3391 // Create some users.
3392 $user1 = self::getDataGenerator()->create_user();
3393
3394 $user2 = new stdClass();
3395 $user2->firstname = 'User';
3396 $user2->lastname = 'A';
3397 $user2 = self::getDataGenerator()->create_user($user2);
3398
3399 $user3 = new stdClass();
3400 $user3->firstname = 'User';
3401 $user3->lastname = 'B';
3402 $user3 = self::getDataGenerator()->create_user($user3);
3403
3404 $user4 = new stdClass();
3405 $user4->firstname = 'User';
3406 $user4->lastname = 'C';
3407 $user4 = self::getDataGenerator()->create_user($user4);
3408
3409 $user5 = new stdClass();
3410 $user5->firstname = 'User';
3411 $user5->lastname = 'D';
3412 $user5 = self::getDataGenerator()->create_user($user5);
3413
3414 // Add some users as contacts.
3415 \core_message\api::add_contact($user1->id, $user2->id);
3416 \core_message\api::add_contact($user1->id, $user3->id);
3417 \core_message\api::add_contact($user1->id, $user4->id);
3418
3419 // Retrieve the contacts.
3420 $result = core_message_external::get_user_contacts($user1->id);
3421
3422 // We need to execute the return values cleaning process to simulate the web service server.
3423 $result = external_api::clean_returnvalue(core_message_external::get_user_contacts_returns(),
3424 $result);
3425
3426 // Confirm the data is correct.
3427 $contacts = $result;
3428 usort($contacts, ['static', 'sort_contacts_id']);
3429 $this->assertCount(3, $contacts);
3430
3431 $contact1 = array_shift($contacts);
3432 $contact2 = array_shift($contacts);
3433 $contact3 = array_shift($contacts);
3434
3435 $this->assertEquals($user2->id, $contact1['id']);
3436 $this->assertEquals(fullname($user2), $contact1['fullname']);
3437 $this->assertTrue($contact1['iscontact']);
3438
3439 $this->assertEquals($user3->id, $contact2['id']);
3440 $this->assertEquals(fullname($user3), $contact2['fullname']);
3441 $this->assertTrue($contact2['iscontact']);
3442
3443 $this->assertEquals($user4->id, $contact3['id']);
3444 $this->assertEquals(fullname($user4), $contact3['fullname']);
3445 $this->assertTrue($contact3['iscontact']);
3446 }
3447
3448 /**
3449 * Tests retrieving contacts as another user without the proper capabilities.
3450 */
3451 public function test_get_user_contacts_as_other_user_without_cap() {
3452 $this->resetAfterTest(true);
3453
3454 // Create some users.
3455 $user1 = self::getDataGenerator()->create_user();
3456 $user2 = self::getDataGenerator()->create_user();
3457
3458 // The person retrieving the contacts for another user.
3459 $this->setUser($user1);
3460
3461 // Perform the WS call and ensure an exception is thrown.
3462 $this->expectException('moodle_exception');
3463 core_message_external::get_user_contacts($user2->id);
3464 }
3465
3466 /**
3467 * Tests retrieving contacts with messaging disabled.
3468 */
3469 public function test_get_user_contacts_messaging_disabled() {
3470 global $CFG;
3471
3472 $this->resetAfterTest(true);
3473
3474 // Create some skeleton data just so we can call the WS.
3475 $user = self::getDataGenerator()->create_user();
3476
3477 // The person retrieving the contacts.
3478 $this->setUser($user);
3479
3480 // Disable messaging.
3481 $CFG->messaging = 0;
3482
3483 // Perform the WS call and ensure we are shown that it is disabled.
3484 $this->expectException('moodle_exception');
3485 core_message_external::get_user_contacts($user->id);
3486 }
3487
3488 /**
3489 * Test getting contacts when there are no results.
3490 */