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