public static function can_post_message($recipient, $sender = null) {
        global $USER;

        if (is_null($sender)) {
            // The message is from the logged in user, unless otherwise specified.
            $sender = $USER;
        }

        $systemcontext = \context_system::instance();
        if (!has_capability('moodle/site:sendmessage', $systemcontext, $sender)) {
            return false;
        }

        if (has_capability('moodle/site:readallmessages', $systemcontext, $sender->id)) {
            return true;
        }

        // Check if the recipient can be messaged by the sender.
        return (self::can_contact_user($recipient->id, $sender->id));
    }