Example #1
0
require_sesskey();
$action = optional_param('action', null, PARAM_ALPHA);
$response = null;
switch ($action) {
    // Sending a message.
    case 'sendmessage':
        $userid = required_param('userid', PARAM_INT);
        if (empty($userid) || isguestuser($userid) || $userid == $USER->id) {
            // Cannot send messags to self, nobody or a guest.
            throw new coding_exception('Invalid user to send the message to');
        }
        $message = required_param('message', PARAM_RAW);
        $user2 = core_user::get_user($userid);
        // Only attempt to send the message if we have permission to message
        // the recipient.
        if (message_can_post_message($user2, $USER)) {
            $messageid = message_post_message($USER, $user2, $message, FORMAT_MOODLE);
            if (!$messageid) {
                throw new moodle_exception('errorwhilesendingmessage', 'core_message');
            }
        } else {
            throw new moodle_exception('unabletomessageuser', 'core_message');
        }
        $response = array();
        break;
}
if ($response !== null) {
    echo json_encode($response);
    exit;
}
throw new coding_exception('Invalid request');
Example #2
0
 /**
  * Test that message_can_post_message returns false if the receiver has blocked the
  * sender from messaging them.
  */
 public function test_message_can_post_message_returns_true()
 {
     $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
     $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
     $this->assertTrue(message_can_post_message($recipient, $sender));
 }