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

/**
 * External message functions unit tests
 *
 * @package    core_message
 * @category   external
 * @copyright  2012 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

global $CFG;

require_once($CFG->dirroot . '/webservice/tests/helpers.php');
require_once($CFG->dirroot . '/message/externallib.php');

33
class core_message_externallib_testcase extends externallib_advanced_testcase {
34

35
36
37
38
39
40
41
42
43
    /**
     * Tests set up
     */
    protected function setUp() {
        global $CFG;

        require_once($CFG->dirroot . '/message/lib.php');
    }

44
45
46
47
48
49
50
51
52
53
    /**
     * Send a fake message.
     *
     * {@link message_send()} does not support transaction, this function will simulate a message
     * sent from a user to another. We should stop using it once {@link message_send()} will support
     * transactions. This is not clean at all, this is just used to add rows to the table.
     *
     * @param stdClass $userfrom user object of the one sending the message.
     * @param stdClass $userto user object of the one receiving the message.
     * @param string $message message to send.
54
     * @param int $notification is the message a notification.
55
     * @param int $time the time the message was sent
56
     */
57
    protected function send_message($userfrom, $userto, $message = 'Hello world!', $notification = 0, $time = 0) {
58
        global $DB;
59
60
61
62
63

        if (empty($time)) {
            $time = time();
        }

64
65
66
67
        $record = new stdClass();
        $record->useridfrom = $userfrom->id;
        $record->useridto = $userto->id;
        $record->subject = 'No subject';
68
        $record->smallmessage = $message;
69
        $record->fullmessage = $message;
70
        $record->timecreated = $time;
71
        $record->notification = $notification;
72
        $DB->insert_record('message', $record);
73
74
    }

75
76
77
78
79
80
81
82
    /**
     * Test send_instant_messages
     */
    public function test_send_instant_messages() {

        global $DB, $USER, $CFG;

        $this->resetAfterTest(true);
83
84
        // Transactions used in tests, tell phpunit use alternative reset method.
        $this->preventResetByRollback();
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

        // Turn off all message processors (so nothing is really sent)
        require_once($CFG->dirroot . '/message/lib.php');
        $messageprocessors = get_message_processors();
        foreach($messageprocessors as $messageprocessor) {
            $messageprocessor->enabled = 0;
            $DB->update_record('message_processors', $messageprocessor);
        }

        // Set the required capabilities by the external function
        $contextid = context_system::instance()->id;
        $roleid = $this->assignUserCapability('moodle/site:sendmessage', $contextid);

        $user1 = self::getDataGenerator()->create_user();

        // Create test message data.
        $message1 = array();
        $message1['touserid'] = $user1->id;
        $message1['text'] = 'the message.';
        $message1['clientmsgid'] = 4;
        $messages = array($message1);

        $sentmessages = core_message_external::send_instant_messages($messages);

109
110
111
        // We need to execute the return values cleaning process to simulate the web service server.
        $sentmessages = external_api::clean_returnvalue(core_message_external::send_instant_messages_returns(), $sentmessages);

112
113
114
115
116
117
118
119
        $themessage = $DB->get_record('message', array('id' => $sentmessages[0]['msgid']));

        // Confirm that the message was inserted correctly.
        $this->assertEquals($themessage->useridfrom, $USER->id);
        $this->assertEquals($themessage->useridto, $message1['touserid']);
        $this->assertEquals($themessage->smallmessage, $message1['text']);
        $this->assertEquals($sentmessages[0]['clientmsgid'], $message1['clientmsgid']);
    }
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

    /**
     * Test create_contacts.
     */
    public function test_create_contacts() {
        $this->resetAfterTest(true);

        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();
        $user4 = self::getDataGenerator()->create_user();
        $user5 = self::getDataGenerator()->create_user();
        $this->setUser($user1);

        // Adding a contact.
        $return = core_message_external::create_contacts(array($user2->id));
        $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
        $this->assertEquals(array(), $return);

        // Adding a contact who is already a contact.
        $return = core_message_external::create_contacts(array($user2->id));
        $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
        $this->assertEquals(array(), $return);

        // Adding multiple contacts.
        $return = core_message_external::create_contacts(array($user3->id, $user4->id));
        $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
        $this->assertEquals(array(), $return);

        // Adding a non-existing user.
        $return = core_message_external::create_contacts(array(99999));
        $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
        $this->assertCount(1, $return);
        $return = array_pop($return);
        $this->assertEquals($return['warningcode'], 'contactnotcreated');
        $this->assertEquals($return['itemid'], 99999);

        // Adding contacts with valid and invalid parameters.
        $return = core_message_external::create_contacts(array($user5->id, 99999));
        $return = external_api::clean_returnvalue(core_message_external::create_contacts_returns(), $return);
        $this->assertCount(1, $return);
        $return = array_pop($return);
        $this->assertEquals($return['warningcode'], 'contactnotcreated');
        $this->assertEquals($return['itemid'], 99999);
164
165
166
167
168

        // Try to add a contact to another user, should throw an exception.
        // All assertions must be added before this point.
        $this->expectException('required_capability_exception');
        core_message_external::create_contacts(array($user2->id), $user3->id);
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    }

    /**
     * Test delete_contacts.
     */
    public function test_delete_contacts() {
        $this->resetAfterTest(true);

        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();
        $user4 = self::getDataGenerator()->create_user();
        $user5 = self::getDataGenerator()->create_user();
        $user6 = self::getDataGenerator()->create_user();
        $this->setUser($user1);
        $this->assertEquals(array(), core_message_external::create_contacts(
            array($user3->id, $user4->id, $user5->id, $user6->id)));

        // Removing a non-contact.
        $return = core_message_external::delete_contacts(array($user2->id));
        $this->assertNull($return);

        // Removing one contact.
        $return = core_message_external::delete_contacts(array($user3->id));
        $this->assertNull($return);

        // Removing multiple contacts.
        $return = core_message_external::delete_contacts(array($user4->id, $user5->id));
        $this->assertNull($return);

        // Removing contact from unexisting user.
        $return = core_message_external::delete_contacts(array(99999));
        $this->assertNull($return);

        // Removing mixed valid and invalid data.
        $return = core_message_external::delete_contacts(array($user6->id, 99999));
        $this->assertNull($return);
206
207
208
209
210

        // Try to delete a contact of another user contact list, should throw an exception.
        // All assertions must be added before this point.
        $this->expectException('required_capability_exception');
        core_message_external::delete_contacts(array($user2->id), $user3->id);
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    }

    /**
     * Test block_contacts.
     */
    public function test_block_contacts() {
        $this->resetAfterTest(true);

        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();
        $user4 = self::getDataGenerator()->create_user();
        $user5 = self::getDataGenerator()->create_user();
        $this->setUser($user1);
        $this->assertEquals(array(), core_message_external::create_contacts(array($user3->id, $user4->id, $user5->id)));

        // Blocking a contact.
        $return = core_message_external::block_contacts(array($user2->id));
        $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
        $this->assertEquals(array(), $return);

        // Blocking a contact who is already a contact.
        $return = core_message_external::block_contacts(array($user2->id));
        $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
        $this->assertEquals(array(), $return);

        // Blocking multiple contacts.
        $return = core_message_external::block_contacts(array($user3->id, $user4->id));
        $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
        $this->assertEquals(array(), $return);

        // Blocking a non-existing user.
        $return = core_message_external::block_contacts(array(99999));
        $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
        $this->assertCount(1, $return);
        $return = array_pop($return);
        $this->assertEquals($return['warningcode'], 'contactnotblocked');
        $this->assertEquals($return['itemid'], 99999);

        // Blocking contacts with valid and invalid parameters.
        $return = core_message_external::block_contacts(array($user5->id, 99999));
        $return = external_api::clean_returnvalue(core_message_external::block_contacts_returns(), $return);
        $this->assertCount(1, $return);
        $return = array_pop($return);
        $this->assertEquals($return['warningcode'], 'contactnotblocked');
        $this->assertEquals($return['itemid'], 99999);
257
258
259
260
261

        // Try to block a contact of another user contact list, should throw an exception.
        // All assertions must be added before this point.
        $this->expectException('required_capability_exception');
        core_message_external::block_contacts(array($user2->id), $user3->id);
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
    }

    /**
     * Test unblock_contacts.
     */
    public function test_unblock_contacts() {
        $this->resetAfterTest(true);

        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();
        $user4 = self::getDataGenerator()->create_user();
        $user5 = self::getDataGenerator()->create_user();
        $user6 = self::getDataGenerator()->create_user();
        $this->setUser($user1);
        $this->assertEquals(array(), core_message_external::create_contacts(
            array($user3->id, $user4->id, $user5->id, $user6->id)));

        // Removing a non-contact.
        $return = core_message_external::unblock_contacts(array($user2->id));
        $this->assertNull($return);

        // Removing one contact.
        $return = core_message_external::unblock_contacts(array($user3->id));
        $this->assertNull($return);

        // Removing multiple contacts.
        $return = core_message_external::unblock_contacts(array($user4->id, $user5->id));
        $this->assertNull($return);

        // Removing contact from unexisting user.
        $return = core_message_external::unblock_contacts(array(99999));
        $this->assertNull($return);

        // Removing mixed valid and invalid data.
        $return = core_message_external::unblock_contacts(array($user6->id, 99999));
        $this->assertNull($return);

300
301
302
303
        // Try to unblock a contact of another user contact list, should throw an exception.
        // All assertions must be added before this point.
        $this->expectException('required_capability_exception');
        core_message_external::unblock_contacts(array($user2->id), $user3->id);
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
    }

    /**
     * Test get_contacts.
     */
    public function test_get_contacts() {
        $this->resetAfterTest(true);

        $user1 = self::getDataGenerator()->create_user();
        $user_stranger = self::getDataGenerator()->create_user();
        $user_offline1 = self::getDataGenerator()->create_user();
        $user_offline2 = self::getDataGenerator()->create_user();
        $user_offline3 = self::getDataGenerator()->create_user();
        $user_online = new stdClass();
        $user_online->lastaccess = time();
        $user_online = self::getDataGenerator()->create_user($user_online);
        $user_blocked = self::getDataGenerator()->create_user();
321
        $noreplyuser = core_user::get_user(core_user::NOREPLY_USER);
322
323
324
325
326
327
328
329
330
331

        // Login as user1.
        $this->setUser($user1);
        $this->assertEquals(array(), core_message_external::create_contacts(
            array($user_offline1->id, $user_offline2->id, $user_offline3->id, $user_online->id)));

        // User_stranger sends a couple of messages to user1.
        $this->send_message($user_stranger, $user1, 'Hello there!');
        $this->send_message($user_stranger, $user1, 'How you goin?');
        $this->send_message($user_stranger, $user1, 'Cya!');
332
        $this->send_message($noreplyuser, $user1, 'I am not a real user');
333
334
335
336
337
338
339
340
341
342

        // User_blocked sends a message to user1.
        $this->send_message($user_blocked, $user1, 'Here, have some spam.');

        // Retrieve the contacts of the user.
        $this->setUser($user1);
        $contacts = core_message_external::get_contacts();
        $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
        $this->assertCount(3, $contacts['offline']);
        $this->assertCount(1, $contacts['online']);
343
        $this->assertCount(3, $contacts['strangers']);
344
345
346
347
348
        core_message_external::block_contacts(array($user_blocked->id));
        $contacts = core_message_external::get_contacts();
        $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
        $this->assertCount(3, $contacts['offline']);
        $this->assertCount(1, $contacts['online']);
349
        $this->assertCount(2, $contacts['strangers']);
350
351
352

        // Checking some of the fields returned.
        $stranger = array_pop($contacts['strangers']);
353

354
355
        $this->assertEquals(core_user::NOREPLY_USER, $stranger['id']);
        $this->assertEquals(1, $stranger['unread']);
356
357
358
359
360
361
362
363
364
365

        // Check that deleted users are not returned.
        delete_user($user_offline1);
        delete_user($user_stranger);
        delete_user($user_online);
        $contacts = core_message_external::get_contacts();
        $contacts = external_api::clean_returnvalue(core_message_external::get_contacts_returns(), $contacts);
        $this->assertCount(2, $contacts['offline']);
        $this->assertCount(0, $contacts['online']);
        $this->assertCount(1, $contacts['strangers']);
366
367
368
369
    }

    /**
     * Test search_contacts.
370
     * @expectedException moodle_exception
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
     */
    public function test_search_contacts() {
        global $DB;
        $this->resetAfterTest(true);

        $course1 = $this->getDataGenerator()->create_course();
        $course2 = $this->getDataGenerator()->create_course();

        $user1 = new stdClass();
        $user1->firstname = 'X';
        $user1->lastname = 'X';
        $user1 = $this->getDataGenerator()->create_user($user1);
        $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
        $this->getDataGenerator()->enrol_user($user1->id, $course2->id);

        $user2 = new stdClass();
        $user2->firstname = 'Eric';
        $user2->lastname = 'Cartman';
        $user2 = self::getDataGenerator()->create_user($user2);
        $user3 = new stdClass();
        $user3->firstname = 'Stan';
        $user3->lastname = 'Marsh';
        $user3 = self::getDataGenerator()->create_user($user3);
        self::getDataGenerator()->enrol_user($user3->id, $course1->id);
        $user4 = new stdClass();
        $user4->firstname = 'Kyle';
        $user4->lastname = 'Broflovski';
        $user4 = self::getDataGenerator()->create_user($user4);
        $user5 = new stdClass();
        $user5->firstname = 'Kenny';
        $user5->lastname = 'McCormick';
        $user5 = self::getDataGenerator()->create_user($user5);
        self::getDataGenerator()->enrol_user($user5->id, $course2->id);

        $this->setUser($user1);
406

407
408
        $results = core_message_external::search_contacts('r');
        $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
409
410
        $this->assertCount(5, $results); // Users 2 through 5 + admin

411
412
413
        $results = core_message_external::search_contacts('r', true);
        $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
        $this->assertCount(2, $results);
414

415
416
417
418
419
        $results = core_message_external::search_contacts('Kyle', false);
        $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
        $this->assertCount(1, $results);
        $result = reset($results);
        $this->assertEquals($user4->id, $result['id']);
420

421
422
423
        $results = core_message_external::search_contacts('y', false);
        $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
        $this->assertCount(2, $results);
424

425
426
427
428
429
430
431
432
433
        $results = core_message_external::search_contacts('y', true);
        $results = external_api::clean_returnvalue(core_message_external::search_contacts_returns(), $results);
        $this->assertCount(1, $results);
        $result = reset($results);
        $this->assertEquals($user5->id, $result['id']);

        // Empty query, will throw an exception.
        $results = core_message_external::search_contacts('');
    }
