public function is_logged_in() {
        // Has the token expired?
        if (isset($this->accesstoken->expires) && time() >= $this->accesstoken->expires) {
            $this->log_out();
            return false;
        }

        // We have a token so we are logged in.
        if (isset($this->accesstoken->token)) {
            // Check that the access token has all the requested scopes.
            $scopemissing = false;
            $scopecheck = ' ' . $this->accesstoken->scope . ' ';

            $requiredscopes = explode(' ', $this->scope);
            foreach ($requiredscopes as $requiredscope) {
                if (strpos($scopecheck, ' ' . $requiredscope . ' ') === false) {
                    $scopemissing = true;
                    break;
                }
            }
            if (!$scopemissing) {
                return true;
            }
        }

        // If we've been passed then authorization code generated by the
        // authorization server try and upgrade the token to an access token.
        $code = optional_param('oauth2code', null, PARAM_RAW);
        // Note - sometimes we may call is_logged_in twice in the same request - we don't want to attempt
        // to upgrade the same token twice.
        if ($code && !in_array($code, self::$upgradedcodes) && $this->upgrade_token($code)) {
            return true;
        }

        return false;
    }