MDL-36941 core: alter events to use new table structure
[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() {
d85bedf7 1164 global $CFG, $PAGE;
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
1173 list($online, $offline, $strangers) = message_get_contacts();
1174 $allcontacts = array('online' => $online, 'offline' => $offline, 'strangers' => $strangers);
1175 foreach ($allcontacts as $mode => $contacts) {
1176 foreach ($contacts as $key => $contact) {
1177 $newcontact = array(
1178 'id' => $contact->id,
1179 'fullname' => fullname($contact),
1180 'unread' => $contact->messagecount
1181 );
1182
d85bedf7
JL
1183 $userpicture = new user_picture($contact);
1184 $userpicture->size = 1; // Size f1.
1185 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1186 $userpicture->size = 0; // Size f2.
1187 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
1188
1189 $allcontacts[$mode][$key] = $newcontact;
1190 }
1191 }
1192 return $allcontacts;
1193 }
1194
1195 /**
1196 * Get contacts return description.
1197 *
1198 * @return external_description
5bcfd504 1199 * @since Moodle 2.5
d6731600
FM
1200 */
1201 public static function get_contacts_returns() {
1202 return new external_single_structure(
1203 array(
1204 'online' => new external_multiple_structure(
1205 new external_single_structure(
1206 array(
1207 'id' => new external_value(PARAM_INT, 'User ID'),
1208 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1209 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
1210 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
1211 'unread' => new external_value(PARAM_INT, 'Unread message count')
1212 )
1213 ),
1214 'List of online contacts'
1215 ),
1216 'offline' => new external_multiple_structure(
1217 new external_single_structure(
1218 array(
1219 'id' => new external_value(PARAM_INT, 'User ID'),
1220 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1221 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
1222 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
1223 'unread' => new external_value(PARAM_INT, 'Unread message count')
1224 )
1225 ),
1226 'List of offline contacts'
1227 ),
1228 'strangers' => new external_multiple_structure(
1229 new external_single_structure(
1230 array(
1231 'id' => new external_value(PARAM_INT, 'User ID'),
1232 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1233 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
1234 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
1235 'unread' => new external_value(PARAM_INT, 'Unread message count')
1236 )
1237 ),
1238 'List of users that are not in the user\'s contact list but have sent a message'
1239 )
1240 )
1241 );
1242 }
1243
1244 /**
1245 * Search contacts parameters description.
1246 *
1247 * @return external_function_parameters
5bcfd504 1248 * @since Moodle 2.5
d6731600
FM
1249 */
1250 public static function search_contacts_parameters() {
1251 return new external_function_parameters(
1252 array(
1253 'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
1254 'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
1255 VALUE_DEFAULT, false)
1256 )
1257 );
1258 }
1259
1260 /**
1261 * Search contacts.
1262 *
1263 * @param string $searchtext query string.
1264 * @param bool $onlymycourses limit the search to the user's courses only.
1265 * @return external_description
5bcfd504 1266 * @since Moodle 2.5
d6731600
FM
1267 */
1268 public static function search_contacts($searchtext, $onlymycourses = false) {
d85bedf7 1269 global $CFG, $USER, $PAGE;
11d83ab3 1270 require_once($CFG->dirroot . '/user/lib.php');
436bbf89
DM
1271
1272 // Check if messaging is enabled.
837941e9 1273 if (empty($CFG->messaging)) {
436bbf89
DM
1274 throw new moodle_exception('disabled', 'message');
1275 }
1276
d6731600
FM
1277 require_once($CFG->libdir . '/enrollib.php');
1278
1279 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
1280 $params = self::validate_parameters(self::search_contacts_parameters(), $params);
1281
1282 // Extra validation, we do not allow empty queries.
1283 if ($params['searchtext'] === '') {
1284 throw new moodle_exception('querystringcannotbeempty');
1285 }
1286
1287 $courseids = array();
1288 if ($params['onlymycourses']) {
1289 $mycourses = enrol_get_my_courses(array('id'));
1290 foreach ($mycourses as $mycourse) {
1291 $courseids[] = $mycourse->id;
1292 }
1293 } else {
1294 $courseids[] = SITEID;
1295 }
1296
1297 // Retrieving the users matching the query.
1298 $users = message_search_users($courseids, $params['searchtext']);
1299 $results = array();
1300 foreach ($users as $user) {
1301 $results[$user->id] = $user;
1302 }
1303
1304 // Reorganising information.
1305 foreach ($results as &$user) {
1306 $newuser = array(
1307 'id' => $user->id,
1308 'fullname' => fullname($user)
1309 );
1310
1311 // Avoid undefined property notice as phone not specified.
1312 $user->phone1 = null;
1313 $user->phone2 = null;
1314
d85bedf7
JL
1315 $userpicture = new user_picture($user);
1316 $userpicture->size = 1; // Size f1.
1317 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1318 $userpicture->size = 0; // Size f2.
1319 $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
1320
1321 $user = $newuser;
1322 }
1323
1324 return $results;
1325 }
1326
1327 /**
1328 * Search contacts return description.
1329 *
1330 * @return external_description
5bcfd504 1331 * @since Moodle 2.5
d6731600
FM
1332 */
1333 public static function search_contacts_returns() {
1334 return new external_multiple_structure(
1335 new external_single_structure(
1336 array(
1337 'id' => new external_value(PARAM_INT, 'User ID'),
1338 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1339 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
1340 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
1341 )
1342 ),
1343 'List of contacts'
1344 );
1345 }
aff9da17
JL
1346
1347 /**
1348 * Get messages parameters description.
1349 *
1350 * @return external_function_parameters
193edf7f 1351 * @since 2.8
aff9da17
JL
1352 */
1353 public static function get_messages_parameters() {
1354 return new external_function_parameters(
1355 array(
6ff4464b 1356 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
127ef540
SH
1357 'useridfrom' => new external_value(
1358 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1359 VALUE_DEFAULT, 0),
1360 'type' => new external_value(
1361 PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
1362 VALUE_DEFAULT, 'both'),
6ff4464b 1363 'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
127ef540
SH
1364 'newestfirst' => new external_value(
1365 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
1366 VALUE_DEFAULT, true),
aff9da17 1367 'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
127ef540
SH
1368 'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
1369 )
aff9da17
JL
1370 );
1371 }
1372
1373 /**
1374 * Get messages function implementation.
127ef540
SH
1375 *
1376 * @since 2.8
1377 * @throws invalid_parameter_exception
1378 * @throws moodle_exception
6ff4464b
JL
1379 * @param int $useridto the user id who received the message
1380 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
193edf7f 1381 * @param string $type type of message to return, expected values: notifications, conversations and both
aff9da17 1382 * @param bool $read true for retreiving read messages, false for unread
6ff4464b 1383 * @param bool $newestfirst true for ordering by newest first, false for oldest first
aff9da17
JL
1384 * @param int $limitfrom limit from
1385 * @param int $limitnum limit num
1386 * @return external_description
aff9da17 1387 */
193edf7f 1388 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
aff9da17 1389 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
127ef540 1390 global $CFG, $USER;
aff9da17
JL
1391
1392 $warnings = array();
1393
1394 $params = array(
1395 'useridto' => $useridto,
6ff4464b 1396 'useridfrom' => $useridfrom,
aff9da17
JL
1397 'type' => $type,
1398 'read' => $read,
aff9da17
JL
1399 'newestfirst' => $newestfirst,
1400 'limitfrom' => $limitfrom,
1401 'limitnum' => $limitnum
1402 );
1403
1404 $params = self::validate_parameters(self::get_messages_parameters(), $params);
1405
1406 $context = context_system::instance();
1407 self::validate_context($context);
1408
1409 $useridto = $params['useridto'];
6ff4464b 1410 $useridfrom = $params['useridfrom'];
aff9da17
JL
1411 $type = $params['type'];
1412 $read = $params['read'];
aff9da17
JL
1413 $newestfirst = $params['newestfirst'];
1414 $limitfrom = $params['limitfrom'];
1415 $limitnum = $params['limitnum'];
1416
1417 $allowedvalues = array('notifications', 'conversations', 'both');
1418 if (!in_array($type, $allowedvalues)) {
1419 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
1420 'allowed values are: ' . implode(',', $allowedvalues));
1421 }
1422
1423 // Check if private messaging between users is allowed.
1424 if (empty($CFG->messaging)) {
1425 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
aff9da17
JL
1426 if ($type == "conversations") {
1427 throw new moodle_exception('disabled', 'message');
1428 }
1429 if ($type == "both") {
1430 $warning = array();
1431 $warning['item'] = 'message';
1432 $warning['itemid'] = $USER->id;
1433 $warning['warningcode'] = '1';
1434 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
1435 Only notifications will be returned';
1436 $warnings[] = $warning;
1437 }
1438 }
1439
1440 if (!empty($useridto)) {
6ff4464b
JL
1441 if (core_user::is_real_user($useridto)) {
1442 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1443 } else {
1444 throw new moodle_exception('invaliduser');
1445 }
aff9da17
JL
1446 }
1447
1448 if (!empty($useridfrom)) {
1449 // We use get_user here because the from user can be the noreply or support user.
1450 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1451 }
1452
1453 // Check if the current user is the sender/receiver or just a privileged user.
1454 if ($useridto != $USER->id and $useridfrom != $USER->id and
1455 !has_capability('moodle/site:readallmessages', $context)) {
1456 throw new moodle_exception('accessdenied', 'admin');
1457 }
1458
127ef540 1459 // Which type of messages to retrieve.
193edf7f 1460 $notifications = -1;
aff9da17 1461 if ($type != 'both') {
193edf7f 1462 $notifications = ($type == 'notifications') ? 1 : 0;
aff9da17
JL
1463 }
1464
aff9da17 1465 $orderdirection = $newestfirst ? 'DESC' : 'ASC';
193edf7f 1466 $sort = "mr.timecreated $orderdirection";
aff9da17 1467
193edf7f 1468 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
aff9da17
JL
1469 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
1470
1471 // In some cases, we don't need to get the to/from user objects from the sql query.
1472 $userfromfullname = '';
1473 $usertofullname = '';
1474
1475 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
1476 if (!empty($useridto)) {
1477 $usertofullname = fullname($userto, $canviewfullname);
1478 // The user from may or may not be filled.
1479 if (!empty($useridfrom)) {
1480 $userfromfullname = fullname($userfrom, $canviewfullname);
1481 }
1482 } else {
1483 // If the useridto field is empty, the useridfrom must be filled.
1484 $userfromfullname = fullname($userfrom, $canviewfullname);
1485 }
aff9da17
JL
1486 foreach ($messages as $mid => $message) {
1487
ea21d637
JL
1488 // Do not return deleted messages.
1489 if (($useridto == $USER->id and $message->timeusertodeleted) or
1490 ($useridfrom == $USER->id and $message->timeuserfromdeleted)) {
1491
1492 unset($messages[$mid]);
1493 continue;
1494 }
1495
aff9da17
JL
1496 // We need to get the user from the query.
1497 if (empty($userfromfullname)) {
6ff4464b
JL
1498 // Check for non-reply and support users.
1499 if (core_user::is_real_user($message->useridfrom)) {
127ef540 1500 $user = new stdClass();
6ff4464b
JL
1501 $user = username_load_fields_from_object($user, $message, 'userfrom');
1502 $message->userfromfullname = fullname($user, $canviewfullname);
1503 } else {
1504 $user = core_user::get_user($message->useridfrom);
1505 $message->userfromfullname = fullname($user, $canviewfullname);
1506 }
aff9da17
JL
1507 } else {
1508 $message->userfromfullname = $userfromfullname;
1509 }
1510
1511 // We need to get the user from the query.
1512 if (empty($usertofullname)) {
127ef540 1513 $user = new stdClass();
aff9da17
JL
1514 $user = username_load_fields_from_object($user, $message, 'userto');
1515 $message->usertofullname = fullname($user, $canviewfullname);
1516 } else {
1517 $message->usertofullname = $usertofullname;
1518 }
1519
193edf7f 1520 // This field is only available in the message_read table.
aff9da17
JL
1521 if (!isset($message->timeread)) {
1522 $message->timeread = 0;
1523 }
1524
aff9da17 1525 $message->text = message_format_message_text($message);
aff9da17
JL
1526 $messages[$mid] = (array) $message;
1527 }
1528 }
1529
1530 $results = array(
1531 'messages' => $messages,
1532 'warnings' => $warnings
1533 );
1534
1535 return $results;
1536 }
1537
1538 /**
1539 * Get messages return description.
1540 *
6ff4464b 1541 * @return external_single_structure
193edf7f 1542 * @since 2.8
aff9da17
JL
1543 */
1544 public static function get_messages_returns() {
1545 return new external_single_structure(
1546 array(
1547 'messages' => new external_multiple_structure(
1548 new external_single_structure(
1549 array(
193edf7f 1550 'id' => new external_value(PARAM_INT, 'Message id'),
aff9da17
JL
1551 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
1552 'useridto' => new external_value(PARAM_INT, 'User to id'),
1553 'subject' => new external_value(PARAM_TEXT, 'The message subject'),
1554 'text' => new external_value(PARAM_RAW, 'The message text formated'),
1555 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
193edf7f 1556 'fullmessageformat' => new external_format_value('fullmessage'),
aff9da17
JL
1557 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
1558 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
1559 'notification' => new external_value(PARAM_INT, 'Is a notification?'),
1560 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
1561 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
1562 'timecreated' => new external_value(PARAM_INT, 'Time created'),
1563 'timeread' => new external_value(PARAM_INT, 'Time read'),
1564 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
1565 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
1566 ), 'message'
1567 )
1568 ),
1569 'warnings' => new external_warnings()
1570 )
1571 );
3274d5ca
RW
1572 }
1573
3274d5ca
RW
1574 /**
1575 * Mark all notifications as read parameters description.
1576 *
1577 * @return external_function_parameters
1578 * @since 3.2
1579 */
1580 public static function mark_all_notifications_as_read_parameters() {
1581 return new external_function_parameters(
1582 array(
1583 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1584 'useridfrom' => new external_value(
1585 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1586 VALUE_DEFAULT, 0),
1587 )
1588 );
1589 }
1590
1591 /**
1592 * Mark all notifications as read function.
1593 *
1594 * @since 3.2
1595 * @throws invalid_parameter_exception
1596 * @throws moodle_exception
1597 * @param int $useridto the user id who received the message
1598 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1599 * @return external_description
1600 */
1601 public static function mark_all_notifications_as_read($useridto, $useridfrom) {
837941e9 1602 global $USER;
3274d5ca
RW
1603
1604 $params = self::validate_parameters(
1605 self::mark_all_notifications_as_read_parameters(),
1606 array(
1607 'useridto' => $useridto,
1608 'useridfrom' => $useridfrom,
1609 )
1610 );
1611
1612 $context = context_system::instance();
1613 self::validate_context($context);
1614
1615 $useridto = $params['useridto'];
1616 $useridfrom = $params['useridfrom'];
1617
1618 if (!empty($useridto)) {
1619 if (core_user::is_real_user($useridto)) {
1620 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1621 } else {
1622 throw new moodle_exception('invaliduser');
1623 }
1624 }
1625
1626 if (!empty($useridfrom)) {
1627 // We use get_user here because the from user can be the noreply or support user.
1628 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1629 }
1630
1631 // Check if the current user is the sender/receiver or just a privileged user.
1632 if ($useridto != $USER->id and $useridfrom != $USER->id and
7b55aaa1 1633 // The deleteanymessage cap seems more reasonable here than readallmessages.
3274d5ca
RW
1634 !has_capability('moodle/site:deleteanymessage', $context)) {
1635 throw new moodle_exception('accessdenied', 'admin');
1636 }
1637
79f6c36c 1638 \core_message\api::mark_all_read_for_user($useridto, $useridfrom, MESSAGE_TYPE_NOTIFICATION);
3274d5ca
RW
1639
1640 return true;
1641 }
1642
1643 /**
1644 * Mark all notifications as read return description.
1645 *
1646 * @return external_single_structure
1647 * @since 3.2
1648 */
1649 public static function mark_all_notifications_as_read_returns() {
1650 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
1651 }
1652
8c55bd6c
RW
1653 /**
1654 * Get unread conversations count parameters description.
1655 *
1656 * @return external_function_parameters
1657 * @since 3.2
1658 */
1659 public static function get_unread_conversations_count_parameters() {
1660 return new external_function_parameters(
1661 array(
1662 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1663 )
1664 );
1665 }
1666
1667 /**
1668 * Get unread messages count function.
1669 *
1670 * @since 3.2
1671 * @throws invalid_parameter_exception
1672 * @throws moodle_exception
1673 * @param int $useridto the user id who received the message
1674 * @return external_description
1675 */
1676 public static function get_unread_conversations_count($useridto) {
a2c7227a
SL
1677 global $USER, $CFG;
1678
1679 // Check if messaging is enabled.
1680 if (empty($CFG->messaging)) {
1681 throw new moodle_exception('disabled', 'message');
1682 }
8c55bd6c
RW
1683
1684 $params = self::validate_parameters(
1685 self::get_unread_conversations_count_parameters(),
1686 array('useridto' => $useridto)
1687 );
1688
1689 $context = context_system::instance();
1690 self::validate_context($context);
1691
1692 $useridto = $params['useridto'];
1693
1694 if (!empty($useridto)) {
1695 if (core_user::is_real_user($useridto)) {
1696 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1697 } else {
1698 throw new moodle_exception('invaliduser');
1699 }
1700 } else {
1701 $useridto = $USER->id;
1702 }
1703
1704 // Check if the current user is the receiver or just a privileged user.
1705 if ($useridto != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
1706 throw new moodle_exception('accessdenied', 'admin');
1707 }
1708
79f6c36c 1709 return \core_message\api::count_unread_conversations($userto);
8c55bd6c
RW
1710 }
1711
1712 /**
1713 * Get unread conversations count return description.
1714 *
1715 * @return external_single_structure
1716 * @since 3.2
1717 */
1718 public static function get_unread_conversations_count_returns() {
1719 return new external_value(PARAM_INT, 'The count of unread messages for the user');
aff9da17
JL
1720 }
1721
60ab2e1b
JL
1722 /**
1723 * Get blocked users parameters description.
1724 *
1725 * @return external_function_parameters
1726 * @since 2.9
1727 */
1728 public static function get_blocked_users_parameters() {
1729 return new external_function_parameters(
1730 array(
1731 'userid' => new external_value(PARAM_INT,
1732 'the user whose blocked users we want to retrieve',
1733 VALUE_REQUIRED),
1734 )
1735 );
1736 }
1737
1738 /**
1739 * Retrieve a list of users blocked
1740 *
1741 * @param int $userid the user whose blocked users we want to retrieve
1742 * @return external_description
1743 * @since 2.9
1744 */
1745 public static function get_blocked_users($userid) {
d85bedf7 1746 global $CFG, $USER, $PAGE;
60ab2e1b
JL
1747
1748 // Warnings array, it can be empty at the end but is mandatory.
1749 $warnings = array();
1750
1751 // Validate params.
1752 $params = array(
1753 'userid' => $userid
1754 );
1755 $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
1756 $userid = $params['userid'];
1757
1758 // Validate context.
1759 $context = context_system::instance();
1760 self::validate_context($context);
1761
1762 // Check if private messaging between users is allowed.
1763 if (empty($CFG->messaging)) {
1764 throw new moodle_exception('disabled', 'message');
1765 }
1766
4485f7c5
JL
1767 $user = core_user::get_user($userid, '*', MUST_EXIST);
1768 core_user::require_active_user($user);
60ab2e1b
JL
1769
1770 // Check if we have permissions for retrieve the information.
343ba16c
SL
1771 $capability = 'moodle/site:manageallmessaging';
1772 if (($USER->id != $userid) && !has_capability($capability, $context)) {
1773 throw new required_capability_exception($context, $capability, 'nopermissions', '');
60ab2e1b
JL
1774 }
1775
1776 // Now, we can get safely all the blocked users.
1777 $users = message_get_blocked_users($user);
1778
1779 $blockedusers = array();
1780 foreach ($users as $user) {
1781 $newuser = array(
1782 'id' => $user->id,
1783 'fullname' => fullname($user),
1784 );
0b074e88 1785
d85bedf7
JL
1786 $userpicture = new user_picture($user);
1787 $userpicture->size = 1; // Size f1.
1788 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
60ab2e1b
JL
1789
1790 $blockedusers[] = $newuser;
1791 }
1792
1793 $results = array(
1794 'users' => $blockedusers,
1795 'warnings' => $warnings
1796 );
1797 return $results;
1798 }
1799
1800 /**
1801 * Get blocked users return description.
1802 *
1803 * @return external_single_structure
1804 * @since 2.9
1805 */
1806 public static function get_blocked_users_returns() {
1807 return new external_single_structure(
1808 array(
1809 'users' => new external_multiple_structure(
1810 new external_single_structure(
1811 array(
1812 'id' => new external_value(PARAM_INT, 'User ID'),
1813 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1814 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL)
1815 )
1816 ),
1817 'List of blocked users'
1818 ),
1819 'warnings' => new external_warnings()
1820 )
1821 );
1822 }
1823
31c474da
JL
1824 /**
1825 * Returns description of method parameters
1826 *
1827 * @return external_function_parameters
1828 * @since 2.9
1829 */
1830 public static function mark_message_read_parameters() {
1831 return new external_function_parameters(
1832 array(
1833 'messageid' => new external_value(PARAM_INT, 'id of the message (in the message table)'),
7b55aaa1
MN
1834 'timeread' => new external_value(PARAM_INT, 'timestamp for when the message should be marked read',
1835 VALUE_DEFAULT, 0)
31c474da
JL
1836 )
1837 );
1838 }
1839
1840 /**
1841 * Mark a single message as read, trigger message_viewed event
1842 *
1843 * @param int $messageid id of the message (in the message table)
1844 * @param int $timeread timestamp for when the message should be marked read
1845 * @return external_description
1846 * @throws invalid_parameter_exception
1847 * @throws moodle_exception
1848 * @since 2.9
1849 */
1850 public static function mark_message_read($messageid, $timeread) {
1851 global $CFG, $DB, $USER;
31c474da
JL
1852
1853 // Check if private messaging between users is allowed.
1854 if (empty($CFG->messaging)) {
1855 throw new moodle_exception('disabled', 'message');
1856 }
1857
1858 // Warnings array, it can be empty at the end but is mandatory.
1859 $warnings = array();
1860
1861 // Validate params.
1862 $params = array(
1863 'messageid' => $messageid,
1864 'timeread' => $timeread
1865 );
1866 $params = self::validate_parameters(self::mark_message_read_parameters(), $params);
1867
0b19d048
RW
1868 if (empty($params['timeread'])) {
1869 $timeread = time();
1870 } else {
1871 $timeread = $params['timeread'];
1872 }
1873
31c474da
JL
1874 // Validate context.
1875 $context = context_system::instance();
1876 self::validate_context($context);
1877
1878 $message = $DB->get_record('message', array('id' => $params['messageid']), '*', MUST_EXIST);
1879
1880 if ($message->useridto != $USER->id) {
1881 throw new invalid_parameter_exception('Invalid messageid, you don\'t have permissions to mark this message as read');
1882 }
1883
0b19d048 1884 $messageid = message_mark_message_read($message, $timeread);
31c474da
JL
1885
1886 $results = array(
1887 'messageid' => $messageid,
1888 'warnings' => $warnings
1889 );
1890 return $results;
1891 }
1892
1893 /**
1894 * Returns description of method result value
1895 *
1896 * @return external_description
1897 * @since 2.9
1898 */
1899 public static function mark_message_read_returns() {
1900 return new external_single_structure(
1901 array(
1902 'messageid' => new external_value(PARAM_INT, 'the id of the message in the message_read table'),
1903 'warnings' => new external_warnings()
1904 )
1905 );
1906 }
1907
8c55bd6c
RW
1908 /**
1909 * Mark all messages as read parameters description.
1910 *
1911 * @return external_function_parameters
1912 * @since 3.2
1913 */
1914 public static function mark_all_messages_as_read_parameters() {
1915 return new external_function_parameters(
1916 array(
1917 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1918 'useridfrom' => new external_value(
1919 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1920 VALUE_DEFAULT, 0),
1921 )
1922 );
1923 }
1924
1925 /**
1926 * Mark all notifications as read function.
1927 *
1928 * @since 3.2
1929 * @throws invalid_parameter_exception
1930 * @throws moodle_exception
1931 * @param int $useridto the user id who received the message
1932 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1933 * @return external_description
1934 */
1935 public static function mark_all_messages_as_read($useridto, $useridfrom) {
a2c7227a
SL
1936 global $USER, $CFG;
1937
1938 // Check if messaging is enabled.
1939 if (empty($CFG->messaging)) {
1940 throw new moodle_exception('disabled', 'message');
1941 }
8c55bd6c
RW
1942
1943 $params = self::validate_parameters(
1944 self::mark_all_messages_as_read_parameters(),
1945 array(
1946 'useridto' => $useridto,
1947 'useridfrom' => $useridfrom,
1948 )
1949 );
1950
1951 $context = context_system::instance();
1952 self::validate_context($context);
1953
1954 $useridto = $params['useridto'];
1955 $useridfrom = $params['useridfrom'];
1956
1957 if (!empty($useridto)) {
1958 if (core_user::is_real_user($useridto)) {
1959 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1960 } else {
1961 throw new moodle_exception('invaliduser');
1962 }
1963 }
1964
1965 if (!empty($useridfrom)) {
1966 // We use get_user here because the from user can be the noreply or support user.
1967 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1968 }
1969
1970 // Check if the current user is the sender/receiver or just a privileged user.
1971 if ($useridto != $USER->id and $useridfrom != $USER->id and
7b55aaa1 1972 // The deleteanymessage cap seems more reasonable here than readallmessages.
8c55bd6c
RW
1973 !has_capability('moodle/site:deleteanymessage', $context)) {
1974 throw new moodle_exception('accessdenied', 'admin');
1975 }
1976
79f6c36c 1977 \core_message\api::mark_all_read_for_user($useridto, $useridfrom, MESSAGE_TYPE_MESSAGE);
8c55bd6c
RW
1978
1979 return true;
1980 }
1981
1982 /**
1983 * Mark all notifications as read return description.
1984 *
1985 * @return external_single_structure
1986 * @since 3.2
1987 */
1988 public static function mark_all_messages_as_read_returns() {
1989 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
1990 }
1991
dec0cd99
MN
1992 /**
1993 * Returns description of method parameters.
1994 *
1995 * @return external_function_parameters
1996 * @since 3.2
1997 */
1998 public static function delete_conversation_parameters() {
1999 return new external_function_parameters(
2000 array(
2001 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the conversation for'),
2002 'otheruserid' => new external_value(PARAM_INT, 'The user id of the other user in the conversation'),
2003 )
2004 );
2005 }
2006
2007 /**
2008 * Deletes a conversation.
2009 *
2010 * @param int $userid The user id of who we want to delete the conversation for
2011 * @param int $otheruserid The user id of the other user in the conversation
2012 * @return array
2013 * @throws moodle_exception
2014 * @since 3.2
2015 */
2016 public static function delete_conversation($userid, $otheruserid) {
2017 global $CFG;
2018
2019 // Check if private messaging between users is allowed.
2020 if (empty($CFG->messaging)) {
2021 throw new moodle_exception('disabled', 'message');
2022 }
2023
2024 // Warnings array, it can be empty at the end but is mandatory.
2025 $warnings = array();
2026
2027 // Validate params.
2028 $params = array(
2029 'userid' => $userid,
2030 'otheruserid' => $otheruserid,
2031 );
2032 $params = self::validate_parameters(self::delete_conversation_parameters(), $params);
2033
2034 // Validate context.
2035 $context = context_system::instance();
2036 self::validate_context($context);
2037
2038 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2039 core_user::require_active_user($user);
2040
2041 if (\core_message\api::can_delete_conversation($user->id)) {
2042 $status = \core_message\api::delete_conversation($user->id, $otheruserid);
2043 } else {
2044 throw new moodle_exception('You do not have permission to delete messages');
2045 }
2046
2047 $results = array(
2048 'status' => $status,
2049 'warnings' => $warnings
2050 );
2051
2052 return $results;
2053 }
2054
2055 /**
2056 * Returns description of method result value.
2057 *
2058 * @return external_description
2059 * @since 3.2
2060 */
2061 public static function delete_conversation_returns() {
2062 return new external_single_structure(
2063 array(
2064 'status' => new external_value(PARAM_BOOL, 'True if the conversation was deleted, false otherwise'),
2065 'warnings' => new external_warnings()
2066 )
2067 );
2068 }
2069
419b1128
JL
2070 /**
2071 * Returns description of method parameters
2072 *
2073 * @return external_function_parameters
2074 * @since 3.1
2075 */
2076 public static function delete_message_parameters() {
2077 return new external_function_parameters(
2078 array(
2079 'messageid' => new external_value(PARAM_INT, 'The message id'),
2080 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the message for'),
2081 'read' => new external_value(PARAM_BOOL, 'If is a message read', VALUE_DEFAULT, true)
2082 )
2083 );
2084 }
2085
2086 /**
2087 * Deletes a message
2088 *
2089 * @param int $messageid the message id
2090 * @param int $userid the user id of who we want to delete the message for
2091 * @param bool $read if is a message read (default to true)
2092 * @return external_description
2093 * @throws moodle_exception
2094 * @since 3.1
2095 */
2096 public static function delete_message($messageid, $userid, $read = true) {
2097 global $CFG, $DB;
419b1128
JL
2098
2099 // Check if private messaging between users is allowed.
2100 if (empty($CFG->messaging)) {
2101 throw new moodle_exception('disabled', 'message');
2102 }
2103
2104 // Warnings array, it can be empty at the end but is mandatory.
2105 $warnings = array();
2106
2107 // Validate params.
2108 $params = array(
2109 'messageid' => $messageid,
2110 'userid' => $userid,
2111 'read' => $read
2112 );
2113 $params = self::validate_parameters(self::delete_message_parameters(), $params);
2114
2115 // Validate context.
2116 $context = context_system::instance();
2117 self::validate_context($context);
2118
2119 $messagestable = $params['read'] ? 'message_read' : 'message';
2120 $message = $DB->get_record($messagestable, array('id' => $params['messageid']), '*', MUST_EXIST);
2121
2122 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2123 core_user::require_active_user($user);
2124
2125 $status = false;
2126 if (message_can_delete_message($message, $user->id)) {
2127 $status = message_delete_message($message, $user->id);;
2128 } else {
2129 throw new moodle_exception('You do not have permission to delete this message');
2130 }
2131
2132 $results = array(
2133 'status' => $status,
2134 'warnings' => $warnings
2135 );
2136 return $results;
2137 }
2138
2139 /**
2140 * Returns description of method result value
2141 *
2142 * @return external_description
2143 * @since 3.1
2144 */
2145 public static function delete_message_returns() {
2146 return new external_single_structure(
2147 array(
2148 'status' => new external_value(PARAM_BOOL, 'True if the message was deleted, false otherwise'),
2149 'warnings' => new external_warnings()
2150 )
2151 );
2152 }
2153
a0eabdd3
RW
2154 /**
2155 * Returns description of method parameters
2156 *
2157 * @return external_function_parameters
2158 * @since 3.2
2159 */
2160 public static function message_processor_config_form_parameters() {
2161 return new external_function_parameters(
2162 array(
2163 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
2164 'name' => new external_value(PARAM_TEXT, 'The name of the message processor'),
2165 'formvalues' => new external_multiple_structure(
2166 new external_single_structure(
2167 array(
2168 'name' => new external_value(PARAM_TEXT, 'name of the form element', VALUE_REQUIRED),
2169 'value' => new external_value(PARAM_RAW, 'value of the form element', VALUE_REQUIRED),
2170 )
2171 ),
2172 'Config form values',
2173 VALUE_REQUIRED
2174 ),
2175 )
2176 );
2177 }
2178
2179 /**
2180 * Processes a message processor config form.
2181 *
2182 * @param int $userid the user id
2183 * @param string $name the name of the processor
2184 * @param array $formvalues the form values
2185 * @return external_description
2186 * @throws moodle_exception
2187 * @since 3.2
2188 */
2189 public static function message_processor_config_form($userid, $name, $formvalues) {
a2c7227a
SL
2190 global $USER, $CFG;
2191
2192 // Check if messaging is enabled.
2193 if (empty($CFG->messaging)) {
2194 throw new moodle_exception('disabled', 'message');
2195 }
8c125526 2196
a0eabdd3
RW
2197 $params = self::validate_parameters(
2198 self::message_processor_config_form_parameters(),
2199 array(
2200 'userid' => $userid,
2201 'name' => $name,
2202 'formvalues' => $formvalues,
2203 )
2204 );
2205
6e65554e 2206 $user = self::validate_preferences_permissions($params['userid']);
a0eabdd3
RW
2207
2208 $processor = get_message_processor($name);
2209 $preferences = [];
2210 $form = new stdClass();
2211
2212 foreach ($formvalues as $formvalue) {
cdff0944
RW
2213 // Curly braces to ensure interpretation is consistent between
2214 // php 5 and php 7.
2215 $form->{$formvalue['name']} = $formvalue['value'];
a0eabdd3
RW
2216 }
2217
2218 $processor->process_form($form, $preferences);
2219
2220 if (!empty($preferences)) {
2221 set_user_preferences($preferences, $userid);
2222 }
2223 }
2224
2225 /**
2226 * Returns description of method result value
2227 *
2228 * @return external_description
2229 * @since 3.2
2230 */
2231 public static function message_processor_config_form_returns() {
2232 return null;
2233 }
8c125526
RW
2234
2235 /**
2236 * Returns description of method parameters
2237 *
2238 * @return external_function_parameters
2239 * @since 3.2
2240 */
2241 public static function get_message_processor_parameters() {
2242 return new external_function_parameters(
2243 array(
2244 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user'),
2245 'name' => new external_value(PARAM_TEXT, 'The name of the message processor', VALUE_REQUIRED),
2246 )
2247 );
2248 }
2249
2250 /**
2251 * Get a message processor.
2252 *
7b55aaa1
MN
2253 * @param int $userid
2254 * @param string $name the name of the processor
8c125526
RW
2255 * @return external_description
2256 * @throws moodle_exception
2257 * @since 3.2
2258 */
2259 public static function get_message_processor($userid = 0, $name) {
a2c7227a
SL
2260 global $USER, $PAGE, $CFG;
2261
2262 // Check if messaging is enabled.
2263 if (empty($CFG->messaging)) {
2264 throw new moodle_exception('disabled', 'message');
2265 }
8c125526
RW
2266
2267 $params = self::validate_parameters(
2268 self::get_message_processor_parameters(),
2269 array(
2270 'userid' => $userid,
2271 'name' => $name,
2272 )
2273 );
2274
2275 if (empty($params['userid'])) {
2276 $params['userid'] = $USER->id;
2277 }
2278
2279 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2280 core_user::require_active_user($user);
2281 self::validate_context(context_user::instance($params['userid']));
2282
2283 $processor = get_message_processor($name);
2284
2285 $processoroutput = new \core_message\output\processor($processor, $user);
2286 $renderer = $PAGE->get_renderer('core_message');
2287
2288 return $processoroutput->export_for_template($renderer);
2289 }
2290
2291 /**
2292 * Returns description of method result value
2293 *
2294 * @return external_description
2295 * @since 3.2
2296 */
2297 public static function get_message_processor_returns() {
2298 return new external_function_parameters(
2299 array(
2300 'systemconfigured' => new external_value(PARAM_BOOL, 'Site configuration status'),
2301 'userconfigured' => new external_value(PARAM_BOOL, 'The user configuration status'),
2302 )
2303 );
2304 }
e86f0cb4 2305
2521afd2
JL
2306 /**
2307 * Check that the user has enough permission to retrieve message or notifications preferences.
2308 *
2309 * @param int $userid the user id requesting the preferences
2310 * @return stdClass full user object
2311 * @throws moodle_exception
2312 * @since Moodle 3.2
2313 */
2314 protected static function validate_preferences_permissions($userid) {
2315 global $USER;
2316
2317 if (empty($userid)) {
2318 $user = $USER;
2319 } else {
2320 $user = core_user::get_user($userid, '*', MUST_EXIST);
2321 core_user::require_active_user($user);
2322 }
2323
2324 $systemcontext = context_system::instance();
2325 self::validate_context($systemcontext);
2326
2327 // Check access control.
2328 if ($user->id == $USER->id) {
2329 // Editing own message profile.
2330 require_capability('moodle/user:editownmessageprofile', $systemcontext);
2331 } else {
2332 // Teachers, parents, etc.
2333 $personalcontext = context_user::instance($user->id);
2334 require_capability('moodle/user:editmessageprofile', $personalcontext);
2335 }
2336 return $user;
2337 }
2338
2339 /**
2340 * Returns a notification or message preference structure.
2341 *
2342 * @return external_single_structure the structure
2343 * @since Moodle 3.2
2344 */
2345 protected static function get_preferences_structure() {
2346 return new external_single_structure(
2347 array(
2348 'userid' => new external_value(PARAM_INT, 'User id'),
2349 'disableall' => new external_value(PARAM_INT, 'Whether all the preferences are disabled'),
2350 'processors' => new external_multiple_structure(
2351 new external_single_structure(
2352 array(
2353 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2354 'name' => new external_value(PARAM_PLUGIN, 'Processor name'),
2355 'hassettings' => new external_value(PARAM_BOOL, 'Whether has settings'),
2356 'contextid' => new external_value(PARAM_INT, 'Context id'),
2357 'userconfigured' => new external_value(PARAM_INT, 'Whether is configured by the user'),
2358 )
2359 ),
2360 'Config form values'
2361 ),
2362 'components' => new external_multiple_structure(
2363 new external_single_structure(
2364 array(
2365 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2366 'notifications' => new external_multiple_structure(
2367 new external_single_structure(
2368 array(
2369 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2370 'preferencekey' => new external_value(PARAM_ALPHANUMEXT, 'Preference key'),
2371 'processors' => new external_multiple_structure(
2372 new external_single_structure(
2373 array(
2374 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2375 'name' => new external_value(PARAM_PLUGIN, 'Processor name'),
2376 'locked' => new external_value(PARAM_BOOL, 'Is locked by admin?'),
2377 'userconfigured' => new external_value(PARAM_INT, 'Is configured?'),
2378 'loggedin' => new external_single_structure(
2379 array(
2380 'name' => new external_value(PARAM_NOTAGS, 'Name'),
2381 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2382 'checked' => new external_value(PARAM_BOOL, 'Is checked?'),
2383 )
2384 ),
2385 'loggedoff' => new external_single_structure(
2386 array(
2387 'name' => new external_value(PARAM_NOTAGS, 'Name'),
2388 'displayname' => new external_value(PARAM_TEXT, 'Display name'),
2389 'checked' => new external_value(PARAM_BOOL, 'Is checked?'),
2390 )
2391 ),
2392 )
2393 ),
2394 'Processors values for this notification'
2395 ),
2396 )
2397 ),
2398 'List of notificaitons for the component'
2399 ),
2400 )
2401 ),
2402 'Available components'
2403 ),
2404 )
2405 );
2406 }
2407
e86f0cb4
JL
2408 /**
2409 * Returns description of method parameters
2410 *
2411 * @return external_function_parameters
2412 * @since 3.2
2413 */
2414 public static function get_user_notification_preferences_parameters() {
2415 return new external_function_parameters(
2416 array(
2417 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_DEFAULT, 0)
2418 )
2419 );
2420 }
2421
2422 /**
2423 * Get the notification preferences for a given user.
2424 *
2425 * @param int $userid id of the user, 0 for current user
2426 * @return external_description
2427 * @throws moodle_exception
2428 * @since 3.2
2429 */
2430 public static function get_user_notification_preferences($userid = 0) {
2521afd2 2431 global $PAGE;
a2c7227a 2432
e86f0cb4
JL
2433 $params = self::validate_parameters(
2434 self::get_user_notification_preferences_parameters(),
2435 array(
2436 'userid' => $userid,
2437 )
2438 );
2521afd2 2439 $user = self::validate_preferences_permissions($params['userid']);
e86f0cb4
JL
2440
2441 $processors = get_message_processors();
2442 $providers = message_get_providers_for_user($user->id);
1686d93a 2443 $preferences = \core_message\api::get_all_message_preferences($processors, $providers, $user);
e86f0cb4
JL
2444 $notificationlist = new \core_message\output\preferences\notification_list($processors, $providers, $preferences, $user);
2445
2446 $renderer = $PAGE->get_renderer('core_message');
2447
2448 $result = array(
2449 'warnings' => array(),
2450 'preferences' => $notificationlist->export_for_template($renderer)
2451 );
2452 return $result;
2453 }
2454
2455 /**
2456 * Returns description of method result value
2457 *
2458 * @return external_description
2459 * @since 3.2
2460 */
2461 public static function get_user_notification_preferences_returns() {
2462 return new external_function_parameters(
2463 array(
2521afd2
JL
2464 'preferences' => self::get_preferences_structure(),
2465 'warnings' => new external_warnings(),
2466 )
2467 );
2468 }
2469
2470
2471 /**
2472 * Returns description of method parameters
2473 *
2474 * @return external_function_parameters
2475 * @since 3.2
2476 */
2477 public static function get_user_message_preferences_parameters() {
2478 return new external_function_parameters(
2479 array(
2480 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_DEFAULT, 0)
2481 )
2482 );
2483 }
2484
2485 /**
2486 * Get the notification preferences for a given user.
2487 *
2488 * @param int $userid id of the user, 0 for current user
2489 * @return external_description
2490 * @throws moodle_exception
2491 * @since 3.2
2492 */
2493 public static function get_user_message_preferences($userid = 0) {
2494 global $PAGE;
2495
2496 $params = self::validate_parameters(
2497 self::get_user_message_preferences_parameters(),
2498 array(
2499 'userid' => $userid,
2500 )
2501 );
2502
2503 $user = self::validate_preferences_permissions($params['userid']);
2504
2505 // Filter out enabled, available system_configured and user_configured processors only.
2506 $readyprocessors = array_filter(get_message_processors(), function($processor) {
2507 return $processor->enabled &&
2508 $processor->configured &&
2509 $processor->object->is_user_configured() &&
2510 // Filter out processors that don't have and message preferences to configure.
2511 $processor->object->has_message_preferences();
2512 });
2513
2514 $providers = array_filter(message_get_providers_for_user($user->id), function($provider) {
2515 return $provider->component === 'moodle';
2516 });
2517 $preferences = \core_message\api::get_all_message_preferences($readyprocessors, $providers, $user);
2518 $notificationlistoutput = new \core_message\output\preferences\message_notification_list($readyprocessors,
2519 $providers, $preferences, $user);
2520
2521 $renderer = $PAGE->get_renderer('core_message');
2522
2523 $result = array(
2524 'warnings' => array(),
2525 'preferences' => $notificationlistoutput->export_for_template($renderer),
2526 'blocknoncontacts' => get_user_preferences('message_blocknoncontacts', '', $user->id) ? true : false,
2527 );
2528 return $result;
2529 }
2530
2531 /**
2532 * Returns description of method result value
2533 *
2534 * @return external_description
2535 * @since 3.2
2536 */
2537 public static function get_user_message_preferences_returns() {
2538 return new external_function_parameters(
2539 array(
2540 'preferences' => self::get_preferences_structure(),
2541 'blocknoncontacts' => new external_value(PARAM_BOOL, 'Whether to block or not messages from non contacts'),
e86f0cb4
JL
2542 'warnings' => new external_warnings(),
2543 )
2544 );
2545 }
a623b6b8 2546}