434
435
436
437
438

    /**
     * Test get_messages.
     */
    public function test_get_messages() {
439
        global $CFG, $DB;
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
        $this->resetAfterTest(true);

        $this->preventResetByRollback();
        // This mark the messages as read!.
        $sink = $this->redirectMessages();

        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();

        $course = self::getDataGenerator()->create_course();

        // Send a message from one user to another.
        message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
        message_post_message($user1, $user3, 'some random text 2', FORMAT_MOODLE);
        message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
        message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
        message_post_message($user3, $user1, 'some random text 5', FORMAT_MOODLE);

        $this->setUser($user1);
        // Get read conversations from user1 to user2.
        $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(1, $messages['messages']);

465
466
467
468
469
470
471
472
473
        // Delete the message.
        $message = array_shift($messages['messages']);
        $messagetobedeleted = $DB->get_record('message_read', array('id' => $message['id']));
        message_delete_message($messagetobedeleted, $user1->id);

        $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(0, $messages['messages']);

474
475
476
477
478
479
480
481
        // Get unread conversations from user1 to user2.
        $messages = core_message_external::get_messages($user2->id, $user1->id, 'conversations', false, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(0, $messages['messages']);

        // Get read messages send from user1.
        $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
482
        $this->assertCount(1, $messages['messages']);
483
484
485
486
487
488
489

        $this->setUser($user2);
        // Get read conversations from any user to user2.
        $messages = core_message_external::get_messages($user2->id, 0, 'conversations', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(2, $messages['messages']);

490
491
492
493
494
495
496
497
498
499
500
501
502
503
        // Conversations from user3 to user2.
        $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(1, $messages['messages']);

        // Delete the message.
        $message = array_shift($messages['messages']);
        $messagetobedeleted = $DB->get_record('message_read', array('id' => $message['id']));
        message_delete_message($messagetobedeleted, $user2->id);

        $messages = core_message_external::get_messages($user2->id, $user3->id, 'conversations', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(0, $messages['messages']);

504
505
506
507
508
509
510
511
512
        $this->setUser($user3);
        // Get read notifications received by user3.
        $messages = core_message_external::get_messages($user3->id, 0, 'notifications', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(0, $messages['messages']);

        // Now, create some notifications...
        // We are creating fake notifications but based on real ones.

513
        // This one omits notification = 1.
514
515
        $eventdata = new \core\message\message();
        $eventdata->courseid          = $course->id;
516
517
518
519
520
521
522
523
524
525
526
527
        $eventdata->modulename        = 'moodle';
        $eventdata->component         = 'enrol_paypal';
        $eventdata->name              = 'paypal_enrolment';
        $eventdata->userfrom          = get_admin();
        $eventdata->userto            = $user1;
        $eventdata->subject           = "Moodle: PayPal payment";
        $eventdata->fullmessage       = "Your PayPal payment is pending.";
        $eventdata->fullmessageformat = FORMAT_PLAIN;
        $eventdata->fullmessagehtml   = '';
        $eventdata->smallmessage      = '';
        message_send($eventdata);

528
        $message = new \core\message\message();
529
        $message->courseid          = $course->id;
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
        $message->notification      = 1;
        $message->component         = 'enrol_manual';
        $message->name              = 'expiry_notification';
        $message->userfrom          = $user2;
        $message->userto            = $user1;
        $message->subject           = 'Enrolment expired';
        $message->fullmessage       = 'Enrolment expired blah blah blah';
        $message->fullmessageformat = FORMAT_MARKDOWN;
        $message->fullmessagehtml   = markdown_to_html($message->fullmessage);
        $message->smallmessage      = $message->subject;
        $message->contexturlname    = $course->fullname;
        $message->contexturl        = (string)new moodle_url('/course/view.php', array('id' => $course->id));
        message_send($message);

        $userfrom = core_user::get_noreply_user();
        $userfrom->maildisplay = true;
546
547
        $eventdata = new \core\message\message();
        $eventdata->courseid          = $course->id;
548
549
550
551
552
553
554
555
556
557
558
559
        $eventdata->component         = 'moodle';
        $eventdata->name              = 'badgecreatornotice';
        $eventdata->userfrom          = $userfrom;
        $eventdata->userto            = $user1;
        $eventdata->notification      = 1;
        $eventdata->subject           = 'New badge';
        $eventdata->fullmessage       = format_text_email($eventdata->subject, FORMAT_HTML);
        $eventdata->fullmessageformat = FORMAT_PLAIN;
        $eventdata->fullmessagehtml   = $eventdata->subject;
        $eventdata->smallmessage      = $eventdata->subject;
        message_send($eventdata);

560
561
        $eventdata = new \core\message\message();
        $eventdata->courseid         = $course->id;
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
        $eventdata->name             = 'submission';
        $eventdata->component        = 'mod_feedback';
        $eventdata->userfrom         = $user1;
        $eventdata->userto           = $user2;
        $eventdata->subject          = 'Feedback submitted';
        $eventdata->fullmessage      = 'Feedback submitted from an user';
        $eventdata->fullmessageformat = FORMAT_PLAIN;
        $eventdata->fullmessagehtml  = '<strong>Feedback submitted</strong>';
        $eventdata->smallmessage     = '';
        message_send($eventdata);

        $this->setUser($user1);
        // Get read notifications from any user to user1.
        $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(3, $messages['messages']);

        // Get one read notifications from any user to user1.
        $messages = core_message_external::get_messages($user1->id, 0, 'notifications', true, true, 0, 1);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(1, $messages['messages']);

        // Get unread notifications from any user to user1.
        $messages = core_message_external::get_messages($user1->id, 0, 'notifications', false, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(0, $messages['messages']);

        // Get read both type of messages from any user to user1.
        $messages = core_message_external::get_messages($user1->id, 0, 'both', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(4, $messages['messages']);

        // Get read notifications from no-reply-user to user1.
        $messages = core_message_external::get_messages($user1->id, $userfrom->id, 'notifications', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(1, $messages['messages']);

        // Get notifications send by user1 to any user.
        $messages = core_message_external::get_messages(0, $user1->id, 'notifications', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(1, $messages['messages']);

        // Test warnings.
        $CFG->messaging = 0;

        $messages = core_message_external::get_messages(0, $user1->id, 'both', true, true, 0, 0);
        $messages = external_api::clean_returnvalue(core_message_external::get_messages_returns(), $messages);
        $this->assertCount(1, $messages['warnings']);

        // Test exceptions.

        // Messaging disabled.
        try {
            $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
            $this->fail('Exception expected due messaging disabled.');
        } catch (moodle_exception $e) {
            $this->assertEquals('disabled', $e->errorcode);
        }

        $CFG->messaging = 1;

        // Invalid users.
        try {
            $messages = core_message_external::get_messages(0, 0, 'conversations', true, true, 0, 0);
            $this->fail('Exception expected due invalid users.');
        } catch (moodle_exception $e) {
            $this->assertEquals('accessdenied', $e->errorcode);
        }

        // Invalid user ids.
        try {
            $messages = core_message_external::get_messages(2500, 0, 'conversations', true, true, 0, 0);
            $this->fail('Exception expected due invalid users.');
        } catch (moodle_exception $e) {
            $this->assertEquals('invaliduser', $e->errorcode);
        }

        // Invalid users (permissions).
        $this->setUser($user2);
        try {
            $messages = core_message_external::get_messages(0, $user1->id, 'conversations', true, true, 0, 0);
            $this->fail('Exception expected due invalid user.');
        } catch (moodle_exception $e) {
            $this->assertEquals('accessdenied', $e->errorcode);
        }

    }
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686

    /**
     * Test get_blocked_users.
     */
    public function test_get_blocked_users() {
        $this->resetAfterTest(true);

        $user1 = self::getDataGenerator()->create_user();
        $userstranger = self::getDataGenerator()->create_user();
        $useroffline1 = self::getDataGenerator()->create_user();
        $useroffline2 = self::getDataGenerator()->create_user();
        $userblocked = self::getDataGenerator()->create_user();

        // Login as user1.
        $this->setUser($user1);
        $this->assertEquals(array(), core_message_external::create_contacts(
            array($useroffline1->id, $useroffline2->id)));

        // The userstranger sends a couple of messages to user1.
        $this->send_message($userstranger, $user1, 'Hello there!');
        $this->send_message($userstranger, $user1, 'How you goin?');

        // The userblocked sends a message to user1.
        // Note that this user is not blocked at this point.
        $this->send_message($userblocked, $user1, 'Here, have some spam.');

        // Retrieve the list of blocked users.
        $this->setUser($user1);
        $blockedusers = core_message_external::get_blocked_users($user1->id);
        $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
        $this->assertCount(0, $blockedusers['users']);

        // Block the $userblocked and retrieve again the list.
        core_message_external::block_contacts(array($userblocked->id));
        $blockedusers = core_message_external::get_blocked_users($user1->id);
        $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
        $this->assertCount(1, $blockedusers['users']);

687
688
689
690
691
692
        // Remove the $userblocked and check that the list now is empty.
        delete_user($userblocked);
        $blockedusers = core_message_external::get_blocked_users($user1->id);
        $blockedusers = external_api::clean_returnvalue(core_message_external::get_blocked_users_returns(), $blockedusers);
        $this->assertCount(0, $blockedusers['users']);

693
694
    }

695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
    /**
     * Test mark_message_read.
     */
    public function test_mark_message_read() {
        $this->resetAfterTest(true);

        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();

        // Login as user1.
        $this->setUser($user1);
        $this->assertEquals(array(), core_message_external::create_contacts(
            array($user2->id, $user3->id)));

        // The user2 sends a couple of messages to user1.
        $this->send_message($user2, $user1, 'Hello there!');
        $this->send_message($user2, $user1, 'How you goin?');
        $this->send_message($user3, $user1, 'How you goin?');
        $this->send_message($user3, $user2, 'How you goin?');

        // Retrieve all messages sent by user2 (they are currently unread).
        $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);

        $messageids = array();
        foreach ($lastmessages as $m) {
            $messageid = core_message_external::mark_message_read($m->id, time());
            $messageids[] = external_api::clean_returnvalue(core_message_external::mark_message_read_returns(), $messageid);
        }

        // Retrieve all messages sent (they are currently read).
        $lastmessages = message_get_messages($user1->id, $user2->id, 0, true);
        $this->assertCount(2, $lastmessages);
        $this->assertArrayHasKey($messageids[0]['messageid'], $lastmessages);
        $this->assertArrayHasKey($messageids[1]['messageid'], $lastmessages);

        // Retrieve all messages sent by any user (that are currently unread).
        $lastmessages = message_get_messages($user1->id, 0, 0, false);
        $this->assertCount(1, $lastmessages);

        // Invalid message ids.
        try {
            $messageid = core_message_external::mark_message_read($messageids[0]['messageid'] * 2, time());
            $this->fail('Exception expected due invalid messageid.');
        } catch (dml_missing_record_exception $e) {
            $this->assertEquals('invalidrecord', $e->errorcode);
        }

        // A message to a different user.
        $lastmessages = message_get_messages($user2->id, $user3->id, 0, false);
        $messageid = array_pop($lastmessages)->id;
        try {
            $messageid = core_message_external::mark_message_read($messageid, time());
            $this->fail('Exception expected due invalid messageid.');
        } catch (invalid_parameter_exception $e) {
            $this->assertEquals('invalidparameter', $e->errorcode);
        }

    }

755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
    /**
     * Test delete_message.
     */
    public function test_delete_message() {
        global $DB;
        $this->resetAfterTest(true);

        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();
        $user4 = self::getDataGenerator()->create_user();

        // Login as user1.
        $this->setUser($user1);
        $this->assertEquals(array(), core_message_external::create_contacts(array($user2->id, $user3->id)));

        // User user1 does not interchange messages with user3.
        $m1to2 = message_post_message($user1, $user2, 'some random text 1', FORMAT_MOODLE);
        $m2to3 = message_post_message($user2, $user3, 'some random text 3', FORMAT_MOODLE);
        $m3to2 = message_post_message($user3, $user2, 'some random text 4', FORMAT_MOODLE);
        $m3to4 = message_post_message($user3, $user4, 'some random text 4', FORMAT_MOODLE);

        // Retrieve all messages sent by user2 (they are currently unread).
        $lastmessages = message_get_messages($user1->id, $user2->id, 0, false);

        // Delete a message not read, as a user from.
        $result = core_message_external::delete_message($m1to2, $user1->id, false);
        $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
        $this->assertTrue($result['status']);
        $this->assertCount(0, $result['warnings']);
        $deletedmessage = $DB->get_record('message', array('id' => $m1to2));
        $this->assertNotEquals(0, $deletedmessage->timeuserfromdeleted);

        // Try to delete the same message again.
        $result = core_message_external::delete_message($m1to2, $user1->id, false);
        $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
        $this->assertFalse($result['status']);

        // Try to delete a message that does not belong to me.
        try {
            $messageid = core_message_external::delete_message($m2to3, $user3->id, false);
            $this->fail('Exception expected due invalid messageid.');
        } catch (moodle_exception $e) {
            $this->assertEquals('You do not have permission to delete this message', $e->errorcode);
        }

        $this->setUser($user3);
        // Delete a message not read, as a user to.
        $result = core_message_external::delete_message($m2to3, $user3->id, false);
        $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
        $this->assertTrue($result['status']);
        $this->assertCount(0, $result['warnings']);
        $deletedmessage = $DB->get_record('message', array('id' => $m2to3));
        $this->assertNotEquals(0, $deletedmessage->timeusertodeleted);

        // Delete a message read.
        $message = $DB->get_record('message', array('id' => $m3to2));
        $messageid = message_mark_message_read($message, time());
        $result = core_message_external::delete_message($messageid, $user3->id);
        $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
        $this->assertTrue($result['status']);
        $this->assertCount(0, $result['warnings']);
        $deletedmessage = $DB->get_record('message_read', array('id' => $messageid));
        $this->assertNotEquals(0, $deletedmessage->timeuserfromdeleted);

        // Invalid message ids.
        try {
            $result = core_message_external::delete_message(-1, $user1->id);
            $this->fail('Exception expected due invalid messageid.');
        } catch (dml_missing_record_exception $e) {
            $this->assertEquals('invalidrecord', $e->errorcode);
        }

        // Invalid user.
        try {
            $result = core_message_external::delete_message($m1to2, -1, false);
            $this->fail('Exception expected due invalid user.');
        } catch (moodle_exception $e) {
            $this->assertEquals('invaliduser', $e->errorcode);
        }

        // Not active user.
        delete_user($user2);
        try {
            $result = core_message_external::delete_message($m1to2, $user2->id, false);
            $this->fail('Exception expected due invalid user.');
        } catch (moodle_exception $e) {
            $this->assertEquals('userdeleted', $e->errorcode);
        }

        // Now, as an admin, try to delete any message.
        $this->setAdminUser();
        $result = core_message_external::delete_message($m3to4, $user4->id, false);
        $result = external_api::clean_returnvalue(core_message_external::delete_message_returns(), $result);
        $this->assertTrue($result['status']);
        $this->assertCount(0, $result['warnings']);
        $deletedmessage = $DB->get_record('message', array('id' => $m3to4));
        $this->assertNotEquals(0, $deletedmessage->timeusertodeleted);

    }

856
857
858
    public function test_mark_all_notifications_as_read_invalid_user_exception() {
        $this->resetAfterTest(true);

859
860
        $this->expectException('moodle_exception');
        core_message_external::mark_all_notifications_as_read(-2132131, 0);
861
862
863
864
865
866
867
868
869
    }

    public function test_mark_all_notifications_as_read_access_denied_exception() {
        $this->resetAfterTest(true);

        $sender = $this->getDataGenerator()->create_user();
        $user = $this->getDataGenerator()->create_user();

        $this->setUser($user);
870
871
        $this->expectException('moodle_exception');
        core_message_external::mark_all_notifications_as_read($sender->id, 0);
872
873
874
875
876
877
878
879
    }

    public function test_mark_all_notifications_as_read_missing_from_user_exception() {
        $this->resetAfterTest(true);

        $sender = $this->getDataGenerator()->create_user();

        $this->setUser($sender);
880
881
        $this->expectException('moodle_exception');
        core_message_external::mark_all_notifications_as_read($sender->id, 99999);
882
883
884
    }

    public function test_mark_all_notifications_as_read() {
885
886
        global $DB;

887
888
889
890
891
892
893
894
895
        $this->resetAfterTest(true);

        $sender1 = $this->getDataGenerator()->create_user();
        $sender2 = $this->getDataGenerator()->create_user();
        $sender3 = $this->getDataGenerator()->create_user();
        $recipient = $this->getDataGenerator()->create_user();

        $this->setUser($recipient);

896
897
898
899
900
901
        $this->send_message($sender1, $recipient, 'Notification', 1);
        $this->send_message($sender1, $recipient, 'Notification', 1);
        $this->send_message($sender2, $recipient, 'Notification', 1);
        $this->send_message($sender2, $recipient, 'Notification', 1);
        $this->send_message($sender3, $recipient, 'Notification', 1);
        $this->send_message($sender3, $recipient, 'Notification', 1);
902
903

        core_message_external::mark_all_notifications_as_read($recipient->id, $sender1->id);
904
905
        $readnotifications = $DB->get_recordset('message_read', ['useridto' => $recipient->id]);
        $unreadnotifications = $DB->get_recordset('message', ['useridto' => $recipient->id]);
906

907
908
        $this->assertCount(2, $readnotifications);
        $this->assertCount(4, $unreadnotifications);
909
910

        core_message_external::mark_all_notifications_as_read($recipient->id, 0);
911
912
        $readnotifications = $DB->get_recordset('message_read', ['useridto' => $recipient->id]);
        $unreadnotifications = $DB->get_recordset('message', ['useridto' => $recipient->id]);
913

914
915
        $this->assertCount(6, $readnotifications);
        $this->assertCount(0, $unreadnotifications);
916
    }
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933

    /**
     * Test get_user_notification_preferences
     */
    public function test_get_user_notification_preferences() {
        $this->resetAfterTest(true);

        $user = self::getDataGenerator()->create_user();
        $this->setUser($user);

        // Set a couple of preferences to test.
        set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
        set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);

        $prefs = core_message_external::get_user_notification_preferences();
        $prefs = external_api::clean_returnvalue(core_message_external::get_user_notification_preferences_returns(), $prefs);
        // Check processors.
934
        $this->assertGreaterThanOrEqual(2, count($prefs['preferences']['processors']));
935
936
937
        $this->assertEquals($user->id, $prefs['preferences']['userid']);

        // Check components.
938
        $this->assertGreaterThanOrEqual(8, count($prefs['preferences']['components']));
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973

        // Check some preferences that we previously set.
        $found = 0;
        foreach ($prefs['preferences']['components'] as $component) {
            foreach ($component['notifications'] as $prefdata) {
                if ($prefdata['preferencekey'] != 'message_provider_mod_assign_assign_notification') {
                    continue;
                }
                foreach ($prefdata['processors'] as $processor) {
                    if ($processor['name'] == 'popup') {
                        $this->assertTrue($processor['loggedin']['checked']);
                        $found++;
                    } else if ($processor['name'] == 'email') {
                        $this->assertTrue($processor['loggedoff']['checked']);
                        $found++;
                    }
                }
            }
        }
        $this->assertEquals(2, $found);
    }

    /**
     * Test get_user_notification_preferences permissions
     */
    public function test_get_user_notification_preferences_permissions() {
        $this->resetAfterTest(true);

        $user = self::getDataGenerator()->create_user();
        $otheruser = self::getDataGenerator()->create_user();
        $this->setUser($user);

        $this->expectException('moodle_exception');
        $prefs = core_message_external::get_user_notification_preferences($otheruser->id);
    }
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032

    /**
     * Tests searching users in a course.
     */
    public function test_messagearea_search_users_in_course() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = new stdClass();
        $user1->firstname = 'User';
        $user1->lastname = 'One';
        $user1 = self::getDataGenerator()->create_user($user1);

        // The person doing the search.
        $this->setUser($user1);

        // Set the second user's status to online by setting their last access to now.
        $user2 = new stdClass();
        $user2->firstname = 'User';
        $user2->lastname = 'Two';
        $user2->lastaccess = time();
        $user2 = self::getDataGenerator()->create_user($user2);

        // Block the second user.
        message_block_contact($user2->id, $user1->id);

        $user3 = new stdClass();
        $user3->firstname = 'User';
        $user3->lastname = 'Three';
        $user3 = self::getDataGenerator()->create_user($user3);

        // Create a course.
        $course1 = new stdClass();
        $course1->fullname = 'Course';
        $course1->shortname = 'One';
        $course1 = $this->getDataGenerator()->create_course();

        // Enrol the user we are doing the search for and one user in the course.
        $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
        $this->getDataGenerator()->enrol_user($user2->id, $course1->id);

        // Perform a search.
        $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');

        // We need to execute the return values cleaning process to simulate the web service.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
            $result);

        // Check that we only retrieved a user that was enrolled, and that the user performing the search was not returned.
        $users = $result['contacts'];
        $this->assertCount(1, $users);

        $user = $users[0];
        $this->assertEquals($user2->id, $user['userid']);
        $this->assertEquals(fullname($user2), $user['fullname']);
        $this->assertFalse($user['ismessaging']);
        $this->assertFalse($user['sentfromcurrentuser']);
        $this->assertNull($user['lastmessage']);
        $this->assertNull($user['messageid']);
1033
        $this->assertNull($user['isonline']);
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
        $this->assertFalse($user['isread']);
        $this->assertTrue($user['isblocked']);
        $this->assertNull($user['unreadcount']);
    }

    /**
     * Tests searching users in course as another user.
     */
    public function test_messagearea_search_users_in_course_as_other_user() {
        $this->resetAfterTest(true);

        // The person doing the search for another user.
        $this->setAdminUser();

        // Create some users.
        $user1 = new stdClass();
        $user1->firstname = 'User';
        $user1->lastname = 'One';
        $user1 = self::getDataGenerator()->create_user($user1);

        $user2 = new stdClass();
        $user2->firstname = 'User';
        $user2->lastname = 'Two';
        $user2 = self::getDataGenerator()->create_user($user2);

        $user3 = new stdClass();
        $user3->firstname = 'User';
        $user3->lastname = 'Three';
        $user3 = self::getDataGenerator()->create_user($user3);

        // Create a course.
        $course1 = new stdClass();
        $course1->fullname = 'Course';
        $course1->shortname = 'One';
        $course1 = $this->getDataGenerator()->create_course();

        // Enrol the user we are doing the search for and one user in the course.
        $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
        $this->getDataGenerator()->enrol_user($user2->id, $course1->id);

        // Perform a search.
        $result = core_message_external::data_for_messagearea_search_users_in_course($user1->id, $course1->id, 'User');

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_in_course_returns(),
            $result);

        // Check that we got the user enrolled, and that the user we are performing the search on behalf of was not returned.
        $users = $result['contacts'];
        $this->assertCount(1, $users);

        $user = $users[0];
        $this->assertEquals($user2->id, $user['userid']);
        $this->assertEquals(fullname($user2), $user['fullname']);
        $this->assertFalse($user['ismessaging']);
        $this->assertFalse($user['sentfromcurrentuser']);
        $this->assertNull($user['lastmessage']);
        $this->assertNull($user['messageid']);
        $this->assertFalse($user['isonline']);
        $this->assertFalse($user['isread']);
        $this->assertFalse($user['isblocked']);
        $this->assertNull($user['unreadcount']);
    }

    /**
     * Tests searching users in course as another user without the proper capabilities.
     */
    public function test_messagearea_search_users_in_course_as_other_user_without_cap() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // The person doing the search for another user.
        $this->setUser($user1);

        // Create a course.
        $course = $this->getDataGenerator()->create_course();

        // Ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_search_users_in_course($user2->id, $course->id, 'User');
    }

    /**
     * Tests searching users in course with messaging disabled.
     */
    public function test_messagearea_search_users_in_course_messaging_disabled() {
        global $CFG;

        $this->resetAfterTest(true);

        // Create some skeleton data just so we can call the WS..
        $user = self::getDataGenerator()->create_user();
        $course = $this->getDataGenerator()->create_course();

        // The person doing the search for another user.
        $this->setUser($user);

        // Disable messaging.
        $CFG->messaging = 0;

        // Ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_search_users_in_course($user->id, $course->id, 'User');
    }

    /**
     * Tests searching users.
     */
    public function test_messagearea_search_users() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = new stdClass();
        $user1->firstname = 'User';
        $user1->lastname = 'One';
        $user1 = self::getDataGenerator()->create_user($user1);

        // Set as the user performing the search.
        $this->setUser($user1);

        $user2 = new stdClass();
        $user2->firstname = 'User search';
        $user2->lastname = 'Two';
        $user2 = self::getDataGenerator()->create_user($user2);

        $user3 = new stdClass();
        $user3->firstname = 'User search';
        $user3->lastname = 'Three';
        $user3 = self::getDataGenerator()->create_user($user3);

        $user4 = new stdClass();
        $user4->firstname = 'User';
        $user4->lastname = 'Four';
        $user4 = self::getDataGenerator()->create_user($user4);

        $user5 = new stdClass();
        $user5->firstname = 'User search';
        $user5->lastname = 'Five';
        $user5 = self::getDataGenerator()->create_user($user5);

        $user6 = new stdClass();
        $user6->firstname = 'User';
        $user6->lastname = 'Six';
        $user6 = self::getDataGenerator()->create_user($user6);

        // Create some courses.
        $course1 = new stdClass();
        $course1->fullname = 'Course search';
        $course1->shortname = 'One';
        $course1 = $this->getDataGenerator()->create_course($course1);

        $course2 = new stdClass();
        $course2->fullname = 'Course';
        $course2->shortname = 'Two';
        $course2 = $this->getDataGenerator()->create_course($course2);

        $course3 = new stdClass();
        $course3->fullname = 'Course';
        $course3->shortname = 'Three search';
        $course3 = $this->getDataGenerator()->create_course($course3);

1198
1199
1200
1201
1202
1203
1204
1205
1206
        $course4 = new stdClass();
        $course4->fullname = 'Course Four';
        $course4->shortname = 'CF100';
        $course4 = $this->getDataGenerator()->create_course($course4);

        $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 'student');
        $this->getDataGenerator()->enrol_user($user1->id, $course2->id, 'student');
        $this->getDataGenerator()->enrol_user($user1->id, $course3->id, 'student');

1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
        // Add some users as contacts.
        message_add_contact($user2->id, 0, $user1->id);
        message_add_contact($user3->id, 0, $user1->id);
        message_add_contact($user4->id, 0, $user1->id);

        // Perform a search.
        $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
            $result);

        // Confirm that we returns contacts, courses and non-contacts.
        $contacts = $result['contacts'];
        $courses = $result['courses'];
        $noncontacts = $result['noncontacts'];

        // Check that we retrieved the correct contacts.
        $this->assertCount(2, $contacts);
        $this->assertEquals($user3->id, $contacts[0]['userid']);
        $this->assertEquals($user2->id, $contacts[1]['userid']);

        // Check that we retrieved the correct courses.
        $this->assertCount(2, $courses);
        $this->assertEquals($course3->id, $courses[0]['id']);
        $this->assertEquals($course1->id, $courses[1]['id']);

        // Check that we retrieved the correct non-contacts.
        $this->assertCount(1, $noncontacts);
        $this->assertEquals($user5->id, $noncontacts[0]['userid']);
    }

    /**
     * Tests searching users as another user.
     */
    public function test_messagearea_search_users_as_other_user() {
        $this->resetAfterTest(true);

        // The person doing the search.
        $this->setAdminUser();

        // Create some users.
        $user1 = new stdClass();
        $user1->firstname = 'User';
        $user1->lastname = 'One';
        $user1 = self::getDataGenerator()->create_user($user1);

        $user2 = new stdClass();
        $user2->firstname = 'User search';
        $user2->lastname = 'Two';
        $user2 = self::getDataGenerator()->create_user($user2);

        $user3 = new stdClass();
        $user3->firstname = 'User search';
        $user3->lastname = 'Three';
        $user3 = self::getDataGenerator()->create_user($user3);

        $user4 = new stdClass();
        $user4->firstname = 'User';
        $user4->lastname = 'Four';
        $user4 = self::getDataGenerator()->create_user($user4);

        $user5 = new stdClass();
        $user5->firstname = 'User search';
        $user5->lastname = 'Five';
        $user5 = self::getDataGenerator()->create_user($user5);

        $user6 = new stdClass();
        $user6->firstname = 'User';
        $user6->lastname = 'Six';
        $user6 = self::getDataGenerator()->create_user($user6);

        // Create some courses.
        $course1 = new stdClass();
        $course1->fullname = 'Course search';
        $course1->shortname = 'One';
        $course1 = $this->getDataGenerator()->create_course($course1);

        $course2 = new stdClass();
        $course2->fullname = 'Course';
        $course2->shortname = 'Two';
        $course2 = $this->getDataGenerator()->create_course($course2);

        $course3 = new stdClass();
        $course3->fullname = 'Course';
        $course3->shortname = 'Three search';
        $course3 = $this->getDataGenerator()->create_course($course3);

        // Add some users as contacts.
        message_add_contact($user2->id, 0, $user1->id);
        message_add_contact($user3->id, 0, $user1->id);
        message_add_contact($user4->id, 0, $user1->id);

        // Perform a search.
        $result = core_message_external::data_for_messagearea_search_users($user1->id, 'search');

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_users_returns(),
            $result);

        // Confirm that we returns contacts, courses and non-contacts.
        $contacts = $result['contacts'];
        $courses = $result['courses'];
        $noncontacts = $result['noncontacts'];

        // Check that we retrieved the correct contacts.
        $this->assertCount(2, $contacts);
        $this->assertEquals($user3->id, $contacts[0]['userid']);
        $this->assertEquals($user2->id, $contacts[1]['userid']);

        // Check that we retrieved the correct courses.
