Merge branch 'wip-MDL-53274-fix' of https://github.com/marinaglancy/moodle
[moodle.git] / message / ajax.php
CommitLineData
cf4a17cb
FM
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.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
0061876d 18 * Ajax point of entry for messaging API.
cf4a17cb
FM
19 *
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
23 */
24
25define('AJAX_SCRIPT', true);
26
27require('../config.php');
28require_once($CFG->libdir . '/filelib.php');
29require_once(__DIR__ . '/lib.php');
30
31// Only real logged in users.
32require_login(null, false, null, true, true);
33if (isguestuser()) {
baa850a3 34 throw new require_login_exception('Guests are not allowed here.');
cf4a17cb
FM
35}
36
37// Messaging needs to be enabled.
38if (empty($CFG->messaging)) {
39 throw new moodle_exception('disabled', 'core_message');
40}
41
0a4f89e5 42$PAGE->set_context(null);
cf4a17cb
FM
43require_sesskey();
44$action = optional_param('action', null, PARAM_ALPHA);
45$response = null;
46
47switch ($action) {
48
49 // Sending a message.
50 case 'sendmessage':
51
cf4a17cb
FM
52 $userid = required_param('userid', PARAM_INT);
53 if (empty($userid) || isguestuser($userid) || $userid == $USER->id) {
54 // Cannot send messags to self, nobody or a guest.
55 throw new coding_exception('Invalid user to send the message to');
56 }
57
58 $message = required_param('message', PARAM_RAW);
59 $user2 = core_user::get_user($userid);
cf4a17cb 60
cd0c9ac8
RW
61 // Only attempt to send the message if we have permission to message
62 // the recipient.
63 if (message_can_post_message($user2, $USER)) {
64 $messageid = message_post_message($USER, $user2, $message, FORMAT_MOODLE);
65
66 if (!$messageid) {
67 throw new moodle_exception('errorwhilesendingmessage', 'core_message');
68 }
69 } else {
70 throw new moodle_exception('unabletomessageuser', 'core_message');
cf4a17cb
FM
71 }
72
73 $response = array();
74 break;
75}
76
77if ($response !== null) {
78 echo json_encode($response);
79 exit();
80}
81
82throw new coding_exception('Invalid request');