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");
30 * Message external functions
32 * @package core_message
34 * @copyright 2011 Jerome Mouneyrac
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 class core_message_external
extends external_api
{
41 * Returns description of method parameters
43 * @return external_function_parameters
46 public static function send_instant_messages_parameters() {
47 return new external_function_parameters(
49 'messages' => new external_multiple_structure(
50 new external_single_structure(
52 'touserid' => new external_value(PARAM_INT
, 'id of the user to send the private message'),
53 'text' => new external_value(PARAM_RAW
, 'the text of the message'),
54 'textformat' => new external_format_value('text', VALUE_DEFAULT
),
55 '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 * Send private messages from the current USER to other users
66 * @param array $messages An array of message to send.
70 public static function send_instant_messages($messages = array()) {
71 global $CFG, $USER, $DB;
72 require_once($CFG->dirroot
. "/message/lib.php");
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');
143 //now we can send the message (at least try)
145 //TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object
146 $success = message_post_message($USER, $tousers[$message['touserid']],
147 $message['text'], external_validate_format($message['textformat']));
150 //build the resultmsg
151 if (isset($message['clientmsgid'])) {
152 $resultmsg['clientmsgid'] = $message['clientmsgid'];
155 $resultmsg['msgid'] = $success;
157 // WARNINGS: for backward compatibility we return this errormessage.
158 // We should have thrown exceptions as these errors prevent results to be returned.
159 // See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
160 $resultmsg['msgid'] = -1;
161 $resultmsg['errormessage'] = $errormessage;
164 $resultmessages[] = $resultmsg;
167 return $resultmessages;
171 * Returns description of method result value
173 * @return external_description
176 public static function send_instant_messages_returns() {
177 return new external_multiple_structure(
178 new external_single_structure(
180 'msgid' => new external_value(PARAM_INT
, 'test this to know if it succeeds: id of the created message if it succeeded, -1 when failed'),
181 'clientmsgid' => new external_value(PARAM_ALPHANUMEXT
, 'your own id for the message', VALUE_OPTIONAL
),
182 'errormessage' => new external_value(PARAM_TEXT
, 'error message - if it failed', VALUE_OPTIONAL
)
189 * Create contacts parameters description.
191 * @return external_function_parameters
194 public static function create_contacts_parameters() {
195 return new external_function_parameters(
197 'userids' => new external_multiple_structure(
198 new external_value(PARAM_INT
, 'User ID'),
208 * @param array $userids array of user IDs.
209 * @return external_description
212 public static function create_contacts($userids) {
213 $params = array('userids' => $userids);
214 $params = self
::validate_parameters(self
::create_contacts_parameters(), $params);
217 foreach ($params['userids'] as $id) {
218 if (!message_add_contact($id)) {
222 'warningcode' => 'contactnotcreated',
223 'message' => 'The contact could not be created'
231 * Create contacts return description.
233 * @return external_description
236 public static function create_contacts_returns() {
237 return new external_warnings();
241 * Delete contacts parameters description.
243 * @return external_function_parameters
246 public static function delete_contacts_parameters() {
247 return new external_function_parameters(
249 'userids' => new external_multiple_structure(
250 new external_value(PARAM_INT
, 'User ID'),
260 * @param array $userids array of user IDs.
264 public static function delete_contacts($userids) {
265 $params = array('userids' => $userids);
266 $params = self
::validate_parameters(self
::delete_contacts_parameters(), $params);
268 foreach ($params['userids'] as $id) {
269 message_remove_contact($id);
276 * Delete contacts return description.
278 * @return external_description
281 public static function delete_contacts_returns() {
286 * Block contacts parameters description.
288 * @return external_function_parameters
291 public static function block_contacts_parameters() {
292 return new external_function_parameters(
294 'userids' => new external_multiple_structure(
295 new external_value(PARAM_INT
, 'User ID'),
305 * @param array $userids array of user IDs.
306 * @return external_description
309 public static function block_contacts($userids) {
310 $params = array('userids' => $userids);
311 $params = self
::validate_parameters(self
::block_contacts_parameters(), $params);
314 foreach ($params['userids'] as $id) {
315 if (!message_block_contact($id)) {
319 'warningcode' => 'contactnotblocked',
320 'message' => 'The contact could not be blocked'
328 * Block contacts return description.
330 * @return external_description
333 public static function block_contacts_returns() {
334 return new external_warnings();
338 * Unblock contacts parameters description.
340 * @return external_function_parameters
343 public static function unblock_contacts_parameters() {
344 return new external_function_parameters(
346 'userids' => new external_multiple_structure(
347 new external_value(PARAM_INT
, 'User ID'),
357 * @param array $userids array of user IDs.
361 public static function unblock_contacts($userids) {
362 $params = array('userids' => $userids);
363 $params = self
::validate_parameters(self
::unblock_contacts_parameters(), $params);
365 foreach ($params['userids'] as $id) {
366 message_unblock_contact($id);
373 * Unblock contacts return description.
375 * @return external_description
378 public static function unblock_contacts_returns() {
383 * Get contacts parameters description.
385 * @return external_function_parameters
388 public static function get_contacts_parameters() {
389 return new external_function_parameters(array());
395 * @param array $userids array of user IDs.
396 * @return external_description
399 public static function get_contacts() {
401 require_once($CFG->dirroot
. '/user/lib.php');
403 list($online, $offline, $strangers) = message_get_contacts();
404 $allcontacts = array('online' => $online, 'offline' => $offline, 'strangers' => $strangers);
405 foreach ($allcontacts as $mode => $contacts) {
406 foreach ($contacts as $key => $contact) {
408 'id' => $contact->id
,
409 'fullname' => fullname($contact),
410 'unread' => $contact->messagecount
413 // Try to get the user picture, but sometimes this method can return null.
414 $userdetails = user_get_user_details($contact, null, array('profileimageurl', 'profileimageurlsmall'));
415 if (!empty($userdetails)) {
416 $newcontact['profileimageurl'] = $userdetails['profileimageurl'];
417 $newcontact['profileimageurlsmall'] = $userdetails['profileimageurlsmall'];
420 $allcontacts[$mode][$key] = $newcontact;
427 * Get contacts return description.
429 * @return external_description
432 public static function get_contacts_returns() {
433 return new external_single_structure(
435 'online' => new external_multiple_structure(
436 new external_single_structure(
438 'id' => new external_value(PARAM_INT
, 'User ID'),
439 'fullname' => new external_value(PARAM_NOTAGS
, 'User full name'),
440 'profileimageurl' => new external_value(PARAM_URL
, 'User picture URL', VALUE_OPTIONAL
),
441 'profileimageurlsmall' => new external_value(PARAM_URL
, 'Small user picture URL', VALUE_OPTIONAL
),
442 'unread' => new external_value(PARAM_INT
, 'Unread message count')
445 'List of online contacts'
447 'offline' => new external_multiple_structure(
448 new external_single_structure(
450 'id' => new external_value(PARAM_INT
, 'User ID'),
451 'fullname' => new external_value(PARAM_NOTAGS
, 'User full name'),
452 'profileimageurl' => new external_value(PARAM_URL
, 'User picture URL', VALUE_OPTIONAL
),
453 'profileimageurlsmall' => new external_value(PARAM_URL
, 'Small user picture URL', VALUE_OPTIONAL
),
454 'unread' => new external_value(PARAM_INT
, 'Unread message count')
457 'List of offline contacts'
459 'strangers' => new external_multiple_structure(
460 new external_single_structure(
462 'id' => new external_value(PARAM_INT
, 'User ID'),
463 'fullname' => new external_value(PARAM_NOTAGS
, 'User full name'),
464 'profileimageurl' => new external_value(PARAM_URL
, 'User picture URL', VALUE_OPTIONAL
),
465 'profileimageurlsmall' => new external_value(PARAM_URL
, 'Small user picture URL', VALUE_OPTIONAL
),
466 'unread' => new external_value(PARAM_INT
, 'Unread message count')
469 'List of users that are not in the user\'s contact list but have sent a message'
476 * Search contacts parameters description.
478 * @return external_function_parameters
481 public static function search_contacts_parameters() {
482 return new external_function_parameters(
484 'searchtext' => new external_value(PARAM_CLEAN
, 'String the user\'s fullname has to match to be found'),
485 'onlymycourses' => new external_value(PARAM_BOOL
, 'Limit search to the user\'s courses',
486 VALUE_DEFAULT
, false)
494 * @param string $searchtext query string.
495 * @param bool $onlymycourses limit the search to the user's courses only.
496 * @return external_description
499 public static function search_contacts($searchtext, $onlymycourses = false) {
501 require_once($CFG->libdir
. '/enrollib.php');
503 $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
504 $params = self
::validate_parameters(self
::search_contacts_parameters(), $params);
506 // Extra validation, we do not allow empty queries.
507 if ($params['searchtext'] === '') {
508 throw new moodle_exception('querystringcannotbeempty');
511 $courseids = array();
512 if ($params['onlymycourses']) {
513 $mycourses = enrol_get_my_courses(array('id'));
514 foreach ($mycourses as $mycourse) {
515 $courseids[] = $mycourse->id
;
518 $courseids[] = SITEID
;
521 // Retrieving the users matching the query.
522 $users = message_search_users($courseids, $params['searchtext']);
524 foreach ($users as $user) {
525 $results[$user->id
] = $user;
528 // Reorganising information.
529 foreach ($results as &$user) {
532 'fullname' => fullname($user)
535 // Avoid undefined property notice as phone not specified.
536 $user->phone1
= null;
537 $user->phone2
= null;
539 // Try to get the user picture, but sometimes this method can return null.
540 $userdetails = user_get_user_details($user, null, array('profileimageurl', 'profileimageurlsmall'));
541 if (!empty($userdetails)) {
542 $newuser['profileimageurl'] = $userdetails['profileimageurl'];
543 $newuser['profileimageurlsmall'] = $userdetails['profileimageurlsmall'];
553 * Search contacts return description.
555 * @return external_description
558 public static function search_contacts_returns() {
559 return new external_multiple_structure(
560 new external_single_structure(
562 'id' => new external_value(PARAM_INT
, 'User ID'),
563 'fullname' => new external_value(PARAM_NOTAGS
, 'User full name'),
564 'profileimageurl' => new external_value(PARAM_URL
, 'User picture URL', VALUE_OPTIONAL
),
565 'profileimageurlsmall' => new external_value(PARAM_URL
, 'Small user picture URL', VALUE_OPTIONAL
)
573 * Get messages parameters description.
575 * @return external_function_parameters
578 public static function get_messages_parameters() {
579 return new external_function_parameters(
581 'useridto' => new external_value(PARAM_INT
, 'the user id who received the message, 0 for any user', VALUE_REQUIRED
),
582 'useridfrom' => new external_value(
583 PARAM_INT
, 'the user id who send the message, 0 for any user. -10 or -20 for no-reply or support user',
585 'type' => new external_value(
586 PARAM_ALPHA
, 'type of message to return, expected values are: notifications, conversations and both',
587 VALUE_DEFAULT
, 'both'),
588 'read' => new external_value(PARAM_BOOL
, 'true for getting read messages, false for unread', VALUE_DEFAULT
, true),
589 'newestfirst' => new external_value(
590 PARAM_BOOL
, 'true for ordering by newest first, false for oldest first',
591 VALUE_DEFAULT
, true),
592 'limitfrom' => new external_value(PARAM_INT
, 'limit from', VALUE_DEFAULT
, 0),
593 'limitnum' => new external_value(PARAM_INT
, 'limit number', VALUE_DEFAULT
, 0)
599 * Get messages function implementation.
602 * @throws invalid_parameter_exception
603 * @throws moodle_exception
604 * @param int $useridto the user id who received the message
605 * @param int $useridfrom the user id who send the message. -10 or -20 for no-reply or support user
606 * @param string $type type of message to return, expected values: notifications, conversations and both
607 * @param bool $read true for retreiving read messages, false for unread
608 * @param bool $newestfirst true for ordering by newest first, false for oldest first
609 * @param int $limitfrom limit from
610 * @param int $limitnum limit num
611 * @return external_description
613 public static function get_messages($useridto, $useridfrom = 0, $type = 'both', $read = true,
614 $newestfirst = true, $limitfrom = 0, $limitnum = 0) {
616 require_once($CFG->dirroot
. "/message/lib.php");
621 'useridto' => $useridto,
622 'useridfrom' => $useridfrom,
625 'newestfirst' => $newestfirst,
626 'limitfrom' => $limitfrom,
627 'limitnum' => $limitnum
630 $params = self
::validate_parameters(self
::get_messages_parameters(), $params);
632 $context = context_system
::instance();
633 self
::validate_context($context);
635 $useridto = $params['useridto'];
636 $useridfrom = $params['useridfrom'];
637 $type = $params['type'];
638 $read = $params['read'];
639 $newestfirst = $params['newestfirst'];
640 $limitfrom = $params['limitfrom'];
641 $limitnum = $params['limitnum'];
643 $allowedvalues = array('notifications', 'conversations', 'both');
644 if (!in_array($type, $allowedvalues)) {
645 throw new invalid_parameter_exception('Invalid value for type parameter (value: ' . $type . '),' .
646 'allowed values are: ' . implode(',', $allowedvalues));
649 // Check if private messaging between users is allowed.
650 if (empty($CFG->messaging
)) {
651 // If we are retreiving only conversations, and messaging is disabled, throw an exception.
652 if ($type == "conversations") {
653 throw new moodle_exception('disabled', 'message');
655 if ($type == "both") {
657 $warning['item'] = 'message';
658 $warning['itemid'] = $USER->id
;
659 $warning['warningcode'] = '1';
660 $warning['message'] = 'Private messages (conversations) are not enabled in this site.
661 Only notifications will be returned';
662 $warnings[] = $warning;
666 if (!empty($useridto)) {
667 if (core_user
::is_real_user($useridto)) {
668 $userto = core_user
::get_user($useridto, '*', MUST_EXIST
);
670 throw new moodle_exception('invaliduser');
674 if (!empty($useridfrom)) {
675 // We use get_user here because the from user can be the noreply or support user.
676 $userfrom = core_user
::get_user($useridfrom, '*', MUST_EXIST
);
679 // Check if the current user is the sender/receiver or just a privileged user.
680 if ($useridto != $USER->id
and $useridfrom != $USER->id
and
681 !has_capability('moodle/site:readallmessages', $context)) {
682 throw new moodle_exception('accessdenied', 'admin');
685 // Which type of messages to retrieve.
687 if ($type != 'both') {
688 $notifications = ($type == 'notifications') ?
1 : 0;
691 $orderdirection = $newestfirst ?
'DESC' : 'ASC';
692 $sort = "mr.timecreated $orderdirection";
694 if ($messages = message_get_messages($useridto, $useridfrom, $notifications, $read, $sort, $limitfrom, $limitnum)) {
695 $canviewfullname = has_capability('moodle/site:viewfullnames', $context);
697 // In some cases, we don't need to get the to/from user objects from the sql query.
698 $userfromfullname = '';
699 $usertofullname = '';
701 // In this case, the useridto field is not empty, so we can get the user destinatary fullname from there.
702 if (!empty($useridto)) {
703 $usertofullname = fullname($userto, $canviewfullname);
704 // The user from may or may not be filled.
705 if (!empty($useridfrom)) {
706 $userfromfullname = fullname($userfrom, $canviewfullname);
709 // If the useridto field is empty, the useridfrom must be filled.
710 $userfromfullname = fullname($userfrom, $canviewfullname);
712 foreach ($messages as $mid => $message) {
714 // We need to get the user from the query.
715 if (empty($userfromfullname)) {
716 // Check for non-reply and support users.
717 if (core_user
::is_real_user($message->useridfrom
)) {
718 $user = new stdClass();
719 $user = username_load_fields_from_object($user, $message, 'userfrom');
720 $message->userfromfullname
= fullname($user, $canviewfullname);
722 $user = core_user
::get_user($message->useridfrom
);
723 $message->userfromfullname
= fullname($user, $canviewfullname);
726 $message->userfromfullname
= $userfromfullname;
729 // We need to get the user from the query.
730 if (empty($usertofullname)) {
731 $user = new stdClass();
732 $user = username_load_fields_from_object($user, $message, 'userto');
733 $message->usertofullname
= fullname($user, $canviewfullname);
735 $message->usertofullname
= $usertofullname;
738 // This field is only available in the message_read table.
739 if (!isset($message->timeread
)) {
740 $message->timeread
= 0;
743 $message->text
= message_format_message_text($message);
744 $messages[$mid] = (array) $message;
749 'messages' => $messages,
750 'warnings' => $warnings
757 * Get messages return description.
759 * @return external_single_structure
762 public static function get_messages_returns() {
763 return new external_single_structure(
765 'messages' => new external_multiple_structure(
766 new external_single_structure(
768 'id' => new external_value(PARAM_INT
, 'Message id'),
769 'useridfrom' => new external_value(PARAM_INT
, 'User from id'),
770 'useridto' => new external_value(PARAM_INT
, 'User to id'),
771 'subject' => new external_value(PARAM_TEXT
, 'The message subject'),
772 'text' => new external_value(PARAM_RAW
, 'The message text formated'),
773 'fullmessage' => new external_value(PARAM_RAW
, 'The message'),
774 'fullmessageformat' => new external_format_value('fullmessage'),
775 'fullmessagehtml' => new external_value(PARAM_RAW
, 'The message in html'),
776 'smallmessage' => new external_value(PARAM_RAW
, 'The shorten message'),
777 'notification' => new external_value(PARAM_INT
, 'Is a notification?'),
778 'contexturl' => new external_value(PARAM_RAW
, 'Context URL'),
779 'contexturlname' => new external_value(PARAM_TEXT
, 'Context URL link name'),
780 'timecreated' => new external_value(PARAM_INT
, 'Time created'),
781 'timeread' => new external_value(PARAM_INT
, 'Time read'),
782 'usertofullname' => new external_value(PARAM_TEXT
, 'User to full name'),
783 'userfromfullname' => new external_value(PARAM_TEXT
, 'User from full name')
787 'warnings' => new external_warnings()
795 * Deprecated message external functions
797 * @package core_message
798 * @copyright 2011 Jerome Mouneyrac
799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
801 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
802 * @see core_notes_external
804 class moodle_message_external
extends external_api
{
807 * Returns description of method parameters
809 * @return external_function_parameters
811 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
812 * @see core_message_external::send_instant_messages_parameters()
814 public static function send_instantmessages_parameters() {
815 return core_message_external
::send_instant_messages_parameters();
819 * Send private messages from the current USER to other users
821 * @param array $messages An array of message to send.
824 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
825 * @see core_message_external::send_instant_messages()
827 public static function send_instantmessages($messages = array()) {
828 return core_message_external
::send_instant_messages($messages);
832 * Returns description of method result value
834 * @return external_description
836 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
837 * @see core_message_external::send_instant_messages_returns()
839 public static function send_instantmessages_returns() {
840 return core_message_external
::send_instant_messages_returns();