1318
        $this->assertCount(0, $courses);
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404

        // Check that we retrieved the correct non-contacts.
        $this->assertCount(1, $noncontacts);
        $this->assertEquals($user5->id, $noncontacts[0]['userid']);
    }

    /**
     * Tests searching users as another user without the proper capabilities.
     */
    public function test_messagearea_search_users_as_other_user_without_cap() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // The person doing the search for another user.
        $this->setUser($user1);

        // Ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_search_users($user2->id, 'User');
    }

    /**
     * Tests searching users with messaging disabled.
     */
    public function test_messagearea_search_users_messaging_disabled() {
        global $CFG;

        $this->resetAfterTest(true);

        // Create some skeleton data just so we can call the WS.
        $user = self::getDataGenerator()->create_user();

        // The person doing the search.
        $this->setUser($user);

        // Disable messaging.
        $CFG->messaging = 0;

        // Ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_search_users($user->id, 'User');
    }

    /**
     * Tests searching messages.
     */
    public function test_messagearea_search_messages() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // The person doing the search.
        $this->setUser($user1);

        // Send some messages back and forth.
        $time = time();
        $this->send_message($user1, $user2, 'Yo!', 0, $time);
        $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
        $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
        $this->send_message($user2, $user1, 'Word.', 0, $time + 3);

        // Perform a search.
        $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
            $result);

        // Confirm the data is correct.
        $messages = $result['contacts'];
        $this->assertCount(2, $messages);

        $message1 = $messages[0];
        $message2 = $messages[1];

        $this->assertEquals($user2->id, $message1['userid']);
        $this->assertEquals(fullname($user2), $message1['fullname']);
        $this->assertTrue($message1['ismessaging']);
        $this->assertFalse($message1['sentfromcurrentuser']);
        $this->assertEquals('Word.', $message1['lastmessage']);
        $this->assertNotEmpty($message1['messageid']);
