MDL-64773 core_message: added API to mute/unmute conversations
[moodle.git] / message / externallib.php
CommitLineData
a623b6b8 1<?php
a623b6b8
JM
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
4615817d 17
a623b6b8
JM
18/**
19 * External message API
20 *
6fbd60ef 21 * @package core_message
4615817d
JM
22 * @category external
23 * @copyright 2011 Jerome Mouneyrac
a623b6b8
JM
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
4615817d 26
e71687ba
JL
27defined('MOODLE_INTERNAL') || die();
28
a623b6b8 29require_once("$CFG->libdir/externallib.php");
705afe6f 30require_once($CFG->dirroot . "/message/lib.php");
a623b6b8 31
5d1017e1 32/**
4615817d 33 * Message external functions
6fbd60ef
AD
34 *
35 * @package core_message
4615817d
JM
36 * @category external
37 * @copyright 2011 Jerome Mouneyrac
75e4f98c 38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4615817d 39 * @since Moodle 2.2
5d1017e1
JM
40 */
41class core_message_external extends external_api {
2553e9db
JD
42 /**
43 * Returns description of method parameters
44 *
45 * @return external_function_parameters
46 * @since Moodle 3.6
47 */
48 public static function send_messages_to_conversation_parameters() {
49 return new external_function_parameters(
50 array(
51 'conversationid' => new external_value(PARAM_INT, 'id of the conversation'),
52 'messages' => new external_multiple_structure(
53 new external_single_structure(
54 array(
55 'text' => new external_value(PARAM_RAW, 'the text of the message'),
56 'textformat' => new external_format_value('text', VALUE_DEFAULT, FORMAT_MOODLE),
57 )
58 )
59 )
60 )
61 );
62 }
63
64 /**
65 * Send messages from the current USER to a conversation.
66 *
67 * This conversation may be any type of conversation, individual or group.
68 *
69 * @param int $conversationid the id of the conversation to which the messages will be sent.
70 * @param array $messages An array of message to send.
71 * @return array the array of messages which were sent (created).
72 * @since Moodle 3.6
73 */
74 public static function send_messages_to_conversation(int $conversationid, array $messages = []) {
75 global $CFG, $USER;
76
77 // Check if messaging is enabled.
78 if (empty($CFG->messaging)) {
79 throw new moodle_exception('disabled', 'message');
80 }
81
82 // Ensure the current user is allowed to run this function.
83 $context = context_system::instance();
84 self::validate_context($context);
85
86 $params = self::validate_parameters(self::send_messages_to_conversation_parameters(), [
87 'conversationid' => $conversationid,
88 'messages' => $messages
89 ]);
90
91 $messages = [];
92 foreach ($params['messages'] as $message) {
a111ab44 93 $createdmessage = \core_message\api::send_message_to_conversation($USER->id, $params['conversationid'], $message['text'],
2553e9db 94 $message['textformat']);
a111ab44
RW
95 $createdmessage->text = message_format_message_text((object) [
96 'smallmessage' => $createdmessage->text,
97 'fullmessageformat' => external_validate_format($message['textformat'])
98 ]);
99 $messages[] = $createdmessage;
2553e9db
JD
100 }
101
102 return $messages;
103 }
104
105 /**
106 * Returns description of method result value.
107 *
108 * @return external_description
109 * @since Moodle 3.6
110 */
111 public static function send_messages_to_conversation_returns() {
112 return new external_multiple_structure(
113 self::get_conversation_message_structure()
114 );
115 }
116
a623b6b8
JM
117
118 /**
119 * Returns description of method parameters
4615817d 120 *
a623b6b8 121 * @return external_function_parameters
4615817d 122 * @since Moodle 2.2
a623b6b8 123 */
5d1017e1 124 public static function send_instant_messages_parameters() {
a623b6b8
JM
125 return new external_function_parameters(
126 array(
127 'messages' => new external_multiple_structure(
128 new external_single_structure(
129 array(
130 'touserid' => new external_value(PARAM_INT, 'id of the user to send the private message'),
93ce0e82 131 'text' => new external_value(PARAM_RAW, 'the text of the message'),
14968ca9 132 'textformat' => new external_format_value('text', VALUE_DEFAULT, FORMAT_MOODLE),
a623b6b8
JM
133 'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own client id for the message. If this id is provided, the fail message id will be returned to you', VALUE_OPTIONAL),
134 )
135 )
136 )
137 )
138 );
139 }
140
141 /**
142 * Send private messages from the current USER to other users
143 *
4615817d
JM
144 * @param array $messages An array of message to send.
145 * @return array
146 * @since Moodle 2.2
a623b6b8 147 */
5d1017e1 148 public static function send_instant_messages($messages = array()) {
a623b6b8 149 global $CFG, $USER, $DB;
a623b6b8 150
436bbf89 151 // Check if messaging is enabled.
837941e9 152 if (empty($CFG->messaging)) {
a623b6b8
JM
153 throw new moodle_exception('disabled', 'message');
154 }
155
156 // Ensure the current user is allowed to run this function
bf0f06b1 157 $context = context_system::instance();
a623b6b8
JM
158 self::validate_context($context);
159 require_capability('moodle/site:sendmessage', $context);
160
5d1017e1 161 $params = self::validate_parameters(self::send_instant_messages_parameters(), array('messages' => $messages));
a623b6b8
JM
162
163 //retrieve all tousers of the messages
4de00da7 164 $receivers = array();
a623b6b8 165 foreach($params['messages'] as $message) {
4de00da7 166 $receivers[] = $message['touserid'];
a623b6b8 167 }
f219eac7 168 list($sqluserids, $sqlparams) = $DB->get_in_or_equal($receivers);
a623b6b8 169 $tousers = $DB->get_records_select("user", "id " . $sqluserids . " AND deleted = 0", $sqlparams);
a623b6b8
JM
170
171 $resultmessages = array();
886b0178 172 $messageids = array();
a623b6b8 173 foreach ($params['messages'] as $message) {
a623b6b8
JM
174 $resultmsg = array(); //the infos about the success of the operation
175
f7dfa9ba
SA
176 // We are going to do some checking.
177 // Code should match /messages/index.php checks.
a623b6b8
JM
178 $success = true;
179
f7dfa9ba 180 // Check the user exists.
a623b6b8
JM
181 if (empty($tousers[$message['touserid']])) {
182 $success = false;
183 $errormessage = get_string('touserdoesntexist', 'message', $message['touserid']);
184 }
185
f7dfa9ba
SA
186 // TODO MDL-31118 performance improvement - edit the function so we can pass an array instead userid
187 // Check if the recipient can be messaged by the sender.
188 if ($success && !\core_message\api::can_post_message($tousers[$message['touserid']], $USER)) {
a623b6b8 189 $success = false;
f7dfa9ba 190 $errormessage = get_string('usercantbemessaged', 'message', fullname(\core_user::get_user($message['touserid'])));
a623b6b8
JM
191 }
192
f7dfa9ba 193 // Now we can send the message (at least try).
a623b6b8 194 if ($success) {
f7dfa9ba 195 // TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object.
93ce0e82
JM
196 $success = message_post_message($USER, $tousers[$message['touserid']],
197 $message['text'], external_validate_format($message['textformat']));
a623b6b8
JM
198 }
199
f7dfa9ba 200 // Build the resultmsg.
a623b6b8 201 if (isset($message['clientmsgid'])) {
78736e5d 202 $resultmsg['clientmsgid'] = $message['clientmsgid'];
a623b6b8
JM
203 }
204 if ($success) {
205 $resultmsg['msgid'] = $success;
886b0178
RW
206 $resultmsg['text'] = message_format_message_text((object) [
207 'smallmessage' => $message['text'],
208 'fullmessageformat' => external_validate_format($message['textformat'])
209 ]);
210 $resultmsg['timecreated'] = time();
211 $messageids[] = $success;
a623b6b8 212 } else {
93ce0e82
JM
213 // WARNINGS: for backward compatibility we return this errormessage.
214 // We should have thrown exceptions as these errors prevent results to be returned.
215 // See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
a623b6b8
JM
216 $resultmsg['msgid'] = -1;
217 $resultmsg['errormessage'] = $errormessage;
218 }
219
220 $resultmessages[] = $resultmsg;
221 }
222
886b0178
RW
223 if (!empty($messageids)) {
224 $messagerecords = $DB->get_records_list('messages', 'id', $messageids, '', 'id, conversationid');
225 $resultmessages = array_map(function($resultmessage) use ($messagerecords, $USER) {
226 $id = $resultmessage['msgid'];
227 $resultmessage['conversationid'] = isset($messagerecords[$id]) ? $messagerecords[$id]->conversationid : null;
228 $resultmessage['useridfrom'] = $USER->id;
229 return $resultmessage;
230 }, $resultmessages);
231 }
232
a623b6b8
JM
233 return $resultmessages;
234 }
235
236 /**
237 * Returns description of method result value
4615817d 238 *
a623b6b8 239 * @return external_description
4615817d 240 * @since Moodle 2.2
a623b6b8 241 */
5d1017e1 242 public static function send_instant_messages_returns() {
a623b6b8
JM
243 return new external_multiple_structure(
244 new external_single_structure(
245 array(
78736e5d 246 'msgid' => new external_value(PARAM_INT, 'test this to know if it succeeds: id of the created message if it succeeded, -1 when failed'),
4de00da7 247 'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own id for the message', VALUE_OPTIONAL),
886b0178
RW
248 'errormessage' => new external_value(PARAM_TEXT, 'error message - if it failed', VALUE_OPTIONAL),
249 'text' => new external_value(PARAM_RAW, 'The text of the message', VALUE_OPTIONAL),
250 'timecreated' => new external_value(PARAM_INT, 'The timecreated timestamp for the message', VALUE_OPTIONAL),
251 'conversationid' => new external_value(PARAM_INT, 'The conversation id for this message', VALUE_OPTIONAL),
252 'useridfrom' => new external_value(PARAM_INT, 'The user id who sent the message', VALUE_OPTIONAL),
a623b6b8
JM
253 )
254 )
255 );
256 }
257
d6731600
FM
258 /**
259 * Create contacts parameters description.
260 *
0b3eadcd 261 * @deprecated since Moodle 3.6
d6731600 262 * @return external_function_parameters
5bcfd504 263 * @since Moodle 2.5
d6731600
FM
264 */
265 public static function create_contacts_parameters() {
266 return new external_function_parameters(
267 array(
268 'userids' => new external_multiple_structure(
269 new external_value(PARAM_INT, 'User ID'),
270 'List of user IDs'
34c2f347
MN
271 ),
272 'userid' => new external_value(PARAM_INT, 'The id of the user we are creating the contacts for, 0 for the
273 current user', VALUE_DEFAULT, 0)
d6731600
FM
274 )
275 );
276 }
277
278 /**
279 * Create contacts.
280 *
0b3eadcd 281 * @deprecated since Moodle 3.6
d6731600 282 * @param array $userids array of user IDs.
34c2f347 283 * @param int $userid The id of the user we are creating the contacts for
d6731600 284 * @return external_description
5bcfd504 285 * @since Moodle 2.5
d6731600 286 */
34c2f347 287 public static function create_contacts($userids, $userid = 0) {
343ba16c 288 global $CFG, $USER;
436bbf89
DM
289
290 // Check if messaging is enabled.
837941e9 291 if (empty($CFG->messaging)) {
436bbf89
DM
292 throw new moodle_exception('disabled', 'message');
293 }
294
343ba16c
SL
295 if (empty($userid)) {
296 $userid = $USER->id;
297 }
298
299 // Validate context.
300 $context = context_system::instance();
301 self::validate_context($context);
302
bb650761
DW
303 $params = array('userids' => $userids, 'userid' => $userid);
304 $params = self::validate_parameters(self::create_contacts_parameters(), $params);
305
343ba16c 306 $capability = 'moodle/site:manageallmessaging';
bb650761 307 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
343ba16c
SL
308 throw new required_capability_exception($context, $capability, 'nopermissions', '');
309 }
310
d6731600
FM
311 $warnings = array();
312 foreach ($params['userids'] as $id) {
bb650761 313 if (!message_add_contact($id, 0, $params['userid'])) {
d6731600
FM
314 $warnings[] = array(
315 'item' => 'user',
316 'itemid' => $id,
317 'warningcode' => 'contactnotcreated',
318 'message' => 'The contact could not be created'
319 );
320 }
321 }
322 return $warnings;
323 }
324
325 /**
326 * Create contacts return description.
327 *
0b3eadcd 328 * @deprecated since Moodle 3.6
d6731600 329 * @return external_description
5bcfd504 330 * @since Moodle 2.5
d6731600
FM
331 */
332 public static function create_contacts_returns() {
333 return new external_warnings();
334 }
335
0b3eadcd
MN
336 /**
337 * Marking the method as deprecated.
338 *
339 * @return bool
340 */
341 public static function create_contacts_is_deprecated() {
342 return true;
343 }
344
d6731600
FM
345 /**
346 * Delete contacts parameters description.
347 *
348 * @return external_function_parameters
5bcfd504 349 * @since Moodle 2.5
d6731600
FM
350 */
351 public static function delete_contacts_parameters() {
352 return new external_function_parameters(
353 array(
354 'userids' => new external_multiple_structure(
355 new external_value(PARAM_INT, 'User ID'),
356 'List of user IDs'
34c2f347
MN
357 ),
358 'userid' => new external_value(PARAM_INT, 'The id of the user we are deleting the contacts for, 0 for the
359 current user', VALUE_DEFAULT, 0)
d6731600
FM
360 )
361 );
362 }
363
364 /**
365 * Delete contacts.
366 *
367 * @param array $userids array of user IDs.
34c2f347 368 * @param int $userid The id of the user we are deleting the contacts for
d6731600 369 * @return null
5bcfd504 370 * @since Moodle 2.5
d6731600 371 */
34c2f347 372 public static function delete_contacts($userids, $userid = 0) {
343ba16c 373 global $CFG, $USER;
436bbf89
DM
374
375 // Check if messaging is enabled.
837941e9 376 if (empty($CFG->messaging)) {
436bbf89
DM
377 throw new moodle_exception('disabled', 'message');
378 }
379
343ba16c
SL
380 if (empty($userid)) {
381 $userid = $USER->id;
382 }
383
384 // Validate context.
385 $context = context_system::instance();
386 self::validate_context($context);
387
bb650761
DW
388 $params = array('userids' => $userids, 'userid' => $userid);
389 $params = self::validate_parameters(self::delete_contacts_parameters(), $params);
390
343ba16c 391 $capability = 'moodle/site:manageallmessaging';
bb650761 392 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
343ba16c
SL
393 throw new required_capability_exception($context, $capability, 'nopermissions', '');
394 }
395
d6731600 396 foreach ($params['userids'] as $id) {
bb650761 397 \core_message\api::remove_contact($params['userid'], $id);
d6731600
FM
398 }
399
400 return null;
401 }
402
403 /**
404 * Delete contacts return description.
405 *
406 * @return external_description
5bcfd504 407 * @since Moodle 2.5
d6731600
FM
408 */
409 public static function delete_contacts_returns() {
410 return null;
411 }
412
52284186
MN
413 /**
414 * Block user parameters description.
415 *
416 * @return external_function_parameters
417 */
418 public static function block_user_parameters() {
419 return new external_function_parameters(
420 [
421 'userid' => new external_value(PARAM_INT, 'The id of the user who is blocking'),
422 'blockeduserid' => new external_value(PARAM_INT, 'The id of the user being blocked'),
423 ]
424 );
425 }
426
427 /**
428 * Blocks a user.
429 *
430 * @param int $userid The id of the user who is blocking
431 * @param int $blockeduserid The id of the user being blocked
432 * @return external_description
433 */
434 public static function block_user(int $userid, int $blockeduserid) {
435 global $CFG, $USER;
436
437 // Check if messaging is enabled.
438 if (empty($CFG->messaging)) {
439 throw new moodle_exception('disabled', 'message');
440 }
441
442 // Validate context.
443 $context = context_system::instance();
444 self::validate_context($context);
445
bb650761
DW
446 $params = ['userid' => $userid, 'blockeduserid' => $blockeduserid];
447 $params = self::validate_parameters(self::block_user_parameters(), $params);
448
52284186 449 $capability = 'moodle/site:manageallmessaging';
bb650761 450 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
52284186
MN
451 throw new required_capability_exception($context, $capability, 'nopermissions', '');
452 }
453
52284186
MN
454 if (!\core_message\api::is_blocked($params['userid'], $params['blockeduserid'])) {
455 \core_message\api::block_user($params['userid'], $params['blockeduserid']);
456 }
457
458 return [];
459 }
460
461 /**
462 * Block user return description.
463 *
464 * @return external_description
465 */
466 public static function block_user_returns() {
467 return new external_warnings();
468 }
469
470 /**
471 * Unblock user parameters description.
472 *
473 * @return external_function_parameters
474 */
475 public static function unblock_user_parameters() {
476 return new external_function_parameters(
477 [
478 'userid' => new external_value(PARAM_INT, 'The id of the user who is unblocking'),
479 'unblockeduserid' => new external_value(PARAM_INT, 'The id of the user being unblocked'),
480 ]
481 );
482 }
483
484 /**
485 * Unblock user.
486 *
487 * @param int $userid The id of the user who is unblocking
488 * @param int $unblockeduserid The id of the user being unblocked
489 */
490 public static function unblock_user(int $userid, int $unblockeduserid) {
491 global $CFG, $USER;
492
493 // Check if messaging is enabled.
494 if (empty($CFG->messaging)) {
495 throw new moodle_exception('disabled', 'message');
496 }
497
498 // Validate context.
499 $context = context_system::instance();
500 self::validate_context($context);
501
bb650761
DW
502 $params = ['userid' => $userid, 'unblockeduserid' => $unblockeduserid];
503 $params = self::validate_parameters(self::unblock_user_parameters(), $params);
504
52284186 505 $capability = 'moodle/site:manageallmessaging';
bb650761 506 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
52284186
MN
507 throw new required_capability_exception($context, $capability, 'nopermissions', '');
508 }
509
52284186
MN
510 \core_message\api::unblock_user($params['userid'], $params['unblockeduserid']);
511
512 return [];
513 }
514
515 /**
516 * Unblock user return description.
517 *
518 * @return external_description
519 */
520 public static function unblock_user_returns() {
521 return new external_warnings();
522 }
523
d6731600
FM
524 /**
525 * Block contacts parameters description.
526 *
0b3eadcd 527 * @deprecated since Moodle 3.6
d6731600 528 * @return external_function_parameters
5bcfd504 529 * @since Moodle 2.5
d6731600
FM
530 */
531 public static function block_contacts_parameters() {
532 return new external_function_parameters(
533 array(
534 'userids' => new external_multiple_structure(
535 new external_value(PARAM_INT, 'User ID'),
536 'List of user IDs'
34c2f347
MN
537 ),
538 'userid' => new external_value(PARAM_INT, 'The id of the user we are blocking the contacts for, 0 for the
539 current user', VALUE_DEFAULT, 0)
d6731600
FM
540 )
541 );
542 }
543
544 /**
545 * Block contacts.
546 *
0b3eadcd 547 * @deprecated since Moodle 3.6
d6731600 548 * @param array $userids array of user IDs.
34c2f347 549 * @param int $userid The id of the user we are blocking the contacts for
d6731600 550 * @return external_description
5bcfd504 551 * @since Moodle 2.5
d6731600 552 */
34c2f347 553 public static function block_contacts($userids, $userid = 0) {
343ba16c 554 global $CFG, $USER;
436bbf89
DM
555
556 // Check if messaging is enabled.
837941e9 557 if (empty($CFG->messaging)) {
436bbf89
DM
558 throw new moodle_exception('disabled', 'message');
559 }
560
343ba16c
SL
561 if (empty($userid)) {
562 $userid = $USER->id;
563 }
564
565 // Validate context.
566 $context = context_system::instance();
567 self::validate_context($context);
568
bb650761
DW
569 $params = array('userids' => $userids, 'userid' => $userid);
570 $params = self::validate_parameters(self::block_contacts_parameters(), $params);
571
343ba16c 572 $capability = 'moodle/site:manageallmessaging';
bb650761 573 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
343ba16c
SL
574 throw new required_capability_exception($context, $capability, 'nopermissions', '');
575 }
576
d6731600
FM
577 $warnings = array();
578 foreach ($params['userids'] as $id) {
bb650761 579 if (!message_block_contact($id, $params['userid'])) {
d6731600
FM
580 $warnings[] = array(
581 'item' => 'user',
582 'itemid' => $id,
583 'warningcode' => 'contactnotblocked',
584 'message' => 'The contact could not be blocked'
585 );
586 }
587 }
588 return $warnings;
589 }
590
591 /**
592 * Block contacts return description.
593 *
0b3eadcd 594 * @deprecated since Moodle 3.6
d6731600 595 * @return external_description
5bcfd504 596 * @since Moodle 2.5
d6731600
FM
597 */
598 public static function block_contacts_returns() {
599 return new external_warnings();
600 }
601
0b3eadcd
MN
602 /**
603 * Marking the method as deprecated.
604 *
605 * @return bool
606 */
607 public static function block_contacts_is_deprecated() {
608 return true;
609 }
610
d6731600
FM
611 /**
612 * Unblock contacts parameters description.
613 *
0b3eadcd 614 * @deprecated since Moodle 3.6
d6731600 615 * @return external_function_parameters
5bcfd504 616 * @since Moodle 2.5
d6731600
FM
617 */
618 public static function unblock_contacts_parameters() {
619 return new external_function_parameters(
620 array(
621 'userids' => new external_multiple_structure(
622 new external_value(PARAM_INT, 'User ID'),
623 'List of user IDs'
34c2f347
MN
624 ),
625 'userid' => new external_value(PARAM_INT, 'The id of the user we are unblocking the contacts for, 0 for the
626 current user', VALUE_DEFAULT, 0)
d6731600
FM
627 )
628 );
629 }
630
631 /**
632 * Unblock contacts.
633 *
634 * @param array $userids array of user IDs.
34c2f347 635 * @param int $userid The id of the user we are unblocking the contacts for
d6731600 636 * @return null
5bcfd504 637 * @since Moodle 2.5
d6731600 638 */
34c2f347 639 public static function unblock_contacts($userids, $userid = 0) {
343ba16c 640 global $CFG, $USER;
436bbf89
DM
641
642 // Check if messaging is enabled.
837941e9 643 if (empty($CFG->messaging)) {
436bbf89
DM
644 throw new moodle_exception('disabled', 'message');
645 }
646
343ba16c
SL
647 if (empty($userid)) {
648 $userid = $USER->id;
649 }
650
651 // Validate context.
652 $context = context_system::instance();
653 self::validate_context($context);
654
bb650761
DW
655 $params = array('userids' => $userids, 'userid' => $userid);
656 $params = self::validate_parameters(self::unblock_contacts_parameters(), $params);
657
343ba16c 658 $capability = 'moodle/site:manageallmessaging';
bb650761 659 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
343ba16c
SL
660 throw new required_capability_exception($context, $capability, 'nopermissions', '');
661 }
662
d6731600 663 foreach ($params['userids'] as $id) {
bb650761 664 message_unblock_contact($id, $params['userid']);
d6731600
FM
665 }
666
667 return null;
668 }
669
670 /**
671 * Unblock contacts return description.
672 *
0b3eadcd 673 * @deprecated since Moodle 3.6
d6731600 674 * @return external_description
5bcfd504 675 * @since Moodle 2.5
d6731600
FM
676 */
677 public static function unblock_contacts_returns() {
678 return null;
679 }
680
0b3eadcd
MN
681 /**
682 * Marking the method as deprecated.
683 *
684 * @return bool
685 */
686 public static function unblock_contacts_is_deprecated() {
687 return true;
688 }
689
52284186
MN
690 /**
691 * Returns contact requests parameters description.
692 *
693 * @return external_function_parameters
694 */
695 public static function get_contact_requests_parameters() {
696 return new external_function_parameters(
697 [
accd6482
MN
698 'userid' => new external_value(PARAM_INT, 'The id of the user we want the requests for'),
699 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
700 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
52284186
MN
701 ]
702 );
703 }
704
705 /**
706 * Handles returning the contact requests for a user.
707 *
708 * This also includes the user data necessary to display information
709 * about the user.
710 *
711 * It will not include blocked users.
712 *
713 * @param int $userid The id of the user we want to get the contact requests for
accd6482
MN
714 * @param int $limitfrom
715 * @param int $limitnum
52284186 716 */
accd6482 717 public static function get_contact_requests(int $userid, int $limitfrom = 0, int $limitnum = 0) {
52284186
MN
718 global $CFG, $USER;
719
720 // Check if messaging is enabled.
721 if (empty($CFG->messaging)) {
722 throw new moodle_exception('disabled', 'message');
723 }
724
725 // Validate context.
726 $context = context_system::instance();
727 self::validate_context($context);
728
accd6482
MN
729 $params = [
730 'userid' => $userid,
731 'limitfrom' => $limitfrom,
732 'limitnum' => $limitnum
733 ];
52284186
MN
734 $params = self::validate_parameters(self::get_contact_requests_parameters(), $params);
735
52284186 736 $capability = 'moodle/site:manageallmessaging';
bb650761 737 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
52284186
MN
738 throw new required_capability_exception($context, $capability, 'nopermissions', '');
739 }
740
accd6482 741 return \core_message\api::get_contact_requests($params['userid'], $params['limitfrom'], $params['limitnum']);
52284186
MN
742 }
743
744 /**
745 * Returns the contact requests return description.
746 *
747 * @return external_description
748 */
749 public static function get_contact_requests_returns() {
750 return new external_multiple_structure(
daa33803 751 self::get_conversation_member_structure()
52284186
MN
752 );
753 }
754
7d678923
MN
755 /**
756 * Returns the number of contact requests the user has received parameters description.
757 *
758 * @return external_function_parameters
759 */
760 public static function get_received_contact_requests_count_parameters() {
761 return new external_function_parameters(
762 array(
763 'userid' => new external_value(PARAM_INT, 'The id of the user we want to return the number of ' .
764 'received contact requests for', VALUE_REQUIRED),
765 )
766 );
767 }
768
769 /**
770 * Returns the number of contact requests the user has received.
771 *
772 * @param int $userid The ID of the user we want to return the number of received contact requests for
773 * @return external_value
774 */
775 public static function get_received_contact_requests_count(int $userid) {
776 global $CFG, $USER;
777
778 // Check if messaging is enabled.
779 if (empty($CFG->messaging)) {
780 throw new moodle_exception('disabled', 'message');
781 }
782
783 // Validate context.
784 $context = context_system::instance();
785 self::validate_context($context);
786
787 $params = [
788 'userid' => $userid,
789 ];
790 $params = self::validate_parameters(self::get_received_contact_requests_count_parameters(), $params);
791
792 $capability = 'moodle/site:manageallmessaging';
793 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
794 throw new required_capability_exception($context, $capability, 'nopermissions', '');
795 }
796
797 return \core_message\api::get_received_contact_requests_count($params['userid']);
798 }
799
800 /**
801 * Returns the number of contact requests the user has received return description.
802 *
803 * @return external_value
804 */
805 public static function get_received_contact_requests_count_returns() {
806 return new external_value(PARAM_INT, 'The number of received contact requests');
807 }
808
5584c48a
MN
809 /**
810 * Returns get conversation members parameters description.
811 *
812 * @return external_function_parameters
813 */
814 public static function get_conversation_members_parameters() {
815 return new external_function_parameters(
816 [
817 'userid' => new external_value(PARAM_INT, 'The id of the user we are performing this action on behalf of'),
818 'conversationid' => new external_value(PARAM_INT, 'The id of the conversation'),
819 'includecontactrequests' => new external_value(PARAM_BOOL, 'Do we want to include contact requests?',
820 VALUE_DEFAULT, false),
663ccd58
RW
821 'includeprivacyinfo' => new external_value(PARAM_BOOL, 'Do we want to include privacy info?',
822 VALUE_DEFAULT, false),
5584c48a
MN
823 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
824 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
825 ]
826 );
827 }
828
829 /**
830 * Returns a list of conversation members.
831 *
832 * @param int $userid The user we are returning the conversation members for, used by helper::get_member_info.
833 * @param int $conversationid The id of the conversation
834 * @param bool $includecontactrequests Do we want to include contact requests with this data?
663ccd58 835 * @param bool $includeprivacyinfo Do we want to include privacy info?
5584c48a
MN
836 * @param int $limitfrom
837 * @param int $limitnum
838 * @return array
839 */
840 public static function get_conversation_members(int $userid, int $conversationid, bool $includecontactrequests = false,
663ccd58 841 bool $includeprivacyinfo = false, int $limitfrom = 0, int $limitnum = 0) {
5584c48a
MN
842 global $CFG, $USER;
843
844 // Check if messaging is enabled.
845 if (empty($CFG->messaging)) {
846 throw new moodle_exception('disabled', 'message');
847 }
848
849 // Validate context.
850 $context = context_system::instance();
851 self::validate_context($context);
852
bb650761
DW
853 $params = [
854 'userid' => $userid,
855 'conversationid' => $conversationid,
856 'includecontactrequests' => $includecontactrequests,
663ccd58 857 'includeprivacyinfo' => $includeprivacyinfo,
bb650761
DW
858 'limitfrom' => $limitfrom,
859 'limitnum' => $limitnum
860 ];
861 $params = self::validate_parameters(self::get_conversation_members_parameters(), $params);
862
5584c48a 863 $capability = 'moodle/site:manageallmessaging';
bb650761 864 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
5584c48a
MN
865 throw new required_capability_exception($context, $capability, 'nopermissions', '');
866 }
867
bc667050 868 // The user needs to be a part of the conversation before querying who the members are.
bb650761 869 if (!\core_message\api::is_user_in_conversation($params['userid'], $params['conversationid'])) {
bc667050
MN
870 throw new moodle_exception('You are not a member of this conversation.');
871 }
872
bb650761 873 return \core_message\api::get_conversation_members($params['userid'], $params['conversationid'], $params['includecontactrequests'],
663ccd58 874 $params['includeprivacyinfo'], $params['limitfrom'], $params['limitnum']);
5584c48a
MN
875 }
876
877 /**
878 * Returns the get conversation members return description.
879 *
880 * @return external_description
881 */
882 public static function get_conversation_members_returns() {
883 return new external_multiple_structure(
34b940f6 884 self::get_conversation_member_structure()
5584c48a
MN
885 );
886 }
887
52284186
MN
888 /**
889 * Creates a contact request parameters description.
890 *
891 * @return external_function_parameters
892 */
893 public static function create_contact_request_parameters() {
894 return new external_function_parameters(
895 [
896 'userid' => new external_value(PARAM_INT, 'The id of the user making the request'),
897 'requesteduserid' => new external_value(PARAM_INT, 'The id of the user being requested')
898 ]
899 );
900 }
901
902 /**
903 * Creates a contact request.
904 *
905 * @param int $userid The id of the user who is creating the contact request
906 * @param int $requesteduserid The id of the user being requested
907 */
908 public static function create_contact_request(int $userid, int $requesteduserid) {
909 global $CFG, $USER;
910
911 // Check if messaging is enabled.
912 if (empty($CFG->messaging)) {
913 throw new moodle_exception('disabled', 'message');
914 }
915
916 // Validate context.
917 $context = context_system::instance();
918 self::validate_context($context);
919
bb650761
DW
920 $params = ['userid' => $userid, 'requesteduserid' => $requesteduserid];
921 $params = self::validate_parameters(self::create_contact_request_parameters(), $params);
922
52284186 923 $capability = 'moodle/site:manageallmessaging';
bb650761 924 if (($USER->id != $params['userid']) && !has_capability($capability, $context)) {
52284186
MN
925 throw new required_capability_exception($context, $capability, 'nopermissions', '');
926 }
927
0866b336
RW
928 $result = [
929 'warnings' => []
930 ];
931
0d203bbf 932 if (!\core_message\api::can_create_contact($params['userid'], $params['requesteduserid'])) {
0866b336 933 $result['warnings'][] = [
0d203bbf
MN
934 'item' => 'user',
935 'itemid' => $params['requesteduserid'],
936 'warningcode' => 'cannotcreatecontactrequest',
937 'message' => 'You are unable to create a contact request for this user'
938 ];
0866b336
RW
939 } else {
940 if ($requests = \core_message\api::get_contact_requests_between_users($params['userid'], $params['requesteduserid'])) {
941 // There should only ever be one but just in case there are multiple then we can return the first.
942 $result['request'] = array_shift($requests);
943 } else {
944 $result['request'] = \core_message\api::create_contact_request($params['userid'], $params['requesteduserid']);
945 }
52284186
MN
946 }
947
0866b336 948 return $result;
52284186
MN
949 }
950
951 /**
952 * Creates a contact request return description.
953 *
954 * @return external_description
955 */
956 public static function create_contact_request_returns() {
0866b336
RW
957 return new external_single_structure(
958 array(
959 'request' => new external_single_structure(
960 array(
961 'id' => new external_value(PARAM_INT, 'Message id'),
962 'userid' => new external_value(PARAM_INT, 'User from id'),
963 'requesteduserid' => new external_value(PARAM_INT, 'User to id'),
964 'timecreated' => new external_value(PARAM_INT, 'Time created'),
965 ),
966 'request record',
967 VALUE_OPTIONAL
968 ),
969 'warnings' => new external_warnings()
970 )
971 );
52284186
MN
972 }
973
974 /**
975 * Confirm a contact request parameters description.
976 *
977 * @return external_function_parameters
978 */
979 public static function confirm_contact_request_parameters() {
980 return new external_function_parameters(
981 [
982 'userid' => new external_value(PARAM_INT, 'The id of the user making the request'),
983 'requesteduserid' => new external_value(PARAM_INT, 'The id of the user being requested')
984 ]
985 );
986 }
987
988 /**
989 * Confirm a contact request.
990 *
991 * @param int $userid The id of the user who is creating the contact request
992 * @param int $requesteduserid The id of the user being requested
993 */
994 public static function confirm_contact_request(int $userid, int $requesteduserid) {
995 global $CFG, $USER;
996
997 // Check if messaging is enabled.
998 if (empty($CFG->messaging)) {
999 throw new moodle_exception('disabled', 'message');
1000 }
1001
1002 // Validate context.
1003 $context = context_system::instance();
1004 self::validate_context($context);
1005
bb650761
DW
1006 $params = ['userid' => $userid, 'requesteduserid' => $requesteduserid];
1007 $params = self::validate_parameters(self::confirm_contact_request_parameters(), $params);
1008
52284186 1009 $capability = 'moodle/site:manageallmessaging';
bb650761 1010 if (($USER->id != $params['requesteduserid']) && !has_capability($capability, $context)) {
52284186
MN
1011 throw new required_capability_exception($context, $capability, 'nopermissions', '');
1012 }
1013
52284186
MN
1014 \core_message\api::confirm_contact_request($params['userid'], $params['requesteduserid']);
1015
1016 return [];
1017 }
1018
1019 /**
1020 * Confirm a contact request return description.
1021 *
1022 * @return external_description
1023 */
1024 public static function confirm_contact_request_returns() {
1025 return new external_warnings();
1026 }
1027
1028 /**
1029 * Declines a contact request parameters description.
1030 *
1031 * @return external_function_parameters
1032 */
1033 public static function decline_contact_request_parameters() {
1034 return new external_function_parameters(
1035 [
1036 'userid' => new external_value(PARAM_INT, 'The id of the user making the request'),
1037 'requesteduserid' => new external_value(PARAM_INT, 'The id of the user being requested')
1038 ]
1039 );
1040 }
1041
1042 /**
1043 * Declines a contact request.
1044 *
1045 * @param int $userid The id of the user who is creating the contact request
1046 * @param int $requesteduserid The id of the user being requested
1047 */
1048 public static function decline_contact_request(int $userid, int $requesteduserid) {
1049 global $CFG, $USER;
1050
1051 // Check if messaging is enabled.
1052 if (empty($CFG->messaging)) {
1053 throw new moodle_exception('disabled', 'message');
1054 }
1055
1056 // Validate context.
1057 $context = context_system::instance();
1058 self::validate_context($context);
1059
bb650761
DW
1060 $params = ['userid' => $userid, 'requesteduserid' => $requesteduserid];
1061 $params = self::validate_parameters(self::decline_contact_request_parameters(), $params);
1062
52284186 1063 $capability = 'moodle/site:manageallmessaging';
bb650761 1064 if (($USER->id != $params['requesteduserid']) && !has_capability($capability, $context)) {
52284186
MN
1065 throw new required_capability_exception($context, $capability, 'nopermissions', '');
1066 }
1067
52284186
MN
1068 \core_message\api::decline_contact_request($params['userid'], $params['requesteduserid']);
1069
1070 return [];
1071 }
1072
1073 /**
1074 * Declines a contact request return description.
1075 *
1076 * @return external_description
1077 */
1078 public static function decline_contact_request_returns() {
1079 return new external_warnings();
1080 }
1081
a3e3a3a1
MN
1082 /**
1083 * Return the structure of a message area contact.
1084 *
1085 * @return external_single_structure
1086 * @since Moodle 3.2
1087 */
1088 private static function get_messagearea_contact_structure() {
1089 return new external_single_structure(
1090 array(
1091 'userid' => new external_value(PARAM_INT, 'The user\'s id'),
1092 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
1093 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
1094 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
5bf0ff27 1095 'ismessaging' => new external_value(PARAM_BOOL, 'If we are messaging the user'),
89a70ba1 1096 'sentfromcurrentuser' => new external_value(PARAM_BOOL, 'Was the last message sent from the current user?'),
a3e3a3a1 1097 'lastmessage' => new external_value(PARAM_NOTAGS, 'The user\'s last message'),
0802c38a 1098 'lastmessagedate' => new external_value(PARAM_INT, 'Timestamp for last message', VALUE_DEFAULT, null),
a3e3a3a1 1099 'messageid' => new external_value(PARAM_INT, 'The unique search message id', VALUE_DEFAULT, null),
cb805753 1100 'showonlinestatus' => new external_value(PARAM_BOOL, 'Show the user\'s online status?'),
a3e3a3a1
MN
1101 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status'),
1102 'isread' => new external_value(PARAM_BOOL, 'If the user has read the message'),
dd0c1403 1103 'isblocked' => new external_value(PARAM_BOOL, 'If the user has been blocked'),
a3e3a3a1
MN
1104 'unreadcount' => new external_value(PARAM_INT, 'The number of unread messages in this conversation',
1105 VALUE_DEFAULT, null),
d2708759 1106 'conversationid' => new external_value(PARAM_INT, 'The id of the conversation', VALUE_DEFAULT, null),
a3e3a3a1
MN
1107 )
1108 );
1109 }
1110
6f31927a
JD
1111 /**
1112 * Return the structure of a conversation.
1113 *
1114 * @return external_single_structure
1115 * @since Moodle 3.6
1116 */
1117 private static function get_conversation_structure() {
1118 return new external_single_structure(
1119 array(
1120 'id' => new external_value(PARAM_INT, 'The conversation id'),
e66e867f
JD
1121 'name' => new external_value(PARAM_TEXT, 'The conversation name, if set', VALUE_DEFAULT, null),
1122 'subname' => new external_value(PARAM_TEXT, 'A subtitle for the conversation name, if set', VALUE_DEFAULT, null),
003cdcce 1123 'imageurl' => new external_value(PARAM_URL, 'A link to the conversation picture, if set', VALUE_DEFAULT, null),
6f31927a
JD
1124 'type' => new external_value(PARAM_INT, 'The type of the conversation (1=individual,2=group)'),
1125 'membercount' => new external_value(PARAM_INT, 'Total number of conversation members'),
1126 'isfavourite' => new external_value(PARAM_BOOL, 'If the user marked conversation this conversation as a favourite'),
1127 'isread' => new external_value(PARAM_BOOL, 'If the user has read all messages in the conversation'),
1128 'unreadcount' => new external_value(PARAM_INT, 'The number of unread messages in this conversation',
1129 VALUE_DEFAULT, null),
1130 'members' => new external_multiple_structure(
34b940f6 1131 self::get_conversation_member_structure()
6f31927a
JD
1132 ),
1133 'messages' => new external_multiple_structure(
1134 self::get_conversation_message_structure()
1135 ),
1136 )
1137 );
1138 }
1139
fb04293b
SA
1140 /**
1141 * Return the structure of a conversation member.
1142 *
1143 * @return external_single_structure
1144 * @since Moodle 3.6
1145 */
34b940f6 1146 private static function get_conversation_member_structure() {
5584c48a
MN
1147 $result = [
1148 'id' => new external_value(PARAM_INT, 'The user id'),
1149 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
9b39f282 1150 'profileurl' => new external_value(PARAM_URL, 'The link to the user\'s profile page'),
5584c48a
MN
1151 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
1152 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
1153 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status'),
1154 'showonlinestatus' => new external_value(PARAM_BOOL, 'Show the user\'s online status?'),
1155 'isblocked' => new external_value(PARAM_BOOL, 'If the user has been blocked'),
1156 'iscontact' => new external_value(PARAM_BOOL, 'Is the user a contact?'),
d15c1e77 1157 'isdeleted' => new external_value(PARAM_BOOL, 'Is the user deleted?'),
cef1d977
MN
1158 'canmessage' => new external_value(PARAM_BOOL, 'If the user can be messaged'),
1159 'requirescontact' => new external_value(PARAM_BOOL, 'If the user requires to be contacts'),
5584c48a
MN
1160 ];
1161
5e47224a
AN
1162 $result['contactrequests'] = new external_multiple_structure(
1163 new external_single_structure(
1164 [
2be9a4ae
MN
1165 'id' => new external_value(PARAM_INT, 'The id of the contact request'),
1166 'userid' => new external_value(PARAM_INT, 'The id of the user who created the contact request'),
1167 'requesteduserid' => new external_value(PARAM_INT, 'The id of the user confirming the request'),
1168 'timecreated' => new external_value(PARAM_INT, 'The timecreated timestamp for the contact request'),
5e47224a
AN
1169 ]
1170 ), 'The contact requests', VALUE_OPTIONAL
1171 );
5584c48a 1172
5e47224a
AN
1173 $result['conversations'] = new external_multiple_structure(new external_single_structure(
1174 array(
1175 'id' => new external_value(PARAM_INT, 'Conversations id'),
1176 'type' => new external_value(PARAM_INT, 'Conversation type: private or public'),
1177 'name' => new external_value(PARAM_TEXT, 'Multilang compatible conversation name'. VALUE_OPTIONAL),
1178 'timecreated' => new external_value(PARAM_INT, 'The timecreated timestamp for the conversation'),
1179 ), 'information about conversation', VALUE_OPTIONAL),
1180 'Conversations between users', VALUE_OPTIONAL
1181 );
548cac7d 1182
fb04293b 1183 return new external_single_structure(
5584c48a 1184 $result
fb04293b
SA
1185 );
1186 }
1187
1188 /**
1189 * Return the structure of a message area message.
1190 *
1191 * @return external_single_structure
1192 * @since Moodle 3.6
1193 */
1194 private static function get_conversation_message_structure() {
1195 return new external_single_structure(
1196 array(
1197 'id' => new external_value(PARAM_INT, 'The id of the message'),
1198 'useridfrom' => new external_value(PARAM_INT, 'The id of the user who sent the message'),
1199 'text' => new external_value(PARAM_RAW, 'The text of the message'),
1200 'timecreated' => new external_value(PARAM_INT, 'The timecreated timestamp for the message'),
1201 )
1202 );
1203 }
1204
94e1db61
MN
1205 /**
1206 * Return the structure of a message area message.
1207 *
1208 * @return external_single_structure
1209 * @since Moodle 3.2
1210 */
1211 private static function get_messagearea_message_structure() {
1212 return new external_single_structure(
1213 array(
1214 'id' => new external_value(PARAM_INT, 'The id of the message'),
89a70ba1
MN
1215 'useridfrom' => new external_value(PARAM_INT, 'The id of the user who sent the message'),
1216 'useridto' => new external_value(PARAM_INT, 'The id of the user who received the message'),
94e1db61
MN
1217 'text' => new external_value(PARAM_RAW, 'The text of the message'),
1218 'displayblocktime' => new external_value(PARAM_BOOL, 'Should we display the block time?'),
1219 'blocktime' => new external_value(PARAM_NOTAGS, 'The time to display above the message'),
1220 'position' => new external_value(PARAM_ALPHA, 'The position of the text'),
1221 'timesent' => new external_value(PARAM_NOTAGS, 'The time the message was sent'),
fb1469d8 1222 'timecreated' => new external_value(PARAM_INT, 'The timecreated timestamp for the message'),
94e1db61
MN
1223 'isread' => new external_value(PARAM_INT, 'Determines if the message was read or not'),
1224 )
1225 );
1226 }
1227
cd03b8d7 1228 /**
48e8bdba 1229 * Get messagearea search users in course parameters.
cd03b8d7 1230 *
548cac7d
AA
1231 * @deprecated since 3.6
1232 *
cd03b8d7
MN
1233 * @return external_function_parameters
1234 * @since 3.2
1235 */
48e8bdba 1236 public static function data_for_messagearea_search_users_in_course_parameters() {
cd03b8d7
MN
1237 return new external_function_parameters(
1238 array(
1239 'userid' => new external_value(PARAM_INT, 'The id of the user who is performing the search'),
1240 'courseid' => new external_value(PARAM_INT, 'The id of the course'),
1241 'search' => new external_value(PARAM_RAW, 'The string being searched'),
1242 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
1243 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
1244 )
1245 );
1246 }
1247
1248 /**
48e8bdba 1249 * Get messagearea search users in course results.
cd03b8d7 1250 *
548cac7d
AA
1251 * @deprecated since 3.6
1252 *
cd03b8d7
MN
1253 * @param int $userid The id of the user who is performing the search
1254 * @param int $courseid The id of the course
1255 * @param string $search The string being searched
1256 * @param int $limitfrom
1257 * @param int $limitnum
1258 * @return stdClass
1259 * @throws moodle_exception
1260 * @since 3.2
1261 */
48e8bdba 1262 public static function data_for_messagearea_search_users_in_course($userid, $courseid, $search, $limitfrom = 0,
de55cb1b 1263 $limitnum = 0) {
837941e9 1264 global $CFG, $PAGE, $USER;
cd03b8d7
MN
1265
1266 // Check if messaging is enabled.
837941e9 1267 if (empty($CFG->messaging)) {
cd03b8d7
MN
1268 throw new moodle_exception('disabled', 'message');
1269 }
1270
837941e9
MN
1271 $systemcontext = context_system::instance();
1272
cd03b8d7
MN
1273 $params = array(
1274 'userid' => $userid,
1275 'courseid' => $courseid,
1276 'search' => $search,
1277 'limitfrom' => $limitfrom,
1278 'limitnum' => $limitnum
1279 );
bb650761 1280 $params = self::validate_parameters(self::data_for_messagearea_search_users_in_course_parameters(), $params);
837941e9 1281 self::validate_context($systemcontext);
cd03b8d7 1282
bb650761 1283 if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
837941e9
MN
1284 throw new moodle_exception('You do not have permission to perform this action.');
1285 }
cd03b8d7 1286
bb650761
DW
1287 $users = \core_message\api::search_users_in_course(
1288 $params['userid'],
1289 $params['courseid'],
1290 $params['search'],
1291 $params['limitfrom'],
1292 $params['limitnum']
1293 );
de55cb1b 1294 $results = new \core_message\output\messagearea\user_search_results($users);
cd03b8d7
MN
1295
1296 $renderer = $PAGE->get_renderer('core_message');
de55cb1b 1297 return $results->export_for_template($renderer);
cd03b8d7
MN
1298 }
1299
1300 /**
48e8bdba 1301 * Get messagearea search users in course returns.
cd03b8d7 1302 *
548cac7d
AA
1303 * @deprecated since 3.6
1304 *
cd03b8d7
MN
1305 * @return external_single_structure
1306 * @since 3.2
1307 */
48e8bdba 1308 public static function data_for_messagearea_search_users_in_course_returns() {
cd03b8d7
MN
1309 return new external_single_structure(
1310 array(
cd03b8d7 1311 'contacts' => new external_multiple_structure(
a3e3a3a1 1312 self::get_messagearea_contact_structure()
cd03b8d7
MN
1313 ),
1314 )
1315 );
1316 }
1317
548cac7d
AA
1318 /**
1319 * Marking the method as deprecated.
1320 *
1321 * @return bool
1322 */
1323 public static function data_for_messagearea_search_users_in_course_is_deprecated() {
1324 return true;
1325 }
1326
cd03b8d7 1327 /**
48e8bdba 1328 * Get messagearea search users parameters.
cd03b8d7 1329 *
548cac7d
AA
1330 * @deprecated since 3.6
1331 *
cd03b8d7
MN
1332 * @return external_function_parameters
1333 * @since 3.2
1334 */
48e8bdba 1335 public static function data_for_messagearea_search_users_parameters() {
cd03b8d7
MN
1336 return new external_function_parameters(
1337 array(
1338 'userid' => new external_value(PARAM_INT, 'The id of the user who is performing the search'),
1339 'search' => new external_value(PARAM_RAW, 'The string being searched'),
1340 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
1341 )
1342 );
1343 }
1344
1345 /**
48e8bdba 1346 * Get messagearea search users results.
cd03b8d7 1347 *
548cac7d
AA
1348 * @deprecated since 3.6
1349 *
cd03b8d7
MN
1350 * @param int $userid The id of the user who is performing the search
1351 * @param string $search The string being searched
1352 * @param int $limitnum
1353 * @return stdClass
1354 * @throws moodle_exception
1355 * @since 3.2
1356 */
48e8bdba 1357 public static function data_for_messagearea_search_users($userid, $search, $limitnum = 0) {
837941e9 1358 global $CFG, $PAGE, $USER;
cd03b8d7
MN
1359
1360 // Check if messaging is enabled.
837941e9 1361 if (empty($CFG->messaging)) {
cd03b8d7
MN
1362 throw new moodle_exception('disabled', 'message');
1363 }
1364
837941e9
MN
1365 $systemcontext = context_system::instance();
1366
cd03b8d7
MN
1367 $params = array(
1368 'userid' => $userid,
1369 'search' => $search,
1370 'limitnum' => $limitnum
1371 );
bb650761 1372 $params = self::validate_parameters(self::data_for_messagearea_search_users_parameters(), $params);
837941e9 1373 self::validate_context($systemcontext);
cd03b8d7 1374
bb650761 1375 if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
837941e9
MN
1376 throw new moodle_exception('You do not have permission to perform this action.');
1377 }
cd03b8d7 1378
bb650761
DW
1379 list($contacts, $courses, $noncontacts) = \core_message\api::search_users(
1380 $params['userid'],
1381 $params['search'],
1382 $params['limitnum']
1383 );
1384
de55cb1b 1385 $search = new \core_message\output\messagearea\user_search_results($contacts, $courses, $noncontacts);
cd03b8d7
MN
1386
1387 $renderer = $PAGE->get_renderer('core_message');
1388 return $search->export_for_template($renderer);
1389 }
1390
1391 /**
48e8bdba 1392 * Get messagearea search users returns.
cd03b8d7 1393 *
548cac7d
AA
1394 * @deprecated since 3.6
1395 *
cd03b8d7
MN
1396 * @return external_single_structure
1397 * @since 3.2
1398 */
48e8bdba 1399 public static function data_for_messagearea_search_users_returns() {
cd03b8d7
MN
1400 return new external_single_structure(
1401 array(
cd03b8d7 1402 'contacts' => new external_multiple_structure(
a3e3a3a1 1403 self::get_messagearea_contact_structure()
cd03b8d7 1404 ),
cd03b8d7
MN
1405 'courses' => new external_multiple_structure(
1406 new external_single_structure(
1407 array(
1408 'id' => new external_value(PARAM_INT, 'The course id'),
7597ab0b
AA
1409 'shortname' => new external_value(PARAM_TEXT, 'The course shortname'),
1410 'fullname' => new external_value(PARAM_TEXT, 'The course fullname'),
cd03b8d7
MN
1411 )
1412 )
1413 ),
cd03b8d7 1414 'noncontacts' => new external_multiple_structure(
a3e3a3a1 1415 self::get_messagearea_contact_structure()
cd03b8d7
MN
1416 )
1417 )
1418 );
1419 }
1420
548cac7d
AA
1421 /**
1422 * Marking the method as deprecated.
1423 *
1424 * @return bool
1425 */
1426 public static function data_for_messagearea_search_users_is_deprecated() {
1427 return true;
1428 }
1429
1430 /**
1431 * Get messagearea message search users parameters.
1432 *
1433 * @return external_function_parameters
1434 * @since 3.6
1435 */
1436 public static function message_search_users_parameters() {
1437 return new external_function_parameters(
1438 array(
1439 'userid' => new external_value(PARAM_INT, 'The id of the user who is performing the search'),
1440 'search' => new external_value(PARAM_RAW, 'The string being searched'),
1441 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
1442 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0),
1443 )
1444 );
1445 }
1446
1447 /**
1448 * Get search users results.
1449 *
1450 * @param int $userid The id of the user who is performing the search
1451 * @param string $search The string being searched
1452 * @param int $limitfrom
1453 * @param int $limitnum
1454 * @return array
1455 * @throws moodle_exception
1456 * @since 3.6
1457 */
1458 public static function message_search_users($userid, $search, $limitfrom = 0, $limitnum = 0) {
41485be2 1459 global $USER;
548cac7d
AA
1460
1461 $systemcontext = context_system::instance();
1462
1463 $params = array(
1464 'userid' => $userid,
1465 'search' => $search,
1466 'limitfrom' => $limitfrom,
1467 'limitnum' => $limitnum
1468 );
1469 $params = self::validate_parameters(self::message_search_users_parameters(), $params);
1470 self::validate_context($systemcontext);
1471
1472 if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
1473 throw new moodle_exception('You do not have permission to perform this action.');
1474 }
1475
1476 list($contacts, $noncontacts) = \core_message\api::message_search_users(
1477 $params['userid'],
1478 $params['search'],
1479 $params['limitfrom'],
1480 $params['limitnum']);
1481
1482 return array('contacts' => $contacts, 'noncontacts' => $noncontacts);
1483 }
1484
1485 /**
1486 * Get messagearea message search users returns.
1487 *
1488 * @return external_single_structure
1489 * @since 3.2
1490 */
1491 public static function message_search_users_returns() {
1492 return new external_single_structure(
1493 array(
1494 'contacts' => new external_multiple_structure(
34b940f6 1495 self::get_conversation_member_structure()
548cac7d
AA
1496 ),
1497 'noncontacts' => new external_multiple_structure(
34b940f6 1498 self::get_conversation_member_structure()
548cac7d
AA
1499 )
1500 )
1501 );
1502 }
1503
cd03b8d7
MN
1504 /**
1505 * Get messagearea search messages parameters.
1506 *
1507 * @return external_function_parameters
1508 * @since 3.2
1509 */
1510 public static function data_for_messagearea_search_messages_parameters() {
1511 return new external_function_parameters(
1512 array(
1513 'userid' => new external_value(PARAM_INT, 'The id of the user who is performing the search'),
1514 'search' => new external_value(PARAM_RAW, 'The string being searched'),
1515 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
1516 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
1517 )
1518 );
1519 }
1520
1521 /**
1522 * Get messagearea search messages results.
1523 *
1524 * @param int $userid The id of the user who is performing the search
1525 * @param string $search The string being searched
1526 * @param int $limitfrom
1527 * @param int $limitnum
1528 * @return stdClass
1529 * @throws moodle_exception
1530 * @since 3.2
1531 */
1532 public static function data_for_messagearea_search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
ee45ecc0 1533 global $CFG, $USER;
cd03b8d7
MN
1534
1535 // Check if messaging is enabled.
837941e9 1536 if (empty($CFG->messaging)) {
cd03b8d7
MN
1537 throw new moodle_exception('disabled', 'message');
1538 }
1539
837941e9
MN
1540 $systemcontext = context_system::instance();
1541
cd03b8d7
MN
1542 $params = array(
1543 'userid' => $userid,
1544 'search' => $search,
1545 'limitfrom' => $limitfrom,
1546 'limitnum' => $limitnum
1547
1548 );
bb650761 1549 $params = self::validate_parameters(self::data_for_messagearea_search_messages_parameters(), $params);
837941e9 1550 self::validate_context($systemcontext);
cd03b8d7 1551
bb650761 1552 if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
837941e9
MN
1553 throw new moodle_exception('You do not have permission to perform this action.');
1554 }
cd03b8d7 1555
bb650761
DW
1556 $messages = \core_message\api::search_messages(
1557 $params['userid'],
1558 $params['search'],
1559 $params['limitfrom'],
1560 $params['limitnum']
1561 );
cd03b8d7 1562
ee45ecc0
MN
1563 $data = new \stdClass();
1564 $data->contacts = [];
1565 foreach ($messages as $message) {
1566 $contact = new \stdClass();
1567 $contact->userid = $message->userid;
1568 $contact->fullname = $message->fullname;
1569 $contact->profileimageurl = $message->profileimageurl;
1570 $contact->profileimageurlsmall = $message->profileimageurlsmall;
1571 $contact->messageid = $message->messageid;
1572 $contact->ismessaging = $message->ismessaging;
1573 $contact->sentfromcurrentuser = false;
1574 if ($message->lastmessage) {
1575 if ($message->userid !== $message->useridfrom) {
1576 $contact->sentfromcurrentuser = true;
1577 }
1578 $contact->lastmessage = shorten_text($message->lastmessage, 60);
1579 } else {
1580 $contact->lastmessage = null;
1581 }
1582 $contact->lastmessagedate = $message->lastmessagedate;
1583 $contact->showonlinestatus = is_null($message->isonline) ? false : true;
1584 $contact->isonline = $message->isonline;
1585 $contact->isblocked = $message->isblocked;
1586 $contact->isread = $message->isread;
1587 $contact->unreadcount = $message->unreadcount;
1588 $contact->conversationid = $message->conversationid;
1589
1590 $data->contacts[] = $contact;
1591 }
1592
1593 return $data;
cd03b8d7
MN
1594 }
1595
1596 /**
1597 * Get messagearea search messages returns.
1598 *
1599 * @return external_single_structure
1600 * @since 3.2
1601 */
1602 public static function data_for_messagearea_search_messages_returns() {
1603 return new external_single_structure(
1604 array(
cd03b8d7 1605 'contacts' => new external_multiple_structure(
a3e3a3a1 1606 self::get_messagearea_contact_structure()
cd03b8d7
MN
1607 )
1608 )
1609 );
1610 }
1611
6f31927a
JD
1612 /**
1613 * Get conversations parameters.
1614 *
1615 * @return external_function_parameters
1616 * @since 3.6
1617 */
1618 public static function get_conversations_parameters() {
1619 return new external_function_parameters(
1620 array(
1621 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
1622 'limitfrom' => new external_value(PARAM_INT, 'The offset to start at', VALUE_DEFAULT, 0),
1623 'limitnum' => new external_value(PARAM_INT, 'Limit number of conversations to this', VALUE_DEFAULT, 0),
1624 'type' => new external_value(PARAM_INT, 'Filter by type', VALUE_DEFAULT, null),
1625 'favourites' => new external_value(PARAM_BOOL, 'Whether to restrict the results to contain NO favourite
1626 conversations (false), ONLY favourite conversation (true), or ignore any restriction altogether (null)',
1627 VALUE_DEFAULT, null),
1628
1629 )
1630 );
1631 }
1632
1633 /**
1634 * Get the list of conversations for the user.
1635 *
1636 * @param int $userid The id of the user who is performing the search
1637 * @param int $limitfrom
1638 * @param int $limitnum
1639 * @param int|null $type
1640 * @param bool|null $favourites
1641 * @return stdClass
1642 * @throws \moodle_exception if the messaging feature is disabled on the site.
1643 * @since 3.2
1644 */
1645 public static function get_conversations($userid, $limitfrom = 0, $limitnum = 0, int $type = null, bool $favourites = null) {
1646 global $CFG, $USER;
1647
1648 // All the standard BL checks.
1649 if (empty($CFG->messaging)) {
1650 throw new moodle_exception('disabled', 'message');
1651 }
1652
1653 $params = array(
1654 'userid' => $userid,
1655 'limitfrom' => $limitfrom,
1656 'limitnum' => $limitnum,
1657 'type' => $type,
1658 'favourites' => $favourites
1659 );
bb650761 1660 $params = self::validate_parameters(self::get_conversations_parameters(), $params);
6f31927a
JD
1661
1662 $systemcontext = context_system::instance();
1663 self::validate_context($systemcontext);
1664
bb650761 1665 if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
6f31927a
JD
1666 throw new moodle_exception('You do not have permission to perform this action.');
1667 }
1668
bb650761
DW
1669 $conversations = \core_message\api::get_conversations(
1670 $params['userid'],
1671 $params['limitfrom'],
1672 $params['limitnum'],
1673 $params['type'],
1674 $params['favourites']
1675 );
1676
6f31927a
JD
1677 return (object) ['conversations' => $conversations];
1678 }
1679
1680 /**
1681 * Get conversations returns.
1682 *
1683 * @return external_single_structure
1684 * @since 3.6
1685 */
1686 public static function get_conversations_returns() {
1687 return new external_single_structure(
1688 [
1689 'conversations' => new external_multiple_structure(
b3bbd4a0 1690 self::get_conversation_structure(true)
6f31927a
JD
1691 )
1692 ]
1693 );
1694 }
1695
4e313026
RW
1696 /**
1697 * Get conversation parameters.
1698 *
1699 * @return external_function_parameters
1700 */
1701 public static function get_conversation_parameters() {
1702 return new external_function_parameters(
1703 array(
1704 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
1705 'conversationid' => new external_value(PARAM_INT, 'The id of the conversation to fetch'),
1706 'includecontactrequests' => new external_value(PARAM_BOOL, 'Include contact requests in the members'),
1707 'includeprivacyinfo' => new external_value(PARAM_BOOL, 'Include privacy info in the members'),
1708 'memberlimit' => new external_value(PARAM_INT, 'Limit for number of members', VALUE_DEFAULT, 0),
1709 'memberoffset' => new external_value(PARAM_INT, 'Offset for member list', VALUE_DEFAULT, 0),
1710 'messagelimit' => new external_value(PARAM_INT, 'Limit for number of messages', VALUE_DEFAULT, 100),
1711 'messageoffset' => new external_value(PARAM_INT, 'Offset for messages list', VALUE_DEFAULT, 0),
1712 'newestmessagesfirst' => new external_value(PARAM_BOOL, 'Order messages by newest first', VALUE_DEFAULT, true)
1713 )
1714 );
1715 }
1716
1717 /**
1718 * Get a single conversation.
1719 *
1720 * @param int $userid The user id to get the conversation for
1721 * @param int $conversationid The id of the conversation to fetch
1722 * @param bool $includecontactrequests Should contact requests be included between members
1723 * @param bool $includeprivacyinfo Should privacy info be included between members
1724 * @param int $memberlimit Limit number of members to load
1725 * @param int $memberoffset Offset members by this amount
1726 * @param int $messagelimit Limit number of messages to load
1727 * @param int $messageoffset Offset the messages
1728 * @param bool $newestmessagesfirst Order messages by newest first
1729 * @return stdClass
1730 * @throws \moodle_exception if the messaging feature is disabled on the site.
1731 */
1732 public static function get_conversation(
1733 int $userid,
1734 int $conversationid,
1735 bool $includecontactrequests = false,
1736 bool $includeprivacyinfo = false,
1737 int $memberlimit = 0,
1738 int $memberoffset = 0,
1739 int $messagelimit = 0,
1740 int $messageoffset = 0,
1741 bool $newestmessagesfirst = true
1742 ) {
1743 global $CFG, $DB, $USER;
1744
1745 // All the standard BL checks.
1746 if (empty($CFG->messaging)) {
1747 throw new moodle_exception('disabled', 'message');
1748 }
1749
1750 $params = [
1751 'userid' => $userid,
1752 'conversationid' => $conversationid,
1753 'includecontactrequests' => $includecontactrequests,
1754 'includeprivacyinfo' => $includeprivacyinfo,
1755 'memberlimit' => $memberlimit,
1756 'memberoffset' => $memberoffset,
1757 'messagelimit' => $messagelimit,
1758 'messageoffset' => $messageoffset,
1759 'newestmessagesfirst' => $newestmessagesfirst
1760 ];
1761 self::validate_parameters(self::get_conversation_parameters(), $params);
1762
1763 $systemcontext = context_system::instance();
1764 self::validate_context($systemcontext);
1765
1766 $conversation = \core_message\api::get_conversation(
1767 $params['userid'],
1768 $params['conversationid'],
1769 $params['includecontactrequests'],
1770 $params['includeprivacyinfo'],
1771 $params['memberlimit'],
1772 $params['memberoffset'],
1773 $params['messagelimit'],
1774 $params['messageoffset'],
1775 $params['newestmessagesfirst']
1776 );
1777
1778 if ($conversation) {
1779 return $conversation;
1780 } else {
1781 // We have to throw an exception here because the external functions annoyingly
1782 // don't accept null to be returned for a single structure.
892356ac 1783 throw new \moodle_exception('errorconversationdoesnotexist', 'message');
4e313026
RW
1784 }
1785 }
1786
1787 /**
1788 * Get conversation returns.
1789 *
1790 * @return external_single_structure
1791 */
1792 public static function get_conversation_returns() {
1793 return self::get_conversation_structure();
1794 }
1795
569c0bae
RW
1796 /**
1797 * Get conversation parameters.
1798 *
1799 * @return external_function_parameters
1800 */
1801 public static function get_conversation_between_users_parameters() {
1802 return new external_function_parameters(
1803 array(
1804 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
1805 'otheruserid' => new external_value(PARAM_INT, 'The other user id'),
1806 'includecontactrequests' => new external_value(PARAM_BOOL, 'Include contact requests in the members'),
1807 'includeprivacyinfo' => new external_value(PARAM_BOOL, 'Include privacy info in the members'),
1808 'memberlimit' => new external_value(PARAM_INT, 'Limit for number of members', VALUE_DEFAULT, 0),
1809 'memberoffset' => new external_value(PARAM_INT, 'Offset for member list', VALUE_DEFAULT, 0),
1810 'messagelimit' => new external_value(PARAM_INT, 'Limit for number of messages', VALUE_DEFAULT, 100),
1811 'messageoffset' => new external_value(PARAM_INT, 'Offset for messages list', VALUE_DEFAULT, 0),
1812 'newestmessagesfirst' => new external_value(PARAM_BOOL, 'Order messages by newest first', VALUE_DEFAULT, true)
1813 )
1814 );
1815 }
1816
1817 /**
1818 * Get a single conversation between users.
1819 *
1820 * @param int $userid The user id to get the conversation for
1821 * @param int $otheruserid The other user id
1822 * @param bool $includecontactrequests Should contact requests be included between members
1823 * @param bool $includeprivacyinfo Should privacy info be included between members
1824 * @param int $memberlimit Limit number of members to load
1825 * @param int $memberoffset Offset members by this amount
1826 * @param int $messagelimit Limit number of messages to load
1827 * @param int $messageoffset Offset the messages
1828 * @param bool $newestmessagesfirst Order messages by newest first
1829 * @return stdClass
1830 * @throws \moodle_exception if the messaging feature is disabled on the site.
1831 */
1832 public static function get_conversation_between_users(
1833 int $userid,
1834 int $otheruserid,
1835 bool $includecontactrequests = false,
1836 bool $includeprivacyinfo = false,
1837 int $memberlimit = 0,
1838 int $memberoffset = 0,
1839 int $messagelimit = 0,
1840 int $messageoffset = 0,
1841 bool $newestmessagesfirst = true
1842 ) {
1843 global $CFG, $DB, $USER;
1844
1845 // All the standard BL checks.
1846 if (empty($CFG->messaging)) {
1847 throw new moodle_exception('disabled', 'message');
1848 }
1849
1850 $params = [
1851 'userid' => $userid,
1852 'otheruserid' => $otheruserid,
1853 'includecontactrequests' => $includecontactrequests,
1854 'includeprivacyinfo' => $includeprivacyinfo,
1855 'memberlimit' => $memberlimit,
1856 'memberoffset' => $memberoffset,
1857 'messagelimit' => $messagelimit,
1858 'messageoffset' => $messageoffset,
1859 'newestmessagesfirst' => $newestmessagesfirst
1860 ];
1861 self::validate_parameters(self::get_conversation_between_users_parameters(), $params);
1862
1863 $systemcontext = context_system::instance();
1864 self::validate_context($systemcontext);
1865
1866 $conversationid = \core_message\api::get_conversation_between_users([$params['userid'], $params['otheruserid']]);
1867 $conversation = null;
1868
1869 if ($conversationid) {
1870 $conversation = \core_message\api::get_conversation(
1871 $params['userid'],
1872 $conversationid,
1873 $params['includecontactrequests'],
1874 $params['includeprivacyinfo'],
1875 $params['memberlimit'],
1876 $params['memberoffset'],
1877 $params['messagelimit'],
1878 $params['messageoffset'],
1879 $params['newestmessagesfirst']
1880 );
1881 }
1882
1883 if ($conversation) {
1884 return $conversation;
1885 } else {
1886 // We have to throw an exception here because the external functions annoyingly
1887 // don't accept null to be returned for a single structure.
892356ac 1888 throw new \moodle_exception('errorconversationdoesnotexist', 'message');
569c0bae
RW
1889 }
1890 }
1891
1892 /**
1893 * Get conversation returns.
1894 *
1895 * @return external_single_structure
1896 */
1897 public static function get_conversation_between_users_returns() {
1898 return self::get_conversation_structure(true);
1899 }
1900
9aa012b5 1901 /**
49aaadc3 1902 * The messagearea conversations parameters.
9aa012b5 1903 *
eb35e0b1 1904 * @deprecated since 3.6
9aa012b5 1905 * @return external_function_parameters
49aaadc3 1906 * @since 3.2
9aa012b5
MN
1907 */
1908 public static function data_for_messagearea_conversations_parameters() {
1909 return new external_function_parameters(
1910 array(
1911 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
1912 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
1913 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
1914 )
1915 );
1916 }
1917
1918 /**
1919 * Get messagearea conversations.
1920 *
eb35e0b1
JD
1921 * NOTE FOR FINAL DEPRECATION:
1922 * When removing this method, please also consider removal of get_conversations_legacy_formatter()
1923 * from the \core_message\helper class. This helper method was used solely to format the new get_conversations() return data
1924 * into the old format used here, and in message/index.php. If we no longer need either of these, then that method can be
1925 * removed.
1926 *
1927 * @deprecated since 3.6
9aa012b5
MN
1928 * @param int $userid The id of the user who we are viewing conversations for
1929 * @param int $limitfrom
1930 * @param int $limitnum
49aaadc3
MN
1931 * @return stdClass
1932 * @throws moodle_exception
1933 * @since 3.2
9aa012b5
MN
1934 */
1935 public static function data_for_messagearea_conversations($userid, $limitfrom = 0, $limitnum = 0) {
837941e9 1936 global $CFG, $PAGE, $USER;
9aa012b5
MN
1937
1938 // Check if messaging is enabled.
837941e9 1939 if (empty($CFG->messaging)) {
9aa012b5
MN
1940 throw new moodle_exception('disabled', 'message');
1941 }
1942
837941e9
MN
1943 $systemcontext = context_system::instance();
1944
9aa012b5
MN
1945 $params = array(
1946 'userid' => $userid,
1947 'limitfrom' => $limitfrom,
1948 'limitnum' => $limitnum
1949 );
bb650761 1950 $params = self::validate_parameters(self::data_for_messagearea_conversations_parameters(), $params);
837941e9 1951 self::validate_context($systemcontext);
9aa012b5 1952
bb650761 1953 if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
837941e9
MN
1954 throw new moodle_exception('You do not have permission to perform this action.');
1955 }
9aa012b5 1956
bb650761 1957 $conversations = \core_message\api::get_conversations($params['userid'], $params['limitfrom'], $params['limitnum']);
eb35e0b1
JD
1958
1959 // Format the conversations in the legacy style, as the get_conversations method has since been changed.
1960 $conversations = \core_message\helper::get_conversations_legacy_formatter($conversations);
1961
de55cb1b 1962 $conversations = new \core_message\output\messagearea\contacts(null, $conversations);
9aa012b5
MN
1963
1964 $renderer = $PAGE->get_renderer('core_message');
de55cb1b 1965 return $conversations->export_for_template($renderer);
9aa012b5
MN
1966 }
1967
1968 /**
49aaadc3 1969 * The messagearea conversations return structure.
9aa012b5 1970 *
eb35e0b1 1971 * @deprecated since 3.6
49aaadc3
MN
1972 * @return external_single_structure
1973 * @since 3.2
9aa012b5
MN
1974 */
1975 public static function data_for_messagearea_conversations_returns() {
49aaadc3 1976 return new external_single_structure(
9aa012b5 1977 array(
9aa012b5 1978 'contacts' => new external_multiple_structure(
a3e3a3a1 1979 self::get_messagearea_contact_structure()
9aa012b5
MN
1980 )
1981 )
1982 );
1983 }
1984
eb35e0b1
JD
1985 /**
1986 * Marking the method as deprecated.
1987 *
1988 * @return bool
1989 */
1990 public static function data_for_messagearea_conversations_is_deprecated() {
1991 return true;
1992 }
1993
9aa012b5 1994 /**
49aaadc3 1995 * The messagearea contacts return parameters.
9aa012b5 1996 *
a6049a79 1997 * @deprecated since 3.6
9aa012b5 1998 * @return external_function_parameters
49aaadc3 1999 * @since 3.2
9aa012b5
MN
2000 */
2001 public static function data_for_messagearea_contacts_parameters() {
2002 return self::data_for_messagearea_conversations_parameters();
2003 }
2004
2005 /**
2006 * Get messagearea contacts parameters.
2007 *
a6049a79 2008 * @deprecated since 3.6
9aa012b5
MN
2009 * @param int $userid The id of the user who we are viewing conversations for
2010 * @param int $limitfrom
2011 * @param int $limitnum
49aaadc3
MN
2012 * @return stdClass
2013 * @throws moodle_exception
2014 * @since 3.2
9aa012b5
MN
2015 */
2016 public static function data_for_messagearea_contacts($userid, $limitfrom = 0, $limitnum = 0) {
837941e9 2017 global $CFG, $PAGE, $USER;
9aa012b5
MN
2018
2019 // Check if messaging is enabled.
837941e9 2020 if (empty($CFG->messaging)) {
9aa012b5
MN
2021 throw new moodle_exception('disabled', 'message');
2022 }
2023
837941e9
MN
2024 $systemcontext = context_system::instance();
2025
9aa012b5
MN
2026 $params = array(
2027 'userid' => $userid,
2028 'limitfrom' => $limitfrom,
2029 'limitnum' => $limitnum
2030 );
bb650761 2031 $params = self::validate_parameters(self::data_for_messagearea_contacts_parameters(), $params);
837941e9 2032 self::validate_context($systemcontext);
9aa012b5 2033
bb650761 2034 if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
837941e9
MN
2035 throw new moodle_exception('You do not have permission to perform this action.');
2036 }
9aa012b5 2037
bb650761 2038 $contacts = \core_message\api::get_contacts($params['userid'], $params['limitfrom'], $params['limitnum']);
de55cb1b 2039 $contacts = new \core_message\output\messagearea\contacts(null, $contacts);
9aa012b5
MN
2040
2041 $renderer = $PAGE->get_renderer('core_message');
2042 return $contacts->export_for_template($renderer);
2043 }
2044
2045 /**
49aaadc3 2046 * The messagearea contacts return structure.
9aa012b5 2047 *
a6049a79 2048 * @deprecated since 3.6
49aaadc3
MN
2049 * @return external_single_structure
2050 * @since 3.2
9aa012b5
MN
2051 */
2052 public static function data_for_messagearea_contacts_returns() {
2053 return self::data_for_messagearea_conversations_returns();
2054 }
2055
a6049a79
MN
2056 /**
2057 * Marking the method as deprecated.
2058 *
2059 * @return bool
2060 */
2061 public static function data_for_messagearea_contacts_is_deprecated() {
2062 return true;
2063 }
2064
3cd13828 2065 /**
49aaadc3 2066 * The messagearea messages parameters.
3cd13828 2067 *
a6049a79 2068 * @deprecated since 3.6
3cd13828 2069 * @return external_function_parameters
49aaadc3 2070 * @since 3.2
3cd13828
MN
2071 */
2072 public static function data_for_messagearea_messages_parameters() {
2073 return new external_function_parameters(
2074 array(
2075 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
2076 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
2077 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
8ec78c48
MN
2078 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0),
2079 'newest' => new external_value(PARAM_BOOL, 'Newest first?', VALUE_DEFAULT, false),
ffd7798c 2080 'timefrom' => new external_value(PARAM_INT,
fb1469d8 2081 'The timestamp from which the messages were created', VALUE_DEFAULT, 0),
3cd13828
MN
2082 )
2083 );
2084 }
2085
2086 /**
2087 * Get messagearea messages.
2088 *
a6049a79 2089 * @deprecated since 3.6
3cd13828
MN
2090 * @param int $currentuserid The current user's id
2091 * @param int $otheruserid The other user's id
2092 * @param int $limitfrom
2093 * @param int $limitnum
8ec78c48 2094 * @param boolean $newest
49aaadc3
MN
2095 * @return stdClass
2096 * @throws moodle_exception
2097 * @since 3.2
3cd13828 2098 */
7b55aaa1 2099 public static function data_for_messagearea_messages($currentuserid, $otheruserid, $limitfrom = 0, $limitnum = 0,
ffd7798c 2100 $newest = false, $timefrom = 0) {
837941e9 2101 global $CFG, $PAGE, $USER;
3cd13828
MN
2102
2103 // Check if messaging is enabled.
837941e9 2104 if (empty($CFG->messaging)) {
3cd13828
MN
2105 throw new moodle_exception('disabled', 'message');
2106 }
2107
837941e9
MN
2108 $systemcontext = context_system::instance();
2109
3cd13828
MN
2110 $params = array(
2111 'currentuserid' => $currentuserid,
2112 'otheruserid' => $otheruserid,
2113 'limitfrom' => $limitfrom,
8ec78c48 2114 'limitnum' => $limitnum,
fb1469d8 2115 'newest' => $newest,
ffd7798c 2116 'timefrom' => $timefrom,
3cd13828 2117 );
bb650761 2118 $params = self::validate_parameters(self::data_for_messagearea_messages_parameters(), $params);
837941e9 2119 self::validate_context($systemcontext);
3cd13828 2120
bb650761 2121 if (($USER->id != $params['currentuserid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
837941e9
MN
2122 throw new moodle_exception('You do not have permission to perform this action.');
2123 }
3cd13828 2124
bb650761 2125 if ($params['newest']) {
8ec78c48
MN
2126 $sort = 'timecreated DESC';
2127 } else {
2128 $sort = 'timecreated ASC';
2129 }
fb1469d8
RW
2130
2131 // We need to enforce a one second delay on messages to avoid race conditions of current
2132 // messages still being sent.
2133 //
2134 // There is a chance that we could request messages before the current time's
2135 // second has elapsed and while other messages are being sent in that same second. In which
2136 // case those messages will be lost.
2137 //
2138 // Instead we ignore the current time in the result set to ensure that second is allowed to finish.
bb650761 2139 if (!empty($params['timefrom'])) {
ffd7798c 2140 $timeto = time() - 1;
fb1469d8 2141 } else {
ffd7798c 2142 $timeto = 0;
fb1469d8
RW
2143 }
2144
2145 // No requesting messages from the current time, as stated above.
bb650761 2146 if ($params['timefrom'] == time()) {
ffd7798c 2147 $messages = [];
fb1469d8 2148 } else {
bb650761
DW
2149 $messages = \core_message\api::get_messages($params['currentuserid'], $params['otheruserid'], $params['limitfrom'],
2150 $params['limitnum'], $sort, $params['timefrom'], $timeto);
fb1469d8
RW
2151 }
2152
bb650761 2153 $messages = new \core_message\output\messagearea\messages($params['currentuserid'], $params['otheruserid'], $messages);
3cd13828
MN
2154
2155 $renderer = $PAGE->get_renderer('core_message');
2156 return $messages->export_for_template($renderer);
2157 }
2158
2159 /**
49aaadc3 2160 * The messagearea messages return structure.
3cd13828 2161 *
a6049a79 2162 * @deprecated since 3.6
49aaadc3
MN
2163 * @return external_single_structure
2164 * @since 3.2
3cd13828
MN
2165 */
2166 public static function data_for_messagearea_messages_returns() {
49aaadc3 2167 return new external_single_structure(
3cd13828 2168 array(
7b55aaa1
MN
2169 'iscurrentuser' => new external_value(PARAM_BOOL, 'Is the currently logged in user the user we are viewing
2170 the messages on behalf of?'),
3cd13828
MN
2171 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
2172 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
2173 'otheruserfullname' => new external_value(PARAM_NOTAGS, 'The other user\'s fullname'),
cb805753 2174 'showonlinestatus' => new external_value(PARAM_BOOL, 'Show the user\'s online status?'),
bf58081d 2175 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status'),
3cd13828 2176 'messages' => new external_multiple_structure(
94e1db61 2177 self::get_messagearea_message_structure()
26dca05d
JP
2178 ),
2179 'isblocked' => new external_value(PARAM_BOOL, 'Is this user blocked by the current user?', VALUE_DEFAULT, false),
3cd13828
MN
2180 )
2181 );
2182 }
2183
a6049a79
MN
2184 /**
2185 * Marking the method as deprecated.
2186 *
2187 * @return bool
2188 */
2189 public static function data_for_messagearea_messages_is_deprecated() {
2190 return true;
2191 }
2192
fb04293b
SA
2193 /**
2194 * The conversation messages parameters.
2195 *
2196 * @return external_function_parameters
2197 * @since 3.6
2198 */
2199 public static function get_conversation_messages_parameters() {
2200 return new external_function_parameters(
2201 array(
2202 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
2203 'convid' => new external_value(PARAM_INT, 'The conversation id'),
2204 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
2205 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0),
2206 'newest' => new external_value(PARAM_BOOL, 'Newest first?', VALUE_DEFAULT, false),
2207 'timefrom' => new external_value(PARAM_INT,
2208 'The timestamp from which the messages were created', VALUE_DEFAULT, 0),
2209 )
2210 );
2211 }
2212
2213 /**
2214 * Get conversation messages.
2215 *
2216 * @param int $currentuserid The current user's id.
2217 * @param int $convid The conversation id.
2218 * @param int $limitfrom Return a subset of records, starting at this point (optional).
2219 * @param int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
2220 * @param bool $newest True for getting first newest messages, false otherwise.
2221 * @param int $timefrom The time from the conversation messages to get.
2222 * @return stdClass The messages and members who have sent some of these messages.
2223 * @throws moodle_exception
2224 * @since 3.6
2225 */
2226 public static function get_conversation_messages(int $currentuserid, int $convid, int $limitfrom = 0, int $limitnum = 0,
2227 bool $newest = false, int $timefrom = 0) {
2228 global $CFG, $PAGE, $USER;
2229
2230 // Check if messaging is enabled.
2231 if (empty($CFG->messaging)) {
2232 throw new moodle_exception('disabled', 'message');
2233 }
2234
2235 $systemcontext = context_system::instance();
2236
2237 $params = array(
2238 'currentuserid' => $currentuserid,
2239 'convid' => $convid,
2240 'limitfrom' => $limitfrom,
2241 'limitnum' => $limitnum,
2242 'newest' => $newest,
2243 'timefrom' => $timefrom,
2244 );
bb650761 2245 $params = self::validate_parameters(self::get_conversation_messages_parameters(), $params);
fb04293b
SA
2246 self::validate_context($systemcontext);
2247
bb650761 2248 if (($USER->id != $params['currentuserid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
fb04293b
SA
2249 throw new moodle_exception('You do not have permission to perform this action.');
2250 }
2251
2252 $sort = $newest ? 'timecreated DESC' : 'timecreated ASC';
2253
2254 // We need to enforce a one second delay on messages to avoid race conditions of current
2255 // messages still being sent.
2256 //
2257 // There is a chance that we could request messages before the current time's
2258 // second has elapsed and while other messages are being sent in that same second. In which
2259 // case those messages will be lost.
2260 //
2261 // Instead we ignore the current time in the result set to ensure that second is allowed to finish.
bb650761 2262 $timeto = empty($params['timefrom']) ? 0 : time() - 1;
fb04293b
SA
2263
2264 // No requesting messages from the current time, as stated above.
bb650761 2265 if ($params['timefrom'] == time()) {
fb04293b
SA
2266 $messages = [];
2267 } else {
bb650761
DW
2268 $messages = \core_message\api::get_conversation_messages(
2269 $params['currentuserid'],
2270 $params['convid'],
2271 $params['limitfrom'],
2272 $params['limitnum'],
2273 $sort,
2274 $params['timefrom'],
2275 $timeto);
fb04293b
SA
2276 }
2277
2278 return $messages;
2279 }
2280
2281 /**
2282 * The messagearea messages return structure.
2283 *
2284 * @return external_single_structure
2285 * @since 3.6
2286 */
2287 public static function get_conversation_messages_returns() {
2288 return new external_single_structure(
2289 array(
2290 'id' => new external_value(PARAM_INT, 'The conversation id'),
2291 'members' => new external_multiple_structure(
2292 self::get_conversation_member_structure()
2293 ),
2294 'messages' => new external_multiple_structure(
2295 self::get_conversation_message_structure()
2296 ),
2297 )
2298 );
2299 }
2300
c9b0f33f
MN
2301 /**
2302 * The user contacts return parameters.
2303 *
2304 * @return external_function_parameters
2305 */
2306 public static function get_user_contacts_parameters() {
2307 return new external_function_parameters(
2308 array(
2309 'userid' => new external_value(PARAM_INT, 'The id of the user who we retrieving the contacts for'),
2310 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
2311 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
2312 )
2313 );
2314 }
2315
2316 /**
2317 * Get user contacts.
2318 *
2319 * @param int $userid The id of the user who we are viewing conversations for
2320 * @param int $limitfrom
2321 * @param int $limitnum
2322 * @return array
2323 * @throws moodle_exception
2324 */
2325 public static function get_user_contacts(int $userid, int $limitfrom = 0, int $limitnum = 0) {
2326 global $CFG, $USER;
2327
2328 // Check if messaging is enabled.
2329 if (empty($CFG->messaging)) {
2330 throw new moodle_exception('disabled', 'message');
2331 }
2332
2333 $systemcontext = context_system::instance();
2334
2335 $params = array(
2336 'userid' => $userid,
2337 'limitfrom' => $limitfrom,
2338 'limitnum' => $limitnum
2339 );
2340 $params = self::validate_parameters(self::get_user_contacts_parameters(), $params);
2341 self::validate_context($systemcontext);
2342
2343 if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
2344 throw new moodle_exception('You do not have permission to perform this action.');
2345 }
2346
2347 return \core_message\api::get_user_contacts($params['userid'], $params['limitfrom'], $params['limitnum']);
2348 }
2349
2350 /**
2351 * The user contacts return structure.
2352 *
2353 * @return external_multiple_structure
2354 */
2355 public static function get_user_contacts_returns() {
2356 return new external_multiple_structure(
2357 self::get_conversation_member_structure()
2358 );
2359 }
2360
c060cd49 2361 /**
49aaadc3 2362 * The get most recent message return parameters.
c060cd49 2363 *
a6049a79 2364 * @deprecated since 3.6
c060cd49 2365 * @return external_function_parameters
49aaadc3 2366 * @since 3.2
c060cd49
MN
2367 */
2368 public static function data_for_messagearea_get_most_recent_message_parameters() {
2369 return new external_function_parameters(
2370 array(
2371 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
2372 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
2373 )
2374 );
2375 }
2376
2377 /**
2378 * Get the most recent message in a conversation.
2379 *
a6049a79 2380 * @deprecated since 3.6
c060cd49
MN
2381 * @param int $currentuserid The current user's id
2382 * @param int $otheruserid The other user's id
49aaadc3
MN
2383 * @return stdClass
2384 * @throws moodle_exception
2385 * @since 3.2
c060cd49
MN
2386 */
2387 public static function data_for_messagearea_get_most_recent_message($currentuserid, $otheruserid) {
837941e9 2388 global $CFG, $PAGE, $USER;
c060cd49
MN
2389
2390 // Check if messaging is enabled.
837941e9 2391 if (empty($CFG->messaging)) {
c060cd49
MN
2392 throw new moodle_exception('disabled', 'message');
2393 }
2394
837941e9
MN
2395 $systemcontext = context_system::instance();
2396
c060cd49
MN
2397 $params = array(
2398 'currentuserid' => $currentuserid,
2399 'otheruserid' => $otheruserid
2400 );
bb650761 2401 $params = self::validate_parameters(self::data_for_messagearea_get_most_recent_message_parameters(), $params);
837941e9 2402 self::validate_context($systemcontext);
c060cd49 2403
bb650761 2404 if (($USER->id != $params['currentuserid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
837941e9
MN
2405 throw new moodle_exception('You do not have permission to perform this action.');
2406 }
c060cd49 2407
bb650761 2408 $message = \core_message\api::get_most_recent_message($params['currentuserid'], $params['otheruserid']);
de55cb1b 2409 $message = new \core_message\output\messagearea\message($message);
c060cd49
MN
2410
2411 $renderer = $PAGE->get_renderer('core_message');
2412 return $message->export_for_template($renderer);
2413 }
2414
2415 /**
49aaadc3 2416 * The get most recent message return structure.
c060cd49 2417 *
a6049a79 2418 * @deprecated since 3.6
c060cd49 2419 * @return external_single_structure
49aaadc3 2420 * @since 3.2
c060cd49
MN
2421 */
2422 public static function data_for_messagearea_get_most_recent_message_returns() {
94e1db61 2423 return self::get_messagearea_message_structure();
c060cd49
MN
2424 }
2425
a6049a79
MN
2426 /**
2427 * Marking the method as deprecated.
2428 *
2429 * @return bool
2430 */
2431 public static function data_for_messagearea_get_most_recent_message_is_deprecated() {
2432 return true;
2433 }
2434
c6e97f54
MN
2435 /**
2436 * The get profile parameters.
2437 *
a6049a79 2438 * @deprecated since 3.6
c6e97f54 2439 * @return external_function_parameters
49aaadc3 2440 * @since 3.2
c6e97f54
MN
2441 */
2442 public static function data_for_messagearea_get_profile_parameters() {
2443 return new external_function_parameters(
2444 array(
2445 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
2446 'otheruserid' => new external_value(PARAM_INT, 'The id of the user whose profile we want to view'),
2447 )
2448 );
2449 }
2450
2451 /**
2452 * Get the profile information for a contact.
2453 *
a6049a79 2454 * @deprecated since 3.6
c6e97f54
MN
2455 * @param int $currentuserid The current user's id
2456 * @param int $otheruserid The id of the user whose profile we are viewing
49aaadc3
MN
2457 * @return stdClass
2458 * @throws moodle_exception
2459 * @since 3.2
c6e97f54
MN
2460 */
2461 public static function data_for_messagearea_get_profile($currentuserid, $otheruserid) {
837941e9 2462 global $CFG, $PAGE, $USER;
c6e97f54
MN
2463
2464 // Check if messaging is enabled.
837941e9 2465 if (empty($CFG->messaging)) {
c6e97f54
MN
2466 throw new moodle_exception('disabled', 'message');
2467 }
2468
837941e9
MN
2469 $systemcontext = context_system::instance();
2470
c6e97f54
MN
2471 $params = array(
2472 'currentuserid' => $currentuserid,
2473 'otheruserid' => $otheruserid
2474 );
bb650761 2475 $params = self::validate_parameters(self::data_for_messagearea_get_profile_parameters(), $params);
837941e9 2476 self::validate_context($systemcontext);
c6e97f54 2477
bb650761 2478 if (($USER->id != $params['currentuserid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
837941e9
MN
2479 throw new moodle_exception('You do not have permission to perform this action.');
2480 }
c6e97f54 2481
bb650761 2482 $profile = \core_message\api::get_profile($params['currentuserid'], $params['otheruserid']);
de55cb1b 2483 $profile = new \core_message\output\messagearea\profile($profile);
c6e97f54
MN
2484
2485 $renderer = $PAGE->get_renderer('core_message');
2486 return $profile->export_for_template($renderer);
2487 }
2488
2489 /**
49aaadc3 2490 * The get profile return structure.
c6e97f54 2491 *
a6049a79 2492 * @deprecated since 3.6
c6e97f54 2493 * @return external_single_structure
49aaadc3 2494 * @since 3.2
c6e97f54
MN
2495 */
2496 public static function data_for_messagearea_get_profile_returns() {
2497 return new external_single_structure(
2498 array(
de55cb1b 2499 'userid' => new external_value(PARAM_INT, 'The id of the user whose profile we are viewing'),
c6e97f54 2500 'email' => new external_value(core_user::get_property_type('email'), 'An email address'),
cc22b515 2501 'country' => new external_value(PARAM_TEXT, 'Home country of the user'),
c6e97f54
MN
2502 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user'),
2503 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
2504 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
2505 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
cb805753 2506 'showonlinestatus' => new external_value(PARAM_BOOL, 'Show the user\'s online status?'),
bf58081d 2507 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status'),
c6e97f54
MN
2508 'isblocked' => new external_value(PARAM_BOOL, 'Is the user blocked?'),
2509 'iscontact' => new external_value(PARAM_BOOL, 'Is the user a contact?')
2510 )
2511 );
2512 }
2513
a6049a79
MN
2514 /**
2515 * Marking the method as deprecated.
2516 *
2517 * @return bool
2518 */
2519 public static function data_for_messagearea_get_profile_is_deprecated() {
2520 return true;
2521 }
2522
d6731600
FM
2523 /**
2524 * Get contacts parameters description.
2525 *
f8905537 2526 * @deprecated since 3.6
d6731600 2527 * @return external_function_parameters
5bcfd504 2528 * @since Moodle 2.5
d6731600
FM
2529 */
2530 public static function get_contacts_parameters() {
2531 return new external_function_parameters(array());
2532 }
2533
2534 /**
2535 * Get contacts.
2536 *
f8905537 2537 * @deprecated since 3.6
d6731600 2538 * @return external_description
5bcfd504 2539 * @since Moodle 2.5
d6731600
FM
2540 */
2541 public static function get_contacts() {
883ce421 2542 global $CFG, $PAGE, $USER;
436bbf89
DM
2543
2544 // Check if messaging is enabled.
837941e9 2545 if (empty($CFG->messaging)) {
436bbf89
DM
2546 throw new moodle_exception('disabled', 'message');
2547 }
2548
d6731600
FM
2549 require_once($CFG->dirroot . '/user/lib.php');
2550
883ce421
MN
2551 $allcontacts = array('online' => [], 'offline' => [], 'strangers' => []);
2552 $contacts = \core_message\api::get_contacts_with_unread_message_count($USER->id);
2553 foreach ($contacts as $contact) {
2554 // Set the mode.
2555 $mode = 'offline';
2556 if (\core_message\helper::is_online($contact->lastaccess)) {
2557 $mode = 'online';
2558 }
2559
2560 $newcontact = array(
2561 'id' => $contact->id,
2562 'fullname' => fullname($contact),
2563 'unread' => $contact->messagecount
2564 );
2565
2566 $userpicture = new user_picture($contact);
2567 $userpicture->size = 1; // Size f1.
2568 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
2569 $userpicture->size = 0; // Size f2.
2570 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
2571
2572 $allcontacts[$mode][$contact->id] = $newcontact;
2573 }
2574
2575 $strangers = \core_message\api::get_non_contacts_with_unread_message_count($USER->id);
2576 foreach ($strangers as $contact) {
2577 $newcontact = array(
2578 'id' => $contact->id,
2579 'fullname' => fullname($contact),
2580 'unread' => $contact->messagecount
2581 );
2582
2583 $userpicture = new user_picture($contact);
2584 $userpicture->size = 1; // Size f1.
2585 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
2586 $userpicture->size = 0; // Size f2.
2587 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600 2588
883ce421
MN
2589 $allcontacts['strangers'][$contact->id] = $newcontact;
2590 }
d6731600 2591
883ce421
MN
2592 // Add noreply user and support user to the list, if they don't exist.
2593 $supportuser = core_user::get_support_user();
2594 if (!isset($strangers[$supportuser->id]) && !$supportuser->deleted) {
2595 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
2596 if ($supportuser->messagecount > 0) {
2597 $supportuser->fullname = fullname($supportuser);
2598 $supportuser->unread = $supportuser->messagecount;
2599 $allcontacts['strangers'][$supportuser->id] = $supportuser;
d6731600
FM
2600 }
2601 }
883ce421
MN
2602
2603 $noreplyuser = core_user::get_noreply_user();
2604 if (!isset($strangers[$noreplyuser->id]) && !$noreplyuser->deleted) {
2605 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
2606 if ($noreplyuser->messagecount > 0) {
2607 $noreplyuser->fullname = fullname($noreplyuser);
2608 $noreplyuser->unread = $noreplyuser->messagecount;
2609 $allcontacts['strangers'][$noreplyuser->id] = $noreplyuser;
2610 }
2611 }
2612
d6731600
FM
2613 return $allcontacts;
2614 }
2615
2616 /**
2617 * Get contacts return description.
2618 *
f8905537 2619 * @deprecated since 3.6
d6731600 2620 * @return external_description
5bcfd504 2621 * @since Moodle 2.5
d6731600
FM
2622 */
2623 public static function get_contacts_returns() {
2624 return new external_single_structure(
2625 array(
2626 'online' => new external_multiple_structure(
2627 new external_single_structure(
2628 array(
2629 'id' => new external_value(PARAM_INT, 'User ID'),
2630 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
2631 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
2632 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
2633 'unread' => new external_value(PARAM_INT, 'Unread message count')
2634 )
2635 ),
2636 'List of online contacts'
2637 ),
2638 'offline' => new external_multiple_structure(
2639 new external_single_structure(
2640 array(
2641 'id' => new external_value(PARAM_INT, 'User ID'),
2642 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
2643 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
2644 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
2645 'unread' => new external_value(PARAM_INT, 'Unread message count')
2646 )
2647 ),
2648 'List of offline contacts'
2649 ),
2650 'strangers' => new external_multiple_structure(
2651 new external_single_structure(
2652 array(
2653 'id' => new external_value(PARAM_INT, 'User ID'),
2654 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
2655 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
2656 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
2657 'unread' => new external_value(PARAM_INT, 'Unread message count')
2658 )
2659 ),
2660 'List of users that are not in the user\'s contact list but have sent a message'
2661 )
2662 )
2663 );
2664 }
2665
f8905537
MN
2666 /**
2667 * Marking the method as deprecated.
2668 *
2669 * @return bool
2670 */
2671 public static function get_contacts_is_deprecated() {
2672 return true;
2673 }
2674
d6731600
FM
2675 /**
2676 * Search contacts parameters description.
2677 *
2678 * @return external_function_parameters
5bcfd504 2679 * @since Moodle 2.5
d6731600
FM
2680 */
2681 public static function search_contacts_parameters() {
2682 return new external_function_parameters(
2683 array(
2684 'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
2685 'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
2686 VALUE_DEFAULT, false)
2687 )
2688 );
2689 }
2690
2691 /**
2692 * Search contacts.
2693 *
2694 * @param string $searchtext query string.
2695 * @param bool $onlymycourses limit the search to the user's courses only.
2696 * @return external_description
5bcfd504 2697 * @since Moodle 2.5
d6731600
FM
2698 */
2699 public static function search_contacts($searchtext, $onlymycourses = false) {
d85bedf7 2700 global $CFG, $USER, $PAGE;
11d83ab3 2701 require_once($CFG->dirroot . '/user/lib.php');
436bbf89
DM
2702
2703 // Check if messaging is enabled.
837941e9 2704 if (empty($CFG->messaging)) {
436bbf89
DM
2705 throw new moodle_exception('disabled', 'message');
2706 }
2707
d6731600
FM
2708 require_once($CFG->libdir . '/enrollib.php');
2709
2710 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
2711 $params = self::validate_parameters(self::search_contacts_parameters(), $params);
2712
2713 // Extra validation, we do not allow empty queries.
2714 if ($params['searchtext'] === '') {
2715 throw new moodle_exception('querystringcannotbeempty');
2716 }
2717
2718 $courseids = array();
2719 if ($params['onlymycourses']) {
2720 $mycourses = enrol_get_my_courses(array('id'));
2721 foreach ($mycourses as $mycourse) {
2722 $courseids[] = $mycourse->id;
2723 }
2724 } else {
2725 $courseids[] = SITEID;
2726 }
2727
2728 // Retrieving the users matching the query.
2729 $users = message_search_users($courseids, $params['searchtext']);
2730 $results = array();
2731 foreach ($users as $user) {
2732 $results[$user->id] = $user;
2733 }
2734
2735 // Reorganising information.
2736 foreach ($results as &$user) {
2737 $newuser = array(
2738 'id' => $user->id,
2739 'fullname' => fullname($user)
2740 );
2741
2742 // Avoid undefined property notice as phone not specified.
2743 $user->phone1 = null;
2744 $user->phone2 = null;
2745
d85bedf7
JL
2746 $userpicture = new user_picture($user);
2747 $userpicture->size = 1; // Size f1.
2748 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
2749 $userpicture->size = 0; // Size f2.
2750 $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
2751
2752 $user = $newuser;
2753 }
2754
2755 return $results;
2756 }
2757
2758 /**
2759 * Search contacts return description.
2760 *
2761 * @return external_description
5bcfd504 2762 * @since Moodle 2.5
d6731600
FM
2763 */
2764 public static function search_contacts_returns() {
2765 return new external_multiple_structure(
2766 new external_single_structure(
2767 array(
2768 'id' => new external_value(PARAM_INT, 'User ID'),
2769 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
2770 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
2771 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
2772 )
2773 ),
2774 'List of contacts'
2775 );
2776 }
aff9da17
JL
2777
2778 /**
2779 * Get messages parameters description.
2780 *
2781 * @return external_function_parameters
193edf7f 2782 * @since 2.8
aff9da17
JL
2783 */
2784 public static function get_messages_parameters() {
2785 return new external_function_parameters(
2786 array(
6ff4464b 2787 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
127ef540
SH
2788 'useridfrom' => new external_value(
2789 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
2790 VALUE_DEFAULT, 0),
2791 'type' => new external_value(
2792 PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
2793 VALUE_DEFAULT, 'both'),
6ff4464b 2794 'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
127ef540
SH
2795 'newestfirst' => new external_value(
2796 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
2797 VALUE_DEFAULT, true),
aff9da17 2798 'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
127ef540
SH
2799 'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
2800 )
aff9da17
JL
2801 );
2802 }
2803
2804 /**
2805 * Get messages function implementation.
127ef540
SH
2806 *
2807 * @since 2.8
2808 * @throws invalid_parameter_exception
2809 * @throws moodle_exception
6ff4464b
JL
2810 * @param int $useridto the user id who received the message
2811 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
193edf7f 2812 * @param string $type type of message to return, expected values: notifications, conversations and both
aff9da17 2813 * @param bool $read true for retreiving read messages, false for unread
6ff4464b 2814 * @param bool $newestfirst true for ordering by newest first, false for oldest first
aff9da17
JL
2815 * @param int $limitfrom limit from
2816 * @param int $limitnum limit num
2817 * @return external_description
aff9da17 2818 */
193edf7f 2819 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
aff9da17 2820 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
127ef540 2821 global $CFG, $USER;
aff9da17
JL
2822
2823 $warnings = array();
2824
2825 $params = array(
2826 'useridto' => $useridto,
6ff4464b 2827 'useridfrom' => $useridfrom,
aff9da17
JL
2828 'type' => $type,
2829 'read' => $read,
aff9da17
JL
2830 'newestfirst' => $newestfirst,
2831 'limitfrom' => $limitfrom,
2832 'limitnum' => $limitnum
2833 );
2834
2835 $params = self::validate_parameters(self::get_messages_parameters(), $params);
2836
2837 $context = context_system::instance();
2838 self::validate_context($context);
2839
2840 $useridto = $params['useridto'];
6ff4464b 2841 $useridfrom = $params['useridfrom'];
aff9da17
JL
2842 $type = $params['type'];
2843 $read = $params['read'];
aff9da17
JL
2844 $newestfirst = $params['newestfirst'];
2845 $limitfrom = $params['limitfrom'];
2846 $limitnum = $params['limitnum'];
2847
2848 $allowedvalues = array('notifications', 'conversations', 'both');
2849 if (!in_array($type, $allowedvalues)) {
2850 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
2851 'allowed values are: ' . implode(',', $allowedvalues));
2852 }
2853
2854 // Check if private messaging between users is allowed.
2855 if (empty($CFG->messaging)) {
2856 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
aff9da17
JL
2857 if ($type == "conversations") {
2858 throw new moodle_exception('disabled', 'message');
2859 }
2860 if ($type == "both") {
2861 $warning = array();
2862 $warning['item'] = 'message';
2863 $warning['itemid'] = $USER->id;
2864 $warning['warningcode'] = '1';
2865 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
2866 Only notifications will be returned';
2867 $warnings[] = $warning;
2868 }
2869 }
2870
2871 if (!empty($useridto)) {
6ff4464b
JL
2872 if (core_user::is_real_user($useridto)) {
2873 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
2874 } else {
2875 throw new moodle_exception('invaliduser');
2876 }
aff9da17
JL
2877 }
2878
2879 if (!empty($useridfrom)) {
2880 // We use get_user here because the from user can be the noreply or support user.
2881 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
2882 }
2883
2884 // Check if the current user is the sender/receiver or just a privileged user.
2885 if ($useridto != $USER->id and $useridfrom != $USER->id and
2886 !has_capability('moodle/site:readallmessages', $context)) {
2887 throw new moodle_exception('accessdenied', 'admin');
2888 }
2889
127ef540 2890 // Which type of messages to retrieve.
193edf7f 2891 $notifications = -1;
aff9da17 2892 if ($type != 'both') {
193edf7f 2893 $notifications = ($type == 'notifications') ? 1 : 0;
aff9da17
JL
2894 }
2895
aff9da17 2896 $orderdirection = $newestfirst ? 'DESC' : 'ASC';
193edf7f 2897 $sort = "mr.timecreated $orderdirection";
aff9da17 2898
193edf7f 2899 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
aff9da17
JL
2900 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
2901
2902 // In some cases, we don't need to get the to/from user objects from the sql query.
2903 $userfromfullname = '';
2904 $usertofullname = '';
2905
2906 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
2907 if (!empty($useridto)) {
2908 $usertofullname = fullname($userto, $canviewfullname);
2909 // The user from may or may not be filled.
2910 if (!empty($useridfrom)) {
2911 $userfromfullname = fullname($userfrom, $canviewfullname);
2912 }
2913 } else {
2914 // If the useridto field is empty, the useridfrom must be filled.
2915 $userfromfullname = fullname($userfrom, $canviewfullname);
2916 }
aff9da17
JL
2917 foreach ($messages as $mid => $message) {
2918
ea21d637 2919 // Do not return deleted messages.
883ce421
MN
2920 if (!$message->notification) {
2921 if (($useridto == $USER->id and $message->timeusertodeleted) or
ea21d637 2922 ($useridfrom == $USER->id and $message->timeuserfromdeleted)) {
883ce421
MN
2923 unset($messages[$mid]);
2924 continue;
2925 }
ea21d637
JL
2926 }
2927
aff9da17
JL
2928 // We need to get the user from the query.
2929 if (empty($userfromfullname)) {
6ff4464b
JL
2930 // Check for non-reply and support users.
2931 if (core_user::is_real_user($message->useridfrom)) {
127ef540 2932 $user = new stdClass();
6ff4464b
JL
2933 $user = username_load_fields_from_object($user, $message, 'userfrom');
2934 $message->userfromfullname = fullname($user, $canviewfullname);
2935 } else {
2936 $user = core_user::get_user($message->useridfrom);
2937 $message->userfromfullname = fullname($user, $canviewfullname);
2938 }
aff9da17
JL
2939 } else {
2940 $message->userfromfullname = $userfromfullname;
2941 }
2942
2943 // We need to get the user from the query.
2944 if (empty($usertofullname)) {
127ef540 2945 $user = new stdClass();
aff9da17
JL
2946 $user = username_load_fields_from_object($user, $message, 'userto');
2947 $message->usertofullname = fullname($user, $canviewfullname);
2948 } else {
2949 $message->usertofullname = $usertofullname;
2950 }
2951
aff9da17 2952 $message->text = message_format_message_text($message);
aff9da17
JL
2953 $messages[$mid] = (array) $message;
2954 }
2955 }
2956
2957 $results = array(
2958 'messages' => $messages,
2959 'warnings' => $warnings
2960 );
2961
2962 return $results;
2963 }
2964
2965 /**
2966 * Get messages return description.
2967 *
6ff4464b 2968 * @return external_single_structure
193edf7f 2969 * @since 2.8
aff9da17
JL
2970 */
2971 public static function get_messages_returns() {
2972 return new external_single_structure(
2973 array(
2974 'messages' => new external_multiple_structure(
2975 new external_single_structure(
2976 array(
193edf7f 2977 'id' => new external_value(PARAM_INT, 'Message id'),
aff9da17
JL
2978 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
2979 'useridto' => new external_value(PARAM_INT, 'User to id'),
2980 'subject' => new external_value(PARAM_TEXT, 'The message subject'),
2981 'text' => new external_value(PARAM_RAW, 'The message text formated'),
2982 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
193edf7f 2983 'fullmessageformat' => new external_format_value('fullmessage'),
aff9da17
JL
2984 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
2985 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
2986 'notification' => new external_value(PARAM_INT, 'Is a notification?'),
2987 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
2988 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
2989 'timecreated' => new external_value(PARAM_INT, 'Time created'),
2990 'timeread' => new external_value(PARAM_INT, 'Time read'),
2991 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
2992 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
2993 ), 'message'
2994 )
2995 ),
2996 'warnings' => new external_warnings()
2997 )
2998 );
3274d5ca
RW
2999 }
3000
3274d5ca
RW
3001 /**
3002 * Mark all notifications as read parameters description.
3003 *
3004 * @return external_function_parameters
3005 * @since 3.2
3006 */
3007 public static function mark_all_notifications_as_read_parameters() {
3008 return new external_function_parameters(
3009 array(
3010 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
3011 'useridfrom' => new external_value(
3012 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
3013 VALUE_DEFAULT, 0),
3014 )
3015 );
3016 }
3017
3018 /**
3019 * Mark all notifications as read function.
3020 *
3021 * @since 3.2
3022 * @throws invalid_parameter_exception
3023 * @throws moodle_exception
3024 * @param int $useridto the user id who received the message
3025 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
3026 * @return external_description
3027 */
3028 public static function mark_all_notifications_as_read($useridto, $useridfrom) {
837941e9 3029 global $USER;
3274d5ca
RW
3030
3031 $params = self::validate_parameters(
3032 self::mark_all_notifications_as_read_parameters(),
3033 array(
3034 'useridto' => $useridto,
3035 'useridfrom' => $useridfrom,
3036 )
3037 );
3038
3039 $context = context_system::instance();
3040 self::validate_context($context);
3041
3042 $useridto = $params['useridto'];
3043 $useridfrom = $params['useridfrom'];
3044
3045 if (!empty($useridto)) {
3046 if (core_user::is_real_user($useridto)) {
3047 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
3048 } else {
3049 throw new moodle_exception('invaliduser');
3050 }
3051 }
3052
3053 if (!empty($useridfrom)) {
3054 // We use get_user here because the from user can be the noreply or support user.
3055 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
3056 }
3057
3058 // Check if the current user is the sender/receiver or just a privileged user.
3059 if ($useridto != $USER->id and $useridfrom != $USER->id and
7b55aaa1 3060 // The deleteanymessage cap seems more reasonable here than readallmessages.
3274d5ca
RW
3061 !has_capability('moodle/site:deleteanymessage', $context)) {
3062 throw new moodle_exception('accessdenied', 'admin');
3063 }
3064
74ad60bf 3065 \core_message\api::mark_all_notifications_as_read($useridto, $useridfrom);
3274d5ca
RW
3066
3067 return true;
3068 }
3069
3070 /**
3071 * Mark all notifications as read return description.
3072 *
3073 * @return external_single_structure
3074 * @since 3.2
3075 */
3076 public static function mark_all_notifications_as_read_returns() {
3077 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
3078 }
3079
8c55bd6c
RW
3080 /**
3081 * Get unread conversations count parameters description.
3082 *
3083 * @return external_function_parameters
3084 * @since 3.2
3085 */
3086 public static function get_unread_conversations_count_parameters() {
3087 return new external_function_parameters(
3088 array(
3089 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
3090 )
3091 );
3092 }
3093
3094 /**
3095 * Get unread messages count function.
3096 *
3097 * @since 3.2
3098 * @throws invalid_parameter_exception
3099 * @throws moodle_exception
3100 * @param int $useridto the user id who received the message
3101 * @return external_description
3102 */
3103 public static function get_unread_conversations_count($useridto) {
a2c7227a
SL
3104 global $USER, $CFG;
3105
3106 // Check if messaging is enabled.
3107 if (empty($CFG->messaging)) {
3108 throw new moodle_exception('disabled', 'message');
3109 }
8c55bd6c
RW
3110
3111 $params = self::validate_parameters(
3112 self::get_unread_conversations_count_parameters(),
3113 array('useridto' => $useridto)
3114 );
3115
3116 $context = context_system::instance();
3117 self::validate_context($context);
3118
3119 $useridto = $params['useridto'];
3120
3121 if (!empty($useridto)) {
3122 if (core_user::is_real_user($useridto)) {
3123 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
3124 } else {
3125 throw new moodle_exception('invaliduser');
3126 }
3127 } else {
3128 $useridto = $USER->id;
3129 }
3130
3131 // Check if the current user is the receiver or just a privileged user.
3132 if ($useridto != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
3133 throw new moodle_exception('accessdenied', 'admin');
3134 }
3135
79f6c36c 3136 return \core_message\api::count_unread_conversations($userto);
8c55bd6c
RW
3137 }
3138
3139 /**
3140 * Get unread conversations count return description.
3141 *
3142 * @return external_single_structure
3143 * @since 3.2
3144 */
3145 public static function get_unread_conversations_count_returns() {
3146 return new external_value(PARAM_INT, 'The count of unread messages for the user');
aff9da17
JL
3147 }
3148
60ab2e1b
JL
3149 /**
3150 * Get blocked users parameters description.
3151 *
3152 * @return external_function_parameters
3153 * @since 2.9
3154 */
3155 public static function get_blocked_users_parameters() {
3156 return new external_function_parameters(
3157 array(
3158 'userid' => new external_value(PARAM_INT,
3159 'the user whose blocked users we want to retrieve',
3160 VALUE_REQUIRED),
3161 )
3162 );
3163 }
3164
3165 /**
3166 * Retrieve a list of users blocked
3167 *
3168 * @param int $userid the user whose blocked users we want to retrieve
3169 * @return external_description
3170 * @since 2.9
3171 */
3172 public static function get_blocked_users($userid) {
d85bedf7 3173 global $CFG, $USER, $PAGE;
60ab2e1b
JL
3174
3175 // Warnings array, it can be empty at the end but is mandatory.
3176 $warnings = array();
3177
3178 // Validate params.
3179 $params = array(
3180 'userid' => $userid
3181 );
3182 $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
3183 $userid = $params['userid'];
3184
3185 // Validate context.
3186 $context = context_system::instance();
3187 self::validate_context($context);
3188
3189 // Check if private messaging between users is allowed.
3190 if (empty($CFG->messaging)) {
3191 throw new moodle_exception('disabled', 'message');
3192 }
3193
4485f7c5
JL
3194 $user = core_user::get_user($userid, '*', MUST_EXIST);
3195 core_user::require_active_user($user);
60ab2e1b
JL
3196
3197 // Check if we have permissions for retrieve the information.
343ba16c
SL
3198 $capability = 'moodle/site:manageallmessaging';
3199 if (($USER->id != $userid) && !has_capability($capability, $context)) {
3200 throw new required_capability_exception($context, $capability, 'nopermissions', '');
60ab2e1b
JL
3201 }
3202
3203 // Now, we can get safely all the blocked users.
883ce421 3204 $users = \core_message\api::get_blocked_users($user->id);
60ab2e1b
JL
3205
3206 $blockedusers = array();
3207 foreach ($users as $user) {
3208 $newuser = array(
3209 'id' => $user->id,
3210 'fullname' => fullname($user),
3211 );
0b074e88 3212
d85bedf7
JL
3213 $userpicture = new user_picture($user);
3214 $userpicture->size = 1; // Size f1.
3215 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
60ab2e1b
JL
3216
3217 $blockedusers[] = $newuser;
3218 }
3219
3220 $results = array(
3221 'users' => $blockedusers,
3222 'warnings' => $warnings
3223 );
3224 return $results;
3225 }
3226
3227 /**
3228 * Get blocked users return description.
3229 *
3230 * @return external_single_structure
3231 * @since 2.9
3232 */
3233 public static function get_blocked_users_returns() {
3234 return new external_single_structure(
3235 array(
3236 'users' => new external_multiple_structure(
3237 new external_single_structure(
3238 array(
3239 'id' => new external_value(PARAM_INT, 'User ID'),
3240 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
3241 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL)
3242 )
3243 ),
3244 'List of blocked users'
3245 ),
3246 'warnings' => new external_warnings()
3247 )
3248 );
3249 }
3250
31c474da
JL
3251 /**
3252 * Returns description of method parameters
3253 *
3254 * @return external_function_parameters
3255 * @since 2.9
3256 */
3257 public static function mark_message_read_parameters() {
3258 return new external_function_parameters(
3259 array(
2b595d96 3260 'messageid' => new external_value(PARAM_INT, 'id of the message in the messages table'),
7b55aaa1
MN
3261 'timeread' => new external_value(PARAM_INT, 'timestamp for when the message should be marked read',
3262 VALUE_DEFAULT, 0)
31c474da
JL
3263 )
3264 );
3265 }
3266
3267 /**
3268 * Mark a single message as read, trigger message_viewed event
3269 *
3270 * @param int $messageid id of the message (in the message table)
3271 * @param int $timeread timestamp for when the message should be marked read
3272 * @return external_description
3273 * @throws invalid_parameter_exception
3274 * @throws moodle_exception
3275 * @since 2.9
3276 */
3277 public static function mark_message_read($messageid, $timeread) {
3278 global $CFG, $DB, $USER;
31c474da
JL
3279
3280 // Check if private messaging between users is allowed.
3281 if (empty($CFG->messaging)) {
3282 throw new moodle_exception('disabled', 'message');
3283 }
3284
3285 // Warnings array, it can be empty at the end but is mandatory.
3286 $warnings = array();
3287
3288 // Validate params.
3289 $params = array(
3290 'messageid' => $messageid,
3291 'timeread' => $timeread
3292 );
3293 $params = self::validate_parameters(self::mark_message_read_parameters(), $params);
3294
0b19d048
RW
3295 if (empty($params['timeread'])) {
3296 $timeread = time();
3297 } else {
3298 $timeread = $params['timeread'];
3299 }
3300
31c474da
JL
3301 // Validate context.
3302 $context = context_system::instance();
3303 self::validate_context($context);
3304
883ce421
MN
3305 $sql = "SELECT m.*, mcm.userid as useridto
3306 FROM {messages} m
3307 INNER JOIN {message_conversations} mc
3308 ON m.conversationid = mc.id
3309 INNER JOIN {message_conversation_members} mcm
3310 ON mcm.conversationid = mc.id
5aac33c7
MN
3311 LEFT JOIN {message_user_actions} mua
3312 ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
3313 WHERE mua.id is NULL
3314 AND mcm.userid != m.useridfrom
883ce421 3315 AND m.id = ?";
5aac33c7
MN
3316 $messageparams = [];
3317 $messageparams[] = $USER->id;
3318 $messageparams[] = \core_message\api::MESSAGE_ACTION_READ;
3319 $messageparams[] = $params['messageid'];
3320 $message = $DB->get_record_sql($sql, $messageparams, MUST_EXIST);
31c474da
JL
3321
3322 if ($message->useridto != $USER->id) {
3323 throw new invalid_parameter_exception('Invalid messageid, you don\'t have permissions to mark this message as read');
3324 }
3325
548936a6 3326 \core_message\api::mark_message_as_read($USER->id, $message, $timeread);
31c474da
JL
3327
3328 $results = array(
883ce421 3329 'messageid' => $message->id,
31c474da
JL
3330 'warnings' => $warnings
3331 );
3332 return $results;
3333 }
3334
3335 /**
3336 * Returns description of method result value
3337 *
3338 * @return external_description
3339 * @since 2.9
3340 */
3341 public static function mark_message_read_returns() {
3342 return new external_single_structure(
3343 array(
2b595d96
MN
3344 'messageid' => new external_value(PARAM_INT, 'the id of the message in the messages table'),
3345 'warnings' => new external_warnings()
3346 )
3347 );
3348 }
3349
3350 /**
3351 * Returns description of method parameters
3352 *
3353 * @return external_function_parameters
3354 */
3355 public static function mark_notification_read_parameters() {
3356 return new external_function_parameters(
3357 array(
3358 'notificationid' => new external_value(PARAM_INT, 'id of the notification'),
3359 'timeread' => new external_value(PARAM_INT, 'timestamp for when the notification should be marked read',
3360 VALUE_DEFAULT, 0)
3361 )
3362 );
3363 }
3364
3365 /**
3366 * Mark a single notification as read.
3367 *
3368 * This will trigger a 'notification_viewed' event.
3369 *
3370 * @param int $notificationid id of the notification
3371 * @param int $timeread timestamp for when the notification should be marked read
3372 * @return external_description
3373 * @throws invalid_parameter_exception
3374 * @throws moodle_exception
3375 */
3376 public static function mark_notification_read($notificationid, $timeread) {
3377 global $CFG, $DB, $USER;
3378
3379 // Check if private messaging between users is allowed.
3380 if (empty($CFG->messaging)) {
3381 throw new moodle_exception('disabled', 'message');
3382 }
3383
3384 // Warnings array, it can be empty at the end but is mandatory.
3385 $warnings = array();
3386
3387 // Validate params.
3388 $params = array(
3389 'notificationid' => $notificationid,
3390 'timeread' => $timeread
3391 );
3392 $params = self::validate_parameters(self::mark_notification_read_parameters(), $params);
3393
3394 if (empty($params['timeread'])) {
3395 $timeread = time();
3396 } else {
3397 $timeread = $params['timeread'];
3398 }
3399
3400 // Validate context.
3401 $context = context_system::instance();
3402 self::validate_context($context);
3403
3404 $notification = $DB->get_record('notifications', ['id' => $params['notificationid']], '*', MUST_EXIST);
3405
3406 if ($notification->useridto != $USER->id) {
3407 throw new invalid_parameter_exception('Invalid notificationid, you don\'t have permissions to mark this ' .
3408 'notification as read');
3409 }
3410
3411 \core_message\api::mark_notification_as_read($notification, $timeread);
3412
3413 $results = array(
3414 'notificationid' => $notification->id,
3415 'warnings' => $warnings
3416 );
3417
3418 return $results;
3419 }
3420
3421 /**
3422 * Returns description of method result value
3423 *
3424 * @return external_description
3425 */
3426 public static function mark_notification_read_returns() {
3427 return new external_single_structure(
3428 array(
3429 'notificationid' => new external_value(PARAM_INT, 'id of the notification'),
31c474da
JL
3430 'warnings' => new external_warnings()
3431 )
3432 );
3433 }
3434
8c55bd6c
RW
3435 /**
3436 * Mark all messages as read parameters description.
3437 *
e4c30994 3438 * @deprecated since 3.6
8c55bd6c
RW
3439 * @return external_function_parameters
3440 * @since 3.2
3441 */
3442 public static function mark_all_messages_as_read_parameters() {
3443 return new external_function_parameters(
3444 array(
3445 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
3446 'useridfrom' => new external_value(
3447 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
3448 VALUE_DEFAULT, 0),
3449 )
3450 );
3451 }
3452
3453 /**
e4c30994 3454 * Mark all messages as read function.