ajax.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. * Ajax point of entry for messaging API.
  18. *
  19. * @package core_message
  20. * @copyright 2015 Frédéric Massart - FMCorz.net
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. define('AJAX_SCRIPT', true);
  24. require('../config.php');
  25. require_once($CFG->libdir . '/filelib.php');
  26. require_once(__DIR__ . '/lib.php');
  27. // Only real logged in users.
  28. require_login(null, false, null, true, true);
  29. if (isguestuser()) {
  30. throw new require_login_exception('Guests are not allowed here.');
  31. }
  32. // Messaging needs to be enabled.
  33. if (empty($CFG->messaging)) {
  34. throw new moodle_exception('disabled', 'core_message');
  35. }
  36. $PAGE->set_context(null);
  37. require_sesskey();
  38. $action = optional_param('action', null, PARAM_ALPHA);
  39. $response = null;
  40. switch ($action) {
  41. // Sending a message.
  42. case 'sendmessage':
  43. $userid = required_param('userid', PARAM_INT);
  44. if (empty($userid) || isguestuser($userid) || $userid == $USER->id) {
  45. // Cannot send messags to self, nobody or a guest.
  46. throw new coding_exception('Invalid user to send the message to');
  47. }
  48. $message = required_param('message', PARAM_RAW);
  49. $user2 = core_user::get_user($userid);
  50. // Only attempt to send the message if we have permission to message
  51. // the recipient.
  52. if (message_can_post_message($user2, $USER)) {
  53. $messageid = message_post_message($USER, $user2, $message, FORMAT_MOODLE);
  54. if (!$messageid) {
  55. throw new moodle_exception('errorwhilesendingmessage', 'core_message');
  56. }
  57. } else {
  58. throw new moodle_exception('unabletomessageuser', 'core_message');
  59. }
  60. $response = array();
  61. break;
  62. }
  63. if ($response !== null) {
  64. echo json_encode($response);
  65. exit();
  66. }
  67. throw new coding_exception('Invalid request');