1405
        $this->assertNull($message1['isonline']);
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
        $this->assertFalse($message1['isread']);
        $this->assertFalse($message1['isblocked']);
        $this->assertNull($message1['unreadcount']);

        $this->assertEquals($user2->id, $message2['userid']);
        $this->assertEquals(fullname($user2), $message2['fullname']);
        $this->assertTrue($message2['ismessaging']);
        $this->assertTrue($message2['sentfromcurrentuser']);
        $this->assertEquals('Yo!', $message2['lastmessage']);
        $this->assertNotEmpty($message2['messageid']);
1416
        $this->assertNull($message2['isonline']);
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
        $this->assertTrue($message2['isread']);
        $this->assertFalse($message2['isblocked']);
        $this->assertNull($message2['unreadcount']);
    }

    /**
     * Tests searching messages as another user.
     */
    public function test_messagearea_search_messages_as_other_user() {
        $this->resetAfterTest(true);

        // The person doing the search.
        $this->setAdminUser();

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // Send some messages back and forth.
        $time = time();
        $this->send_message($user1, $user2, 'Yo!', 0, $time);
        $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
        $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
        $this->send_message($user2, $user1, 'Word.', 0, $time + 3);

        // Perform a search.
        $result = core_message_external::data_for_messagearea_search_messages($user1->id, 'o');

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_search_messages_returns(),
            $result);

        // Confirm the data is correct.
        $messages = $result['contacts'];
        $this->assertCount(2, $messages);

        $message1 = $messages[0];
        $message2 = $messages[1];

        $this->assertEquals($user2->id, $message1['userid']);
        $this->assertEquals(fullname($user2), $message1['fullname']);
        $this->assertTrue($message1['ismessaging']);
        $this->assertFalse($message1['sentfromcurrentuser']);
        $this->assertEquals('Word.', $message1['lastmessage']);
        $this->assertNotEmpty($message1['messageid']);
        $this->assertFalse($message1['isonline']);
        $this->assertFalse($message1['isread']);
        $this->assertFalse($message1['isblocked']);
        $this->assertNull($message1['unreadcount']);

        $this->assertEquals($user2->id, $message2['userid']);
        $this->assertEquals(fullname($user2), $message2['fullname']);
        $this->assertTrue($message2['ismessaging']);
        $this->assertTrue($message2['sentfromcurrentuser']);
        $this->assertEquals('Yo!', $message2['lastmessage']);
        $this->assertNotEmpty($message2['messageid']);
        $this->assertFalse($message2['isonline']);
        $this->assertTrue($message2['isread']);
        $this->assertFalse($message2['isblocked']);
        $this->assertNull($message2['unreadcount']);
    }

    /**
     * Tests searching messages as another user without the proper capabilities.
     */
    public function test_messagearea_search_messages_as_other_user_without_cap() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // The person doing the search for another user.
        $this->setUser($user1);

        // Ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_search_messages($user2->id, 'Search');
    }

    /**
     * Tests searching messages with messaging disabled
     */
    public function test_messagearea_search_messages_messaging_disabled() {
        global $CFG;

        $this->resetAfterTest(true);

        // Create some skeleton data just so we can call the WS.
        $user = self::getDataGenerator()->create_user();

        // The person doing the search .
        $this->setUser($user);

        // Disable messaging.
        $CFG->messaging = 0;

        // Ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_search_messages($user->id, 'Search');
    }

    /**
     * Tests retrieving conversations.
     */
    public function test_messagearea_conversations() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();
        $user4 = self::getDataGenerator()->create_user();

        // The person retrieving the conversations.
        $this->setUser($user1);

        // Send some messages back and forth, have some different conversations with different users.
        $time = time();
        $this->send_message($user1, $user2, 'Yo!', 0, $time);
        $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
        $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
        $this->send_message($user2, $user1, 'Word.', 0, $time + 3);

        $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
        $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
        $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
        $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);

        $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
        $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
        $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);

        // Retrieve the conversations.
        $result = core_message_external::data_for_messagearea_conversations($user1->id);

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
            $result);

        // Confirm the data is correct.
        $messages = $result['contacts'];
        $this->assertCount(3, $messages);

        $message1 = $messages[0];
        $message2 = $messages[1];
        $message3 = $messages[2];

        $this->assertEquals($user4->id, $message1['userid']);
        $this->assertTrue($message1['ismessaging']);
        $this->assertTrue($message1['sentfromcurrentuser']);
        $this->assertEquals('Dope.', $message1['lastmessage']);
        $this->assertNull($message1['messageid']);
