Merge branch 'MDL-48499' of https://github.com/danielneis/moodle
[moodle.git] / message / ajax.php
bloba4dd12fbfb917ba67cdcea1afff0cdd2e46f2b22
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/>.
17 /**
18 * Ajax point of entry for messaging API.
20 * @package core_message
21 * @copyright 2015 Frédéric Massart - FMCorz.net
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 define('AJAX_SCRIPT', true);
27 require('../config.php');
28 require_once($CFG->libdir . '/filelib.php');
29 require_once(__DIR__ . '/lib.php');
31 // Only real logged in users.
32 require_login(null, false, null, true, true);
33 if (isguestuser()) {
34 throw new require_login_exception();
37 // Messaging needs to be enabled.
38 if (empty($CFG->messaging)) {
39 throw new moodle_exception('disabled', 'core_message');
42 require_sesskey();
43 $action = optional_param('action', null, PARAM_ALPHA);
44 $response = null;
46 switch ($action) {
48 // Sending a message.
49 case 'sendmessage':
51 require_capability('moodle/site:sendmessage', context_system::instance());
53 $userid = required_param('userid', PARAM_INT);
54 if (empty($userid) || isguestuser($userid) || $userid == $USER->id) {
55 // Cannot send messags to self, nobody or a guest.
56 throw new coding_exception('Invalid user to send the message to');
59 $message = required_param('message', PARAM_RAW);
60 $user2 = core_user::get_user($userid);
61 $messageid = message_post_message($USER, $user2, $message, FORMAT_MOODLE);
63 if (!$messageid) {
64 throw new moodle_exception('errorwhilesendingmessage', 'core_message');
67 $response = array();
68 break;
71 if ($response !== null) {
72 echo json_encode($response);
73 exit();
76 throw new coding_exception('Invalid request');