MDL-36941 core: removed 'message_working' table
[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 {
a623b6b8
JM
42
43 /**
44 * Returns description of method parameters
4615817d 45 *
a623b6b8 46 * @return external_function_parameters
4615817d 47 * @since Moodle 2.2
a623b6b8 48 */
5d1017e1 49 public static function send_instant_messages_parameters() {
a623b6b8
JM
50 return new external_function_parameters(
51 array(
52 'messages' => new external_multiple_structure(
53 new external_single_structure(
54 array(
55 'touserid' => new external_value(PARAM_INT, 'id of the user to send the private message'),
93ce0e82 56 'text' => new external_value(PARAM_RAW, 'the text of the message'),
14968ca9 57 'textformat' => new external_format_value('text', VALUE_DEFAULT, FORMAT_MOODLE),
a623b6b8
JM
58 '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),
59 )
60 )
61 )
62 )
63 );
64 }
65
66 /**
67 * Send private messages from the current USER to other users
68 *
4615817d
JM
69 * @param array $messages An array of message to send.
70 * @return array
71 * @since Moodle 2.2
a623b6b8 72 */
5d1017e1 73 public static function send_instant_messages($messages = array()) {
a623b6b8 74 global $CFG, $USER, $DB;
a623b6b8 75
436bbf89 76 // Check if messaging is enabled.
837941e9 77 if (empty($CFG->messaging)) {
a623b6b8
JM
78 throw new moodle_exception('disabled', 'message');
79 }
80
81 // Ensure the current user is allowed to run this function
bf0f06b1 82 $context = context_system::instance();
a623b6b8
JM
83 self::validate_context($context);
84 require_capability('moodle/site:sendmessage', $context);
85
5d1017e1 86 $params = self::validate_parameters(self::send_instant_messages_parameters(), array('messages' => $messages));
a623b6b8
JM
87
88 //retrieve all tousers of the messages
4de00da7 89 $receivers = array();
a623b6b8 90 foreach($params['messages'] as $message) {
4de00da7 91 $receivers[] = $message['touserid'];
a623b6b8 92 }
4de00da7 93 list($sqluserids, $sqlparams) = $DB->get_in_or_equal($receivers, SQL_PARAMS_NAMED, 'userid_');
a623b6b8 94 $tousers = $DB->get_records_select("user", "id " . $sqluserids . " AND deleted = 0", $sqlparams);
4de00da7
DC
95 $blocklist = array();
96 $contactlist = array();
a623b6b8 97 $sqlparams['contactid'] = $USER->id;
4de00da7
DC
98 $rs = $DB->get_recordset_sql("SELECT *
99 FROM {message_contacts}
100 WHERE userid $sqluserids
101 AND contactid = :contactid", $sqlparams);
102 foreach ($rs as $record) {
103 if ($record->blocked) {
104 // $record->userid is blocking current user
105 $blocklist[$record->userid] = true;
106 } else {
107 // $record->userid have current user as contact
108 $contactlist[$record->userid] = true;
109 }
110 }
111 $rs->close();
a623b6b8
JM
112
113 $canreadallmessages = has_capability('moodle/site:readallmessages', $context);
114
115 $resultmessages = array();
116 foreach ($params['messages'] as $message) {
a623b6b8
JM
117 $resultmsg = array(); //the infos about the success of the operation
118
119 //we are going to do some checking
120 //code should match /messages/index.php checks
121 $success = true;
122
123 //check the user exists
124 if (empty($tousers[$message['touserid']])) {
125 $success = false;
126 $errormessage = get_string('touserdoesntexist', 'message', $message['touserid']);
127 }
128
129 //check that the touser is not blocking the current user
4de00da7 130 if ($success and !empty($blocklist[$message['touserid']]) and !$canreadallmessages) {
a623b6b8
JM
131 $success = false;
132 $errormessage = get_string('userisblockingyou', 'message');
133 }
134
78736e5d 135 // Check if the user is a contact
4615817d 136 //TODO MDL-31118 performance improvement - edit the function so we can pass an array instead userid
4de00da7
DC
137 $blocknoncontacts = get_user_preferences('message_blocknoncontacts', NULL, $message['touserid']);
138 // message_blocknoncontacts option is on and current user is not in contact list
139 if ($success && empty($contactlist[$message['touserid']]) && !empty($blocknoncontacts)) {
78736e5d
SH
140 // The user isn't a contact and they have selected to block non contacts so this message won't be sent.
141 $success = false;
126a4bc4
CS
142 $errormessage = get_string('userisblockingyounoncontact', 'message',
143 fullname(core_user::get_user($message['touserid'])));
a623b6b8
JM
144 }
145
146 //now we can send the message (at least try)
147 if ($success) {
4615817d 148 //TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object
93ce0e82
JM
149 $success = message_post_message($USER, $tousers[$message['touserid']],
150 $message['text'], external_validate_format($message['textformat']));
a623b6b8
JM
151 }
152
153 //build the resultmsg
154 if (isset($message['clientmsgid'])) {
78736e5d 155 $resultmsg['clientmsgid'] = $message['clientmsgid'];
a623b6b8
JM
156 }
157 if ($success) {
158 $resultmsg['msgid'] = $success;
159 } else {
93ce0e82
JM
160 // WARNINGS: for backward compatibility we return this errormessage.
161 // We should have thrown exceptions as these errors prevent results to be returned.
162 // See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
a623b6b8
JM
163 $resultmsg['msgid'] = -1;
164 $resultmsg['errormessage'] = $errormessage;
165 }
166
167 $resultmessages[] = $resultmsg;
168 }
169
170 return $resultmessages;
171 }
172
173 /**
174 * Returns description of method result value
4615817d 175 *
a623b6b8 176 * @return external_description
4615817d 177 * @since Moodle 2.2
a623b6b8 178 */
5d1017e1 179 public static function send_instant_messages_returns() {
a623b6b8
JM
180 return new external_multiple_structure(
181 new external_single_structure(
182 array(
78736e5d 183 '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 184 'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own id for the message', VALUE_OPTIONAL),
78736e5d 185 'errormessage' => new external_value(PARAM_TEXT, 'error message - if it failed', VALUE_OPTIONAL)
a623b6b8
JM
186 )
187 )
188 );
189 }
190
d6731600
FM
191 /**
192 * Create contacts parameters description.
193 *
194 * @return external_function_parameters
5bcfd504 195 * @since Moodle 2.5
d6731600
FM
196 */
197 public static function create_contacts_parameters() {
198 return new external_function_parameters(
199 array(
200 'userids' => new external_multiple_structure(
201 new external_value(PARAM_INT, 'User ID'),
202 'List of user IDs'
34c2f347
MN
203 ),
204 'userid' => new external_value(PARAM_INT, 'The id of the user we are creating the contacts for, 0 for the
205 current user', VALUE_DEFAULT, 0)
d6731600
FM
206 )
207 );
208 }
209
210 /**
211 * Create contacts.
212 *
213 * @param array $userids array of user IDs.
34c2f347 214 * @param int $userid The id of the user we are creating the contacts for
d6731600 215 * @return external_description
5bcfd504 216 * @since Moodle 2.5
d6731600 217 */
34c2f347 218 public static function create_contacts($userids, $userid = 0) {
343ba16c 219 global $CFG, $USER;
436bbf89
DM
220
221 // Check if messaging is enabled.
837941e9 222 if (empty($CFG->messaging)) {
436bbf89
DM
223 throw new moodle_exception('disabled', 'message');
224 }
225
343ba16c
SL
226 if (empty($userid)) {
227 $userid = $USER->id;
228 }
229
230 // Validate context.
231 $context = context_system::instance();
232 self::validate_context($context);
233
234 $capability = 'moodle/site:manageallmessaging';
235 if (($USER->id != $userid) && !has_capability($capability, $context)) {
236 throw new required_capability_exception($context, $capability, 'nopermissions', '');
237 }
238
34c2f347 239 $params = array('userids' => $userids, 'userid' => $userid);
d6731600
FM
240 $params = self::validate_parameters(self::create_contacts_parameters(), $params);
241
242 $warnings = array();
243 foreach ($params['userids'] as $id) {
34c2f347 244 if (!message_add_contact($id, 0, $userid)) {
d6731600
FM
245 $warnings[] = array(
246 'item' => 'user',
247 'itemid' => $id,
248 'warningcode' => 'contactnotcreated',
249 'message' => 'The contact could not be created'
250 );
251 }
252 }
253 return $warnings;
254 }
255
256 /**
257 * Create contacts return description.
258 *
259 * @return external_description
5bcfd504 260 * @since Moodle 2.5
d6731600
FM
261 */
262 public static function create_contacts_returns() {
263 return new external_warnings();
264 }
265
266 /**
267 * Delete contacts parameters description.
268 *
269 * @return external_function_parameters
5bcfd504 270 * @since Moodle 2.5
d6731600
FM
271 */
272 public static function delete_contacts_parameters() {
273 return new external_function_parameters(
274 array(
275 'userids' => new external_multiple_structure(
276 new external_value(PARAM_INT, 'User ID'),
277 'List of user IDs'
34c2f347
MN
278 ),
279 'userid' => new external_value(PARAM_INT, 'The id of the user we are deleting the contacts for, 0 for the
280 current user', VALUE_DEFAULT, 0)
d6731600
FM
281 )
282 );
283 }
284
285 /**
286 * Delete contacts.
287 *
288 * @param array $userids array of user IDs.
34c2f347 289 * @param int $userid The id of the user we are deleting the contacts for
d6731600 290 * @return null
5bcfd504 291 * @since Moodle 2.5
d6731600 292 */
34c2f347 293 public static function delete_contacts($userids, $userid = 0) {
343ba16c 294 global $CFG, $USER;
436bbf89
DM
295
296 // Check if messaging is enabled.
837941e9 297 if (empty($CFG->messaging)) {
436bbf89
DM
298 throw new moodle_exception('disabled', 'message');
299 }
300
343ba16c
SL
301 if (empty($userid)) {
302 $userid = $USER->id;
303 }
304
305 // Validate context.
306 $context = context_system::instance();
307 self::validate_context($context);
308
309 $capability = 'moodle/site:manageallmessaging';
310 if (($USER->id != $userid) && !has_capability($capability, $context)) {
311 throw new required_capability_exception($context, $capability, 'nopermissions', '');
312 }
313
34c2f347 314 $params = array('userids' => $userids, 'userid' => $userid);
d6731600
FM
315 $params = self::validate_parameters(self::delete_contacts_parameters(), $params);
316
317 foreach ($params['userids'] as $id) {
34c2f347 318 message_remove_contact($id, $userid);
d6731600
FM
319 }
320
321 return null;
322 }
323
324 /**
325 * Delete contacts return description.
326 *
327 * @return external_description
5bcfd504 328 * @since Moodle 2.5
d6731600
FM
329 */
330 public static function delete_contacts_returns() {
331 return null;
332 }
333
334 /**
335 * Block contacts parameters description.
336 *
337 * @return external_function_parameters
5bcfd504 338 * @since Moodle 2.5
d6731600
FM
339 */
340 public static function block_contacts_parameters() {
341 return new external_function_parameters(
342 array(
343 'userids' => new external_multiple_structure(
344 new external_value(PARAM_INT, 'User ID'),
345 'List of user IDs'
34c2f347
MN
346 ),
347 'userid' => new external_value(PARAM_INT, 'The id of the user we are blocking the contacts for, 0 for the
348 current user', VALUE_DEFAULT, 0)
d6731600
FM
349 )
350 );
351 }
352
353 /**
354 * Block contacts.
355 *
356 * @param array $userids array of user IDs.
34c2f347 357 * @param int $userid The id of the user we are blocking the contacts for
d6731600 358 * @return external_description
5bcfd504 359 * @since Moodle 2.5
d6731600 360 */
34c2f347 361 public static function block_contacts($userids, $userid = 0) {
343ba16c 362 global $CFG, $USER;
436bbf89
DM
363
364 // Check if messaging is enabled.
837941e9 365 if (empty($CFG->messaging)) {
436bbf89
DM
366 throw new moodle_exception('disabled', 'message');
367 }
368
343ba16c
SL
369 if (empty($userid)) {
370 $userid = $USER->id;
371 }
372
373 // Validate context.
374 $context = context_system::instance();
375 self::validate_context($context);
376
377 $capability = 'moodle/site:manageallmessaging';
378 if (($USER->id != $userid) && !has_capability($capability, $context)) {
379 throw new required_capability_exception($context, $capability, 'nopermissions', '');
380 }
381
34c2f347 382 $params = array('userids' => $userids, 'userid' => $userid);
d6731600
FM
383 $params = self::validate_parameters(self::block_contacts_parameters(), $params);
384
385 $warnings = array();
386 foreach ($params['userids'] as $id) {
34c2f347 387 if (!message_block_contact($id, $userid)) {
d6731600
FM
388 $warnings[] = array(
389 'item' => 'user',
390 'itemid' => $id,
391 'warningcode' => 'contactnotblocked',
392 'message' => 'The contact could not be blocked'
393 );
394 }
395 }
396 return $warnings;
397 }
398
399 /**
400 * Block contacts return description.
401 *
402 * @return external_description
5bcfd504 403 * @since Moodle 2.5
d6731600
FM
404 */
405 public static function block_contacts_returns() {
406 return new external_warnings();
407 }
408
409 /**
410 * Unblock contacts parameters description.
411 *
412 * @return external_function_parameters
5bcfd504 413 * @since Moodle 2.5
d6731600
FM
414 */
415 public static function unblock_contacts_parameters() {
416 return new external_function_parameters(
417 array(
418 'userids' => new external_multiple_structure(
419 new external_value(PARAM_INT, 'User ID'),
420 'List of user IDs'
34c2f347
MN
421 ),
422 'userid' => new external_value(PARAM_INT, 'The id of the user we are unblocking the contacts for, 0 for the
423 current user', VALUE_DEFAULT, 0)
d6731600
FM
424 )
425 );
426 }
427
428 /**
429 * Unblock contacts.
430 *
431 * @param array $userids array of user IDs.
34c2f347 432 * @param int $userid The id of the user we are unblocking the contacts for
d6731600 433 * @return null
5bcfd504 434 * @since Moodle 2.5
d6731600 435 */
34c2f347 436 public static function unblock_contacts($userids, $userid = 0) {
343ba16c 437 global $CFG, $USER;
436bbf89
DM
438
439 // Check if messaging is enabled.
837941e9 440 if (empty($CFG->messaging)) {
436bbf89
DM
441 throw new moodle_exception('disabled', 'message');
442 }
443
343ba16c
SL
444 if (empty($userid)) {
445 $userid = $USER->id;
446 }
447
448 // Validate context.
449 $context = context_system::instance();
450 self::validate_context($context);
451
452 $capability = 'moodle/site:manageallmessaging';
453 if (($USER->id != $userid) && !has_capability($capability, $context)) {
454 throw new required_capability_exception($context, $capability, 'nopermissions', '');
455 }
456
34c2f347 457 $params = array('userids' => $userids, 'userid' => $userid);
d6731600
FM
458 $params = self::validate_parameters(self::unblock_contacts_parameters(), $params);
459
460 foreach ($params['userids'] as $id) {
34c2f347 461 message_unblock_contact($id, $userid);
d6731600
FM
462 }
463
464 return null;
465 }
466
467 /**
468 * Unblock contacts return description.
469 *
470 * @return external_description
5bcfd504 471 * @since Moodle 2.5
d6731600
FM
472 */
473 public static function unblock_contacts_returns() {
474 return null;
475 }
476
a3e3a3a1
MN
477 /**
478 * Return the structure of a message area contact.
479 *
480 * @return external_single_structure
481 * @since Moodle 3.2
482 */
483 private static function get_messagearea_contact_structure() {
484 return new external_single_structure(
485 array(
486 'userid' => new external_value(PARAM_INT, 'The user\'s id'),
487 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
488 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
489 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
5bf0ff27 490 'ismessaging' => new external_value(PARAM_BOOL, 'If we are messaging the user'),
89a70ba1 491 'sentfromcurrentuser' => new external_value(PARAM_BOOL, 'Was the last message sent from the current user?'),
a3e3a3a1
MN
492 'lastmessage' => new external_value(PARAM_NOTAGS, 'The user\'s last message'),
493 'messageid' => new external_value(PARAM_INT, 'The unique search message id', VALUE_DEFAULT, null),
cb805753 494 'showonlinestatus' => new external_value(PARAM_BOOL, 'Show the user\'s online status?'),
a3e3a3a1
MN
495 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status'),
496 'isread' => new external_value(PARAM_BOOL, 'If the user has read the message'),
dd0c1403 497 'isblocked' => new external_value(PARAM_BOOL, 'If the user has been blocked'),
a3e3a3a1
MN
498 'unreadcount' => new external_value(PARAM_INT, 'The number of unread messages in this conversation',
499 VALUE_DEFAULT, null),
500 )
501 );
502 }
503
94e1db61
MN
504 /**
505 * Return the structure of a message area message.
506 *
507 * @return external_single_structure
508 * @since Moodle 3.2
509 */
510 private static function get_messagearea_message_structure() {
511 return new external_single_structure(
512 array(
513 'id' => new external_value(PARAM_INT, 'The id of the message'),
89a70ba1
MN
514 'useridfrom' => new external_value(PARAM_INT, 'The id of the user who sent the message'),
515 'useridto' => new external_value(PARAM_INT, 'The id of the user who received the message'),
94e1db61
MN
516 'text' => new external_value(PARAM_RAW, 'The text of the message'),
517 'displayblocktime' => new external_value(PARAM_BOOL, 'Should we display the block time?'),
518 'blocktime' => new external_value(PARAM_NOTAGS, 'The time to display above the message'),
519 'position' => new external_value(PARAM_ALPHA, 'The position of the text'),
520 'timesent' => new external_value(PARAM_NOTAGS, 'The time the message was sent'),
fb1469d8 521 'timecreated' => new external_value(PARAM_INT, 'The timecreated timestamp for the message'),
94e1db61
MN
522 'isread' => new external_value(PARAM_INT, 'Determines if the message was read or not'),
523 )
524 );
525 }
526
cd03b8d7 527 /**
48e8bdba 528 * Get messagearea search users in course parameters.
cd03b8d7
MN
529 *
530 * @return external_function_parameters
531 * @since 3.2
532 */
48e8bdba 533 public static function data_for_messagearea_search_users_in_course_parameters() {
cd03b8d7
MN
534 return new external_function_parameters(
535 array(
536 'userid' => new external_value(PARAM_INT, 'The id of the user who is performing the search'),
537 'courseid' => new external_value(PARAM_INT, 'The id of the course'),
538 'search' => new external_value(PARAM_RAW, 'The string being searched'),
539 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
540 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
541 )
542 );
543 }
544
545 /**
48e8bdba 546 * Get messagearea search users in course results.
cd03b8d7
MN
547 *
548 * @param int $userid The id of the user who is performing the search
549 * @param int $courseid The id of the course
550 * @param string $search The string being searched
551 * @param int $limitfrom
552 * @param int $limitnum
553 * @return stdClass
554 * @throws moodle_exception
555 * @since 3.2
556 */
48e8bdba 557 public static function data_for_messagearea_search_users_in_course($userid, $courseid, $search, $limitfrom = 0,
de55cb1b 558 $limitnum = 0) {
837941e9 559 global $CFG, $PAGE, $USER;
cd03b8d7
MN
560
561 // Check if messaging is enabled.
837941e9 562 if (empty($CFG->messaging)) {
cd03b8d7
MN
563 throw new moodle_exception('disabled', 'message');
564 }
565
837941e9
MN
566 $systemcontext = context_system::instance();
567
cd03b8d7
MN
568 $params = array(
569 'userid' => $userid,
570 'courseid' => $courseid,
571 'search' => $search,
572 'limitfrom' => $limitfrom,
573 'limitnum' => $limitnum
574 );
48e8bdba 575 self::validate_parameters(self::data_for_messagearea_search_users_in_course_parameters(), $params);
837941e9 576 self::validate_context($systemcontext);
cd03b8d7 577
837941e9
MN
578 if (($USER->id != $userid) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
579 throw new moodle_exception('You do not have permission to perform this action.');
580 }
cd03b8d7 581
de55cb1b
MN
582 $users = \core_message\api::search_users_in_course($userid, $courseid, $search, $limitfrom, $limitnum);
583 $results = new \core_message\output\messagearea\user_search_results($users);
cd03b8d7
MN
584
585 $renderer = $PAGE->get_renderer('core_message');
de55cb1b 586 return $results->export_for_template($renderer);
cd03b8d7
MN
587 }
588
589 /**
48e8bdba 590 * Get messagearea search users in course returns.
cd03b8d7
MN
591 *
592 * @return external_single_structure
593 * @since 3.2
594 */
48e8bdba 595 public static function data_for_messagearea_search_users_in_course_returns() {
cd03b8d7
MN
596 return new external_single_structure(
597 array(
cd03b8d7 598 'contacts' => new external_multiple_structure(
a3e3a3a1 599 self::get_messagearea_contact_structure()
cd03b8d7
MN
600 ),
601 )
602 );
603 }
604
605 /**
48e8bdba 606 * Get messagearea search users parameters.
cd03b8d7
MN
607 *
608 * @return external_function_parameters
609 * @since 3.2
610 */
48e8bdba 611 public static function data_for_messagearea_search_users_parameters() {
cd03b8d7
MN
612 return new external_function_parameters(
613 array(
614 'userid' => new external_value(PARAM_INT, 'The id of the user who is performing the search'),
615 'search' => new external_value(PARAM_RAW, 'The string being searched'),
616 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
617 )
618 );
619 }
620
621 /**
48e8bdba 622 * Get messagearea search users results.
cd03b8d7
MN
623 *
624 * @param int $userid The id of the user who is performing the search
625 * @param string $search The string being searched
626 * @param int $limitnum
627 * @return stdClass
628 * @throws moodle_exception
629 * @since 3.2
630 */
48e8bdba 631 public static function data_for_messagearea_search_users($userid, $search, $limitnum = 0) {
837941e9 632 global $CFG, $PAGE, $USER;
cd03b8d7
MN
633
634 // Check if messaging is enabled.
837941e9 635 if (empty($CFG->messaging)) {
cd03b8d7
MN
636 throw new moodle_exception('disabled', 'message');
637 }
638
837941e9
MN
639 $systemcontext = context_system::instance();
640
cd03b8d7
MN
641 $params = array(
642 'userid' => $userid,
643 'search' => $search,
644 'limitnum' => $limitnum
645 );
48e8bdba 646 self::validate_parameters(self::data_for_messagearea_search_users_parameters(), $params);
837941e9 647 self::validate_context($systemcontext);
cd03b8d7 648
837941e9
MN
649 if (($USER->id != $userid) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
650 throw new moodle_exception('You do not have permission to perform this action.');
651 }
cd03b8d7 652
de55cb1b
MN
653 list($contacts, $courses, $noncontacts) = \core_message\api::search_users($userid, $search, $limitnum);
654 $search = new \core_message\output\messagearea\user_search_results($contacts, $courses, $noncontacts);
cd03b8d7
MN
655
656 $renderer = $PAGE->get_renderer('core_message');
657 return $search->export_for_template($renderer);
658 }
659
660 /**
48e8bdba 661 * Get messagearea search users returns.
cd03b8d7
MN
662 *
663 * @return external_single_structure
664 * @since 3.2
665 */
48e8bdba 666 public static function data_for_messagearea_search_users_returns() {
cd03b8d7
MN
667 return new external_single_structure(
668 array(
cd03b8d7 669 'contacts' => new external_multiple_structure(
a3e3a3a1 670 self::get_messagearea_contact_structure()
cd03b8d7 671 ),
cd03b8d7
MN
672 'courses' => new external_multiple_structure(
673 new external_single_structure(
674 array(
675 'id' => new external_value(PARAM_INT, 'The course id'),
7597ab0b
AA
676 'shortname' => new external_value(PARAM_TEXT, 'The course shortname'),
677 'fullname' => new external_value(PARAM_TEXT, 'The course fullname'),
cd03b8d7
MN
678 )
679 )
680 ),
cd03b8d7 681 'noncontacts' => new external_multiple_structure(
a3e3a3a1 682 self::get_messagearea_contact_structure()
cd03b8d7
MN
683 )
684 )
685 );
686 }
687
688 /**
689 * Get messagearea search messages parameters.
690 *
691 * @return external_function_parameters
692 * @since 3.2
693 */
694 public static function data_for_messagearea_search_messages_parameters() {
695 return new external_function_parameters(
696 array(
697 'userid' => new external_value(PARAM_INT, 'The id of the user who is performing the search'),
698 'search' => new external_value(PARAM_RAW, 'The string being searched'),
699 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
700 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
701 )
702 );
703 }
704
705 /**
706 * Get messagearea search messages results.
707 *
708 * @param int $userid The id of the user who is performing the search
709 * @param string $search The string being searched
710 * @param int $limitfrom
711 * @param int $limitnum
712 * @return stdClass
713 * @throws moodle_exception
714 * @since 3.2
715 */
716 public static function data_for_messagearea_search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
837941e9 717 global $CFG, $PAGE, $USER;
cd03b8d7
MN
718
719 // Check if messaging is enabled.
837941e9 720 if (empty($CFG->messaging)) {
cd03b8d7
MN
721 throw new moodle_exception('disabled', 'message');
722 }
723
837941e9
MN
724 $systemcontext = context_system::instance();
725
cd03b8d7
MN
726 $params = array(
727 'userid' => $userid,
728 'search' => $search,
729 'limitfrom' => $limitfrom,
730 'limitnum' => $limitnum
731
732 );
733 self::validate_parameters(self::data_for_messagearea_search_messages_parameters(), $params);
837941e9 734 self::validate_context($systemcontext);
cd03b8d7 735
837941e9
MN
736 if (($USER->id != $userid) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
737 throw new moodle_exception('You do not have permission to perform this action.');
738 }
cd03b8d7 739
de55cb1b
MN
740 $messages = \core_message\api::search_messages($userid, $search, $limitfrom, $limitnum);
741 $results = new \core_message\output\messagearea\message_search_results($messages);
cd03b8d7
MN
742
743 $renderer = $PAGE->get_renderer('core_message');
de55cb1b 744 return $results->export_for_template($renderer);
cd03b8d7
MN
745 }
746
747 /**
748 * Get messagearea search messages returns.
749 *
750 * @return external_single_structure
751 * @since 3.2
752 */
753 public static function data_for_messagearea_search_messages_returns() {
754 return new external_single_structure(
755 array(
cd03b8d7 756 'contacts' => new external_multiple_structure(
a3e3a3a1 757 self::get_messagearea_contact_structure()
cd03b8d7
MN
758 )
759 )
760 );
761 }
762
9aa012b5 763 /**
49aaadc3 764 * The messagearea conversations parameters.
9aa012b5
MN
765 *
766 * @return external_function_parameters
49aaadc3 767 * @since 3.2
9aa012b5
MN
768 */
769 public static function data_for_messagearea_conversations_parameters() {
770 return new external_function_parameters(
771 array(
772 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
773 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
774 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
775 )
776 );
777 }
778
779 /**
780 * Get messagearea conversations.
781 *
782 * @param int $userid The id of the user who we are viewing conversations for
783 * @param int $limitfrom
784 * @param int $limitnum
49aaadc3
MN
785 * @return stdClass
786 * @throws moodle_exception
787 * @since 3.2
9aa012b5
MN
788 */
789 public static function data_for_messagearea_conversations($userid, $limitfrom = 0, $limitnum = 0) {
837941e9 790 global $CFG, $PAGE, $USER;
9aa012b5
MN
791
792 // Check if messaging is enabled.
837941e9 793 if (empty($CFG->messaging)) {
9aa012b5
MN
794 throw new moodle_exception('disabled', 'message');
795 }
796
837941e9
MN
797 $systemcontext = context_system::instance();
798
9aa012b5
MN
799 $params = array(
800 'userid' => $userid,
801 'limitfrom' => $limitfrom,
802 'limitnum' => $limitnum
803 );
804 self::validate_parameters(self::data_for_messagearea_conversations_parameters(), $params);
837941e9 805 self::validate_context($systemcontext);
9aa012b5 806
837941e9
MN
807 if (($USER->id != $userid) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
808 throw new moodle_exception('You do not have permission to perform this action.');
809 }
9aa012b5 810
de55cb1b
MN
811 $conversations = \core_message\api::get_conversations($userid, $limitfrom, $limitnum);
812 $conversations = new \core_message\output\messagearea\contacts(null, $conversations);
9aa012b5
MN
813
814 $renderer = $PAGE->get_renderer('core_message');
de55cb1b 815 return $conversations->export_for_template($renderer);
9aa012b5
MN
816 }
817
818 /**
49aaadc3 819 * The messagearea conversations return structure.
9aa012b5 820 *
49aaadc3
MN
821 * @return external_single_structure
822 * @since 3.2
9aa012b5
MN
823 */
824 public static function data_for_messagearea_conversations_returns() {
49aaadc3 825 return new external_single_structure(
9aa012b5 826 array(
9aa012b5 827 'contacts' => new external_multiple_structure(
a3e3a3a1 828 self::get_messagearea_contact_structure()
9aa012b5
MN
829 )
830 )
831 );
832 }
833
834 /**
49aaadc3 835 * The messagearea contacts return parameters.
9aa012b5
MN
836 *
837 * @return external_function_parameters
49aaadc3 838 * @since 3.2
9aa012b5
MN
839 */
840 public static function data_for_messagearea_contacts_parameters() {
841 return self::data_for_messagearea_conversations_parameters();
842 }
843
844 /**
845 * Get messagearea contacts parameters.
846 *
847 * @param int $userid The id of the user who we are viewing conversations for
848 * @param int $limitfrom
849 * @param int $limitnum
49aaadc3
MN
850 * @return stdClass
851 * @throws moodle_exception
852 * @since 3.2
9aa012b5
MN
853 */
854 public static function data_for_messagearea_contacts($userid, $limitfrom = 0, $limitnum = 0) {
837941e9 855 global $CFG, $PAGE, $USER;
9aa012b5
MN
856
857 // Check if messaging is enabled.
837941e9 858 if (empty($CFG->messaging)) {
9aa012b5
MN
859 throw new moodle_exception('disabled', 'message');
860 }
861
837941e9
MN
862 $systemcontext = context_system::instance();
863
9aa012b5
MN
864 $params = array(
865 'userid' => $userid,
866 'limitfrom' => $limitfrom,
867 'limitnum' => $limitnum
868 );
869 self::validate_parameters(self::data_for_messagearea_contacts_parameters(), $params);
837941e9 870 self::validate_context($systemcontext);
9aa012b5 871
837941e9
MN
872 if (($USER->id != $userid) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
873 throw new moodle_exception('You do not have permission to perform this action.');
874 }
9aa012b5
MN
875
876 $contacts = \core_message\api::get_contacts($userid, $limitfrom, $limitnum);
de55cb1b 877 $contacts = new \core_message\output\messagearea\contacts(null, $contacts);
9aa012b5
MN
878
879 $renderer = $PAGE->get_renderer('core_message');
880 return $contacts->export_for_template($renderer);
881 }
882
883 /**
49aaadc3 884 * The messagearea contacts return structure.
9aa012b5 885 *
49aaadc3
MN
886 * @return external_single_structure
887 * @since 3.2
9aa012b5
MN
888 */
889 public static function data_for_messagearea_contacts_returns() {
890 return self::data_for_messagearea_conversations_returns();
891 }
892
3cd13828 893 /**
49aaadc3 894 * The messagearea messages parameters.
3cd13828
MN
895 *
896 * @return external_function_parameters
49aaadc3 897 * @since 3.2
3cd13828
MN
898 */
899 public static function data_for_messagearea_messages_parameters() {
900 return new external_function_parameters(
901 array(
902 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
903 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
904 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
8ec78c48
MN
905 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0),
906 'newest' => new external_value(PARAM_BOOL, 'Newest first?', VALUE_DEFAULT, false),
ffd7798c 907 'timefrom' => new external_value(PARAM_INT,
fb1469d8 908 'The timestamp from which the messages were created', VALUE_DEFAULT, 0),
3cd13828
MN
909 )
910 );
911 }
912
913 /**
914 * Get messagearea messages.
915 *
916 * @param int $currentuserid The current user's id
917 * @param int $otheruserid The other user's id
918 * @param int $limitfrom
919 * @param int $limitnum
8ec78c48 920 * @param boolean $newest
49aaadc3
MN
921 * @return stdClass
922 * @throws moodle_exception
923 * @since 3.2
3cd13828 924 */
7b55aaa1 925 public static function data_for_messagearea_messages($currentuserid, $otheruserid, $limitfrom = 0, $limitnum = 0,
ffd7798c 926 $newest = false, $timefrom = 0) {
837941e9 927 global $CFG, $PAGE, $USER;
3cd13828
MN
928
929 // Check if messaging is enabled.
837941e9 930 if (empty($CFG->messaging)) {
3cd13828
MN
931 throw new moodle_exception('disabled', 'message');
932 }
933
837941e9
MN
934 $systemcontext = context_system::instance();
935
3cd13828
MN
936 $params = array(
937 'currentuserid' => $currentuserid,
938 'otheruserid' => $otheruserid,
939 'limitfrom' => $limitfrom,
8ec78c48 940 'limitnum' => $limitnum,
fb1469d8 941 'newest' => $newest,
ffd7798c 942 'timefrom' => $timefrom,
3cd13828
MN
943 );
944 self::validate_parameters(self::data_for_messagearea_messages_parameters(), $params);
837941e9 945 self::validate_context($systemcontext);
3cd13828 946
837941e9
MN
947 if (($USER->id != $currentuserid) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
948 throw new moodle_exception('You do not have permission to perform this action.');
949 }
3cd13828 950
8ec78c48
MN
951 if ($newest) {
952 $sort = 'timecreated DESC';
953 } else {
954 $sort = 'timecreated ASC';
955 }
fb1469d8
RW
956
957 // We need to enforce a one second delay on messages to avoid race conditions of current
958 // messages still being sent.
959 //
960 // There is a chance that we could request messages before the current time's
961 // second has elapsed and while other messages are being sent in that same second. In which
962 // case those messages will be lost.
963 //
964 // Instead we ignore the current time in the result set to ensure that second is allowed to finish.
ffd7798c
MN
965 if (!empty($timefrom)) {
966 $timeto = time() - 1;
fb1469d8 967 } else {
ffd7798c 968 $timeto = 0;
fb1469d8
RW
969 }
970
971 // No requesting messages from the current time, as stated above.
ffd7798c
MN
972 if ($timefrom == time()) {
973 $messages = [];
fb1469d8
RW
974 } else {
975 $messages = \core_message\api::get_messages($currentuserid, $otheruserid, $limitfrom,
ffd7798c 976 $limitnum, $sort, $timefrom, $timeto);
fb1469d8
RW
977 }
978
de55cb1b 979 $messages = new \core_message\output\messagearea\messages($currentuserid, $otheruserid, $messages);
3cd13828
MN
980
981 $renderer = $PAGE->get_renderer('core_message');
982 return $messages->export_for_template($renderer);
983 }
984
985 /**
49aaadc3 986 * The messagearea messages return structure.
3cd13828 987 *
49aaadc3
MN
988 * @return external_single_structure
989 * @since 3.2
3cd13828
MN
990 */
991 public static function data_for_messagearea_messages_returns() {
49aaadc3 992 return new external_single_structure(
3cd13828 993 array(
7b55aaa1
MN
994 'iscurrentuser' => new external_value(PARAM_BOOL, 'Is the currently logged in user the user we are viewing
995 the messages on behalf of?'),
3cd13828
MN
996 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
997 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
998 'otheruserfullname' => new external_value(PARAM_NOTAGS, 'The other user\'s fullname'),
cb805753 999 'showonlinestatus' => new external_value(PARAM_BOOL, 'Show the user\'s online status?'),
bf58081d 1000 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status'),
3cd13828 1001 'messages' => new external_multiple_structure(
94e1db61 1002 self::get_messagearea_message_structure()
26dca05d
JP
1003 ),
1004 'isblocked' => new external_value(PARAM_BOOL, 'Is this user blocked by the current user?', VALUE_DEFAULT, false),
3cd13828
MN
1005 )
1006 );
1007 }
1008
c060cd49 1009 /**
49aaadc3 1010 * The get most recent message return parameters.
c060cd49
MN
1011 *
1012 * @return external_function_parameters
49aaadc3 1013 * @since 3.2
c060cd49
MN
1014 */
1015 public static function data_for_messagearea_get_most_recent_message_parameters() {
1016 return new external_function_parameters(
1017 array(
1018 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
1019 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
1020 )
1021 );
1022 }
1023
1024 /**
1025 * Get the most recent message in a conversation.
1026 *
1027 * @param int $currentuserid The current user's id
1028 * @param int $otheruserid The other user's id
49aaadc3
MN
1029 * @return stdClass
1030 * @throws moodle_exception
1031 * @since 3.2
c060cd49
MN
1032 */
1033 public static function data_for_messagearea_get_most_recent_message($currentuserid, $otheruserid) {
837941e9 1034 global $CFG, $PAGE, $USER;
c060cd49
MN
1035
1036 // Check if messaging is enabled.
837941e9 1037 if (empty($CFG->messaging)) {
c060cd49
MN
1038 throw new moodle_exception('disabled', 'message');
1039 }
1040
837941e9
MN
1041 $systemcontext = context_system::instance();
1042
c060cd49
MN
1043 $params = array(
1044 'currentuserid' => $currentuserid,
1045 'otheruserid' => $otheruserid
1046 );
1047 self::validate_parameters(self::data_for_messagearea_get_most_recent_message_parameters(), $params);
837941e9 1048 self::validate_context($systemcontext);
c060cd49 1049
837941e9
MN
1050 if (($USER->id != $currentuserid) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
1051 throw new moodle_exception('You do not have permission to perform this action.');
1052 }
c060cd49
MN
1053
1054 $message = \core_message\api::get_most_recent_message($currentuserid, $otheruserid);
de55cb1b 1055 $message = new \core_message\output\messagearea\message($message);
c060cd49
MN
1056
1057 $renderer = $PAGE->get_renderer('core_message');
1058 return $message->export_for_template($renderer);
1059 }
1060
1061 /**
49aaadc3 1062 * The get most recent message return structure.
c060cd49
MN
1063 *
1064 * @return external_single_structure
49aaadc3 1065 * @since 3.2
c060cd49
MN
1066 */
1067 public static function data_for_messagearea_get_most_recent_message_returns() {
94e1db61 1068 return self::get_messagearea_message_structure();
c060cd49
MN
1069 }
1070
c6e97f54
MN
1071 /**
1072 * The get profile parameters.
1073 *
1074 * @return external_function_parameters
49aaadc3 1075 * @since 3.2
c6e97f54
MN
1076 */
1077 public static function data_for_messagearea_get_profile_parameters() {
1078 return new external_function_parameters(
1079 array(
1080 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
1081 'otheruserid' => new external_value(PARAM_INT, 'The id of the user whose profile we want to view'),
1082 )
1083 );
1084 }
1085
1086 /**
1087 * Get the profile information for a contact.
1088 *
1089 * @param int $currentuserid The current user's id
1090 * @param int $otheruserid The id of the user whose profile we are viewing
49aaadc3
MN
1091 * @return stdClass
1092 * @throws moodle_exception
1093 * @since 3.2
c6e97f54
MN
1094 */
1095 public static function data_for_messagearea_get_profile($currentuserid, $otheruserid) {
837941e9 1096 global $CFG, $PAGE, $USER;
c6e97f54
MN
1097
1098 // Check if messaging is enabled.
837941e9 1099 if (empty($CFG->messaging)) {
c6e97f54
MN
1100 throw new moodle_exception('disabled', 'message');
1101 }
1102
837941e9
MN
1103 $systemcontext = context_system::instance();
1104
c6e97f54
MN
1105 $params = array(
1106 'currentuserid' => $currentuserid,
1107 'otheruserid' => $otheruserid
1108 );
1109 self::validate_parameters(self::data_for_messagearea_get_profile_parameters(), $params);
837941e9 1110 self::validate_context($systemcontext);
c6e97f54 1111
837941e9
MN
1112 if (($USER->id != $currentuserid) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
1113 throw new moodle_exception('You do not have permission to perform this action.');
1114 }
c6e97f54
MN
1115
1116 $profile = \core_message\api::get_profile($currentuserid, $otheruserid);
de55cb1b 1117 $profile = new \core_message\output\messagearea\profile($profile);
c6e97f54
MN
1118
1119 $renderer = $PAGE->get_renderer('core_message');
1120 return $profile->export_for_template($renderer);
1121 }
1122
1123 /**
49aaadc3 1124 * The get profile return structure.
c6e97f54
MN
1125 *
1126 * @return external_single_structure
49aaadc3 1127 * @since 3.2
c6e97f54
MN
1128 */
1129 public static function data_for_messagearea_get_profile_returns() {
1130 return new external_single_structure(
1131 array(
de55cb1b 1132 'userid' => new external_value(PARAM_INT, 'The id of the user whose profile we are viewing'),
c6e97f54 1133 'email' => new external_value(core_user::get_property_type('email'), 'An email address'),
cc22b515 1134 'country' => new external_value(PARAM_TEXT, 'Home country of the user'),
c6e97f54
MN
1135 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user'),
1136 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
1137 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
1138 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
cb805753 1139 'showonlinestatus' => new external_value(PARAM_BOOL, 'Show the user\'s online status?'),
bf58081d 1140 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status'),
c6e97f54
MN
1141 'isblocked' => new external_value(PARAM_BOOL, 'Is the user blocked?'),
1142 'iscontact' => new external_value(PARAM_BOOL, 'Is the user a contact?')
1143 )
1144 );
1145 }
1146
d6731600
FM
1147 /**
1148 * Get contacts parameters description.
1149 *
1150 * @return external_function_parameters
5bcfd504 1151 * @since Moodle 2.5
d6731600
FM
1152 */
1153 public static function get_contacts_parameters() {
1154 return new external_function_parameters(array());
1155 }
1156
1157 /**
1158 * Get contacts.
1159 *
d6731600 1160 * @return external_description
5bcfd504 1161 * @since Moodle 2.5
d6731600
FM
1162 */
1163 public static function get_contacts() {
883ce421 1164 global $CFG, $PAGE, $USER;
436bbf89
DM
1165
1166 // Check if messaging is enabled.
837941e9 1167 if (empty($CFG->messaging)) {
436bbf89
DM
1168 throw new moodle_exception('disabled', 'message');
1169 }
1170
d6731600
FM
1171 require_once($CFG->dirroot . '/user/lib.php');
1172
883ce421
MN
1173 $allcontacts = array('online' => [], 'offline' => [], 'strangers' => []);
1174 $contacts = \core_message\api::get_contacts_with_unread_message_count($USER->id);
1175 foreach ($contacts as $contact) {
1176 // Set the mode.
1177 $mode = 'offline';
1178 if (\core_message\helper::is_online($contact->lastaccess)) {
1179 $mode = 'online';
1180 }
1181
1182 $newcontact = array(
1183 'id' => $contact->id,
1184 'fullname' => fullname($contact),
1185 'unread' => $contact->messagecount
1186 );
1187
1188 $userpicture = new user_picture($contact);
1189 $userpicture->size = 1; // Size f1.
1190 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1191 $userpicture->size = 0; // Size f2.
1192 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
1193
1194 $allcontacts[$mode][$contact->id] = $newcontact;
1195 }
1196
1197 $strangers = \core_message\api::get_non_contacts_with_unread_message_count($USER->id);
1198 foreach ($strangers as $contact) {
1199 $newcontact = array(
1200 'id' => $contact->id,
1201 'fullname' => fullname($contact),
1202 'unread' => $contact->messagecount
1203 );
1204
1205 $userpicture = new user_picture($contact);
1206 $userpicture->size = 1; // Size f1.
1207 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1208 $userpicture->size = 0; // Size f2.
1209 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600 1210
883ce421
MN
1211 $allcontacts['strangers'][$contact->id] = $newcontact;
1212 }
d6731600 1213
883ce421
MN
1214 // Add noreply user and support user to the list, if they don't exist.
1215 $supportuser = core_user::get_support_user();
1216 if (!isset($strangers[$supportuser->id]) && !$supportuser->deleted) {
1217 $supportuser->messagecount = message_count_unread_messages($USER, $supportuser);
1218 if ($supportuser->messagecount > 0) {
1219 $supportuser->fullname = fullname($supportuser);
1220 $supportuser->unread = $supportuser->messagecount;
1221 $allcontacts['strangers'][$supportuser->id] = $supportuser;
d6731600
FM
1222 }
1223 }
883ce421
MN
1224
1225 $noreplyuser = core_user::get_noreply_user();
1226 if (!isset($strangers[$noreplyuser->id]) && !$noreplyuser->deleted) {
1227 $noreplyuser->messagecount = message_count_unread_messages($USER, $noreplyuser);
1228 if ($noreplyuser->messagecount > 0) {
1229 $noreplyuser->fullname = fullname($noreplyuser);
1230 $noreplyuser->unread = $noreplyuser->messagecount;
1231 $allcontacts['strangers'][$noreplyuser->id] = $noreplyuser;
1232 }
1233 }
1234
d6731600
FM
1235 return $allcontacts;
1236 }
1237
1238 /**
1239 * Get contacts return description.
1240 *
1241 * @return external_description
5bcfd504 1242 * @since Moodle 2.5
d6731600
FM
1243 */
1244 public static function get_contacts_returns() {
1245 return new external_single_structure(
1246 array(
1247 'online' => new external_multiple_structure(
1248 new external_single_structure(
1249 array(
1250 'id' => new external_value(PARAM_INT, 'User ID'),
1251 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1252 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
1253 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
1254 'unread' => new external_value(PARAM_INT, 'Unread message count')
1255 )
1256 ),
1257 'List of online contacts'
1258 ),
1259 'offline' => new external_multiple_structure(
1260 new external_single_structure(
1261 array(
1262 'id' => new external_value(PARAM_INT, 'User ID'),
1263 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1264 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
1265 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
1266 'unread' => new external_value(PARAM_INT, 'Unread message count')
1267 )
1268 ),
1269 'List of offline contacts'
1270 ),
1271 'strangers' => new external_multiple_structure(
1272 new external_single_structure(
1273 array(
1274 'id' => new external_value(PARAM_INT, 'User ID'),
1275 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1276 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
1277 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
1278 'unread' => new external_value(PARAM_INT, 'Unread message count')
1279 )
1280 ),
1281 'List of users that are not in the user\'s contact list but have sent a message'
1282 )
1283 )
1284 );
1285 }
1286
1287 /**
1288 * Search contacts parameters description.
1289 *
1290 * @return external_function_parameters
5bcfd504 1291 * @since Moodle 2.5
d6731600
FM
1292 */
1293 public static function search_contacts_parameters() {
1294 return new external_function_parameters(
1295 array(
1296 'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
1297 'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
1298 VALUE_DEFAULT, false)
1299 )
1300 );
1301 }
1302
1303 /**
1304 * Search contacts.
1305 *
1306 * @param string $searchtext query string.
1307 * @param bool $onlymycourses limit the search to the user's courses only.
1308 * @return external_description
5bcfd504 1309 * @since Moodle 2.5
d6731600
FM
1310 */
1311 public static function search_contacts($searchtext, $onlymycourses = false) {
d85bedf7 1312 global $CFG, $USER, $PAGE;
11d83ab3 1313 require_once($CFG->dirroot . '/user/lib.php');
436bbf89
DM
1314
1315 // Check if messaging is enabled.
837941e9 1316 if (empty($CFG->messaging)) {
436bbf89
DM
1317 throw new moodle_exception('disabled', 'message');
1318 }
1319
d6731600
FM
1320 require_once($CFG->libdir . '/enrollib.php');
1321
1322 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
1323 $params = self::validate_parameters(self::search_contacts_parameters(), $params);
1324
1325 // Extra validation, we do not allow empty queries.
1326 if ($params['searchtext'] === '') {
1327 throw new moodle_exception('querystringcannotbeempty');
1328 }
1329
1330 $courseids = array();
1331 if ($params['onlymycourses']) {
1332 $mycourses = enrol_get_my_courses(array('id'));
1333 foreach ($mycourses as $mycourse) {
1334 $courseids[] = $mycourse->id;
1335 }
1336 } else {
1337 $courseids[] = SITEID;
1338 }
1339
1340 // Retrieving the users matching the query.
1341 $users = message_search_users($courseids, $params['searchtext']);
1342 $results = array();
1343 foreach ($users as $user) {
1344 $results[$user->id] = $user;
1345 }
1346
1347 // Reorganising information.
1348 foreach ($results as &$user) {
1349 $newuser = array(
1350 'id' => $user->id,
1351 'fullname' => fullname($user)
1352 );
1353
1354 // Avoid undefined property notice as phone not specified.
1355 $user->phone1 = null;
1356 $user->phone2 = null;
1357
d85bedf7
JL
1358 $userpicture = new user_picture($user);
1359 $userpicture->size = 1; // Size f1.
1360 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1361 $userpicture->size = 0; // Size f2.
1362 $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
1363
1364 $user = $newuser;
1365 }
1366
1367 return $results;
1368 }
1369
1370 /**
1371 * Search contacts return description.
1372 *
1373 * @return external_description
5bcfd504 1374 * @since Moodle 2.5
d6731600
FM
1375 */
1376 public static function search_contacts_returns() {
1377 return new external_multiple_structure(
1378 new external_single_structure(
1379 array(
1380 'id' => new external_value(PARAM_INT, 'User ID'),
1381 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1382 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
1383 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
1384 )
1385 ),
1386 'List of contacts'
1387 );
1388 }
aff9da17
JL
1389
1390 /**
1391 * Get messages parameters description.
1392 *
1393 * @return external_function_parameters
193edf7f 1394 * @since 2.8
aff9da17
JL
1395 */
1396 public static function get_messages_parameters() {
1397 return new external_function_parameters(
1398 array(
6ff4464b 1399 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
127ef540
SH
1400 'useridfrom' => new external_value(
1401 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1402 VALUE_DEFAULT, 0),
1403 'type' => new external_value(
1404 PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
1405 VALUE_DEFAULT, 'both'),
6ff4464b 1406 'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
127ef540
SH
1407 'newestfirst' => new external_value(
1408 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
1409 VALUE_DEFAULT, true),
aff9da17 1410 'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
127ef540
SH
1411 'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
1412 )
aff9da17
JL
1413 );
1414 }
1415
1416 /**
1417 * Get messages function implementation.
127ef540
SH
1418 *
1419 * @since 2.8
1420 * @throws invalid_parameter_exception
1421 * @throws moodle_exception
6ff4464b
JL
1422 * @param int $useridto the user id who received the message
1423 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
193edf7f 1424 * @param string $type type of message to return, expected values: notifications, conversations and both
aff9da17 1425 * @param bool $read true for retreiving read messages, false for unread
6ff4464b 1426 * @param bool $newestfirst true for ordering by newest first, false for oldest first
aff9da17
JL
1427 * @param int $limitfrom limit from
1428 * @param int $limitnum limit num
1429 * @return external_description
aff9da17 1430 */
193edf7f 1431 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
aff9da17 1432 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
127ef540 1433 global $CFG, $USER;
aff9da17
JL
1434
1435 $warnings = array();
1436
1437 $params = array(
1438 'useridto' => $useridto,
6ff4464b 1439 'useridfrom' => $useridfrom,
aff9da17
JL
1440 'type' => $type,
1441 'read' => $read,
aff9da17
JL
1442 'newestfirst' => $newestfirst,
1443 'limitfrom' => $limitfrom,
1444 'limitnum' => $limitnum
1445 );
1446
1447 $params = self::validate_parameters(self::get_messages_parameters(), $params);
1448
1449 $context = context_system::instance();
1450 self::validate_context($context);
1451
1452 $useridto = $params['useridto'];
6ff4464b 1453 $useridfrom = $params['useridfrom'];
aff9da17
JL
1454 $type = $params['type'];
1455 $read = $params['read'];
aff9da17
JL
1456 $newestfirst = $params['newestfirst'];
1457 $limitfrom = $params['limitfrom'];
1458 $limitnum = $params['limitnum'];
1459
1460 $allowedvalues = array('notifications', 'conversations', 'both');
1461 if (!in_array($type, $allowedvalues)) {
1462 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
1463 'allowed values are: ' . implode(',', $allowedvalues));
1464 }
1465
1466 // Check if private messaging between users is allowed.
1467 if (empty($CFG->messaging)) {
1468 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
aff9da17
JL
1469 if ($type == "conversations") {
1470 throw new moodle_exception('disabled', 'message');
1471 }
1472 if ($type == "both") {
1473 $warning = array();
1474 $warning['item'] = 'message';
1475 $warning['itemid'] = $USER->id;
1476 $warning['warningcode'] = '1';
1477 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
1478 Only notifications will be returned';
1479 $warnings[] = $warning;
1480 }
1481 }
1482
1483 if (!empty($useridto)) {
6ff4464b
JL
1484 if (core_user::is_real_user($useridto)) {
1485 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1486 } else {
1487 throw new moodle_exception('invaliduser');
1488 }
aff9da17
JL
1489 }
1490
1491 if (!empty($useridfrom)) {
1492 // We use get_user here because the from user can be the noreply or support user.
1493 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1494 }
1495
1496 // Check if the current user is the sender/receiver or just a privileged user.
1497 if ($useridto != $USER->id and $useridfrom != $USER->id and
1498 !has_capability('moodle/site:readallmessages', $context)) {
1499 throw new moodle_exception('accessdenied', 'admin');
1500 }
1501
127ef540 1502 // Which type of messages to retrieve.
193edf7f 1503 $notifications = -1;
aff9da17 1504 if ($type != 'both') {
193edf7f 1505 $notifications = ($type == 'notifications') ? 1 : 0;
aff9da17
JL
1506 }
1507
aff9da17 1508 $orderdirection = $newestfirst ? 'DESC' : 'ASC';
193edf7f 1509 $sort = "mr.timecreated $orderdirection";
aff9da17 1510
193edf7f 1511 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
aff9da17
JL
1512 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
1513
1514 // In some cases, we don't need to get the to/from user objects from the sql query.
1515 $userfromfullname = '';
1516 $usertofullname = '';
1517
1518 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
1519 if (!empty($useridto)) {
1520 $usertofullname = fullname($userto, $canviewfullname);
1521 // The user from may or may not be filled.
1522 if (!empty($useridfrom)) {
1523 $userfromfullname = fullname($userfrom, $canviewfullname);
1524 }
1525 } else {
1526 // If the useridto field is empty, the useridfrom must be filled.
1527 $userfromfullname = fullname($userfrom, $canviewfullname);
1528 }
aff9da17
JL
1529 foreach ($messages as $mid => $message) {
1530
ea21d637 1531 // Do not return deleted messages.
883ce421
MN
1532 if (!$message->notification) {
1533 if (($useridto == $USER->id and $message->timeusertodeleted) or
ea21d637 1534 ($useridfrom == $USER->id and $message->timeuserfromdeleted)) {
883ce421
MN
1535 unset($messages[$mid]);
1536 continue;
1537 }
ea21d637
JL
1538 }
1539
883ce421
MN
1540 $message->useridto = $useridto;
1541
aff9da17
JL
1542 // We need to get the user from the query.
1543 if (empty($userfromfullname)) {
6ff4464b
JL
1544 // Check for non-reply and support users.
1545 if (core_user::is_real_user($message->useridfrom)) {
127ef540 1546 $user = new stdClass();
6ff4464b
JL
1547 $user = username_load_fields_from_object($user, $message, 'userfrom');
1548 $message->userfromfullname = fullname($user, $canviewfullname);
1549 } else {
1550 $user = core_user::get_user($message->useridfrom);
1551 $message->userfromfullname = fullname($user, $canviewfullname);
1552 }
aff9da17
JL
1553 } else {
1554 $message->userfromfullname = $userfromfullname;
1555 }
1556
1557 // We need to get the user from the query.
1558 if (empty($usertofullname)) {
127ef540 1559 $user = new stdClass();
aff9da17
JL
1560 $user = username_load_fields_from_object($user, $message, 'userto');
1561 $message->usertofullname = fullname($user, $canviewfullname);
1562 } else {
1563 $message->usertofullname = $usertofullname;
1564 }
1565
aff9da17 1566 $message->text = message_format_message_text($message);
aff9da17
JL
1567 $messages[$mid] = (array) $message;
1568 }
1569 }
1570
1571 $results = array(
1572 'messages' => $messages,
1573 'warnings' => $warnings
1574 );
1575
1576 return $results;
1577 }
1578
1579 /**
1580 * Get messages return description.
1581 *
6ff4464b 1582 * @return external_single_structure
193edf7f 1583 * @since 2.8
aff9da17
JL
1584 */
1585 public static function get_messages_returns() {
1586 return new external_single_structure(
1587 array(
1588 'messages' => new external_multiple_structure(
1589 new external_single_structure(
1590 array(
193edf7f 1591 'id' => new external_value(PARAM_INT, 'Message id'),
aff9da17
JL
1592 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
1593 'useridto' => new external_value(PARAM_INT, 'User to id'),
1594 'subject' => new external_value(PARAM_TEXT, 'The message subject'),
1595 'text' => new external_value(PARAM_RAW, 'The message text formated'),
1596 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
193edf7f 1597 'fullmessageformat' => new external_format_value('fullmessage'),
aff9da17
JL
1598 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
1599 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
1600 'notification' => new external_value(PARAM_INT, 'Is a notification?'),
1601 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
1602 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
1603 'timecreated' => new external_value(PARAM_INT, 'Time created'),
1604 'timeread' => new external_value(PARAM_INT, 'Time read'),
1605 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
1606 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
1607 ), 'message'
1608 )
1609 ),
1610 'warnings' => new external_warnings()
1611 )
1612 );
3274d5ca
RW
1613 }
1614
3274d5ca
RW
1615 /**
1616 * Mark all notifications as read parameters description.
1617 *
1618 * @return external_function_parameters
1619 * @since 3.2
1620 */
1621 public static function mark_all_notifications_as_read_parameters() {
1622 return new external_function_parameters(
1623 array(
1624 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1625 'useridfrom' => new external_value(
1626 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1627 VALUE_DEFAULT, 0),
1628 )
1629 );
1630 }
1631
1632 /**
1633 * Mark all notifications as read function.
1634 *
1635 * @since 3.2
1636 * @throws invalid_parameter_exception
1637 * @throws moodle_exception
1638 * @param int $useridto the user id who received the message
1639 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1640 * @return external_description
1641 */
1642 public static function mark_all_notifications_as_read($useridto, $useridfrom) {
837941e9 1643 global $USER;
3274d5ca
RW
1644
1645 $params = self::validate_parameters(
1646 self::mark_all_notifications_as_read_parameters(),
1647 array(
1648 'useridto' => $useridto,
1649 'useridfrom' => $useridfrom,
1650 )
1651 );
1652
1653 $context = context_system::instance();
1654 self::validate_context($context);
1655
1656 $useridto = $params['useridto'];
1657 $useridfrom = $params['useridfrom'];
1658
1659 if (!empty($useridto)) {
1660 if (core_user::is_real_user($useridto)) {
1661 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1662 } else {
1663 throw new moodle_exception('invaliduser');
1664 }
1665 }
1666
1667 if (!empty($useridfrom)) {
1668 // We use get_user here because the from user can be the noreply or support user.
1669 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1670 }
1671
1672 // Check if the current user is the sender/receiver or just a privileged user.
1673 if ($useridto != $USER->id and $useridfrom != $USER->id and
7b55aaa1 1674 // The deleteanymessage cap seems more reasonable here than readallmessages.
3274d5ca
RW
1675 !has_capability('moodle/site:deleteanymessage', $context)) {
1676 throw new moodle_exception('accessdenied', 'admin');
1677 }
1678
79f6c36c 1679 \core_message\api::mark_all_read_for_user($useridto, $useridfrom, MESSAGE_TYPE_NOTIFICATION);
3274d5ca
RW
1680
1681 return true;
1682 }
1683
1684 /**
1685 * Mark all notifications as read return description.
1686 *
1687 * @return external_single_structure
1688 * @since 3.2
1689 */
1690 public static function mark_all_notifications_as_read_returns() {
1691 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
1692 }
1693
8c55bd6c
RW
1694 /**
1695 * Get unread conversations count parameters description.
1696 *
1697 * @return external_function_parameters
1698 * @since 3.2
1699 */
1700 public static function get_unread_conversations_count_parameters() {
1701 return new external_function_parameters(
1702 array(
1703 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1704 )
1705 );
1706 }
1707
1708 /**
1709 * Get unread messages count function.
1710 *
1711 * @since 3.2
1712 * @throws invalid_parameter_exception
1713 * @throws moodle_exception
1714 * @param int $useridto the user id who received the message
1715 * @return external_description
1716 */
1717 public static function get_unread_conversations_count($useridto) {
a2c7227a
SL
1718 global $USER, $CFG;
1719
1720 // Check if messaging is enabled.
1721 if (empty($CFG->messaging)) {
1722 throw new moodle_exception('disabled', 'message');
1723 }
8c55bd6c
RW
1724
1725 $params = self::validate_parameters(
1726 self::get_unread_conversations_count_parameters(),
1727 array('useridto' => $useridto)
1728 );
1729
1730 $context = context_system::instance();
1731 self::validate_context($context);
1732
1733 $useridto = $params['useridto'];
1734
1735 if (!empty($useridto)) {
1736 if (core_user::is_real_user($useridto)) {
1737 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1738 } else {
1739 throw new moodle_exception('invaliduser');
1740 }
1741 } else {
1742 $useridto = $USER->id;
1743 }
1744
1745 // Check if the current user is the receiver or just a privileged user.
1746 if ($useridto != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
1747 throw new moodle_exception('accessdenied', 'admin');
1748 }
1749
79f6c36c 1750 return \core_message\api::count_unread_conversations($userto);
8c55bd6c
RW
1751 }
1752
1753 /**
1754 * Get unread conversations count return description.
1755 *
1756 * @return external_single_structure
1757 * @since 3.2
1758 */
1759 public static function get_unread_conversations_count_returns() {
1760 return new external_value(PARAM_INT, 'The count of unread messages for the user');
aff9da17
JL
1761 }
1762
60ab2e1b
JL
1763 /**
1764 * Get blocked users parameters description.
1765 *
1766 * @return external_function_parameters
1767 * @since 2.9
1768 */
1769 public static function get_blocked_users_parameters() {
1770 return new external_function_parameters(
1771 array(
1772 'userid' => new external_value(PARAM_INT,
1773 'the user whose blocked users we want to retrieve',
1774 VALUE_REQUIRED),
1775 )
1776 );
1777 }
1778
1779 /**
1780 * Retrieve a list of users blocked
1781 *
1782 * @param int $userid the user whose blocked users we want to retrieve
1783 * @return external_description
1784 * @since 2.9
1785 */
1786 public static function get_blocked_users($userid) {
d85bedf7 1787 global $CFG, $USER, $PAGE;
60ab2e1b
JL
1788
1789 // Warnings array, it can be empty at the end but is mandatory.
1790 $warnings = array();
1791
1792 // Validate params.
1793 $params = array(
1794 'userid' => $userid
1795 );
1796 $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
1797 $userid = $params['userid'];
1798
1799 // Validate context.
1800 $context = context_system::instance();
1801 self::validate_context($context);
1802
1803 // Check if private messaging between users is allowed.
1804 if (empty($CFG->messaging)) {
1805 throw new moodle_exception('disabled', 'message');
1806 }
1807
4485f7c5
JL
1808 $user = core_user::get_user($userid, '*', MUST_EXIST);
1809 core_user::require_active_user($user);
60ab2e1b
JL
1810
1811 // Check if we have permissions for retrieve the information.
343ba16c
SL
1812 $capability = 'moodle/site:manageallmessaging';
1813 if (($USER->id != $userid) && !has_capability($capability, $context)) {
1814 throw new required_capability_exception($context, $capability, 'nopermissions', '');
60ab2e1b
JL
1815 }
1816
1817 // Now, we can get safely all the blocked users.
883ce421 1818 $users = \core_message\api::get_blocked_users($user->id);
60ab2e1b
JL
1819
1820 $blockedusers = array();
1821 foreach ($users as $user) {
1822 $newuser = array(
1823 'id' => $user->id,
1824 'fullname' => fullname($user),
1825 );
0b074e88 1826
d85bedf7
JL
1827 $userpicture = new user_picture($user);
1828 $userpicture->size = 1; // Size f1.
1829 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
60ab2e1b
JL
1830
1831 $blockedusers[] = $newuser;
1832 }
1833
1834 $results = array(
1835 'users' => $blockedusers,
1836 'warnings' => $warnings
1837 );
1838 return $results;
1839 }
1840
1841 /**
1842 * Get blocked users return description.
1843 *
1844 * @return external_single_structure
1845 * @since 2.9
1846 */
1847 public static function get_blocked_users_returns() {
1848 return new external_single_structure(
1849 array(
1850 'users' => new external_multiple_structure(
1851 new external_single_structure(
1852 array(
1853 'id' => new external_value(PARAM_INT, 'User ID'),
1854 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1855 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL)
1856 )
1857 ),
1858 'List of blocked users'
1859 ),
1860 'warnings' => new external_warnings()
1861 )
1862 );
1863 }
1864
31c474da
JL
1865 /**
1866 * Returns description of method parameters
1867 *
1868 * @return external_function_parameters
1869 * @since 2.9
1870 */
1871 public static function mark_message_read_parameters() {
1872 return new external_function_parameters(
1873 array(
2b595d96 1874 'messageid' => new external_value(PARAM_INT, 'id of the message in the messages table'),
7b55aaa1
MN
1875 'timeread' => new external_value(PARAM_INT, 'timestamp for when the message should be marked read',
1876 VALUE_DEFAULT, 0)
31c474da
JL
1877 )
1878 );
1879 }
1880
1881 /**
1882 * Mark a single message as read, trigger message_viewed event
1883 *
1884 * @param int $messageid id of the message (in the message table)
1885 * @param int $timeread timestamp for when the message should be marked read
1886 * @return external_description
1887 * @throws invalid_parameter_exception
1888 * @throws moodle_exception
1889 * @since 2.9
1890 */
1891 public static function mark_message_read($messageid, $timeread) {
1892 global $CFG, $DB, $USER;
31c474da
JL
1893
1894 // Check if private messaging between users is allowed.
1895 if (empty($CFG->messaging)) {
1896 throw new moodle_exception('disabled', 'message');
1897 }
1898
1899 // Warnings array, it can be empty at the end but is mandatory.
1900 $warnings = array();
1901
1902 // Validate params.
1903 $params = array(
1904 'messageid' => $messageid,
1905 'timeread' => $timeread
1906 );
1907 $params = self::validate_parameters(self::mark_message_read_parameters(), $params);
1908
0b19d048
RW
1909 if (empty($params['timeread'])) {
1910 $timeread = time();
1911 } else {
1912 $timeread = $params['timeread'];
1913 }
1914
31c474da
JL
1915 // Validate context.
1916 $context = context_system::instance();
1917 self::validate_context($context);
1918
883ce421
MN
1919 $sql = "SELECT m.*, mcm.userid as useridto
1920 FROM {messages} m
1921 INNER JOIN {message_conversations} mc
1922 ON m.conversationid = mc.id
1923 INNER JOIN {message_conversation_members} mcm
1924 ON mcm.conversationid = mc.id
1925 WHERE mcm.userid != m.useridfrom
1926 AND m.id = ?";
1927 $message = $DB->get_record_sql($sql, [$params['messageid']], MUST_EXIST);
31c474da
JL
1928
1929 if ($message->useridto != $USER->id) {
1930 throw new invalid_parameter_exception('Invalid messageid, you don\'t have permissions to mark this message as read');
1931 }
1932
548936a6 1933 \core_message\api::mark_message_as_read($USER->id, $message, $timeread);
31c474da
JL
1934
1935 $results = array(
883ce421 1936 'messageid' => $message->id,
31c474da
JL
1937 'warnings' => $warnings
1938 );
1939 return $results;
1940 }
1941
1942 /**
1943 * Returns description of method result value
1944 *
1945 * @return external_description
1946 * @since 2.9
1947 */
1948 public static function mark_message_read_returns() {
1949 return new external_single_structure(
1950 array(
2b595d96
MN
1951 'messageid' => new external_value(PARAM_INT, 'the id of the message in the messages table'),
1952 'warnings' => new external_warnings()
1953 )
1954 );
1955 }
1956
1957 /**
1958 * Returns description of method parameters
1959 *
1960 * @return external_function_parameters
1961 */
1962 public static function mark_notification_read_parameters() {
1963 return new external_function_parameters(
1964 array(
1965 'notificationid' => new external_value(PARAM_INT, 'id of the notification'),
1966 'timeread' => new external_value(PARAM_INT, 'timestamp for when the notification should be marked read',
1967 VALUE_DEFAULT, 0)
1968 )
1969 );
1970 }
1971
1972 /**
1973 * Mark a single notification as read.
1974 *
1975 * This will trigger a 'notification_viewed' event.
1976 *
1977 * @param int $notificationid id of the notification
1978 * @param int $timeread timestamp for when the notification should be marked read
1979 * @return external_description
1980 * @throws invalid_parameter_exception
1981 * @throws moodle_exception
1982 */
1983 public static function mark_notification_read($notificationid, $timeread) {
1984 global $CFG, $DB, $USER;
1985
1986 // Check if private messaging between users is allowed.
1987 if (empty($CFG->messaging)) {
1988 throw new moodle_exception('disabled', 'message');
1989 }
1990
1991 // Warnings array, it can be empty at the end but is mandatory.
1992 $warnings = array();
1993
1994 // Validate params.
1995 $params = array(
1996 'notificationid' => $notificationid,
1997 'timeread' => $timeread
1998 );
1999 $params = self::validate_parameters(self::mark_notification_read_parameters(), $params);
2000
2001 if (empty($params['timeread'])) {
2002 $timeread = time();
2003 } else {
2004 $timeread = $params['timeread'];
2005 }
2006
2007 // Validate context.
2008 $context = context_system::instance();
2009 self::validate_context($context);
2010
2011 $notification = $DB->get_record('notifications', ['id' => $params['notificationid']], '*', MUST_EXIST);
2012
2013 if ($notification->useridto != $USER->id) {
2014 throw new invalid_parameter_exception('Invalid notificationid, you don\'t have permissions to mark this ' .
2015 'notification as read');
2016 }
2017
2018 \core_message\api::mark_notification_as_read($notification, $timeread);
2019
2020 $results = array(
2021 'notificationid' => $notification->id,
2022 'warnings' => $warnings
2023 );
2024
2025 return $results;
2026 }
2027
2028 /**
2029 * Returns description of method result value
2030 *
2031 * @return external_description
2032 */
2033 public static function mark_notification_read_returns() {
2034 return new external_single_structure(
2035 array(
2036 'notificationid' => new external_value(PARAM_INT, 'id of the notification'),
31c474da
JL
2037 'warnings' => new external_warnings()
2038 )
2039 );
2040 }
2041
8c55bd6c
RW
2042 /**
2043 * Mark all messages as read parameters description.
2044 *
2045 * @return external_function_parameters
2046 * @since 3.2
2047 */
2048 public static function mark_all_messages_as_read_parameters() {
2049 return new external_function_parameters(
2050 array(
2051 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
2052 'useridfrom' => new external_value(
2053 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
2054 VALUE_DEFAULT, 0),
2055 )
2056 );
2057 }
2058
2059 /**
2060 * Mark all notifications as read function.
2061 *
2062 * @since 3.2
2063 * @throws invalid_parameter_exception
2064 * @throws moodle_exception
2065 * @param int $useridto the user id who received the message
2066 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
2067 * @return external_description
2068 */
2069 public static function mark_all_messages_as_read($useridto, $useridfrom) {
a2c7227a
SL
2070 global $USER, $CFG;
2071
2072 // Check if messaging is enabled.
2073 if (empty($CFG->messaging)) {
2074 throw new moodle_exception('disabled', 'message');
2075 }
8c55bd6c
RW
2076
2077 $params = self::validate_parameters(
2078 self::mark_all_messages_as_read_parameters(),
2079 array(
2080 'useridto' => $useridto,
2081 'useridfrom' => $useridfrom,
2082 )
2083 );
2084
2085 $context = context_system::instance();
2086 self::validate_context($context);
2087
2088 $useridto = $params['useridto'];
2089 $useridfrom = $params['useridfrom'];
2090
2091 if (!empty($useridto)) {
2092 if (core_user::is_real_user($useridto)) {
2093 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
2094 } else {
2095 throw new moodle_exception('invaliduser');
2096 }
2097 }
2098
2099 if (!empty($useridfrom)) {
2100 // We use get_user here because the from user can be the noreply or support user.
2101 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
2102 }
2103
2104 // Check if the current user is the sender/receiver or just a privileged user.
2105 if ($useridto != $USER->id and $useridfrom != $USER->id and
7b55aaa1 2106 // The deleteanymessage cap seems more reasonable here than readallmessages.
8c55bd6c
RW
2107 !has_capability('moodle/site:deleteanymessage', $context)) {
2108 throw new moodle_exception('accessdenied', 'admin');
2109 }
2110
79f6c36c 2111 \core_message\api::mark_all_read_for_user($useridto, $useridfrom, MESSAGE_TYPE_MESSAGE);
8c55bd6c
RW
2112
2113 return true;
2114 }
2115
2116 /**
2117 * Mark all notifications as read return description.
2118 *
2119 * @return external_single_structure
2120 * @since 3.2
2121 */
2122 public static function mark_all_messages_as_read_returns() {
2123 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
2124 }
2125
dec0cd99
MN
2126 /**
2127 * Returns description of method parameters.
2128 *
2129 * @return external_function_parameters
2130 * @since 3.2
2131 */
2132 public static function delete_conversation_parameters() {
2133 return new external_function_parameters(
2134 array(
2135 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the conversation for'),
2136 'otheruserid' => new external_value(PARAM_INT, 'The user id of the other user in the conversation'),
2137 )
2138 );
2139 }
2140
2141 /**
2142 * Deletes a conversation.
2143 *
2144 * @param int $userid The user id of who we want to delete the conversation for
2145 * @param int $otheruserid The user id of the other user in the conversation
2146 * @return array
2147 * @throws moodle_exception
2148 * @since 3.2
2149 */
2150 public static function delete_conversation($userid, $otheruserid) {
2151 global $CFG;
2152
2153 // Check if private messaging between users is allowed.
2154 if (empty($CFG->messaging)) {
2155 throw new moodle_exception('disabled', 'message');
2156 }
2157
2158 // Warnings array, it can be empty at the end but is mandatory.
2159 $warnings = array();
2160
2161 // Validate params.
2162 $params = array(
2163 'userid' => $userid,
2164 'otheruserid' => $otheruserid,
2165 );
2166 $params = self::validate_parameters(self::delete_conversation_parameters(), $params);
2167
2168 // Validate context.
2169 $context = context_system::instance();
2170 self::validate_context($context);
2171
2172 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2173 core_user::require_active_user($user);
2174
2175 if (\core_message\api::can_delete_conversation($user->id)) {
2176 $status = \core_message\api::delete_conversation($user->id, $otheruserid);
2177 } else {
2178 throw new moodle_exception('You do not have permission to delete messages');
2179 }
2180
2181 $results = array(
2182 'status' => $status,
2183 'warnings' => $warnings
2184 );
2185
2186 return $results;
2187 }
2188
2189 /**
2190 * Returns description of method result value.
2191 *
2192 * @return external_description
2193 * @since 3.2
2194 */
2195 public static function delete_conversation_returns() {
2196 return new external_single_structure(
2197 array(
2198 'status' => new external_value(PARAM_BOOL, 'True if the conversation was deleted, false otherwise'),
2199 'warnings' => new external_warnings()
2200 )
2201 );
2202 }
2203
419b1128
JL
2204 /**
2205 * Returns description of method parameters
2206 *
2207 * @return external_function_parameters
2208 * @since 3.1
2209 */
2210 public static function delete_message_parameters() {
2211 return new external_function_parameters(
2212 array(
2213 'messageid' => new external_value(PARAM_INT, 'The message id'),
2214 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the message for'),
2215 'read' => new external_value(PARAM_BOOL, 'If is a message read', VALUE_DEFAULT, true)
2216 )
2217 );
2218 }
2219
2220 /**
2221 * Deletes a message
2222 *
2223 * @param int $messageid the message id
2224 * @param int $userid the user id of who we want to delete the message for
2225 * @param bool $read if is a message read (default to true)
2226 * @return external_description
2227 * @throws moodle_exception
2228 * @since 3.1
2229 */
2230 public static function delete_message($messageid, $userid, $read = true) {
883ce421 2231 global $CFG;
419b1128
JL
2232
2233 // Check if private messaging between users is allowed.
2234 if (empty($CFG->messaging)) {
2235 throw new moodle_exception('disabled', 'message');
2236 }
2237
2238 // Warnings array, it can be empty at the end but is mandatory.
2239 $warnings = array();
2240
2241 // Validate params.
2242 $params = array(
2243 'messageid' => $messageid,
2244 'userid' => $userid,
2245 'read' => $read
2246 );
2247 $params = self::validate_parameters(self::delete_message_parameters(), $params);
2248
2249 // Validate context.
2250 $context = context_system::instance();
2251 self::validate_context($context);
2252
419b1128
JL
2253 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2254 core_user::require_active_user($user);
2255
883ce421
MN
2256 if (\core_message\api::can_delete_message($user->id, $messageid)) {
2257 $status = \core_message\api::delete_message($user->id, $messageid);
419b1128
JL
2258 } else {
2259 throw new moodle_exception('You do not have permission to delete this message');
2260 }
2261
2262 $results = array(
2263 'status' => $status,
2264 'warnings' => $warnings
2265 );
2266 return $results;
2267 }
2268
2269 /**
2270 * Returns description of method result value
2271 *
2272 * @return external_description
2273 * @since 3.1
2274 */
2275 public static function delete_message_returns() {
2276 return new external_single_structure(
2277 array(
2278 'status' => new external_value(PARAM_BOOL, 'True if the message was deleted, false otherwise'),
2279 'warnings' => new external_warnings()
2280 )
2281 );
2282 }
2283
a0eabdd3
RW
2284 /**
2285 * Returns description of method parameters
2286 *
2287 * @return external_function_parameters
2288 * @since 3.2
2289 */
2290 public static function message_processor_config_form_parameters() {
2291 return new external_function_parameters(
2292 array(
2293 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
2294 'name' => new external_value(PARAM_TEXT, 'The name of the message processor'),
2295 'formvalues' => new external_multiple_structure(
2296 new external_single_structure(
2297 array(
2298 'name' => new external_value(PARAM_TEXT, 'name of the form element', VALUE_REQUIRED),
2299 'value' => new external_value(PARAM_RAW, 'value of the form element', VALUE_REQUIRED),
2300 )
2301 ),
2302 'Config form values',
2303 VALUE_REQUIRED
2304 ),
2305 )
2306 );
2307 }
2308
2309 /**
2310 * Processes a message processor config form.
2311 *
2312 * @param int $userid the user id
2313 * @param string $name the name of the processor
2314 * @param array $formvalues the form values
2315 * @return external_description
2316 * @throws moodle_exception
2317 * @since 3.2
2318 */
2319 public static function message_processor_config_form($userid, $name, $formvalues) {
a2c7227a
SL
2320 global $USER, $CFG;
2321
2322 // Check if messaging is enabled.
2323 if (empty($CFG->messaging)) {
2324 throw new moodle_exception('disabled', 'message');
2325 }
8c125526 2326
a0eabdd3
RW
2327 $params = self::validate_parameters(
2328 self::message_processor_config_form_parameters(),
2329 array(
2330 'userid' => $userid,
2331 'name' => $name,
2332 'formvalues' => $formvalues,
2333 )
2334 );
2335
6e65554e 2336 $user = self::validate_preferences_permissions($params['userid']);
a0eabdd3
RW
2337
2338 $processor = get_message_processor($name);
2339 $preferences = [];
2340 $form = new stdClass();
2341
2342 foreach ($formvalues as $formvalue) {
cdff0944
RW
2343 // Curly braces to ensure interpretation is consistent between
2344 // php 5 and php 7.
2345 $form->{$formvalue['name']} = $formvalue['value'];
a0eabdd3
RW
2346 }
2347
2348 $processor->process_form($form, $preferences);
2349
2350 if (!empty($preferences)) {
2351 set_user_preferences($preferences, $userid);
2352 }
2353 }
2354
2355 /**
2356 * Returns description of method result value
2357 *
2358 * @return external_description
2359 * @since 3.2
2360 */
2361 public static function message_processor_config_form_returns() {
2362 return null;
2363 }
8c125526
RW
2364
2365 /**
2366 * Returns description of method parameters
2367 *
2368 * @return external_function_parameters
2369 * @since 3.2
2370 */
2371 public static function get_message_processor_parameters() {
2372 return new external_function_parameters(
2373 array(
2374 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user'),
2375 'name' => new external_value(PARAM_TEXT, 'The name of the message processor', VALUE_REQUIRED),
2376 )
2377 );
2378 }
2379
2380 /**
2381 * Get a message processor.
2382 *
7b55aaa1
MN
2383 * @param int $userid
2384 * @param string $name the name of the processor
8c125526
RW
2385 * @return external_description
2386 * @throws moodle_exception
2387 * @since 3.2
2388 */
2389 public static function get_message_processor($userid = 0, $name) {
a2c7227a
SL
2390 global $USER, $PAGE, $CFG;
2391
2392 // Check if messaging is enabled.
2393 if (empty($CFG->messaging)) {
2394 throw new moodle_exception('disabled', 'message');
2395 }
8c125526
RW
2396
2397 $params = self::validate_parameters(
2398 self::get_message_processor_parameters(),
2399 array(
2400 'userid' => $userid,
2401 'name' => $name,
2402 )
2403 );
2404
2405 if (empty($params['userid'])) {
2406 $params['userid'] = $USER->id;
2407 }
2408
2409 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2410 core_user::require_active_user($user);
2411 self::validate_context(context_user::instance($params['userid']));
2412
2413 $processor = get_message_processor($name);
2414
2415 $processoroutput = new \core_message\output\processor($processor, $user);
2416 $renderer = $PAGE->get_renderer('core_message');
2417
2418 return $processoroutput->export_for_template($renderer);
2419 }
2420
2421 /**
2422 * Returns description of method result value
2423 *
2424 * @return external_description
2425 * @since 3.2
2426 */
2427 public static function get_message_processor_returns() {
2428 return new external_function_parameters(
2429 array(
2430 'systemconfigured' => new external_value(PARAM_BOOL, 'Site configuration status'),
2431 'userconfigured' => new external_value(PARAM_BOOL, 'The user configuration status'),
2432 )
2433 );
2434 }
e86f0cb4 2435
2521afd2
JL
2436 /**
2437 * Check that the user has enough permission to retrieve message or notifications preferences.
2438 *
2439 * @param int $userid the user id requesting the preferences
2440 * @return stdClass full user object
2441 * @throws moodle_exception
2442 * @since Moodle 3.2
2443 */
2444 protected static function validate_preferences_permissions($userid) {
2445 global $USER;
2446
2447 if (empty($userid)) {
2448 $user = $USER;
2449 } else {
2450 $user = core_user::get_user($userid, '*', MUST_EXIST);
2451 core_user::require_active_user($user);
2452 }
2453
2454 $systemcontext = context_system::instance();
2455 self::validate_context($systemcontext);
2456
2457 // Check access control.
2458 if ($user->id == $USER->id) {
2459 // Editing own message profile.
2460 require_capability('moodle/user:editownmessageprofile', $systemcontext);
2461 } else {
2462 // Teachers, parents, etc.
2463 $personalcontext = context_user::instance($user->id);
2464 require_capability('moodle/user:editmessageprofile', $personalcontext);
2465 }
2466 return $user;
2467 }
2468
2469 /**
2470 * Returns a notification or message preference structure.
2471 *
2472 * @return external_single_structure the structure
2473 * @since Moodle 3.2
2474 */
2475 protected static function get_preferences_structure() {
2476 return new external_single_structure(
2477 array(
2478 'userid' => new external_value(PARAM_INT, 'User id'),
2479 'disableall' => new external_value(PARAM_INT, 'Whether all the preferences are disabled'),
2480 'processors' => new external_multiple_structure(
2481 new external_single_structure(
2482 array(
2483 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2484 'name' => new external_value(PARAM_PLUGIN, 'Processor name'),
2485 'hassettings' => new external_value(PARAM_BOOL, 'Whether has settings'),
2486 'contextid' => new external_value(PARAM_INT, 'Context id'),
2487 'userconfigured' => new external_value(PARAM_INT, 'Whether is configured by the user'),
2488 )
2489 ),
2490 'Config form values'
2491 ),
2492 'components' => new external_multiple_structure(
2493 new external_single_structure(
2494 array(
2495 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2496 'notifications' => new external_multiple_structure(
2497 new external_single_structure(
2498 array(
2499 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2500 'preferencekey' => new external_value(PARAM_ALPHANUMEXT, 'Preference key'),
2501 'processors' => new external_multiple_structure(
2502 new external_single_structure(
2503 array(
2504 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2505 'name' => new external_value(PARAM_PLUGIN, 'Processor name'),
2506 'locked' => new external_value(PARAM_BOOL, 'Is locked by admin?'),
2507 'userconfigured' => new external_value(PARAM_INT, 'Is configured?'),
2508 'loggedin' => new external_single_structure(
2509 array(
2510 'name' => new external_value(PARAM_NOTAGS, 'Name'),
2511 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2512 'checked' => new external_value(PARAM_BOOL, 'Is checked?'),
2513 )
2514 ),
2515 'loggedoff' => new external_single_structure(
2516 array(
2517 'name' => new external_value(PARAM_NOTAGS, 'Name'),
2518 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2519 'checked' => new external_value(PARAM_BOOL, 'Is checked?'),
2520 )
2521 ),
2522 )
2523 ),
2524 'Processors values for this notification'
2525 ),
2526 )
2527 ),
2528 'List of notificaitons for the component'
2529 ),
2530 )
2531 ),
2532 'Available components'
2533 ),
2534 )
2535 );
2536 }
2537
e86f0cb4
JL
2538 /**
2539 * Returns description of method parameters
2540 *
2541 * @return external_function_parameters
2542 * @since 3.2
2543 */
2544 public static function get_user_notification_preferences_parameters() {
2545 return new external_function_parameters(
2546 array(
2547 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_DEFAULT, 0)
2548 )
2549 );
2550 }
2551
2552 /**
2553 * Get the notification preferences for a given user.
2554 *
2555 * @param int $userid id of the user, 0 for current user
2556 * @return external_description
2557 * @throws moodle_exception
2558 * @since 3.2
2559 */
2560 public static function get_user_notification_preferences($userid = 0) {
2521afd2 2561 global $PAGE;
a2c7227a 2562
e86f0cb4
JL
2563 $params = self::validate_parameters(
2564 self::get_user_notification_preferences_parameters(),
2565 array(
2566 'userid' => $userid,
2567 )
2568 );
2521afd2 2569 $user = self::validate_preferences_permissions($params['userid']);
e86f0cb4
JL
2570
2571 $processors = get_message_processors();
2572 $providers = message_get_providers_for_user($user->id);
1686d93a 2573 $preferences = \core_message\api::get_all_message_preferences($processors, $providers, $user);
e86f0cb4
JL
2574 $notificationlist = new \core_message\output\preferences\notification_list($processors, $providers, $preferences, $user);
2575
2576 $renderer = $PAGE->get_renderer('core_message');
2577
2578 $result = array(
2579 'warnings' => array(),
2580 'preferences' => $notificationlist->export_for_template($renderer)
2581 );
2582 return $result;
2583 }
2584
2585 /**
2586 * Returns description of method result value
2587 *
2588 * @return external_description
2589 * @since 3.2
2590 */
2591 public static function get_user_notification_preferences_returns() {
2592 return new external_function_parameters(
2593 array(
2521afd2
JL
2594 'preferences' => self::get_preferences_structure(),
2595 'warnings' => new external_warnings(),
2596 )
2597 );
2598 }
2599
2600
2601 /**
2602 * Returns description of method parameters
2603 *
2604 * @return external_function_parameters
2605 * @since 3.2
2606 */
2607 public static function get_user_message_preferences_parameters() {
2608 return new external_function_parameters(
2609 array(
2610 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_DEFAULT, 0)
2611 )
2612 );
2613 }
2614
2615 /**
2616 * Get the notification preferences for a given user.
2617 *
2618 * @param int $userid id of the user, 0 for current user
2619 * @return external_description
2620 * @throws moodle_exception
2621 * @since 3.2
2622 */
2623 public static function get_user_message_preferences($userid = 0) {
2624 global $PAGE;
2625
2626 $params = self::validate_parameters(
2627 self::get_user_message_preferences_parameters(),
2628 array(
2629 'userid' => $userid,
2630 )
2631 );
2632
2633 $user = self::validate_preferences_permissions($params['userid']);
2634
2635 // Filter out enabled, available system_configured and user_configured processors only.
2636 $readyprocessors = array_filter(get_message_processors(), function($processor) {
2637 return $processor->enabled &&
2638 $processor->configured &&
2639 $processor->object->is_user_configured() &&
2640 // Filter out processors that don't have and message preferences to configure.
2641 $processor->object->has_message_preferences();
2642 });
2643
2644 $providers = array_filter(message_get_providers_for_user($user->id), function($provider) {
2645 return $provider->component === 'moodle';
2646 });
2647 $preferences = \core_message\api::get_all_message_preferences($readyprocessors, $providers, $user);
2648 $notificationlistoutput = new \core_message\output\preferences\message_notification_list($readyprocessors,
2649 $providers, $preferences, $user);
2650
2651 $renderer = $PAGE->get_renderer('core_message');
2652
2653 $result = array(
2654 'warnings' => array(),
2655 'preferences' => $notificationlistoutput->export_for_template($renderer),
2656 'blocknoncontacts' => get_user_preferences('message_blocknoncontacts', '', $user->id) ? true : false,
2657 );
2658 return $result;
2659 }
2660
2661 /**
2662 * Returns description of method result value
2663 *
2664 * @return external_description
2665 * @since 3.2
2666 */
2667 public static function get_user_message_preferences_returns() {
2668 return new external_function_parameters(
2669 array(
2670 'preferences' => self::get_preferences_structure(),
2671 'blocknoncontacts' => new external_value(PARAM_BOOL, 'Whether to block or not messages from non contacts'),
e86f0cb4
JL
2672 'warnings' => new external_warnings(),
2673 )
2674 );
2675 }
a623b6b8 2676}