1570
        $this->assertNull($message1['isonline']);
1571
1572
1573
1574
1575
1576
1577
1578
1579
        $this->assertTrue($message1['isread']);
        $this->assertFalse($message1['isblocked']);
        $this->assertEquals(0, $message1['unreadcount']);

        $this->assertEquals($user3->id, $message2['userid']);
        $this->assertTrue($message2['ismessaging']);
        $this->assertFalse($message2['sentfromcurrentuser']);
        $this->assertEquals('Cool.', $message2['lastmessage']);
        $this->assertNull($message2['messageid']);
1580
        $this->assertNull($message2['isonline']);
1581
1582
1583
1584
1585
1586
1587
1588
1589
        $this->assertFalse($message2['isread']);
        $this->assertFalse($message2['isblocked']);
        $this->assertEquals(2, $message2['unreadcount']);

        $this->assertEquals($user2->id, $message3['userid']);
        $this->assertTrue($message3['ismessaging']);
        $this->assertFalse($message3['sentfromcurrentuser']);
        $this->assertEquals('Word.', $message3['lastmessage']);
        $this->assertNull($message3['messageid']);
1590
        $this->assertNull($message3['isonline']);
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
        $this->assertFalse($message3['isread']);
        $this->assertFalse($message3['isblocked']);
        $this->assertEquals(2, $message3['unreadcount']);
    }

    /**
     * Tests retrieving conversations as another user.
     */
    public function test_messagearea_conversations_as_other_user() {
        $this->resetAfterTest(true);

        // Set as admin.
        $this->setAdminUser();

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();
        $user3 = self::getDataGenerator()->create_user();
        $user4 = self::getDataGenerator()->create_user();

        // Send some messages back and forth, have some different conversations with different users.
        $time = time();
        $this->send_message($user1, $user2, 'Yo!', 0, $time);
        $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
        $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
        $this->send_message($user2, $user1, 'Word.', 0, $time + 3);

        $this->send_message($user1, $user3, 'Booyah', 0, $time + 4);
        $this->send_message($user3, $user1, 'Whaaat?', 0, $time + 5);
        $this->send_message($user1, $user3, 'Nothing.', 0, $time + 6);
        $this->send_message($user3, $user1, 'Cool.', 0, $time + 7);

        $this->send_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 8);
        $this->send_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 9);
        $this->send_message($user1, $user4, 'Dope.', 0, $time + 10);

        // Retrieve the conversations.
        $result = core_message_external::data_for_messagearea_conversations($user1->id);

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_conversations_returns(),
            $result);

        // Confirm the data is correct.
        $messages = $result['contacts'];
        $this->assertCount(3, $messages);

        $message1 = $messages[0];
        $message2 = $messages[1];
        $message3 = $messages[2];

        $this->assertEquals($user4->id, $message1['userid']);
        $this->assertTrue($message1['ismessaging']);
        $this->assertTrue($message1['sentfromcurrentuser']);
        $this->assertEquals('Dope.', $message1['lastmessage']);
        $this->assertNull($message1['messageid']);
        $this->assertFalse($message1['isonline']);
        $this->assertTrue($message1['isread']);
        $this->assertFalse($message1['isblocked']);
        $this->assertEquals(0, $message1['unreadcount']);

        $this->assertEquals($user3->id, $message2['userid']);
        $this->assertTrue($message2['ismessaging']);
        $this->assertFalse($message2['sentfromcurrentuser']);
        $this->assertEquals('Cool.', $message2['lastmessage']);
        $this->assertNull($message2['messageid']);
        $this->assertFalse($message2['isonline']);
        $this->assertFalse($message2['isread']);
        $this->assertFalse($message2['isblocked']);
        $this->assertEquals(2, $message2['unreadcount']);

        $this->assertEquals($user2->id, $message3['userid']);
        $this->assertTrue($message3['ismessaging']);
        $this->assertFalse($message3['sentfromcurrentuser']);
        $this->assertEquals('Word.', $message3['lastmessage']);
        $this->assertNull($message3['messageid']);
        $this->assertFalse($message3['isonline']);
        $this->assertFalse($message3['isread']);
        $this->assertFalse($message3['isblocked']);
        $this->assertEquals(2, $message3['unreadcount']);
    }

    /**
     * Tests retrieving conversations as another user without the proper capabilities.
     */
    public function test_messagearea_conversations_as_other_user_without_cap() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // The person retrieving the conversations for another user.
        $this->setUser($user1);

        // Ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_conversations($user2->id);
    }

    /**
     * Tests retrieving conversations with messaging disabled.
     */
    public function test_messagearea_conversations_messaging_disabled() {
        global $CFG;

        $this->resetAfterTest(true);

        // Create some skeleton data just so we can call the WS.
        $user = self::getDataGenerator()->create_user();

        // The person retrieving the conversations.
        $this->setUser($user);

        // Disable messaging.
        $CFG->messaging = 0;

        // Ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_conversations($user->id);
    }

    /**
     * Tests retrieving contacts.
     */
    public function test_messagearea_contacts() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();

        // Set as the user.
        $this->setUser($user1);

        $user2 = new stdClass();
        $user2->firstname = 'User';
        $user2->lastname = 'A';
        $user2 = self::getDataGenerator()->create_user($user2);

        $user3 = new stdClass();
        $user3->firstname = 'User';
        $user3->lastname = 'B';
        $user3 = self::getDataGenerator()->create_user($user3);

        $user4 = new stdClass();
        $user4->firstname = 'User';
        $user4->lastname = 'C';
        $user4 = self::getDataGenerator()->create_user($user4);

        $user5 = new stdClass();
        $user5->firstname = 'User';
        $user5->lastname = 'D';
        $user5 = self::getDataGenerator()->create_user($user5);

        // Add some users as contacts.
        message_add_contact($user2->id, 0, $user1->id);
        message_add_contact($user3->id, 0, $user1->id);
        message_add_contact($user4->id, 0, $user1->id);

        // Retrieve the contacts.
        $result = core_message_external::data_for_messagearea_contacts($user1->id);

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
            $result);

        // Confirm the data is correct.
        $contacts = $result['contacts'];
        $this->assertCount(3, $contacts);

        $contact1 = $contacts[0];
        $contact2 = $contacts[1];
        $contact3 = $contacts[2];

        $this->assertEquals($user2->id, $contact1['userid']);
        $this->assertFalse($contact1['ismessaging']);
        $this->assertFalse($contact1['sentfromcurrentuser']);
        $this->assertNull($contact1['lastmessage']);
        $this->assertNull($contact1['messageid']);
