2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * External message API
21 * @package core_message
23 * @copyright 2011 Jerome Mouneyrac
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require_once("$CFG->libdir/externallib.php");
28 require_once($CFG->dirroot . "/message/lib.php");
31 * Message external functions
33 * @package core_message
35 * @copyright 2011 Jerome Mouneyrac
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class core_message_external extends external_api {
42 * Returns description of method parameters
44 * @return external_function_parameters
47 public static function send_instant_messages_parameters() {
48 return new external_function_parameters(
50 'messages' => new external_multiple_structure(
51 new external_single_structure(
53 'touserid' => new external_value(PARAM_INT, 'id of the user to send the private message'),
54 'text' => new external_value(PARAM_RAW, 'the text of the message'),
55 'textformat' => new external_format_value('text', VALUE_DEFAULT),
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),
65 * Send private messages from the current USER to other users
67 * @param array $messages An array of message to send.
71 public static function send_instant_messages($messages = array()) {
72 global $CFG, $USER, $DB;
74 // Check if messaging is enabled.
75 if (!$CFG->messaging) {
76 throw new moodle_exception('disabled', 'message');
79 // Ensure the current user is allowed to run this function
80 $context = context_system::instance();
81 self::validate_context($context);
82 require_capability('moodle/site:sendmessage', $context);
84 $params = self::validate_parameters(self::send_instant_messages_parameters(), array('messages' => $messages));
86 //retrieve all tousers of the messages
88 foreach($params['messages'] as $message) {
89 $receivers[] = $message['touserid'];
91 list($sqluserids, $sqlparams) = $DB->get_in_or_equal($receivers, SQL_PARAMS_NAMED, 'userid_');
92 $tousers = $DB->get_records_select("user", "id " . $sqluserids . " AND deleted = 0", $sqlparams);
94 $contactlist = array();
95 $sqlparams['contactid'] = $USER->id;
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;
105 // $record->userid have current user as contact
106 $contactlist[$record->userid] = true;
111 $canreadallmessages = has_capability('moodle/site:readallmessages', $context);
113 $resultmessages = array();
114 foreach ($params['messages'] as $message) {
115 $resultmsg = array(); //the infos about the success of the operation
117 //we are going to do some checking
118 //code should match /messages/index.php checks
121 //check the user exists
122 if (empty($tousers[$message['touserid']])) {
124 $errormessage = get_string('touserdoesntexist', 'message', $message['touserid']);
127 //check that the touser is not blocking the current user
128 if ($success and !empty($blocklist[$message['touserid']]) and !$canreadallmessages) {
130 $errormessage = get_string('userisblockingyou', 'message');
133 // Check if the user is a contact
134 //TODO MDL-31118 performance improvement - edit the function so we can pass an array instead userid
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)) {
138 // The user isn't a contact and they have selected to block non contacts so this message won't be sent.
140 $errormessage = get_string('userisblockingyounoncontact', 'message',
141 fullname(core_user::get_user($message['touserid'])));
144 //now we can send the message (at least try)
146 //TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object
147 $success = message_post_message($USER, $tousers[$message['touserid']],
148 $message['text'], external_validate_format($message['textformat']));
151 //build the resultmsg
152 if (isset($message['clientmsgid'])) {
153 $resultmsg['clientmsgid'] = $message['clientmsgid'];
156 $resultmsg['msgid'] = $success;
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 .
161 $resultmsg['msgid'] = -1;
162 $resultmsg['errormessage'] = $errormessage;
165 $resultmessages[] = $resultmsg;
168 return $resultmessages;
172 * Returns description of method result value
174 * @return external_description
177 public static function send_instant_messages_returns() {
178 return new external_multiple_structure(
179 new external_single_structure(
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'),
182 'clientmsgid' => new external_value(PARAM_ALPHANUMEXT, 'your own id for the message', VALUE_OPTIONAL),
183 'errormessage' => new external_value(PARAM_TEXT, 'error message - if it failed', VALUE_OPTIONAL)
190 * Create contacts parameters description.
192 * @return external_function_parameters
195 public static function create_contacts_parameters() {
196 return new external_function_parameters(
198 'userids' => new external_multiple_structure(
199 new external_value(PARAM_INT, 'User ID'),
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)
211 * @param array $userids array of user IDs.
212 * @param int $userid The id of the user we are creating the contacts for
213 * @return external_description
216 public static function create_contacts($userids, $userid = 0) {
219 // Check if messaging is enabled.
220 if (!$CFG->messaging) {
221 throw new moodle_exception('disabled', 'message');
224 $params = array('userids' => $userids, 'userid' => $userid);
225 $params = self::validate_parameters(self::create_contacts_parameters(), $params);
228 foreach ($params['userids'] as $id) {
229 if (!message_add_contact($id, 0, $userid)) {
233 'warningcode' => 'contactnotcreated',
234 'message' => 'The contact could not be created'
242 * Create contacts return description.
244 * @return external_description
247 public static function create_contacts_returns() {
248 return new external_warnings();
252 * Delete contacts parameters description.
254 * @return external_function_parameters
257 public static function delete_contacts_parameters() {
258 return new external_function_parameters(
260 'userids' => new external_multiple_structure(
261 new external_value(PARAM_INT, 'User ID'),
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)
273 * @param array $userids array of user IDs.
274 * @param int $userid The id of the user we are deleting the contacts for
278 public static function delete_contacts($userids, $userid = 0) {
281 // Check if messaging is enabled.
282 if (!$CFG->messaging) {
283 throw new moodle_exception('disabled', 'message');
286 $params = array('userids' => $userids, 'userid' => $userid);
287 $params = self::validate_parameters(self::delete_contacts_parameters(), $params);
289 foreach ($params['userids'] as $id) {
290 message_remove_contact($id, $userid);
297 * Delete contacts return description.
299 * @return external_description
302 public static function delete_contacts_returns() {
307 * Block contacts parameters description.
309 * @return external_function_parameters
312 public static function block_contacts_parameters() {
313 return new external_function_parameters(
315 'userids' => new external_multiple_structure(
316 new external_value(PARAM_INT, 'User ID'),
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)
328 * @param array $userids array of user IDs.
329 * @param int $userid The id of the user we are blocking the contacts for
330 * @return external_description
333 public static function block_contacts($userids, $userid = 0) {
336 // Check if messaging is enabled.
337 if (!$CFG->messaging) {
338 throw new moodle_exception('disabled', 'message');
341 $params = array('userids' => $userids, 'userid' => $userid);
342 $params = self::validate_parameters(self::block_contacts_parameters(), $params);
345 foreach ($params['userids'] as $id) {
346 if (!message_block_contact($id, $userid)) {
350 'warningcode' => 'contactnotblocked',
351 'message' => 'The contact could not be blocked'
359 * Block contacts return description.
361 * @return external_description
364 public static function block_contacts_returns() {
365 return new external_warnings();
369 * Unblock contacts parameters description.
371 * @return external_function_parameters
374 public static function unblock_contacts_parameters() {
375 return new external_function_parameters(
377 'userids' => new external_multiple_structure(
378 new external_value(PARAM_INT, 'User ID'),
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)
390 * @param array $userids array of user IDs.
391 * @param int $userid The id of the user we are unblocking the contacts for
395 public static function unblock_contacts($userids, $userid = 0) {
398 // Check if messaging is enabled.
399 if (!$CFG->messaging) {
400 throw new moodle_exception('disabled', 'message');
403 $params = array('userids' => $userids, 'userid' => $userid);
404 $params = self::validate_parameters(self::unblock_contacts_parameters(), $params);
406 foreach ($params['userids'] as $id) {
407 message_unblock_contact($id, $userid);
414 * Unblock contacts return description.
416 * @return external_description
419 public static function unblock_contacts_returns() {
424 * Get messagearea conversations parameters.
426 * @return external_function_parameters
428 public static function data_for_messagearea_conversations_parameters() {
429 return new external_function_parameters(
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)
439 * Get messagearea conversations.
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
446 public static function data_for_messagearea_conversations($userid, $limitfrom = 0, $limitnum = 0) {
449 // Check if messaging is enabled.
450 if (!$CFG->messaging) {
451 throw new moodle_exception('disabled', 'message');
456 'limitfrom' => $limitfrom,
457 'limitnum' => $limitnum
459 self::validate_parameters(self::data_for_messagearea_conversations_parameters(), $params);
461 self::validate_context(context_user::instance($userid));
463 $contacts = \core_message\api::get_conversations($userid, 0, $limitfrom, $limitnum);
465 $renderer = $PAGE->get_renderer('core_message');
466 return $contacts->export_for_template($renderer);
470 * Get messagearea conversations returns.
472 * @return external_function_parameters
474 public static function data_for_messagearea_conversations_returns() {
475 return new external_function_parameters(
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(
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 'isread' => new external_value(PARAM_BOOL, 'If the user has read the message', VALUE_OPTIONAL),
498 * Get messagearea contacts parameters.
500 * @return external_function_parameters
502 public static function data_for_messagearea_contacts_parameters() {
503 return self::data_for_messagearea_conversations_parameters();
507 * Get messagearea contacts parameters.
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
514 public static function data_for_messagearea_contacts($userid, $limitfrom = 0, $limitnum = 0) {
517 // Check if messaging is enabled.
518 if (!$CFG->messaging) {
519 throw new moodle_exception('disabled', 'message');
524 'limitfrom' => $limitfrom,
525 'limitnum' => $limitnum
527 self::validate_parameters(self::data_for_messagearea_contacts_parameters(), $params);
529 self::validate_context(context_user::instance($userid));
531 $contacts = \core_message\api::get_contacts($userid, $limitfrom, $limitnum);
533 $renderer = $PAGE->get_renderer('core_message');
534 return $contacts->export_for_template($renderer);
538 * Get messagearea contacts returns.
540 * @return external_function_parameters
542 public static function data_for_messagearea_contacts_returns() {
543 return self::data_for_messagearea_conversations_returns();
547 * Get messagearea messages parameters.
549 * @return external_function_parameters
551 public static function data_for_messagearea_messages_parameters() {
552 return new external_function_parameters(
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),
557 'limitnum' => new external_value(PARAM_INT, 'Limit number', VALUE_DEFAULT, 0)
563 * Get messagearea messages.
565 * @param int $currentuserid The current user's id
566 * @param int $otheruserid The other user's id
567 * @param int $limitfrom
568 * @param int $limitnum
569 * @return external_description
571 public static function data_for_messagearea_messages($currentuserid, $otheruserid, $limitfrom = 0, $limitnum = 0) {
574 // Check if messaging is enabled.
575 if (!$CFG->messaging) {
576 throw new moodle_exception('disabled', 'message');
580 'currentuserid' => $currentuserid,
581 'otheruserid' => $otheruserid,
582 'limitfrom' => $limitfrom,
583 'limitnum' => $limitnum
585 self::validate_parameters(self::data_for_messagearea_messages_parameters(), $params);
587 self::validate_context(context_user::instance($currentuserid));
589 $messages = \core_message\api::get_messages($currentuserid, $otheruserid, $limitfrom, $limitnum);
591 $renderer = $PAGE->get_renderer('core_message');
592 return $messages->export_for_template($renderer);
596 * Get messagearea messages returns.
598 * @return external_description
600 public static function data_for_messagearea_messages_returns() {
601 return new external_function_parameters(
603 'iscurrentuser' => new external_value(PARAM_BOOL, 'Is the currently logged in user the user we are viewing the messages on behalf of?'),
604 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
605 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
606 'otheruserfullname' => new external_value(PARAM_NOTAGS, 'The other user\'s fullname'),
607 'messages' => new external_multiple_structure(
608 new external_single_structure(
610 'id' => new external_value(PARAM_INT, 'The id of the message'),
611 'text' => new external_value(PARAM_RAW, 'The text of the message'),
612 'displayblocktime' => new external_value(PARAM_BOOL, 'Should we display the block time?'),
613 'blocktime' => new external_value(PARAM_NOTAGS, 'The time to display above the message'),
614 'position' => new external_value(PARAM_ALPHA, 'The position of the text'),
615 'timesent' => new external_value(PARAM_NOTAGS, 'The time the message was sent'),
616 'isread' => new external_value(PARAM_INT, 'Determines if the message was read or not'),
625 * Get the most recent message in a conversation parameters.
627 * @return external_function_parameters
629 public static function data_for_messagearea_get_most_recent_message_parameters() {
630 return new external_function_parameters(
632 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
633 'otheruserid' => new external_value(PARAM_INT, 'The other user\'s id'),
639 * Get the most recent message in a conversation.
641 * @param int $currentuserid The current user's id
642 * @param int $otheruserid The other user's id
643 * @return external_single_structure
645 public static function data_for_messagearea_get_most_recent_message($currentuserid, $otheruserid) {
648 // Check if messaging is enabled.
649 if (!$CFG->messaging) {
650 throw new moodle_exception('disabled', 'message');
654 'currentuserid' => $currentuserid,
655 'otheruserid' => $otheruserid
657 self::validate_parameters(self::data_for_messagearea_get_most_recent_message_parameters(), $params);
659 self::validate_context(context_user::instance($currentuserid));
661 $message = \core_message\api::get_most_recent_message($currentuserid, $otheruserid);
663 $renderer = $PAGE->get_renderer('core_message');
664 return $message->export_for_template($renderer);
668 * Get messagearea get most recent message returns.
670 * @return external_single_structure
672 public static function data_for_messagearea_get_most_recent_message_returns() {
673 return new external_single_structure(
675 'id' => new external_value(PARAM_INT, 'The id of the message'),
676 'text' => new external_value(PARAM_RAW, 'The text of the message'),
677 'displayblocktime' => new external_value(PARAM_BOOL, 'Should we display the block time?'),
678 'blocktime' => new external_value(PARAM_NOTAGS, 'The time to display above the message'),
679 'position' => new external_value(PARAM_ALPHA, 'The position of the text'),
680 'timesent' => new external_value(PARAM_NOTAGS, 'The time the message was sent'),
681 'isread' => new external_value(PARAM_INT, 'Determines if the message was read or not'),
687 * The get profile parameters.
689 * @return external_function_parameters
691 public static function data_for_messagearea_get_profile_parameters() {
692 return new external_function_parameters(
694 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
695 'otheruserid' => new external_value(PARAM_INT, 'The id of the user whose profile we want to view'),
701 * Get the profile information for a contact.
703 * @param int $currentuserid The current user's id
704 * @param int $otheruserid The id of the user whose profile we are viewing
705 * @return external_single_structure
707 public static function data_for_messagearea_get_profile($currentuserid, $otheruserid) {
710 // Check if messaging is enabled.
711 if (!$CFG->messaging) {
712 throw new moodle_exception('disabled', 'message');
716 'currentuserid' => $currentuserid,
717 'otheruserid' => $otheruserid
719 self::validate_parameters(self::data_for_messagearea_get_profile_parameters(), $params);
721 self::validate_context(context_user::instance($otheruserid));
723 $profile = \core_message\api::get_profile($currentuserid, $otheruserid);
725 $renderer = $PAGE->get_renderer('core_message');
726 return $profile->export_for_template($renderer);
730 * Get profile returns.
732 * @return external_single_structure
734 public static function data_for_messagearea_get_profile_returns() {
735 return new external_single_structure(
737 'iscurrentuser' => new external_value(PARAM_BOOL, 'Is the currently logged in user the user we are viewing the profile on behalf of?'),
738 'currentuserid' => new external_value(PARAM_INT, 'The current user\'s id'),
739 'otheruserid' => new external_value(PARAM_INT, 'The id of the user whose profile we are viewing'),
740 'email' => new external_value(core_user::get_property_type('email'), 'An email address'),
741 'country' => new external_value(core_user::get_property_type('country'), 'Home country code of the user'),
742 'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user'),
743 'fullname' => new external_value(PARAM_NOTAGS, 'The user\'s name'),
744 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL'),
745 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL'),
746 'isblocked' => new external_value(PARAM_BOOL, 'Is the user blocked?'),
747 'iscontact' => new external_value(PARAM_BOOL, 'Is the user a contact?')
753 * Get contacts parameters description.
755 * @return external_function_parameters
758 public static function get_contacts_parameters() {
759 return new external_function_parameters(array());
765 * @param array $userids array of user IDs.
766 * @return external_description
769 public static function get_contacts() {
772 // Check if messaging is enabled.
773 if (!$CFG->messaging) {
774 throw new moodle_exception('disabled', 'message');
777 require_once($CFG->dirroot . '/user/lib.php');
779 list($online, $offline, $strangers) = message_get_contacts();
780 $allcontacts = array('online' => $online, 'offline' => $offline, 'strangers' => $strangers);
781 foreach ($allcontacts as $mode => $contacts) {
782 foreach ($contacts as $key => $contact) {
784 'id' => $contact->id,
785 'fullname' => fullname($contact),
786 'unread' => $contact->messagecount
789 $userpicture = new user_picture($contact);
790 $userpicture->size = 1; // Size f1.
791 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
792 $userpicture->size = 0; // Size f2.
793 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
795 $allcontacts[$mode][$key] = $newcontact;
802 * Get contacts return description.
804 * @return external_description
807 public static function get_contacts_returns() {
808 return new external_single_structure(
810 'online' => new external_multiple_structure(
811 new external_single_structure(
813 'id' => new external_value(PARAM_INT, 'User ID'),
814 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
815 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
816 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
817 'unread' => new external_value(PARAM_INT, 'Unread message count')
820 'List of online contacts'
822 'offline' => new external_multiple_structure(
823 new external_single_structure(
825 'id' => new external_value(PARAM_INT, 'User ID'),
826 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
827 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
828 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
829 'unread' => new external_value(PARAM_INT, 'Unread message count')
832 'List of offline contacts'
834 'strangers' => new external_multiple_structure(
835 new external_single_structure(
837 'id' => new external_value(PARAM_INT, 'User ID'),
838 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
839 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
840 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
841 'unread' => new external_value(PARAM_INT, 'Unread message count')
844 'List of users that are not in the user\'s contact list but have sent a message'
851 * Search contacts parameters description.
853 * @return external_function_parameters
856 public static function search_contacts_parameters() {
857 return new external_function_parameters(
859 'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
860 'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
861 VALUE_DEFAULT, false)
869 * @param string $searchtext query string.
870 * @param bool $onlymycourses limit the search to the user's courses only.
871 * @return external_description
874 public static function search_contacts($searchtext, $onlymycourses = false) {
875 global $CFG, $USER, $PAGE;
876 require_once($CFG->dirroot . '/user/lib.php');
878 // Check if messaging is enabled.
879 if (!$CFG->messaging) {
880 throw new moodle_exception('disabled', 'message');
883 require_once($CFG->libdir . '/enrollib.php');
885 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
886 $params = self::validate_parameters(self::search_contacts_parameters(), $params);
888 // Extra validation, we do not allow empty queries.
889 if ($params['searchtext'] === '') {
890 throw new moodle_exception('querystringcannotbeempty');
893 $courseids = array();
894 if ($params['onlymycourses']) {
895 $mycourses = enrol_get_my_courses(array('id'));
896 foreach ($mycourses as $mycourse) {
897 $courseids[] = $mycourse->id;
900 $courseids[] = SITEID;
903 // Retrieving the users matching the query.
904 $users = message_search_users($courseids, $params['searchtext']);
906 foreach ($users as $user) {
907 $results[$user->id] = $user;
910 // Reorganising information.
911 foreach ($results as &$user) {
914 'fullname' => fullname($user)
917 // Avoid undefined property notice as phone not specified.
918 $user->phone1 = null;
919 $user->phone2 = null;
921 $userpicture = new user_picture($user);
922 $userpicture->size = 1; // Size f1.
923 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
924 $userpicture->size = 0; // Size f2.
925 $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
934 * Search contacts return description.
936 * @return external_description
939 public static function search_contacts_returns() {
940 return new external_multiple_structure(
941 new external_single_structure(
943 'id' => new external_value(PARAM_INT, 'User ID'),
944 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
945 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
946 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
954 * Get messages parameters description.
956 * @return external_function_parameters
959 public static function get_messages_parameters() {
960 return new external_function_parameters(
962 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
963 'useridfrom' => new external_value(
964 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
966 'type' => new external_value(
967 PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
968 VALUE_DEFAULT, 'both'),
969 'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
970 'newestfirst' => new external_value(
971 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
972 VALUE_DEFAULT, true),
973 'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
974 'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
980 * Get messages function implementation.
983 * @throws invalid_parameter_exception
984 * @throws moodle_exception
985 * @param int $useridto the user id who received the message
986 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
987 * @param string $type type of message to return, expected values: notifications, conversations and both
988 * @param bool $read true for retreiving read messages, false for unread
989 * @param bool $newestfirst true for ordering by newest first, false for oldest first
990 * @param int $limitfrom limit from
991 * @param int $limitnum limit num
992 * @return external_description
994 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
995 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
1001 'useridto' => $useridto,
1002 'useridfrom' => $useridfrom,
1005 'newestfirst' => $newestfirst,
1006 'limitfrom' => $limitfrom,
1007 'limitnum' => $limitnum
1010 $params = self::validate_parameters(self::get_messages_parameters(), $params);
1012 $context = context_system::instance();
1013 self::validate_context($context);
1015 $useridto = $params['useridto'];
1016 $useridfrom = $params['useridfrom'];
1017 $type = $params['type'];
1018 $read = $params['read'];
1019 $newestfirst = $params['newestfirst'];
1020 $limitfrom = $params['limitfrom'];
1021 $limitnum = $params['limitnum'];
1023 $allowedvalues = array('notifications', 'conversations', 'both');
1024 if (!in_array($type, $allowedvalues)) {
1025 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
1026 'allowed values are: ' . implode(',', $allowedvalues));
1029 // Check if private messaging between users is allowed.
1030 if (empty($CFG->messaging)) {
1031 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
1032 if ($type == "conversations") {
1033 throw new moodle_exception('disabled', 'message');
1035 if ($type == "both") {
1037 $warning['item'] = 'message';
1038 $warning['itemid'] = $USER->id;
1039 $warning['warningcode'] = '1';
1040 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
1041 Only notifications will be returned';
1042 $warnings[] = $warning;
1046 if (!empty($useridto)) {
1047 if (core_user::is_real_user($useridto)) {
1048 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1050 throw new moodle_exception('invaliduser');
1054 if (!empty($useridfrom)) {
1055 // We use get_user here because the from user can be the noreply or support user.
1056 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1059 // Check if the current user is the sender/receiver or just a privileged user.
1060 if ($useridto != $USER->id and $useridfrom != $USER->id and
1061 !has_capability('moodle/site:readallmessages', $context)) {
1062 throw new moodle_exception('accessdenied', 'admin');
1065 // Which type of messages to retrieve.
1066 $notifications = -1;
1067 if ($type != 'both') {
1068 $notifications = ($type == 'notifications') ? 1 : 0;
1071 $orderdirection = $newestfirst ? 'DESC' : 'ASC';
1072 $sort = "mr.timecreated $orderdirection";
1074 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
1075 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
1077 // In some cases, we don't need to get the to/from user objects from the sql query.
1078 $userfromfullname = '';
1079 $usertofullname = '';
1081 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
1082 if (!empty($useridto)) {
1083 $usertofullname = fullname($userto, $canviewfullname);
1084 // The user from may or may not be filled.
1085 if (!empty($useridfrom)) {
1086 $userfromfullname = fullname($userfrom, $canviewfullname);
1089 // If the useridto field is empty, the useridfrom must be filled.
1090 $userfromfullname = fullname($userfrom, $canviewfullname);
1092 foreach ($messages as $mid => $message) {
1094 // Do not return deleted messages.
1095 if (($useridto == $USER->id and $message->timeusertodeleted) or
1096 ($useridfrom == $USER->id and $message->timeuserfromdeleted)) {
1098 unset($messages[$mid]);
1102 // We need to get the user from the query.
1103 if (empty($userfromfullname)) {
1104 // Check for non-reply and support users.
1105 if (core_user::is_real_user($message->useridfrom)) {
1106 $user = new stdClass();
1107 $user = username_load_fields_from_object($user, $message, 'userfrom');
1108 $message->userfromfullname = fullname($user, $canviewfullname);
1110 $user = core_user::get_user($message->useridfrom);
1111 $message->userfromfullname = fullname($user, $canviewfullname);
1114 $message->userfromfullname = $userfromfullname;
1117 // We need to get the user from the query.
1118 if (empty($usertofullname)) {
1119 $user = new stdClass();
1120 $user = username_load_fields_from_object($user, $message, 'userto');
1121 $message->usertofullname = fullname($user, $canviewfullname);
1123 $message->usertofullname = $usertofullname;
1126 // This field is only available in the message_read table.
1127 if (!isset($message->timeread)) {
1128 $message->timeread = 0;
1131 $message->text = message_format_message_text($message);
1132 $messages[$mid] = (array) $message;
1137 'messages' => $messages,
1138 'warnings' => $warnings
1145 * Get messages return description.
1147 * @return external_single_structure
1150 public static function get_messages_returns() {
1151 return new external_single_structure(
1153 'messages' => new external_multiple_structure(
1154 new external_single_structure(
1156 'id' => new external_value(PARAM_INT, 'Message id'),
1157 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
1158 'useridto' => new external_value(PARAM_INT, 'User to id'),
1159 'subject' => new external_value(PARAM_TEXT, 'The message subject'),
1160 'text' => new external_value(PARAM_RAW, 'The message text formated'),
1161 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
1162 'fullmessageformat' => new external_format_value('fullmessage'),
1163 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
1164 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
1165 'notification' => new external_value(PARAM_INT, 'Is a notification?'),
1166 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
1167 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
1168 'timecreated' => new external_value(PARAM_INT, 'Time created'),
1169 'timeread' => new external_value(PARAM_INT, 'Time read'),
1170 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
1171 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
1175 'warnings' => new external_warnings()
1181 * Get notifications parameters description.
1183 * @return external_function_parameters
1186 public static function get_notifications_parameters() {
1187 return new external_function_parameters(
1189 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1190 'useridfrom' => new external_value(
1191 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1193 'status' => new external_value(
1194 PARAM_ALPHA, 'filter the results to just "read" or "unread" notifications',
1196 'embedpreference' => new external_value(
1197 PARAM_BOOL, 'true for returning user\'s preference for the notification',
1198 VALUE_DEFAULT, false),
1199 'embeduserto' => new external_value(
1200 PARAM_BOOL, 'true for returning user details for the recipient in each notification',
1201 VALUE_DEFAULT, false),
1202 'embeduserfrom' => new external_value(
1203 PARAM_BOOL, 'true for returning user details for the sender in each notification',
1204 VALUE_DEFAULT, false),
1205 'newestfirst' => new external_value(
1206 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
1207 VALUE_DEFAULT, true),
1208 'markasread' => new external_value(
1209 PARAM_BOOL, 'mark notifications as read when they are returned by this function',
1210 VALUE_DEFAULT, false),
1211 'limit' => new external_value(PARAM_INT, 'the number of results to return', VALUE_DEFAULT, 0),
1212 'offset' => new external_value(PARAM_INT, 'offset the result set by a given amount', VALUE_DEFAULT, 0)
1218 * Get notifications function.
1221 * @throws invalid_parameter_exception
1222 * @throws moodle_exception
1223 * @param int $useridto the user id who received the message
1224 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1225 * @param string $status filter the results to only read or unread notifications
1226 * @param bool $embedpreference true to embed the recipient user details in the record for each notification
1227 * @param bool $embeduserto true to embed the recipient user details in the record for each notification
1228 * @param bool $embeduserfrom true to embed the send user details in the record for each notification
1229 * @param bool $newestfirst true for ordering by newest first, false for oldest first
1230 * @param bool $markasread mark notifications as read when they are returned by this function
1231 * @param int $limit the number of results to return
1232 * @param int $offset offset the result set by a given amount
1233 * @return external_description
1235 public static function get_notifications($useridto, $useridfrom, $status, $embedpreference,
1236 $embeduserto, $embeduserfrom, $newestfirst, $markasread, $limit, $offset) {
1237 global $CFG, $USER, $OUTPUT;
1239 $params = self::validate_parameters(
1240 self::get_notifications_parameters(),
1242 'useridto' => $useridto,
1243 'useridfrom' => $useridfrom,
1244 'status' => $status,
1245 'embedpreference' => $embedpreference,
1246 'embeduserto' => $embeduserto,
1247 'embeduserfrom' => $embeduserfrom,
1248 'newestfirst' => $newestfirst,
1249 'markasread' => $markasread,
1251 'offset' => $offset,
1255 $context = context_system::instance();
1256 self::validate_context($context);
1258 $useridto = $params['useridto'];
1259 $useridfrom = $params['useridfrom'];
1260 $status = $params['status'];
1261 $embedpreference = $params['embedpreference'];
1262 $embeduserto = $params['embeduserto'];
1263 $embeduserfrom = $params['embeduserfrom'];
1264 $newestfirst = $params['newestfirst'];
1265 $markasread = $params['markasread'];
1266 $limit = $params['limit'];
1267 $offset = $params['offset'];
1268 $issuperuser = has_capability('moodle/site:readallmessages', $context);
1270 if (!empty($useridto)) {
1271 if (core_user::is_real_user($useridto)) {
1273 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1276 throw new moodle_exception('invaliduser');
1280 if (!empty($useridfrom) && $embeduserfrom) {
1281 // We use get_user here because the from user can be the noreply or support user.
1282 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1285 // Check if the current user is the sender/receiver or just a privileged user.
1286 if ($useridto != $USER->id and $useridfrom != $USER->id and !$issuperuser) {
1287 throw new moodle_exception('accessdenied', 'admin');
1290 $sort = $newestfirst ? 'DESC' : 'ASC';
1291 $notifications = message_get_notifications($useridto, $useridfrom, $status, $embeduserto, $embeduserfrom, $sort, $limit, $offset);
1293 if ($notifications) {
1294 // In some cases, we don't need to get the to/from user objects from the sql query.
1295 $userfromfullname = '';
1296 $usertofullname = '';
1298 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
1299 if (!empty($useridto) && $embeduserto) {
1300 $usertofullname = fullname($userto);
1301 // The user from may or may not be filled.
1302 if (!empty($useridfrom) && $embeduserfrom) {
1303 $userfromfullname = fullname($userfrom);
1305 } else if (!empty($useridfrom) && $embeduserfrom) {
1306 // If the useridto field is empty, the useridfrom must be filled.
1307 $userfromfullname = fullname($userfrom);
1310 foreach ($notifications as $notification) {
1312 if (($useridto == $USER->id and $notification->timeusertodeleted) or
1313 ($useridfrom == $USER->id and $notification->timeuserfromdeleted)) {
1315 $notification->deleted = true;
1317 $notification->deleted = false;
1320 // We need to get the user from the query.
1321 if ($embeduserfrom) {
1322 if (empty($userfromfullname)) {
1323 // Check for non-reply and support users.
1324 if (core_user::is_real_user($notification->useridfrom)) {
1325 $user = new stdClass();
1326 $user = username_load_fields_from_object($user, $notification, 'userfrom');
1327 $profileurl = new moodle_url('/user/profile.php', array('id' => $notification->useridfrom));
1328 $notification->userfromfullname = fullname($user);
1329 $notification->userfromprofileurl = $profileurl->out();
1331 $notification->userfromfullname = get_string('coresystem');
1334 $notification->userfromfullname = $userfromfullname;
1338 // We need to get the user from the query.
1340 if (empty($usertofullname)) {
1341 $user = new stdClass();
1342 $user = username_load_fields_from_object($user, $notification, 'userto');
1343 $notification->usertofullname = fullname($user);
1345 $notification->usertofullname = $usertofullname;
1349 $notification->timecreatedpretty = get_string('ago', 'message', format_time(time() - $notification->timecreated));
1350 $notification->text = message_format_message_text($notification);
1351 $notification->read = $notification->timeread ? true : false;
1353 if (!empty($notification->component) && substr($notification->component, 0, 4) == 'mod_') {
1354 $iconurl = $OUTPUT->pix_url('icon', $notification->component);
1356 $iconurl = $OUTPUT->pix_url('i/marker', 'core');
1359 $notification->iconurl = $iconurl->out();
1361 // We only return the logged in user's preferences, so if it isn't the sender or receiver
1362 // of this notification then skip embedding the preferences.
1363 if ($embedpreference && !empty($notification->component) && !empty($notification->eventtype) && !$issuperuser) {
1364 $key = 'message_provider_' . $notification->component . '_' . $notification->eventtype;
1365 $notification->preference = array(
1367 'loggedin' => get_user_preferences($key . '_loggedin', $USER->id),
1368 'loggedoff' => get_user_preferences($key . '_loggedoff', $USER->id),
1372 if ($markasread && !$notification->read) {
1373 // Have to clone here because this function mutates the given data. Naughty, naughty...
1374 message_mark_message_read(clone $notification, time());
1380 'notifications' => $notifications,
1381 'unreadcount' => message_count_unread_notifications($useridto, $useridfrom),
1386 * Get notifications return description.
1388 * @return external_single_structure
1391 public static function get_notifications_returns() {
1392 return new external_single_structure(
1394 'notifications' => new external_multiple_structure(
1395 new external_single_structure(
1397 'id' => new external_value(PARAM_INT, 'Notification id (this is not guaranteed to be unique within this result set)'),
1398 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
1399 'useridto' => new external_value(PARAM_INT, 'User to id'),
1400 'subject' => new external_value(PARAM_TEXT, 'The notification subject'),
1401 'text' => new external_value(PARAM_RAW, 'The message text formated'),
1402 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
1403 'fullmessageformat' => new external_format_value('fullmessage'),
1404 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
1405 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
1406 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
1407 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
1408 'timecreated' => new external_value(PARAM_INT, 'Time created'),
1409 'timecreatedpretty' => new external_value(PARAM_TEXT, 'Time created in a pretty format'),
1410 'timeread' => new external_value(PARAM_INT, 'Time read'),
1411 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name', VALUE_OPTIONAL),
1412 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name', VALUE_OPTIONAL),
1413 'userfromprofileurl' => new external_value(PARAM_URL, 'User from profile url', VALUE_OPTIONAL),
1414 'read' => new external_value(PARAM_BOOL, 'notification read status'),
1415 'deleted' => new external_value(PARAM_BOOL, 'notification deletion status'),
1416 'iconurl' => new external_value(PARAM_URL, 'URL for notification icon'),
1417 'component' => new external_value(PARAM_TEXT, 'The component that generated the notification', VALUE_OPTIONAL),
1418 'eventtype' => new external_value(PARAM_TEXT, 'The type of notification', VALUE_OPTIONAL),
1419 'preference' => new external_single_structure(
1421 'key' => new external_value(PARAM_TEXT, 'The preference key'),
1422 'loggedin' => new external_value(PARAM_TEXT, 'The logged in preference setting'),
1423 'loggedoff' => new external_value(PARAM_TEXT, 'The logged off preference setting'),
1425 'The preference configuration',
1431 'unreadcount' => new external_value(PARAM_INT, 'the user whose blocked users we want to retrieve'),
1437 * Mark all notifications as read parameters description.
1439 * @return external_function_parameters
1442 public static function mark_all_notifications_as_read_parameters() {
1443 return new external_function_parameters(
1445 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1446 'useridfrom' => new external_value(
1447 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1454 * Mark all notifications as read function.
1457 * @throws invalid_parameter_exception
1458 * @throws moodle_exception
1459 * @param int $useridto the user id who received the message
1460 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1461 * @return external_description
1463 public static function mark_all_notifications_as_read($useridto, $useridfrom) {
1466 $params = self::validate_parameters(
1467 self::mark_all_notifications_as_read_parameters(),
1469 'useridto' => $useridto,
1470 'useridfrom' => $useridfrom,
1474 $context = context_system::instance();
1475 self::validate_context($context);
1477 $useridto = $params['useridto'];
1478 $useridfrom = $params['useridfrom'];
1480 if (!empty($useridto)) {
1481 if (core_user::is_real_user($useridto)) {
1482 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1484 throw new moodle_exception('invaliduser');
1488 if (!empty($useridfrom)) {
1489 // We use get_user here because the from user can be the noreply or support user.
1490 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1493 // Check if the current user is the sender/receiver or just a privileged user.
1494 if ($useridto != $USER->id and $useridfrom != $USER->id and
1495 // deleteanymessage seems more reasonable here than readallmessages.
1496 !has_capability('moodle/site:deleteanymessage', $context)) {
1497 throw new moodle_exception('accessdenied', 'admin');
1500 message_mark_all_read_for_user($useridto, $useridfrom, 'notification');
1506 * Mark all notifications as read return description.
1508 * @return external_single_structure
1511 public static function mark_all_notifications_as_read_returns() {
1512 return new external_value(PARAM_BOOL, 'True if the messages were marked read, false otherwise');
1516 * Get unread notification count parameters description.
1518 * @return external_function_parameters
1521 public static function get_unread_notification_count_parameters() {
1522 return new external_function_parameters(
1524 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
1525 'useridfrom' => new external_value(
1526 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
1533 * Get unread notification count function.
1536 * @throws invalid_parameter_exception
1537 * @throws moodle_exception
1538 * @param int $useridto the user id who received the message
1539 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
1540 * @return external_description
1542 public static function get_unread_notification_count($useridto, $useridfrom) {
1545 $params = self::validate_parameters(
1546 self::get_unread_notification_count_parameters(),
1548 'useridto' => $useridto,
1549 'useridfrom' => $useridfrom,
1553 $context = context_system::instance();
1554 self::validate_context($context);
1556 $useridto = $params['useridto'];
1557 $useridfrom = $params['useridfrom'];
1559 if (!empty($useridto)) {
1560 if (core_user::is_real_user($useridto)) {
1561 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
1563 throw new moodle_exception('invaliduser');
1567 if (!empty($useridfrom)) {
1568 // We use get_user here because the from user can be the noreply or support user.
1569 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
1572 // Check if the current user is the sender/receiver or just a privileged user.
1573 if ($useridto != $USER->id and $useridfrom != $USER->id and
1574 !has_capability('moodle/site:readallmessages', $context)) {
1575 throw new moodle_exception('accessdenied', 'admin');
1578 return message_count_unread_notifications($useridto, $useridfrom);
1582 * Get unread notification count return description.
1584 * @return external_single_structure
1587 public static function get_unread_notification_count_returns() {
1588 return new external_value(PARAM_INT, 'the user whose blocked users we want to retrieve');
1592 * Get blocked users parameters description.
1594 * @return external_function_parameters
1597 public static function get_blocked_users_parameters() {
1598 return new external_function_parameters(
1600 'userid' => new external_value(PARAM_INT,
1601 'the user whose blocked users we want to retrieve',
1608 * Retrieve a list of users blocked
1610 * @param int $userid the user whose blocked users we want to retrieve
1611 * @return external_description
1614 public static function get_blocked_users($userid) {
1615 global $CFG, $USER, $PAGE;
1617 // Warnings array, it can be empty at the end but is mandatory.
1618 $warnings = array();
1624 $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
1625 $userid = $params['userid'];
1627 // Validate context.
1628 $context = context_system::instance();
1629 self::validate_context($context);
1631 // Check if private messaging between users is allowed.
1632 if (empty($CFG->messaging)) {
1633 throw new moodle_exception('disabled', 'message');
1636 $user = core_user::get_user($userid, '*', MUST_EXIST);
1637 core_user::require_active_user($user);
1639 // Check if we have permissions for retrieve the information.
1640 if ($userid != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
1641 throw new moodle_exception('accessdenied', 'admin');
1644 // Now, we can get safely all the blocked users.
1645 $users = message_get_blocked_users($user);
1647 $blockedusers = array();
1648 foreach ($users as $user) {
1651 'fullname' => fullname($user),
1654 $userpicture = new user_picture($user);
1655 $userpicture->size = 1; // Size f1.
1656 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
1658 $blockedusers[] = $newuser;
1662 'users' => $blockedusers,
1663 'warnings' => $warnings
1669 * Get blocked users return description.
1671 * @return external_single_structure
1674 public static function get_blocked_users_returns() {
1675 return new external_single_structure(
1677 'users' => new external_multiple_structure(
1678 new external_single_structure(
1680 'id' => new external_value(PARAM_INT, 'User ID'),
1681 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
1682 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL)
1685 'List of blocked users'
1687 'warnings' => new external_warnings()
1693 * Returns description of method parameters
1695 * @return external_function_parameters
1698 public static function mark_message_read_parameters() {
1699 return new external_function_parameters(
1701 'messageid' => new external_value(PARAM_INT, 'id of the message (in the message table)'),
1702 'timeread' => new external_value(PARAM_INT, 'timestamp for when the message should be marked read')
1708 * Mark a single message as read, trigger message_viewed event
1710 * @param int $messageid id of the message (in the message table)
1711 * @param int $timeread timestamp for when the message should be marked read
1712 * @return external_description
1713 * @throws invalid_parameter_exception
1714 * @throws moodle_exception
1717 public static function mark_message_read($messageid, $timeread) {
1718 global $CFG, $DB, $USER;
1720 // Check if private messaging between users is allowed.
1721 if (empty($CFG->messaging)) {
1722 throw new moodle_exception('disabled', 'message');
1725 // Warnings array, it can be empty at the end but is mandatory.
1726 $warnings = array();
1730 'messageid' => $messageid,
1731 'timeread' => $timeread
1733 $params = self::validate_parameters(self::mark_message_read_parameters(), $params);
1735 // Validate context.
1736 $context = context_system::instance();
1737 self::validate_context($context);
1739 $message = $DB->get_record('message', array('id' => $params['messageid']), '*', MUST_EXIST);
1741 if ($message->useridto != $USER->id) {
1742 throw new invalid_parameter_exception('Invalid messageid, you don\'t have permissions to mark this message as read');
1745 $messageid = message_mark_message_read($message, $params['timeread']);
1748 'messageid' => $messageid,
1749 'warnings' => $warnings
1755 * Returns description of method result value
1757 * @return external_description
1760 public static function mark_message_read_returns() {
1761 return new external_single_structure(
1763 'messageid' => new external_value(PARAM_INT, 'the id of the message in the message_read table'),
1764 'warnings' => new external_warnings()
1770 * Returns description of method parameters.
1772 * @return external_function_parameters
1775 public static function delete_conversation_parameters() {
1776 return new external_function_parameters(
1778 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the conversation for'),
1779 'otheruserid' => new external_value(PARAM_INT, 'The user id of the other user in the conversation'),
1785 * Deletes a conversation.
1787 * @param int $userid The user id of who we want to delete the conversation for
1788 * @param int $otheruserid The user id of the other user in the conversation
1790 * @throws moodle_exception
1793 public static function delete_conversation($userid, $otheruserid) {
1796 // Check if private messaging between users is allowed.
1797 if (empty($CFG->messaging)) {
1798 throw new moodle_exception('disabled', 'message');
1801 // Warnings array, it can be empty at the end but is mandatory.
1802 $warnings = array();
1806 'userid' => $userid,
1807 'otheruserid' => $otheruserid,
1809 $params = self::validate_parameters(self::delete_conversation_parameters(), $params);
1811 // Validate context.
1812 $context = context_system::instance();
1813 self::validate_context($context);
1815 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1816 core_user::require_active_user($user);
1818 if (\core_message\api::can_delete_conversation($user->id)) {
1819 $status = \core_message\api::delete_conversation($user->id, $otheruserid);
1821 throw new moodle_exception('You do not have permission to delete messages');
1825 'status' => $status,
1826 'warnings' => $warnings
1833 * Returns description of method result value.
1835 * @return external_description
1838 public static function delete_conversation_returns() {
1839 return new external_single_structure(
1841 'status' => new external_value(PARAM_BOOL, 'True if the conversation was deleted, false otherwise'),
1842 'warnings' => new external_warnings()
1848 * Returns description of method parameters
1850 * @return external_function_parameters
1853 public static function delete_message_parameters() {
1854 return new external_function_parameters(
1856 'messageid' => new external_value(PARAM_INT, 'The message id'),
1857 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the message for'),
1858 'read' => new external_value(PARAM_BOOL, 'If is a message read', VALUE_DEFAULT, true)
1866 * @param int $messageid the message id
1867 * @param int $userid the user id of who we want to delete the message for
1868 * @param bool $read if is a message read (default to true)
1869 * @return external_description
1870 * @throws moodle_exception
1873 public static function delete_message($messageid, $userid, $read = true) {
1876 // Check if private messaging between users is allowed.
1877 if (empty($CFG->messaging)) {
1878 throw new moodle_exception('disabled', 'message');
1881 // Warnings array, it can be empty at the end but is mandatory.
1882 $warnings = array();
1886 'messageid' => $messageid,
1887 'userid' => $userid,
1890 $params = self::validate_parameters(self::delete_message_parameters(), $params);
1892 // Validate context.
1893 $context = context_system::instance();
1894 self::validate_context($context);
1896 $messagestable = $params['read'] ? 'message_read' : 'message';
1897 $message = $DB->get_record($messagestable, array('id' => $params['messageid']), '*', MUST_EXIST);
1899 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1900 core_user::require_active_user($user);
1903 if (message_can_delete_message($message, $user->id)) {
1904 $status = message_delete_message($message, $user->id);;
1906 throw new moodle_exception('You do not have permission to delete this message');
1910 'status' => $status,
1911 'warnings' => $warnings
1917 * Returns description of method result value
1919 * @return external_description
1922 public static function delete_message_returns() {
1923 return new external_single_structure(
1925 'status' => new external_value(PARAM_BOOL, 'True if the message was deleted, false otherwise'),
1926 'warnings' => new external_warnings()
1932 * Returns description of method parameters
1934 * @return external_function_parameters
1937 public static function message_processor_config_form_parameters() {
1938 return new external_function_parameters(
1940 'userid' => new external_value(PARAM_INT, 'id of the user, 0 for current user', VALUE_REQUIRED),
1941 'name' => new external_value(PARAM_TEXT, 'The name of the message processor'),
1942 'formvalues' => new external_multiple_structure(
1943 new external_single_structure(
1945 'name' => new external_value(PARAM_TEXT, 'name of the form element', VALUE_REQUIRED),
1946 'value' => new external_value(PARAM_RAW, 'value of the form element', VALUE_REQUIRED),
1949 'Config form values',
1957 * Processes a message processor config form.
1959 * @param int $userid the user id
1960 * @param string $name the name of the processor
1961 * @param array $formvalues the form values
1962 * @return external_description
1963 * @throws moodle_exception
1966 public static function message_processor_config_form($userid, $name, $formvalues) {
1967 $params = self::validate_parameters(
1968 self::message_processor_config_form_parameters(),
1970 'userid' => $userid,
1972 'formvalues' => $formvalues,
1976 if (empty($params['userid'])) {
1977 $params['userid'] = $USER->id;
1980 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1981 core_user::require_active_user($user);
1983 $processor = get_message_processor($name);
1985 $form = new stdClass();
1987 foreach ($formvalues as $formvalue) {
1988 $form->$formvalue['name'] = $formvalue['value'];
1991 $processor->process_form($form, $preferences);
1993 if (!empty($preferences)) {
1994 set_user_preferences($preferences, $userid);
1999 * Returns description of method result value
2001 * @return external_description
2004 public static function message_processor_config_form_returns() {