MDL-55747 theme_noname: Display logos in the different pages
[moodle.git] / message / externallib.php
blob6702c3b54388cfacca040b258595d68765acdad2
1 <?php
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.
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/>.
18 /**
19 * External message API
21 * @package core_message
22 * @category external
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");
30 /**
31 * Message external functions
33 * @package core_message
34 * @category external
35 * @copyright 2011 Jerome Mouneyrac
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 * @since Moodle 2.2
39 class core_message_external extends external_api {
41 /**
42 * Returns description of method parameters
44 * @return external_function_parameters
45 * @since Moodle 2.2
47 public static function send_instant_messages_parameters() {
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'),
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),
64 /**
65 * Send private messages from the current USER to other users
67 * @param array $messages An array of message to send.
68 * @return array
69 * @since Moodle 2.2
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
87 $receivers = array();
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);
93 $blocklist = array();
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;
104 } else {
105 // $record->userid have current user as contact
106 $contactlist[$record->userid] = true;
109 $rs->close();
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
119 $success = true;
121 //check the user exists
122 if (empty($tousers[$message['touserid']])) {
123 $success = false;
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) {
129 $success = false;
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.
139 $success = false;
140 $errormessage = get_string('userisblockingyounoncontact', 'message',
141 fullname(core_user::get_user($message['touserid'])));
144 //now we can send the message (at least try)
145 if ($success) {
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'];
155 if ($success) {
156 $resultmsg['msgid'] = $success;
157 } else {
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
175 * @since Moodle 2.2
177 public static function send_instant_messages_returns() {
178 return new external_multiple_structure(
179 new external_single_structure(
180 array(
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
193 * @since Moodle 2.5
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'
207 * Create contacts.
209 * @param array $userids array of user IDs.
210 * @return external_description
211 * @since Moodle 2.5
213 public static function create_contacts($userids) {
214 global $CFG;
216 // Check if messaging is enabled.
217 if (!$CFG->messaging) {
218 throw new moodle_exception('disabled', 'message');
221 $params = array('userids' => $userids);
222 $params = self::validate_parameters(self::create_contacts_parameters(), $params);
224 $warnings = array();
225 foreach ($params['userids'] as $id) {
226 if (!message_add_contact($id)) {
227 $warnings[] = array(
228 'item' => 'user',
229 'itemid' => $id,
230 'warningcode' => 'contactnotcreated',
231 'message' => 'The contact could not be created'
235 return $warnings;
239 * Create contacts return description.
241 * @return external_description
242 * @since Moodle 2.5
244 public static function create_contacts_returns() {
245 return new external_warnings();
249 * Delete contacts parameters description.
251 * @return external_function_parameters
252 * @since Moodle 2.5
254 public static function delete_contacts_parameters() {
255 return new external_function_parameters(
256 array(
257 'userids' => new external_multiple_structure(
258 new external_value(PARAM_INT, 'User ID'),
259 'List of user IDs'
266 * Delete contacts.
268 * @param array $userids array of user IDs.
269 * @return null
270 * @since Moodle 2.5
272 public static function delete_contacts($userids) {
273 global $CFG;
275 // Check if messaging is enabled.
276 if (!$CFG->messaging) {
277 throw new moodle_exception('disabled', 'message');
280 $params = array('userids' => $userids);
281 $params = self::validate_parameters(self::delete_contacts_parameters(), $params);
283 foreach ($params['userids'] as $id) {
284 message_remove_contact($id);
287 return null;
291 * Delete contacts return description.
293 * @return external_description
294 * @since Moodle 2.5
296 public static function delete_contacts_returns() {
297 return null;
301 * Block contacts parameters description.
303 * @return external_function_parameters
304 * @since Moodle 2.5
306 public static function block_contacts_parameters() {
307 return new external_function_parameters(
308 array(
309 'userids' => new external_multiple_structure(
310 new external_value(PARAM_INT, 'User ID'),
311 'List of user IDs'
318 * Block contacts.
320 * @param array $userids array of user IDs.
321 * @return external_description
322 * @since Moodle 2.5
324 public static function block_contacts($userids) {
325 global $CFG;
327 // Check if messaging is enabled.
328 if (!$CFG->messaging) {
329 throw new moodle_exception('disabled', 'message');
332 $params = array('userids' => $userids);
333 $params = self::validate_parameters(self::block_contacts_parameters(), $params);
335 $warnings = array();
336 foreach ($params['userids'] as $id) {
337 if (!message_block_contact($id)) {
338 $warnings[] = array(
339 'item' => 'user',
340 'itemid' => $id,
341 'warningcode' => 'contactnotblocked',
342 'message' => 'The contact could not be blocked'
346 return $warnings;
350 * Block contacts return description.
352 * @return external_description
353 * @since Moodle 2.5
355 public static function block_contacts_returns() {
356 return new external_warnings();
360 * Unblock contacts parameters description.
362 * @return external_function_parameters
363 * @since Moodle 2.5
365 public static function unblock_contacts_parameters() {
366 return new external_function_parameters(
367 array(
368 'userids' => new external_multiple_structure(
369 new external_value(PARAM_INT, 'User ID'),
370 'List of user IDs'
377 * Unblock contacts.
379 * @param array $userids array of user IDs.
380 * @return null
381 * @since Moodle 2.5
383 public static function unblock_contacts($userids) {
384 global $CFG;
386 // Check if messaging is enabled.
387 if (!$CFG->messaging) {
388 throw new moodle_exception('disabled', 'message');
391 $params = array('userids' => $userids);
392 $params = self::validate_parameters(self::unblock_contacts_parameters(), $params);
394 foreach ($params['userids'] as $id) {
395 message_unblock_contact($id);
398 return null;
402 * Unblock contacts return description.
404 * @return external_description
405 * @since Moodle 2.5
407 public static function unblock_contacts_returns() {
408 return null;
412 * Get contacts parameters description.
414 * @return external_function_parameters
415 * @since Moodle 2.5
417 public static function get_contacts_parameters() {
418 return new external_function_parameters(array());
422 * Get contacts.
424 * @param array $userids array of user IDs.
425 * @return external_description
426 * @since Moodle 2.5
428 public static function get_contacts() {
429 global $CFG, $PAGE;
431 // Check if messaging is enabled.
432 if (!$CFG->messaging) {
433 throw new moodle_exception('disabled', 'message');
436 require_once($CFG->dirroot . '/user/lib.php');
438 list($online, $offline, $strangers) = message_get_contacts();
439 $allcontacts = array('online' => $online, 'offline' => $offline, 'strangers' => $strangers);
440 foreach ($allcontacts as $mode => $contacts) {
441 foreach ($contacts as $key => $contact) {
442 $newcontact = array(
443 'id' => $contact->id,
444 'fullname' => fullname($contact),
445 'unread' => $contact->messagecount
448 $userpicture = new user_picture($contact);
449 $userpicture->size = 1; // Size f1.
450 $newcontact['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
451 $userpicture->size = 0; // Size f2.
452 $newcontact['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
454 $allcontacts[$mode][$key] = $newcontact;
457 return $allcontacts;
461 * Get contacts return description.
463 * @return external_description
464 * @since Moodle 2.5
466 public static function get_contacts_returns() {
467 return new external_single_structure(
468 array(
469 'online' => new external_multiple_structure(
470 new external_single_structure(
471 array(
472 'id' => new external_value(PARAM_INT, 'User ID'),
473 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
474 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
475 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
476 'unread' => new external_value(PARAM_INT, 'Unread message count')
479 'List of online contacts'
481 'offline' => new external_multiple_structure(
482 new external_single_structure(
483 array(
484 'id' => new external_value(PARAM_INT, 'User ID'),
485 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
486 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
487 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
488 'unread' => new external_value(PARAM_INT, 'Unread message count')
491 'List of offline contacts'
493 'strangers' => new external_multiple_structure(
494 new external_single_structure(
495 array(
496 'id' => new external_value(PARAM_INT, 'User ID'),
497 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
498 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
499 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL),
500 'unread' => new external_value(PARAM_INT, 'Unread message count')
503 'List of users that are not in the user\'s contact list but have sent a message'
510 * Search contacts parameters description.
512 * @return external_function_parameters
513 * @since Moodle 2.5
515 public static function search_contacts_parameters() {
516 return new external_function_parameters(
517 array(
518 'searchtext' => new external_value(PARAM_CLEAN, 'String the user\'s fullname has to match to be found'),
519 'onlymycourses' => new external_value(PARAM_BOOL, 'Limit search to the user\'s courses',
520 VALUE_DEFAULT, false)
526 * Search contacts.
528 * @param string $searchtext query string.
529 * @param bool $onlymycourses limit the search to the user's courses only.
530 * @return external_description
531 * @since Moodle 2.5
533 public static function search_contacts($searchtext, $onlymycourses = false) {
534 global $CFG, $USER, $PAGE;
535 require_once($CFG->dirroot . '/user/lib.php');
537 // Check if messaging is enabled.
538 if (!$CFG->messaging) {
539 throw new moodle_exception('disabled', 'message');
542 require_once($CFG->libdir . '/enrollib.php');
544 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
545 $params = self::validate_parameters(self::search_contacts_parameters(), $params);
547 // Extra validation, we do not allow empty queries.
548 if ($params['searchtext'] === '') {
549 throw new moodle_exception('querystringcannotbeempty');
552 $courseids = array();
553 if ($params['onlymycourses']) {
554 $mycourses = enrol_get_my_courses(array('id'));
555 foreach ($mycourses as $mycourse) {
556 $courseids[] = $mycourse->id;
558 } else {
559 $courseids[] = SITEID;
562 // Retrieving the users matching the query.
563 $users = message_search_users($courseids, $params['searchtext']);
564 $results = array();
565 foreach ($users as $user) {
566 $results[$user->id] = $user;
569 // Reorganising information.
570 foreach ($results as &$user) {
571 $newuser = array(
572 'id' => $user->id,
573 'fullname' => fullname($user)
576 // Avoid undefined property notice as phone not specified.
577 $user->phone1 = null;
578 $user->phone2 = null;
580 $userpicture = new user_picture($user);
581 $userpicture->size = 1; // Size f1.
582 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
583 $userpicture->size = 0; // Size f2.
584 $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
586 $user = $newuser;
589 return $results;
593 * Search contacts return description.
595 * @return external_description
596 * @since Moodle 2.5
598 public static function search_contacts_returns() {
599 return new external_multiple_structure(
600 new external_single_structure(
601 array(
602 'id' => new external_value(PARAM_INT, 'User ID'),
603 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
604 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL),
605 'profileimageurlsmall' => new external_value(PARAM_URL, 'Small user picture URL', VALUE_OPTIONAL)
608 'List of contacts'
613 * Get messages parameters description.
615 * @return external_function_parameters
616 * @since 2.8
618 public static function get_messages_parameters() {
619 return new external_function_parameters(
620 array(
621 'useridto' => new external_value(PARAM_INT, 'the user id who received the message, 0 for any user', VALUE_REQUIRED),
622 'useridfrom' => new external_value(
623 PARAM_INT, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
624 VALUE_DEFAULT, 0),
625 'type' => new external_value(
626 PARAM_ALPHA, 'type of message to return, expected values are: notifications, conversations and both',
627 VALUE_DEFAULT, 'both'),
628 'read' => new external_value(PARAM_BOOL, 'true for getting read messages, false for unread', VALUE_DEFAULT, true),
629 'newestfirst' => new external_value(
630 PARAM_BOOL, 'true for ordering by newest first, false for oldest first',
631 VALUE_DEFAULT, true),
632 'limitfrom' => new external_value(PARAM_INT, 'limit from', VALUE_DEFAULT, 0),
633 'limitnum' => new external_value(PARAM_INT, 'limit number', VALUE_DEFAULT, 0)
639 * Get messages function implementation.
641 * @since 2.8
642 * @throws invalid_parameter_exception
643 * @throws moodle_exception
644 * @param int $useridto the user id who received the message
645 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
646 * @param string $type type of message to return, expected values: notifications, conversations and both
647 * @param bool $read true for retreiving read messages, false for unread
648 * @param bool $newestfirst true for ordering by newest first, false for oldest first
649 * @param int $limitfrom limit from
650 * @param int $limitnum limit num
651 * @return external_description
653 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
654 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
655 global $CFG, $USER;
657 $warnings = array();
659 $params = array(
660 'useridto' => $useridto,
661 'useridfrom' => $useridfrom,
662 'type' => $type,
663 'read' => $read,
664 'newestfirst' => $newestfirst,
665 'limitfrom' => $limitfrom,
666 'limitnum' => $limitnum
669 $params = self::validate_parameters(self::get_messages_parameters(), $params);
671 $context = context_system::instance();
672 self::validate_context($context);
674 $useridto = $params['useridto'];
675 $useridfrom = $params['useridfrom'];
676 $type = $params['type'];
677 $read = $params['read'];
678 $newestfirst = $params['newestfirst'];
679 $limitfrom = $params['limitfrom'];
680 $limitnum = $params['limitnum'];
682 $allowedvalues = array('notifications', 'conversations', 'both');
683 if (!in_array($type, $allowedvalues)) {
684 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
685 'allowed values are: ' . implode(',', $allowedvalues));
688 // Check if private messaging between users is allowed.
689 if (empty($CFG->messaging)) {
690 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
691 if ($type == "conversations") {
692 throw new moodle_exception('disabled', 'message');
694 if ($type == "both") {
695 $warning = array();
696 $warning['item'] = 'message';
697 $warning['itemid'] = $USER->id;
698 $warning['warningcode'] = '1';
699 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
700 Only notifications will be returned';
701 $warnings[] = $warning;
705 if (!empty($useridto)) {
706 if (core_user::is_real_user($useridto)) {
707 $userto = core_user::get_user($useridto, '*', MUST_EXIST);
708 } else {
709 throw new moodle_exception('invaliduser');
713 if (!empty($useridfrom)) {
714 // We use get_user here because the from user can be the noreply or support user.
715 $userfrom = core_user::get_user($useridfrom, '*', MUST_EXIST);
718 // Check if the current user is the sender/receiver or just a privileged user.
719 if ($useridto != $USER->id and $useridfrom != $USER->id and
720 !has_capability('moodle/site:readallmessages', $context)) {
721 throw new moodle_exception('accessdenied', 'admin');
724 // Which type of messages to retrieve.
725 $notifications = -1;
726 if ($type != 'both') {
727 $notifications = ($type == 'notifications') ? 1 : 0;
730 $orderdirection = $newestfirst ? 'DESC' : 'ASC';
731 $sort = "mr.timecreated $orderdirection";
733 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
734 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
736 // In some cases, we don't need to get the to/from user objects from the sql query.
737 $userfromfullname = '';
738 $usertofullname = '';
740 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
741 if (!empty($useridto)) {
742 $usertofullname = fullname($userto, $canviewfullname);
743 // The user from may or may not be filled.
744 if (!empty($useridfrom)) {
745 $userfromfullname = fullname($userfrom, $canviewfullname);
747 } else {
748 // If the useridto field is empty, the useridfrom must be filled.
749 $userfromfullname = fullname($userfrom, $canviewfullname);
751 foreach ($messages as $mid => $message) {
753 // Do not return deleted messages.
754 if (($useridto == $USER->id and $message->timeusertodeleted) or
755 ($useridfrom == $USER->id and $message->timeuserfromdeleted)) {
757 unset($messages[$mid]);
758 continue;
761 // We need to get the user from the query.
762 if (empty($userfromfullname)) {
763 // Check for non-reply and support users.
764 if (core_user::is_real_user($message->useridfrom)) {
765 $user = new stdClass();
766 $user = username_load_fields_from_object($user, $message, 'userfrom');
767 $message->userfromfullname = fullname($user, $canviewfullname);
768 } else {
769 $user = core_user::get_user($message->useridfrom);
770 $message->userfromfullname = fullname($user, $canviewfullname);
772 } else {
773 $message->userfromfullname = $userfromfullname;
776 // We need to get the user from the query.
777 if (empty($usertofullname)) {
778 $user = new stdClass();
779 $user = username_load_fields_from_object($user, $message, 'userto');
780 $message->usertofullname = fullname($user, $canviewfullname);
781 } else {
782 $message->usertofullname = $usertofullname;
785 // This field is only available in the message_read table.
786 if (!isset($message->timeread)) {
787 $message->timeread = 0;
790 $message->text = message_format_message_text($message);
791 $messages[$mid] = (array) $message;
795 $results = array(
796 'messages' => $messages,
797 'warnings' => $warnings
800 return $results;
804 * Get messages return description.
806 * @return external_single_structure
807 * @since 2.8
809 public static function get_messages_returns() {
810 return new external_single_structure(
811 array(
812 'messages' => new external_multiple_structure(
813 new external_single_structure(
814 array(
815 'id' => new external_value(PARAM_INT, 'Message id'),
816 'useridfrom' => new external_value(PARAM_INT, 'User from id'),
817 'useridto' => new external_value(PARAM_INT, 'User to id'),
818 'subject' => new external_value(PARAM_TEXT, 'The message subject'),
819 'text' => new external_value(PARAM_RAW, 'The message text formated'),
820 'fullmessage' => new external_value(PARAM_RAW, 'The message'),
821 'fullmessageformat' => new external_format_value('fullmessage'),
822 'fullmessagehtml' => new external_value(PARAM_RAW, 'The message in html'),
823 'smallmessage' => new external_value(PARAM_RAW, 'The shorten message'),
824 'notification' => new external_value(PARAM_INT, 'Is a notification?'),
825 'contexturl' => new external_value(PARAM_RAW, 'Context URL'),
826 'contexturlname' => new external_value(PARAM_TEXT, 'Context URL link name'),
827 'timecreated' => new external_value(PARAM_INT, 'Time created'),
828 'timeread' => new external_value(PARAM_INT, 'Time read'),
829 'usertofullname' => new external_value(PARAM_TEXT, 'User to full name'),
830 'userfromfullname' => new external_value(PARAM_TEXT, 'User from full name')
831 ), 'message'
834 'warnings' => new external_warnings()
840 * Get blocked users parameters description.
842 * @return external_function_parameters
843 * @since 2.9
845 public static function get_blocked_users_parameters() {
846 return new external_function_parameters(
847 array(
848 'userid' => new external_value(PARAM_INT,
849 'the user whose blocked users we want to retrieve',
850 VALUE_REQUIRED),
856 * Retrieve a list of users blocked
858 * @param int $userid the user whose blocked users we want to retrieve
859 * @return external_description
860 * @since 2.9
862 public static function get_blocked_users($userid) {
863 global $CFG, $USER, $PAGE;
865 // Warnings array, it can be empty at the end but is mandatory.
866 $warnings = array();
868 // Validate params.
869 $params = array(
870 'userid' => $userid
872 $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
873 $userid = $params['userid'];
875 // Validate context.
876 $context = context_system::instance();
877 self::validate_context($context);
879 // Check if private messaging between users is allowed.
880 if (empty($CFG->messaging)) {
881 throw new moodle_exception('disabled', 'message');
884 $user = core_user::get_user($userid, '*', MUST_EXIST);
885 core_user::require_active_user($user);
887 // Check if we have permissions for retrieve the information.
888 if ($userid != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
889 throw new moodle_exception('accessdenied', 'admin');
892 // Now, we can get safely all the blocked users.
893 $users = message_get_blocked_users($user);
895 $blockedusers = array();
896 foreach ($users as $user) {
897 $newuser = array(
898 'id' => $user->id,
899 'fullname' => fullname($user),
902 $userpicture = new user_picture($user);
903 $userpicture->size = 1; // Size f1.
904 $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
906 $blockedusers[] = $newuser;
909 $results = array(
910 'users' => $blockedusers,
911 'warnings' => $warnings
913 return $results;
917 * Get blocked users return description.
919 * @return external_single_structure
920 * @since 2.9
922 public static function get_blocked_users_returns() {
923 return new external_single_structure(
924 array(
925 'users' => new external_multiple_structure(
926 new external_single_structure(
927 array(
928 'id' => new external_value(PARAM_INT, 'User ID'),
929 'fullname' => new external_value(PARAM_NOTAGS, 'User full name'),
930 'profileimageurl' => new external_value(PARAM_URL, 'User picture URL', VALUE_OPTIONAL)
933 'List of blocked users'
935 'warnings' => new external_warnings()
941 * Returns description of method parameters
943 * @return external_function_parameters
944 * @since 2.9
946 public static function mark_message_read_parameters() {
947 return new external_function_parameters(
948 array(
949 'messageid' => new external_value(PARAM_INT, 'id of the message (in the message table)'),
950 'timeread' => new external_value(PARAM_INT, 'timestamp for when the message should be marked read')
956 * Mark a single message as read, trigger message_viewed event
958 * @param int $messageid id of the message (in the message table)
959 * @param int $timeread timestamp for when the message should be marked read
960 * @return external_description
961 * @throws invalid_parameter_exception
962 * @throws moodle_exception
963 * @since 2.9
965 public static function mark_message_read($messageid, $timeread) {
966 global $CFG, $DB, $USER;
968 // Check if private messaging between users is allowed.
969 if (empty($CFG->messaging)) {
970 throw new moodle_exception('disabled', 'message');
973 // Warnings array, it can be empty at the end but is mandatory.
974 $warnings = array();
976 // Validate params.
977 $params = array(
978 'messageid' => $messageid,
979 'timeread' => $timeread
981 $params = self::validate_parameters(self::mark_message_read_parameters(), $params);
983 // Validate context.
984 $context = context_system::instance();
985 self::validate_context($context);
987 $message = $DB->get_record('message', array('id' => $params['messageid']), '*', MUST_EXIST);
989 if ($message->useridto != $USER->id) {
990 throw new invalid_parameter_exception('Invalid messageid, you don\'t have permissions to mark this message as read');
993 $messageid = message_mark_message_read($message, $params['timeread']);
995 $results = array(
996 'messageid' => $messageid,
997 'warnings' => $warnings
999 return $results;
1003 * Returns description of method result value
1005 * @return external_description
1006 * @since 2.9
1008 public static function mark_message_read_returns() {
1009 return new external_single_structure(
1010 array(
1011 'messageid' => new external_value(PARAM_INT, 'the id of the message in the message_read table'),
1012 'warnings' => new external_warnings()
1018 * Returns description of method parameters
1020 * @return external_function_parameters
1021 * @since 3.1
1023 public static function delete_message_parameters() {
1024 return new external_function_parameters(
1025 array(
1026 'messageid' => new external_value(PARAM_INT, 'The message id'),
1027 'userid' => new external_value(PARAM_INT, 'The user id of who we want to delete the message for'),
1028 'read' => new external_value(PARAM_BOOL, 'If is a message read', VALUE_DEFAULT, true)
1034 * Deletes a message
1036 * @param int $messageid the message id
1037 * @param int $userid the user id of who we want to delete the message for
1038 * @param bool $read if is a message read (default to true)
1039 * @return external_description
1040 * @throws moodle_exception
1041 * @since 3.1
1043 public static function delete_message($messageid, $userid, $read = true) {
1044 global $CFG, $DB;
1046 // Check if private messaging between users is allowed.
1047 if (empty($CFG->messaging)) {
1048 throw new moodle_exception('disabled', 'message');
1051 // Warnings array, it can be empty at the end but is mandatory.
1052 $warnings = array();
1054 // Validate params.
1055 $params = array(
1056 'messageid' => $messageid,
1057 'userid' => $userid,
1058 'read' => $read
1060 $params = self::validate_parameters(self::delete_message_parameters(), $params);
1062 // Validate context.
1063 $context = context_system::instance();
1064 self::validate_context($context);
1066 $messagestable = $params['read'] ? 'message_read' : 'message';
1067 $message = $DB->get_record($messagestable, array('id' => $params['messageid']), '*', MUST_EXIST);
1069 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
1070 core_user::require_active_user($user);
1072 $status = false;
1073 if (message_can_delete_message($message, $user->id)) {
1074 $status = message_delete_message($message, $user->id);;
1075 } else {
1076 throw new moodle_exception('You do not have permission to delete this message');
1079 $results = array(
1080 'status' => $status,
1081 'warnings' => $warnings
1083 return $results;
1087 * Returns description of method result value
1089 * @return external_description
1090 * @since 3.1
1092 public static function delete_message_returns() {
1093 return new external_single_structure(
1094 array(
1095 'status' => new external_value(PARAM_BOOL, 'True if the message was deleted, false otherwise'),
1096 'warnings' => new external_warnings()