1770
        $this->assertNull($contact1['isonline']);
1771
1772
1773
1774
1775
1776
1777
1778
1779
        $this->assertFalse($contact1['isread']);
        $this->assertFalse($contact1['isblocked']);
        $this->assertNull($contact1['unreadcount']);

        $this->assertEquals($user3->id, $contact2['userid']);
        $this->assertFalse($contact2['ismessaging']);
        $this->assertFalse($contact2['sentfromcurrentuser']);
        $this->assertNull($contact2['lastmessage']);
        $this->assertNull($contact2['messageid']);
1780
        $this->assertNull($contact2['isonline']);
1781
1782
1783
1784
1785
1786
1787
1788
1789
        $this->assertFalse($contact2['isread']);
        $this->assertFalse($contact2['isblocked']);
        $this->assertNull($contact2['unreadcount']);

        $this->assertEquals($user4->id, $contact3['userid']);
        $this->assertFalse($contact3['ismessaging']);
        $this->assertFalse($contact3['sentfromcurrentuser']);
        $this->assertNull($contact3['lastmessage']);
        $this->assertNull($contact3['messageid']);
1790
        $this->assertNull($contact3['isonline']);
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
        $this->assertFalse($contact3['isread']);
        $this->assertFalse($contact3['isblocked']);
        $this->assertNull($contact3['unreadcount']);
    }

    /**
     * Tests retrieving contacts as another user.
     */
    public function test_messagearea_contacts_as_other_user() {
        $this->resetAfterTest(true);

        $this->setAdminUser();

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();

        $user2 = new stdClass();
        $user2->firstname = 'User';
        $user2->lastname = 'A';
        $user2 = self::getDataGenerator()->create_user($user2);

        $user3 = new stdClass();
        $user3->firstname = 'User';
        $user3->lastname = 'B';
        $user3 = self::getDataGenerator()->create_user($user3);

        $user4 = new stdClass();
        $user4->firstname = 'User';
        $user4->lastname = 'C';
        $user4 = self::getDataGenerator()->create_user($user4);

        $user5 = new stdClass();
        $user5->firstname = 'User';
        $user5->lastname = 'D';
        $user5 = self::getDataGenerator()->create_user($user5);

        // Add some users as contacts.
        message_add_contact($user2->id, 0, $user1->id);
        message_add_contact($user3->id, 0, $user1->id);
        message_add_contact($user4->id, 0, $user1->id);

        // Retrieve the contacts.
        $result = core_message_external::data_for_messagearea_contacts($user1->id);

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_contacts_returns(),
            $result);

        // Confirm the data is correct.
        $contacts = $result['contacts'];
        $this->assertCount(3, $contacts);

        $contact1 = $contacts[0];
        $contact2 = $contacts[1];
        $contact3 = $contacts[2];

        $this->assertEquals($user2->id, $contact1['userid']);
        $this->assertFalse($contact1['ismessaging']);
        $this->assertFalse($contact1['sentfromcurrentuser']);
        $this->assertNull($contact1['lastmessage']);
        $this->assertNull($contact1['messageid']);
        $this->assertFalse($contact1['isonline']);
        $this->assertFalse($contact1['isread']);
        $this->assertFalse($contact1['isblocked']);
        $this->assertNull($contact1['unreadcount']);

        $this->assertEquals($user3->id, $contact2['userid']);
        $this->assertFalse($contact2['ismessaging']);
        $this->assertFalse($contact2['sentfromcurrentuser']);
        $this->assertNull($contact2['lastmessage']);
        $this->assertNull($contact2['messageid']);
        $this->assertFalse($contact2['isonline']);
        $this->assertFalse($contact2['isread']);
        $this->assertFalse($contact2['isblocked']);
        $this->assertNull($contact2['unreadcount']);

        $this->assertEquals($user4->id, $contact3['userid']);
        $this->assertFalse($contact3['ismessaging']);
        $this->assertFalse($contact3['sentfromcurrentuser']);
        $this->assertNull($contact3['lastmessage']);
        $this->assertNull($contact3['messageid']);
        $this->assertFalse($contact3['isonline']);
        $this->assertFalse($contact3['isread']);
        $this->assertFalse($contact3['isblocked']);
        $this->assertNull($contact3['unreadcount']);
    }

    /**
     * Tests retrieving contacts as another user without the proper capabilities.
     */
    public function test_messagearea_contacts_as_other_user_without_cap() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // The person retrieving the contacts for another user.
        $this->setUser($user1);

        // Perform the WS call and ensure an exception is thrown.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_contacts($user2->id);
    }

    /**
     * Tests retrieving contacts with messaging disabled.
     */
    public function test_messagearea_contacts_messaging_disabled() {
        global $CFG;

        $this->resetAfterTest(true);

        // Create some skeleton data just so we can call the WS.
        $user = self::getDataGenerator()->create_user();

        // The person retrieving the contacts.
        $this->setUser($user);

        // Disable messaging.
        $CFG->messaging = 0;

        // Perform the WS call and ensure we are shown that it is disabled.
        $this->expectException('moodle_exception');
        core_message_external::data_for_messagearea_contacts($user->id);
    }

    /**
     * Tests retrieving messages.
     */
    public function test_messagearea_messages() {
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // The person asking for the messages.
        $this->setUser($user1);

        // Send some messages back and forth.
        $time = time();
        $this->send_message($user1, $user2, 'Yo!', 0, $time);
        $this->send_message($user2, $user1, 'Sup mang?', 0, $time + 1);
        $this->send_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
        $this->send_message($user2, $user1, 'Word.', 0, $time + 3);

        // Retrieve the messages.
        $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id);

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
            $result);

        // Check the results are correct.
        $this->assertTrue($result['iscurrentuser']);
        $this->assertEquals($user1->id, $result['currentuserid']);
        $this->assertEquals($user2->id, $result['otheruserid']);
        $this->assertEquals(fullname($user2), $result['otheruserfullname']);
