MDL-54708 message: add renderer for get_popup_notification
[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
JM
54 'text' => new external_value(PARAM_RAW, 'the text of the message'),
55 'textformat' => new external_format_value('text', VALUE_DEFAULT),
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
9aa012b5
MN
423 /**
424 * Get messagearea conversations parameters.
425 *
426 * @return external_function_parameters
427 */
428 public static function data_for_messagearea_conversations_parameters() {
429 return new external_function_parameters(
430 array(
431 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
432 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
433 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
434 )
435 );
436 }
437
438 /**
439 * Get messagearea conversations.
440 *
441 * @param int $userid The id of the user who we are viewing conversations for
442 * @param int $limitfrom
443 * @param int $limitnum
444 * @return external_function_parameters
445 */
446 public static function data_for_messagearea_conversations($userid, $limitfrom = 0, $limitnum = 0) {
447 global $CFG, $PAGE;
448
449 // Check if messaging is enabled.
450 if (!$CFG->messaging) {
451 throw new moodle_exception('disabled', 'message');
452 }
453
454 $params = array(
455 'userid' => $userid,
456 'limitfrom' => $limitfrom,
457 'limitnum' => $limitnum
458 );
459 self::validate_parameters(self::data_for_messagearea_conversations_parameters(), $params);
460
461 self::validate_context(context_user::instance($userid));
462
463 $contacts = \core_message\api::get_conversations($userid, 0, $limitfrom, $limitnum);
464
465 $renderer = $PAGE->get_renderer('core_message');
466 return $contacts->export_for_template($renderer);
467 }
468
469 /**
470 * Get messagearea conversations returns.
471 *
472 * @return external_function_parameters
473 */
474 public static function data_for_messagearea_conversations_returns() {
475 return new external_function_parameters(
476 array(
477 'userid' => new external_value(PARAM_INT, 'The id of the user who we are viewing conversations for'),
478 'conversationsselected' => new external_value(PARAM_BOOL, 'Determines if conversations were selected,
479 otherwise contacts were'),
480 'contacts' => new external_multiple_structure(
481 new external_single_structure(
482 array(
483 'userid' => new external_value(PARAM_INT, 'The user\'s id'),
484 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
485 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
486 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
487 'lastmessage' => new external_value(PARAM_NOTAGS, 'The user\'s last message', VALUE_OPTIONAL),
eda6bc19
RW
488 'isonline' => new external_value(PARAM_BOOL, 'The user\'s online status', VALUE_OPTIONAL),
489 'isread' => new external_value(PARAM_BOOL, 'If the user has read the message', VALUE_OPTIONAL),
9aa012b5
MN
490 )
491 )
492 )
493 )
494 );
495 }
496
497 /**
498 * Get messagearea contacts parameters.
499 *
500 * @return external_function_parameters
501 */
502 public static function data_for_messagearea_contacts_parameters() {
503 return self::data_for_messagearea_conversations_parameters();
504 }
505
506 /**
507 * Get messagearea contacts parameters.
508 *
509 * @param int $userid The id of the user who we are viewing conversations for
510 * @param int $limitfrom
511 * @param int $limitnum
512 * @return external_function_parameters
513 */
514 public static function data_for_messagearea_contacts($userid, $limitfrom = 0, $limitnum = 0) {
515 global $CFG, $PAGE;
516
517 // Check if messaging is enabled.
518 if (!$CFG->messaging) {
519 throw new moodle_exception('disabled', 'message');
520 }
521
522 $params = array(
523 'userid' => $userid,
524 'limitfrom' => $limitfrom,
525 'limitnum' => $limitnum
526 );
527 self::validate_parameters(self::data_for_messagearea_contacts_parameters(), $params);
528
529 self::validate_context(context_user::instance($userid));
530
531 $contacts = \core_message\api::get_contacts($userid, $limitfrom, $limitnum);
532
533 $renderer = $PAGE->get_renderer('core_message');
534 return $contacts->export_for_template($renderer);
535 }
536
537 /**
538 * Get messagearea contacts returns.
539 *
540 * @return external_function_parameters
541 */
542 public static function data_for_messagearea_contacts_returns() {
543 return self::data_for_messagearea_conversations_returns();
544 }
545
3cd13828
MN
546 /**
547 * Get messagearea messages parameters.
548 *
549 * @return external_function_parameters
550 */
551 public static function data_for_messagearea_messages_parameters() {
552 return new external_function_parameters(
553 array(
554 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
555 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
556 'limitfrom' => new external_value(PARAM_INT, 'Limit from', VALUE_DEFAULT, 0),
8ec78c48
MN
557 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0),
558 'newest' => new external_value(PARAM_BOOL, 'Newest first?', VALUE_DEFAULT, false),
3cd13828
MN
559 )
560 );
561 }
562
563 /**
564 * Get messagearea messages.
565 *
566 * @param int $currentuserid The current user's id
567 * @param int $otheruserid The other user's id
568 * @param int $limitfrom
569 * @param int $limitnum
8ec78c48 570 * @param boolean $newest
3cd13828
MN
571 * @return external_description
572 */
8ec78c48 573 public static function data_for_messagearea_messages($currentuserid, $otheruserid, $limitfrom = 0, $limitnum = 0, $newest = false) {
3cd13828
MN
574 global $CFG, $PAGE;
575
576 // Check if messaging is enabled.
577 if (!$CFG->messaging) {
578 throw new moodle_exception('disabled', 'message');
579 }
580
581 $params = array(
582 'currentuserid' => $currentuserid,
583 'otheruserid' => $otheruserid,
584 'limitfrom' => $limitfrom,
8ec78c48
MN
585 'limitnum' => $limitnum,
586 'newest' => $newest
3cd13828
MN
587 );
588 self::validate_parameters(self::data_for_messagearea_messages_parameters(), $params);
589
590 self::validate_context(context_user::instance($currentuserid));
591
8ec78c48
MN
592 if ($newest) {
593 $sort = 'timecreated DESC';
594 } else {
595 $sort = 'timecreated ASC';
596 }
597 $messages = \core_message\api::get_messages($currentuserid, $otheruserid, $limitfrom, $limitnum, $sort);
3cd13828
MN
598
599 $renderer = $PAGE->get_renderer('core_message');
600 return $messages->export_for_template($renderer);
601 }
602
603 /**
604 * Get messagearea messages returns.
605 *
606 * @return external_description
607 */
608 public static function data_for_messagearea_messages_returns() {
609 return new external_function_parameters(
610 array(
611 'iscurrentuser' => new external_value(PARAM_BOOL, 'Is the currently logged in user the user we are viewing the messages on behalf of?'),
612 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
613 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
614 'otheruserfullname' => new external_value(PARAM_NOTAGS, 'The other user\'s fullname'),
615 'messages' => new external_multiple_structure(
616 new external_single_structure(
617 array(
3090f52f 618 'id' => new external_value(PARAM_INT, 'The id of the message'),
3cd13828 619 'text' => new external_value(PARAM_RAW, 'The text of the message'),
3090f52f 620 'displayblocktime' => new external_value(PARAM_BOOL, 'Should we display the block time?'),
3cd13828
MN
621 'blocktime' => new external_value(PARAM_NOTAGS, 'The time to display above the message'),
622 'position' => new external_value(PARAM_ALPHA, 'The position of the text'),
623 'timesent' => new external_value(PARAM_NOTAGS, 'The time the message was sent'),
3090f52f 624 'isread' => new external_value(PARAM_INT, 'Determines if the message was read or not'),
3cd13828
MN
625 )
626 )
627 )
628 )
629 );
630 }
631
c060cd49
MN
632 /**
633 * Get the most recent message in a conversation parameters.
634 *
635 * @return external_function_parameters
636 */
637 public static function data_for_messagearea_get_most_recent_message_parameters() {
638 return new external_function_parameters(
639 array(
640 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
641 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
642 )
643 );
644 }
645
646 /**
647 * Get the most recent message in a conversation.
648 *
649 * @param int $currentuserid The current user's id
650 * @param int $otheruserid The other user's id
651 * @return external_single_structure
652 */
653 public static function data_for_messagearea_get_most_recent_message($currentuserid, $otheruserid) {
654 global $CFG, $PAGE;
655
656 // Check if messaging is enabled.
657 if (!$CFG->messaging) {
658 throw new moodle_exception('disabled', 'message');
659 }
660
661 $params = array(
662 'currentuserid' => $currentuserid,
663 'otheruserid' => $otheruserid
664 );
665 self::validate_parameters(self::data_for_messagearea_get_most_recent_message_parameters(), $params);
666
667 self::validate_context(context_user::instance($currentuserid));
668
669 $message = \core_message\api::get_most_recent_message($currentuserid, $otheruserid);
670
671 $renderer = $PAGE->get_renderer('core_message');
672 return $message->export_for_template($renderer);
673 }
674
675 /**
676 * Get messagearea get most recent message returns.
677 *
678 * @return external_single_structure
679 */
680 public static function data_for_messagearea_get_most_recent_message_returns() {
681 return new external_single_structure(
682 array(
3090f52f 683 'id' => new external_value(PARAM_INT, 'The id of the message'),
c060cd49 684 'text' => new external_value(PARAM_RAW, 'The text of the message'),
3090f52f 685 'displayblocktime' => new external_value(PARAM_BOOL, 'Should we display the block time?'),
c060cd49
MN
686 'blocktime' => new external_value(PARAM_NOTAGS, 'The time to display above the message'),
687 'position' => new external_value(PARAM_ALPHA, 'The position of the text'),
688 'timesent' => new external_value(PARAM_NOTAGS, 'The time the message was sent'),
3090f52f 689 'isread' => new external_value(PARAM_INT, 'Determines if the message was read or not'),
c060cd49
MN
690 )
691 );
692 }
693
c6e97f54
MN
694 /**
695 * The get profile parameters.
696 *
697 * @return external_function_parameters
698 */
699 public static function data_for_messagearea_get_profile_parameters() {
700 return new external_function_parameters(
701 array(
702 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
703 'otheruserid' => new external_value(PARAM_INT, 'The id of the user whose profile we want to view'),
704 )
705 );
706 }
707
708 /**
709 * Get the profile information for a contact.
710 *
711 * @param int $currentuserid The current user's id
712 * @param int $otheruserid The id of the user whose profile we are viewing
713 * @return external_single_structure
714 */
715 public static function data_for_messagearea_get_profile($currentuserid, $otheruserid) {
716 global $CFG, $PAGE;
717
718 // Check if messaging is enabled.
719 if (!$CFG->messaging) {
720 throw new moodle_exception('disabled', 'message');
721 }
722
723 $params = array(
724 'currentuserid' => $currentuserid,
725 'otheruserid' => $otheruserid
726 );
727 self::validate_parameters(self::data_for_messagearea_get_profile_parameters(), $params);
728
729 self::validate_context(context_user::instance($otheruserid));
730
731 $profile = \core_message\api::get_profile($currentuserid, $otheruserid);
732
733 $renderer = $PAGE->get_renderer('core_message');
734 return $profile->export_for_template($renderer);
735 }
736
737 /**
738 * Get profile returns.
739 *
740 * @return external_single_structure
741 */
742 public static function data_for_messagearea_get_profile_returns() {
743 return new external_single_structure(
744 array(
745 'iscurrentuser' => new external_value(PARAM_BOOL, 'Is the currently logged in user the user we are viewing the profile on behalf of?'),
746 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
747 'otheruserid' => new external_value(PARAM_INT, 'The id of the user whose profile we are viewing'),
748 'email' => new external_value(core_user::get_property_type('email'), 'An email address'),
749 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user'),
750 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user'),
751 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
752 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
753 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
754 'isblocked' => new external_value(PARAM_BOOL, 'Is the user blocked?'),
755 'iscontact' => new external_value(PARAM_BOOL, 'Is the user a contact?')
756 )
757 );
758 }
759
d6731600
FM
760 /**
761 * Get contacts parameters description.
762 *
763 * @return external_function_parameters
5bcfd504 764 * @since Moodle 2.5
d6731600
FM
765 */
766 public static function get_contacts_parameters() {
767 return new external_function_parameters(array());
768 }
769
770 /**
771 * Get contacts.
772 *
773 * @param array $userids array of user IDs.
774 * @return external_description
5bcfd504 775 * @since Moodle 2.5
d6731600
FM
776 */
777 public static function get_contacts() {
d85bedf7 778 global $CFG, $PAGE;
436bbf89
DM
779
780 // Check if messaging is enabled.
781 if (!$CFG->messaging) {
782 throw new moodle_exception('disabled', 'message');
783 }
784
d6731600
FM
785 require_once($CFG->dirroot . '/user/lib.php');
786
787 list($online, $offline, $strangers) = message_get_contacts();
788 $allcontacts = array('online' => $online, 'offline' => $offline, 'strangers' => $strangers);
789 foreach ($allcontacts as $mode => $contacts) {
790 foreach ($contacts as $key => $contact) {
791 $newcontact = array(
792 'id' => $contact->id,
793 'fullname' => fullname($contact),
794 'unread' => $contact->messagecount
795 );
796
d85bedf7
JL
797 $userpicture = new user_picture($contact);
798 $userpicture->size = 1; // Size f1.
799 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
800 $userpicture->size = 0; // Size f2.
801 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
802
803 $allcontacts[$mode][$key] = $newcontact;
804 }
805 }
806 return $allcontacts;
807 }
808
809 /**
810 * Get contacts return description.
811 *
812 * @return external_description
5bcfd504 813 * @since Moodle 2.5
d6731600
FM
814 */
815 public static function get_contacts_returns() {
816 return new external_single_structure(
817 array(
818 'online' => new external_multiple_structure(
819 new external_single_structure(
820 array(
821 'id' => new external_value(PARAM_INT, 'User ID'),
822 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
823 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
824 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
825 'unread' => new external_value(PARAM_INT, 'Unread message count')
826 )
827 ),
828 'List of online contacts'
829 ),
830 'offline' => new external_multiple_structure(
831 new external_single_structure(
832 array(
833 'id' => new external_value(PARAM_INT, 'User ID'),
834 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
835 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
836 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
837 'unread' => new external_value(PARAM_INT, 'Unread message count')
838 )
839 ),
840 'List of offline contacts'
841 ),
842 'strangers' => new external_multiple_structure(
843 new external_single_structure(
844 array(
845 'id' => new external_value(PARAM_INT, 'User ID'),
846 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
847 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
848 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
849 'unread' => new external_value(PARAM_INT, 'Unread message count')
850 )
851 ),
852 'List of users that are not in the user\'s contact list but have sent a message'
853 )
854 )
855 );
856 }
857
858 /**
859 * Search contacts parameters description.
860 *
861 * @return external_function_parameters
5bcfd504 862 * @since Moodle 2.5
d6731600
FM
863 */
864 public static function search_contacts_parameters() {
865 return new external_function_parameters(
866 array(
867 'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
868 'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
869 VALUE_DEFAULT, false)
870 )
871 );
872 }
873
874 /**
875 * Search contacts.
876 *
877 * @param string $searchtext query string.
878 * @param bool $onlymycourses limit the search to the user's courses only.
879 * @return external_description
5bcfd504 880 * @since Moodle 2.5
d6731600
FM
881 */
882 public static function search_contacts($searchtext, $onlymycourses = false) {
d85bedf7 883 global $CFG, $USER, $PAGE;
11d83ab3 884 require_once($CFG->dirroot . '/user/lib.php');
436bbf89
DM
885
886 // Check if messaging is enabled.
887 if (!$CFG->messaging) {
888 throw new moodle_exception('disabled', 'message');
889 }
890
d6731600
FM
891 require_once($CFG->libdir . '/enrollib.php');
892
893 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
894 $params = self::validate_parameters(self::search_contacts_parameters(), $params);
895
896 // Extra validation, we do not allow empty queries.
897 if ($params['searchtext'] === '') {
898 throw new moodle_exception('querystringcannotbeempty');
899 }
900
901 $courseids = array();
902 if ($params['onlymycourses']) {
903 $mycourses = enrol_get_my_courses(array('id'));
904 foreach ($mycourses as $mycourse) {
905 $courseids[] = $mycourse->id;
906 }
907 } else {
908 $courseids[] = SITEID;
909 }
910
911 // Retrieving the users matching the query.
912 $users = message_search_users($courseids, $params['searchtext']);
913 $results = array();
914 foreach ($users as $user) {
915 $results[$user->id] = $user;
916 }
917
918 // Reorganising information.
919 foreach ($results as &$user) {
920 $newuser = array(
921 'id' => $user->id,
922 'fullname' => fullname($user)
923 );
924
925 // Avoid undefined property notice as phone not specified.
926 $user->phone1 = null;
927 $user->phone2 = null;
928
d85bedf7
JL
929 $userpicture = new user_picture($user);
930 $userpicture->size = 1; // Size f1.
931 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
932 $userpicture->size = 0; // Size f2.
933 $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
d6731600
FM
934
935 $user = $newuser;
936 }
937
938 return $results;
939 }
940
941 /**
942 * Search contacts return description.
943 *
944 * @return external_description
5bcfd504 945 * @since Moodle 2.5
d6731600
FM
946 */
947 public static function search_contacts_returns() {
948 return new external_multiple_structure(
949 new external_single_structure(
950 array(
951 'id' => new external_value(PARAM_INT, 'User ID'),
952 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
953 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
954 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
955 )
956 ),
957 'List of contacts'
958 );
959 }
aff9da17
JL
960
961 /**
962 * Get messages parameters description.
963 *
964 * @return external_function_parameters
193edf7f 965 * @since 2.8
aff9da17
JL
966 */
967 public static function get_messages_parameters() {
968 return new external_function_parameters(
969 array(
6ff4464b 970 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
127ef540
SH
971 'useridfrom' => new external_value(
972 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
973 VALUE_DEFAULT, 0),
974 'type' => new external_value(
975 PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
976 VALUE_DEFAULT, 'both'),
6ff4464b 977 'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
127ef540
SH
978 'newestfirst' => new external_value(
979 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
980 VALUE_DEFAULT, true),
aff9da17 981 'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
127ef540
SH
982 'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
983 )
aff9da17
JL
984 );
985 }
986
987 /**
988 * Get messages function implementation.
127ef540
SH
989 *
990 * @since 2.8
991 * @throws invalid_parameter_exception
992 * @throws moodle_exception
6ff4464b
JL
993 * @param int $useridto the user id who received the message
994 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
193edf7f 995 * @param string $type type of message to return, expected values: notifications, conversations and both
aff9da17 996 * @param bool $read true for retreiving read messages, false for unread
6ff4464b 997 * @param bool $newestfirst true for ordering by newest first, false for oldest first
aff9da17
JL
998 * @param int $limitfrom limit from
999 * @param int $limitnum limit num
1000 * @return external_description
aff9da17 1001 */
193edf7f 1002 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
aff9da17 1003 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
127ef540 1004 global $CFG, $USER;
aff9da17
JL
1005
1006 $warnings = array();
1007
1008 $params = array(
1009 'useridto' => $useridto,
6ff4464b 1010 'useridfrom' => $useridfrom,
aff9da17
JL
1011 'type' => $type,
1012 'read' => $read,
aff9da17
JL
1013 'newestfirst' => $newestfirst,
1014 'limitfrom' => $limitfrom,
1015 'limitnum' => $limitnum
1016 );
1017
1018 $params = self::validate_parameters(self::get_messages_parameters(), $params);
1019
1020 $context = context_system::instance();
1021 self::validate_context($context);
1022
1023 $useridto = $params['useridto'];
6ff4464b 1024 $useridfrom = $params['useridfrom'];
aff9da17
JL
1025 $type = $params['type'];
1026 $read = $params['read'];
aff9da17
JL
1027 $newestfirst = $params['newestfirst'];
1028 $limitfrom = $params['limitfrom'];
1029 $limitnum = $params['limitnum'];
1030
1031 $allowedvalues = array('notifications', 'conversations', 'both');
1032 if (!in_array($type, $allowedvalues)) {
1033 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
1034 'allowed values are: ' . implode(',', $allowedvalues));
1035 }
1036
1037 // Check if private messaging between users is allowed.
1038 if (empty($CFG->messaging)) {
1039 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
aff9da17
JL
1040 if ($type == "conversations") {
1041 throw new moodle_exception('disabled', 'message');
1042 }
1043 if ($type == "both") {
1044 $warning = array();
1045 $warning['item'] = 'message';
1046 $warning['itemid'] = $USER->id;
1047 $warning['warningcode'] = '1';
1048 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
1049 Only notifications will be returned';
1050 $warnings[] = $warning;
1051 }
1052 }
1053
1054 if (!empty($useridto)) {
6ff4464b
JL
1055 if (core_user::is_real_user($useridto)) {
1056 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1057 } else {
1058 throw new moodle_exception('invaliduser');
1059 }
aff9da17
JL
1060 }
1061
1062 if (!empty($useridfrom)) {
1063 // We use get_user here because the from user can be the noreply or support user.
1064 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1065 }
1066
1067 // Check if the current user is the sender/receiver or just a privileged user.
1068 if ($useridto != $USER->id and $useridfrom != $USER->id and
1069 !has_capability('moodle/site:readallmessages', $context)) {
1070 throw new moodle_exception('accessdenied', 'admin');
1071 }
1072
127ef540 1073 // Which type of messages to retrieve.
193edf7f 1074 $notifications = -1;
aff9da17 1075 if ($type != 'both') {
193edf7f 1076 $notifications = ($type == 'notifications') ? 1 : 0;
aff9da17
JL
1077 }
1078
aff9da17 1079 $orderdirection = $newestfirst ? 'DESC' : 'ASC';
193edf7f 1080 $sort = "mr.timecreated $orderdirection";
aff9da17 1081
193edf7f 1082 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
aff9da17
JL
1083 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
1084
1085 // In some cases, we don't need to get the to/from user objects from the sql query.
1086 $userfromfullname = '';
1087 $usertofullname = '';
1088
1089 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
1090 if (!empty($useridto)) {
1091 $usertofullname = fullname($userto, $canviewfullname);
1092 // The user from may or may not be filled.
1093 if (!empty($useridfrom)) {
1094 $userfromfullname = fullname($userfrom, $canviewfullname);
1095 }
1096 } else {
1097 // If the useridto field is empty, the useridfrom must be filled.
1098 $userfromfullname = fullname($userfrom, $canviewfullname);
1099 }
aff9da17
JL
1100 foreach ($messages as $mid => $message) {
1101
ea21d637
JL
1102 // Do not return deleted messages.
1103 if (($useridto == $USER->id and $message->timeusertodeleted) or
1104 ($useridfrom == $USER->id and $message->timeuserfromdeleted)) {
1105
1106 unset($messages[$mid]);
1107 continue;
1108 }
1109
aff9da17
JL
1110 // We need to get the user from the query.
1111 if (empty($userfromfullname)) {
6ff4464b
JL
1112 // Check for non-reply and support users.
1113 if (core_user::is_real_user($message->useridfrom)) {
127ef540 1114 $user = new stdClass();
6ff4464b
JL
1115 $user = username_load_fields_from_object($user, $message, 'userfrom');
1116 $message->userfromfullname = fullname($user, $canviewfullname);
1117 } else {
1118 $user = core_user::get_user($message->useridfrom);
1119 $message->userfromfullname = fullname($user, $canviewfullname);
1120 }
aff9da17
JL
1121 } else {
1122 $message->userfromfullname = $userfromfullname;
1123 }
1124
1125 // We need to get the user from the query.
1126 if (empty($usertofullname)) {
127ef540 1127 $user = new stdClass();
aff9da17
JL
1128 $user = username_load_fields_from_object($user, $message, 'userto');
1129 $message->usertofullname = fullname($user, $canviewfullname);
1130 } else {
1131 $message->usertofullname = $usertofullname;
1132 }
1133
193edf7f 1134 // This field is only available in the message_read table.
aff9da17
JL
1135 if (!isset($message->timeread)) {
1136 $message->timeread = 0;
1137 }
1138
aff9da17 1139 $message->text = message_format_message_text($message);
aff9da17
JL
1140 $messages[$mid] = (array) $message;
1141 }
1142 }
1143
1144 $results = array(
1145 'messages' => $messages,
1146 'warnings' => $warnings
1147 );
1148
1149 return $results;
1150 }
1151
1152 /**
1153 * Get messages return description.
1154 *
6ff4464b 1155 * @return external_single_structure
193edf7f 1156 * @since 2.8
aff9da17
JL
1157 */
1158 public static function get_messages_returns() {
1159 return new external_single_structure(
1160 array(
1161 'messages' => new external_multiple_structure(
1162 new external_single_structure(
1163 array(
193edf7f 1164 'id' => new external_value(PARAM_INT, 'Message id'),
aff9da17
JL
1165 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
1166 'useridto' => new external_value(PARAM_INT, 'User to id'),
1167 'subject' => new external_value(PARAM_TEXT, 'The message subject'),
1168 'text' => new external_value(PARAM_RAW, 'The message text formated'),
1169 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
193edf7f 1170 'fullmessageformat' => new external_format_value('fullmessage'),
aff9da17
JL
1171 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
1172 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
1173 'notification' => new external_value(PARAM_INT, 'Is a notification?'),
1174 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
1175 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
1176 'timecreated' => new external_value(PARAM_INT, 'Time created'),
1177 'timeread' => new external_value(PARAM_INT, 'Time read'),
1178 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
1179 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
1180 ), 'message'
1181 )
1182 ),
1183 'warnings' => new external_warnings()
1184 )
1185 );
3274d5ca
RW
1186 }
1187
1188 /**
ada7695d 1189 * Get popup notifications parameters description.
3274d5ca
RW
1190 *
1191 * @return external_function_parameters
1192 * @since 3.2
1193 */
ada7695d 1194 public static function get_popup_notifications_parameters() {
3274d5ca
RW
1195 return new external_function_parameters(
1196 array(
1197 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
3274d5ca
RW
1198 'status' => new external_value(
1199 PARAM_ALPHA, 'filter the results to just "read" or "unread" notifications',
1200 VALUE_DEFAULT, ''),
c5dd16a1
RW
1201 'embedpreference' => new external_value(
1202 PARAM_BOOL, 'true for returning user\'s preference for the notification',
1203 VALUE_DEFAULT, false),
3274d5ca
RW
1204 'embeduserto' => new external_value(
1205 PARAM_BOOL, 'true for returning user details for the recipient in each notification',
1206 VALUE_DEFAULT, false),
1207 'embeduserfrom' => new external_value(
1208 PARAM_BOOL, 'true for returning user details for the sender in each notification',
1209 VALUE_DEFAULT, false),
1210 'newestfirst' => new external_value(
1211 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
1212 VALUE_DEFAULT, true),
1213 'markasread' => new external_value(
1214 PARAM_BOOL, 'mark notifications as read when they are returned by this function',
1215 VALUE_DEFAULT, false),
1216 'limit' => new external_value(PARAM_INT, 'the number of results to return', VALUE_DEFAULT, 0),
1217 'offset' => new external_value(PARAM_INT, 'offset the result set by a given amount', VALUE_DEFAULT, 0)
1218 )
1219 );
1220 }
1221
1222 /**
1223 * Get notifications function.
1224 *
1225 * @since 3.2
1226 * @throws invalid_parameter_exception
1227 * @throws moodle_exception
c5dd16a1 1228 * @param int $useridto the user id who received the message
c5dd16a1
RW
1229 * @param string $status filter the results to only read or unread notifications
1230 * @param bool $embedpreference true to embed the recipient user details in the record for each notification
1231 * @param bool $embeduserto true to embed the recipient user details in the record for each notification
1232 * @param bool $embeduserfrom true to embed the send user details in the record for each notification
1233 * @param bool $newestfirst true for ordering by newest first, false for oldest first
1234 * @param bool $markasread mark notifications as read when they are returned by this function
1235 * @param int $limit the number of results to return
1236 * @param int $offset offset the result set by a given amount
3274d5ca
RW
1237 * @return external_description
1238 */
ada7695d 1239 public static function get_popup_notifications($useridto, $status, $embedpreference,
c5dd16a1 1240 $embeduserto, $embeduserfrom, $newestfirst, $markasread, $limit, $offset) {
24a76780 1241 global $CFG, $USER, $PAGE;
3274d5ca
RW
1242
1243 $params = self::validate_parameters(
ada7695d 1244 self::get_popup_notifications_parameters(),
3274d5ca
RW
1245 array(
1246 'useridto' => $useridto,
3274d5ca 1247 'status' => $status,
c5dd16a1 1248 'embedpreference' => $embedpreference,
3274d5ca
RW
1249 'embeduserto' => $embeduserto,
1250 'embeduserfrom' => $embeduserfrom,
1251 'newestfirst' => $newestfirst,
1252 'markasread' => $markasread,
1253 'limit' => $limit,
1254 'offset' => $offset,
1255 )
1256 );
1257
1258 $context = context_system::instance();
1259 self::validate_context($context);
1260
1261 $useridto = $params['useridto'];
3274d5ca 1262 $status = $params['status'];
c5dd16a1 1263 $embedpreference = $params['embedpreference'];
3274d5ca
RW
1264 $embeduserto = $params['embeduserto'];
1265 $embeduserfrom = $params['embeduserfrom'];
1266 $newestfirst = $params['newestfirst'];
1267 $markasread = $params['markasread'];
1268 $limit = $params['limit'];
1269 $offset = $params['offset'];
c5dd16a1 1270 $issuperuser = has_capability('moodle/site:readallmessages', $context);
24a76780 1271 $renderer = $PAGE->get_renderer('core_message');
3274d5ca
RW
1272
1273 if (!empty($useridto)) {
1274 if (core_user::is_real_user($useridto)) {
1275 if ($embeduserto) {
1276 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1277 }
1278 } else {
1279 throw new moodle_exception('invaliduser');
1280 }
1281 }
1282
3274d5ca 1283 // Check if the current user is the sender/receiver or just a privileged user.
ada7695d 1284 if ($useridto != $USER->id and !$issuperuser) {
3274d5ca
RW
1285 throw new moodle_exception('accessdenied', 'admin');
1286 }
1287
1288 $sort = $newestfirst ? 'DESC' : 'ASC';
ada7695d 1289 $notifications = message_get_popup_notifications($useridto, $status, $embeduserto, $embeduserfrom, $sort, $limit, $offset);
24a76780 1290 $notificationcontexts = [];
3274d5ca
RW
1291
1292 if ($notifications) {
ada7695d 1293 // In some cases, we don't need to get the to user objects from the sql query.
3274d5ca
RW
1294 $usertofullname = '';
1295
1296 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
1297 if (!empty($useridto) && $embeduserto) {
1298 $usertofullname = fullname($userto);
3274d5ca
RW
1299 }
1300
1301 foreach ($notifications as $notification) {
1302
24a76780
RW
1303 $notificationoutput = new \core_message\output\popup_notification($notification, $embeduserto,
1304 $embeduserfrom, $embedpreference, $usertofullname);
3274d5ca 1305
24a76780
RW
1306 $notificationcontext = $notificationoutput->export_for_template($renderer);
1307 $notificationcontexts[] = $notificationcontext;
c5dd16a1 1308
24a76780
RW
1309 if ($markasread && !$notificationcontext->read) {
1310 message_mark_message_read($notification, time());
3274d5ca
RW
1311 }
1312 }
1313 }
1314
1315 return array(
24a76780 1316 'notifications' => $notificationcontexts,
ada7695d 1317 'unreadcount' => message_count_unread_popup_notifications($useridto),
3274d5ca
RW
1318 );
1319 }
1320
1321 /**
1322 * Get notifications return description.
1323 *
1324 * @return external_single_structure
1325 * @since 3.2
1326 */
ada7695d 1327 public static function get_popup_notifications_returns() {
3274d5ca
RW
1328 return new external_single_structure(
1329 array(
1330 'notifications' => new external_multiple_structure(
1331 new external_single_structure(
1332 array(
1333 'id' => new external_value(PARAM_INT, 'Notification id (this is not guaranteed to be unique within this result set)'),
1334 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
1335 'useridto' => new external_value(PARAM_INT, 'User to id'),
1336 'subject' => new external_value(PARAM_TEXT, 'The notification subject'),
1337 'text' => new external_value(PARAM_RAW, 'The message text formated'),
1338 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
1339 'fullmessageformat' => new external_format_value('fullmessage'),
1340 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
1341 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
1342 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
1343 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
1344 'timecreated' => new external_value(PARAM_INT, 'Time created'),
1345 'timecreatedpretty' => new external_value(PARAM_TEXT, 'Time created in a pretty format'),
1346 'timeread' => new external_value(PARAM_INT, 'Time read'),
1347 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name', VALUE_OPTIONAL),
1348 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name', VALUE_OPTIONAL),
1349 'userfromprofileurl' => new external_value(PARAM_URL, 'User from profile url', VALUE_OPTIONAL),
1350 'read' => new external_value(PARAM_BOOL, 'notification read status'),
1351 'deleted' => new external_value(PARAM_BOOL, 'notification deletion status'),
1352 'iconurl' => new external_value(PARAM_URL, 'URL for notification icon'),
1353 'component' => new external_value(PARAM_TEXT, 'The component that generated the notification', VALUE_OPTIONAL),
1354 'eventtype' => new external_value(PARAM_TEXT, 'The type of notification', VALUE_OPTIONAL),
c5dd16a1
RW
1355 'preference' => new external_single_structure(
1356 array (
1357 'key' => new external_value(PARAM_TEXT, 'The preference key'),
1358 'loggedin' => new external_value(PARAM_TEXT, 'The logged in preference setting'),
1359 'loggedoff' => new external_value(PARAM_TEXT, 'The logged off preference setting'),
1360 ),
1361 'The preference configuration',
1362 VALUE_OPTIONAL
1363 ),
3274d5ca
RW
1364 ), 'message'
1365 )
1366 ),
1367 'unreadcount' => new external_value(PARAM_INT, 'the user whose blocked users we want to retrieve'),
1368 )
1369 );
1370 }
1371
1372 /**
1373 * Mark all notifications as read parameters description.
1374 *
1375 * @return external_function_parameters
1376 * @since 3.2
1377 */
1378 public static function mark_all_notifications_as_read_parameters() {
1379 return new external_function_parameters(
1380 array(
1381 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1382 'useridfrom' => new external_value(
1383 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1384 VALUE_DEFAULT, 0),
1385 )
1386 );
1387 }
1388
1389 /**
1390 * Mark all notifications as read function.
1391 *
1392 * @since 3.2
1393 * @throws invalid_parameter_exception
1394 * @throws moodle_exception
1395 * @param int $useridto the user id who received the message
1396 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1397 * @return external_description
1398 */
1399 public static function mark_all_notifications_as_read($useridto, $useridfrom) {
1400 global $CFG, $USER;
1401
1402 $params = self::validate_parameters(
1403 self::mark_all_notifications_as_read_parameters(),
1404 array(
1405 'useridto' => $useridto,
1406 'useridfrom' => $useridfrom,
1407 )
1408 );
1409
1410 $context = context_system::instance();
1411 self::validate_context($context);
1412
1413 $useridto = $params['useridto'];
1414 $useridfrom = $params['useridfrom'];
1415
1416 if (!empty($useridto)) {
1417 if (core_user::is_real_user($useridto)) {
1418 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1419 } else {
1420 throw new moodle_exception('invaliduser');
1421 }
1422 }
1423
1424 if (!empty($useridfrom)) {
1425 // We use get_user here because the from user can be the noreply or support user.
1426 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1427 }
1428
1429 // Check if the current user is the sender/receiver or just a privileged user.
1430 if ($useridto != $USER->id and $useridfrom != $USER->id and
1431 // deleteanymessage seems more reasonable here than readallmessages.
1432 !has_capability('moodle/site:deleteanymessage', $context)) {
1433 throw new moodle_exception('accessdenied', 'admin');
1434 }
1435
1436 message_mark_all_read_for_user($useridto, $useridfrom, 'notification');
1437
1438 return true;
1439 }
1440
1441 /**
1442 * Mark all notifications as read return description.
1443 *
1444 * @return external_single_structure
1445 * @since 3.2
1446 */
1447 public static function mark_all_notifications_as_read_returns() {
1448 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
1449 }
1450
1451 /**
1452 * Get unread notification count parameters description.
1453 *
1454 * @return external_function_parameters
1455 * @since 3.2
1456 */
ada7695d 1457 public static function get_unread_popup_notification_count_parameters() {
3274d5ca
RW
1458 return new external_function_parameters(
1459 array(
1460 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
3274d5ca
RW
1461 )
1462 );
1463 }
1464
1465 /**
1466 * Get unread notification count function.
1467 *
1468 * @since 3.2
1469 * @throws invalid_parameter_exception
1470 * @throws moodle_exception
1471 * @param int $useridto the user id who received the message
3274d5ca
RW
1472 * @return external_description
1473 */
ada7695d 1474 public static function get_unread_popup_notification_count($useridto) {
3274d5ca
RW
1475 global $CFG, $USER;
1476
1477 $params = self::validate_parameters(
ada7695d
RW
1478 self::get_unread_popup_notification_count_parameters(),
1479 array('useridto' => $useridto)
3274d5ca
RW
1480 );
1481
1482 $context = context_system::instance();
1483 self::validate_context($context);
1484
1485 $useridto = $params['useridto'];
3274d5ca
RW
1486
1487 if (!empty($useridto)) {
1488 if (core_user::is_real_user($useridto)) {
1489 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1490 } else {
1491 throw new moodle_exception('invaliduser');
1492 }
1493 }
1494
3274d5ca 1495 // Check if the current user is the sender/receiver or just a privileged user.
ada7695d 1496 if ($useridto != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
3274d5ca
RW
1497 throw new moodle_exception('accessdenied', 'admin');
1498 }
1499
ada7695d 1500 return message_count_unread_popup_notifications($useridto);
3274d5ca
RW
1501 }
1502
1503 /**
ada7695d 1504 * Get unread popup notification count return description.
3274d5ca
RW
1505 *
1506 * @return external_single_structure
1507 * @since 3.2
1508 */
ada7695d 1509 public static function get_unread_popup_notification_count_returns() {
3274d5ca 1510 return new external_value(PARAM_INT, 'the user whose blocked users we want to retrieve');
aff9da17
JL
1511 }
1512
60ab2e1b
JL
1513 /**
1514 * Get blocked users parameters description.
1515 *
1516 * @return external_function_parameters
1517 * @since 2.9
1518 */
1519 public static function get_blocked_users_parameters() {
1520 return new external_function_parameters(
1521 array(
1522 'userid' => new external_value(PARAM_INT,
1523 'the user whose blocked users we want to retrieve',
1524 VALUE_REQUIRED),
1525 )
1526 );
1527 }
1528
1529 /**
1530 * Retrieve a list of users blocked
1531 *
1532 * @param int $userid the user whose blocked users we want to retrieve
1533 * @return external_description
1534 * @since 2.9
1535 */
1536 public static function get_blocked_users($userid) {
d85bedf7 1537 global $CFG, $USER, $PAGE;
60ab2e1b
JL
1538
1539 // Warnings array, it can be empty at the end but is mandatory.
1540 $warnings = array();
1541
1542 // Validate params.
1543 $params = array(
1544 'userid' => $userid
1545 );
1546 $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
1547 $userid = $params['userid'];
1548
1549 // Validate context.
1550 $context = context_system::instance();
1551 self::validate_context($context);
1552
1553 // Check if private messaging between users is allowed.
1554 if (empty($CFG->messaging)) {
1555 throw new moodle_exception('disabled', 'message');
1556 }
1557
4485f7c5
JL
1558 $user = core_user::get_user($userid, '*', MUST_EXIST);
1559 core_user::require_active_user($user);
60ab2e1b
JL
1560
1561 // Check if we have permissions for retrieve the information.
1562 if ($userid != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
1563 throw new moodle_exception('accessdenied', 'admin');
1564 }
1565
1566 // Now, we can get safely all the blocked users.
1567 $users = message_get_blocked_users($user);
1568
1569 $blockedusers = array();
1570 foreach ($users as $user) {
1571 $newuser = array(
1572 'id' => $user->id,
1573 'fullname' => fullname($user),
1574 );
0b074e88 1575
d85bedf7
JL
1576 $userpicture = new user_picture($user);
1577 $userpicture->size = 1; // Size f1.
1578 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
60ab2e1b
JL
1579
1580 $blockedusers[] = $newuser;
1581 }
1582
1583 $results = array(
1584 'users' => $blockedusers,
1585 'warnings' => $warnings
1586 );
1587 return $results;
1588 }
1589
1590 /**
1591 * Get blocked users return description.
1592 *
1593 * @return external_single_structure
1594 * @since 2.9
1595 */
1596 public static function get_blocked_users_returns() {
1597 return new external_single_structure(
1598 array(
1599 'users' => new external_multiple_structure(
1600 new external_single_structure(
1601 array(
1602 'id' => new external_value(PARAM_INT, 'User ID'),
1603 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1604 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL)
1605 )
1606 ),
1607 'List of blocked users'
1608 ),
1609 'warnings' => new external_warnings()
1610 )
1611 );
1612 }
1613
31c474da
JL
1614 /**
1615 * Returns description of method parameters
1616 *
1617 * @return external_function_parameters
1618 * @since 2.9
1619 */
1620 public static function mark_message_read_parameters() {
1621 return new external_function_parameters(
1622 array(
1623 'messageid' => new external_value(PARAM_INT, 'id of the message (in the message table)'),
1624 'timeread' => new external_value(PARAM_INT, 'timestamp for when the message should be marked read')
1625 )
1626 );
1627 }
1628
1629 /**
1630 * Mark a single message as read, trigger message_viewed event
1631 *
1632 * @param int $messageid id of the message (in the message table)
1633 * @param int $timeread timestamp for when the message should be marked read
1634 * @return external_description
1635 * @throws invalid_parameter_exception
1636 * @throws moodle_exception
1637 * @since 2.9
1638 */
1639 public static function mark_message_read($messageid, $timeread) {
1640 global $CFG, $DB, $USER;
31c474da
JL
1641
1642 // Check if private messaging between users is allowed.
1643 if (empty($CFG->messaging)) {
1644 throw new moodle_exception('disabled', 'message');
1645 }
1646
1647 // Warnings array, it can be empty at the end but is mandatory.
1648 $warnings = array();
1649
1650 // Validate params.
1651 $params = array(
1652 'messageid' => $messageid,
1653 'timeread' => $timeread
1654 );
1655 $params = self::validate_parameters(self::mark_message_read_parameters(), $params);
1656
1657 // Validate context.
1658 $context = context_system::instance();
1659 self::validate_context($context);
1660
1661 $message = $DB->get_record('message', array('id' => $params['messageid']), '*', MUST_EXIST);
1662
1663 if ($message->useridto != $USER->id) {
1664 throw new invalid_parameter_exception('Invalid messageid, you don\'t have permissions to mark this message as read');
1665 }
1666
1667 $messageid = message_mark_message_read($message, $params['timeread']);
1668
1669 $results = array(
1670 'messageid' => $messageid,
1671 'warnings' => $warnings
1672 );
1673 return $results;
1674 }
1675
1676 /**
1677 * Returns description of method result value
1678 *
1679 * @return external_description
1680 * @since 2.9
1681 */
1682 public static function mark_message_read_returns() {
1683 return new external_single_structure(
1684 array(
1685 'messageid' => new external_value(PARAM_INT, 'the id of the message in the message_read table'),
1686 'warnings' => new external_warnings()
1687 )
1688 );
1689 }
1690
dec0cd99
MN
1691 /**
1692 * Returns description of method parameters.
1693 *
1694 * @return external_function_parameters
1695 * @since 3.2
1696 */
1697 public static function delete_conversation_parameters() {
1698 return new external_function_parameters(
1699 array(
1700 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the conversation for'),
1701 'otheruserid' => new external_value(PARAM_INT, 'The user id of the other user in the conversation'),
1702 )
1703 );
1704 }
1705
1706 /**
1707 * Deletes a conversation.
1708 *
1709 * @param int $userid The user id of who we want to delete the conversation for
1710 * @param int $otheruserid The user id of the other user in the conversation
1711 * @return array
1712 * @throws moodle_exception
1713 * @since 3.2
1714 */
1715 public static function delete_conversation($userid, $otheruserid) {
1716 global $CFG;
1717
1718 // Check if private messaging between users is allowed.
1719 if (empty($CFG->messaging)) {
1720 throw new moodle_exception('disabled', 'message');
1721 }
1722
1723 // Warnings array, it can be empty at the end but is mandatory.
1724 $warnings = array();
1725
1726 // Validate params.
1727 $params = array(
1728 'userid' => $userid,
1729 'otheruserid' => $otheruserid,
1730 );
1731 $params = self::validate_parameters(self::delete_conversation_parameters(), $params);
1732
1733 // Validate context.
1734 $context = context_system::instance();
1735 self::validate_context($context);
1736
1737 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1738 core_user::require_active_user($user);
1739
1740 if (\core_message\api::can_delete_conversation($user->id)) {
1741 $status = \core_message\api::delete_conversation($user->id, $otheruserid);
1742 } else {
1743 throw new moodle_exception('You do not have permission to delete messages');
1744 }
1745
1746 $results = array(
1747 'status' => $status,
1748 'warnings' => $warnings
1749 );
1750
1751 return $results;
1752 }
1753
1754 /**
1755 * Returns description of method result value.
1756 *
1757 * @return external_description
1758 * @since 3.2
1759 */
1760 public static function delete_conversation_returns() {
1761 return new external_single_structure(
1762 array(
1763 'status' => new external_value(PARAM_BOOL, 'True if the conversation was deleted, false otherwise'),
1764 'warnings' => new external_warnings()
1765 )
1766 );
1767 }
1768
419b1128
JL
1769 /**
1770 * Returns description of method parameters
1771 *
1772 * @return external_function_parameters
1773 * @since 3.1
1774 */
1775 public static function delete_message_parameters() {
1776 return new external_function_parameters(
1777 array(
1778 'messageid' => new external_value(PARAM_INT, 'The message id'),
1779 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the message for'),
1780 'read' => new external_value(PARAM_BOOL, 'If is a message read', VALUE_DEFAULT, true)
1781 )
1782 );
1783 }
1784
1785 /**
1786 * Deletes a message
1787 *
1788 * @param int $messageid the message id
1789 * @param int $userid the user id of who we want to delete the message for
1790 * @param bool $read if is a message read (default to true)
1791 * @return external_description
1792 * @throws moodle_exception
1793 * @since 3.1
1794 */
1795 public static function delete_message($messageid, $userid, $read = true) {
1796 global $CFG, $DB;
419b1128
JL
1797
1798 // Check if private messaging between users is allowed.
1799 if (empty($CFG->messaging)) {
1800 throw new moodle_exception('disabled', 'message');
1801 }
1802
1803 // Warnings array, it can be empty at the end but is mandatory.
1804 $warnings = array();
1805
1806 // Validate params.
1807 $params = array(
1808 'messageid' => $messageid,
1809 'userid' => $userid,
1810 'read' => $read
1811 );
1812 $params = self::validate_parameters(self::delete_message_parameters(), $params);
1813
1814 // Validate context.
1815 $context = context_system::instance();
1816 self::validate_context($context);
1817
1818 $messagestable = $params['read'] ? 'message_read' : 'message';
1819 $message = $DB->get_record($messagestable, array('id' => $params['messageid']), '*', MUST_EXIST);
1820
1821 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1822 core_user::require_active_user($user);
1823
1824 $status = false;
1825 if (message_can_delete_message($message, $user->id)) {
1826 $status = message_delete_message($message, $user->id);;
1827 } else {
1828 throw new moodle_exception('You do not have permission to delete this message');
1829 }
1830
1831 $results = array(
1832 'status' => $status,
1833 'warnings' => $warnings
1834 );
1835 return $results;
1836 }
1837
1838 /**
1839 * Returns description of method result value
1840 *
1841 * @return external_description
1842 * @since 3.1
1843 */
1844 public static function delete_message_returns() {
1845 return new external_single_structure(
1846 array(
1847 'status' => new external_value(PARAM_BOOL, 'True if the message was deleted, false otherwise'),
1848 'warnings' => new external_warnings()
1849 )
1850 );
1851 }
1852
a0eabdd3
RW
1853 /**
1854 * Returns description of method parameters
1855 *
1856 * @return external_function_parameters
1857 * @since 3.2
1858 */
1859 public static function message_processor_config_form_parameters() {
1860 return new external_function_parameters(
1861 array(
1862 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1863 'name' => new external_value(PARAM_TEXT, 'The name of the message processor'),
1864 'formvalues' => new external_multiple_structure(
1865 new external_single_structure(
1866 array(
1867 'name' => new external_value(PARAM_TEXT, 'name of the form element', VALUE_REQUIRED),
1868 'value' => new external_value(PARAM_RAW, 'value of the form element', VALUE_REQUIRED),
1869 )
1870 ),
1871 'Config form values',
1872 VALUE_REQUIRED
1873 ),
1874 )
1875 );
1876 }
1877
1878 /**
1879 * Processes a message processor config form.
1880 *
1881 * @param int $userid the user id
1882 * @param string $name the name of the processor
1883 * @param array $formvalues the form values
1884 * @return external_description
1885 * @throws moodle_exception
1886 * @since 3.2
1887 */
1888 public static function message_processor_config_form($userid, $name, $formvalues) {
1889 $params = self::validate_parameters(
1890 self::message_processor_config_form_parameters(),
1891 array(
1892 'userid' => $userid,
1893 'name' => $name,
1894 'formvalues' => $formvalues,
1895 )
1896 );
1897
1898 if (empty($params['userid'])) {
1899 $params['userid'] = $USER->id;
1900 }
1901
1902 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1903 core_user::require_active_user($user);
1904
1905 $processor = get_message_processor($name);
1906 $preferences = [];
1907 $form = new stdClass();
1908
1909 foreach ($formvalues as $formvalue) {
1910 $form->$formvalue['name'] = $formvalue['value'];
1911 }
1912
1913 $processor->process_form($form, $preferences);
1914
1915 if (!empty($preferences)) {
1916 set_user_preferences($preferences, $userid);
1917 }
1918 }
1919
1920 /**
1921 * Returns description of method result value
1922 *
1923 * @return external_description
1924 * @since 3.2
1925 */
1926 public static function message_processor_config_form_returns() {
1927 return null;
1928 }
a623b6b8 1929}