public static function get_sessions($chatid, $groupid = 0, $showall = false) {
        global $DB;

        $params = self::validate_parameters(self::get_sessions_parameters(),
                                            array(
                                                'chatid' => $chatid,
                                                'groupid' => $groupid,
                                                'showall' => $showall,
                                            ));
        $sessions = $warnings = array();

        // Request and permission validation.
        $chat = $DB->get_record('chat', array('id' => $params['chatid']), '*', MUST_EXIST);
        list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');

        $context = context_module::instance($cm->id);
        self::validate_context($context);

        if (empty($chat->studentlogs) && !has_capability('mod/chat:readlog', $context)) {
            throw new moodle_exception('nopermissiontoseethechatlog', 'chat');
        }

        if (!empty($params['groupid'])) {
            $groupid = $params['groupid'];
            // Determine is the group is visible to user.
            if (!groups_group_visible($groupid, $course, $cm)) {
                throw new moodle_exception('notingroup');
            }
        } else {
            // Check to see if groups are being used here.
            if ($groupmode = groups_get_activity_groupmode($cm)) {
                $groupid = groups_get_activity_group($cm);
                // Determine is the group is visible to user (this is particullary for the group 0).
                if (!groups_group_visible($groupid, $course, $cm)) {
                    throw new moodle_exception('notingroup');
                }
            } else {
                $groupid = 0;
            }
        }

        $messages = chat_get_session_messages($chat->id, $groupid, 0, 0, 'timestamp DESC');
        if ($messages) {
            $chatsessions = chat_get_sessions($messages, $params['showall']);
            // Format sessions for external.
            foreach ($chatsessions as $session) {
                $sessionusers = array();
                foreach ($session->sessionusers as $sessionuser => $usermessagecount) {
                    $sessionusers[] = array(
                        'userid' => $sessionuser,
                        'messagecount' => $usermessagecount
                    );
                }
                $session->sessionusers = $sessionusers;
                $sessions[] = $session;
            }
        }

        $result = array();
        $result['sessions'] = $sessions;
        $result['warnings'] = $warnings;
        return $result;
    }