1950
        $this->assertNull($result['isonline']);
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981

        // Confirm the message data is correct.
        $messages = $result['messages'];
        $this->assertCount(4, $messages);

        $message1 = $messages[0];
        $message2 = $messages[1];
        $message3 = $messages[2];
        $message4 = $messages[3];

        $this->assertEquals($user1->id, $message1['useridfrom']);
        $this->assertEquals($user2->id, $message1['useridto']);
        $this->assertTrue($message1['displayblocktime']);
        $this->assertContains('Yo!', $message1['text']);

        $this->assertEquals($user2->id, $message2['useridfrom']);
        $this->assertEquals($user1->id, $message2['useridto']);
        $this->assertFalse($message2['displayblocktime']);
        $this->assertContains('Sup mang?', $message2['text']);

        $this->assertEquals($user1->id, $message3['useridfrom']);
        $this->assertEquals($user2->id, $message3['useridto']);
        $this->assertFalse($message3['displayblocktime']);
        $this->assertContains('Writing PHPUnit tests!', $message3['text']);

        $this->assertEquals($user2->id, $message4['useridfrom']);
        $this->assertEquals($user1->id, $message4['useridto']);
        $this->assertFalse($message4['displayblocktime']);
        $this->assertContains('Word.', $message4['text']);
    }

