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