1982
1983
1984
    /**
     * Tests retrieving messages.
     */
1985
    public function test_messagearea_messages_timefrom() {
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
        $this->resetAfterTest(true);

        // Create some users.
        $user1 = self::getDataGenerator()->create_user();
        $user2 = self::getDataGenerator()->create_user();

        // The person asking for the messages.
        $this->setUser($user1);

        // Send some messages back and forth.
        $time = time();
        $this->send_message($user1, $user2, 'Message 1', 0, $time - 4);
        $this->send_message($user2, $user1, 'Message 2', 0, $time - 3);
        $this->send_message($user1, $user2, 'Message 3', 0, $time - 2);
        $this->send_message($user2, $user1, 'Message 4', 0, $time - 1);

2002
        // Retrieve the messages from $time - 3, which should be the 3 most recent messages.
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
        $result = core_message_external::data_for_messagearea_messages($user1->id, $user2->id, 0, 0, false, $time - 3);

        // We need to execute the return values cleaning process to simulate the web service server.
        $result = external_api::clean_returnvalue(core_message_external::data_for_messagearea_messages_returns(),
            $result);

        // Confirm the message data is correct. We shouldn't get 'Message 1' back.
        $messages = $result['messages'];
        $this->assertCount(3, $messages);

        $message1 = $messages[0];
        $message2 = $messages[1];
        $message3 = $messages[2];

        $this->assertContains('Message 2', $message1['text']);
        $this->assertContains('Message 3', $message2['text']);
        $this->assertContains('Message 4', $message3['text']);
    }

2022
2023
2024
2025
2026
2027
2028
2029