<?php

function check_authentication($redirect = true)
{
    global $request;
    $cbargs = array();
    $current_page = get_current_page();

    // Some pages are used by both frontend and backend, so check for backend...
    if (defined('BACKEND')) {

        echo 'BACKEND DEFINED';
        check_backend_authentication();
        return;
    }

    if (!is_authenticated()) {

        //do_callbacks(CALLBACK_CHECK_AUTHENTICATION_FAILED, $cbargs);

        if ($redirect == false) {

            // Don't redirect user
            echo 'Your session has timed out.';

        } else {

            $dont_redirect_these_pages = array('login.php', 'install.php');
            if (in_array($current_page, $dont_redirect_these_pages)) {
                return;
            }

            // redirect user to login screen
            $redirecturl = $_SERVER['PHP_SELF'];
            $redirecturl .= urlencode('?');

            $redirect_q_string = urlencode($_SERVER['QUERY_STRING']);
            $redirecturl .= $redirect_q_string;

            $theurl = get_base_url() . "login.php?redirect={$redirecturl}";
            $theurl .= '&noauth=1'; // Needed for auto-login
            header('Location: ' . $theurl);
        }

        exit();
    }

    // User must change password
    if ($current_page != 'login.php' && $current_page != 'ajaxhelper.php') {
        if (get_user_meta("force_password_change", 0, 0) == 1) {
            header("Location: " . get_base_url() . "login.php?forcepasswordchange");
            exit();
        }
    }

    // Update session
    user_update_session();

    //do_callbacks(CALLBACK_CHECK_AUTHENTICATION_PASSED, $cbargs);
}

function is_authenticated() {

    // Some pages are used by both frontend and backend, so check for backend...
    if (defined('BACKEND')) {
        return is_backend_authenticated();
    }

    // Session variable is set, so they are already logged in
    if (isset($_SESSION['user_id'])) {
        if (is_valid_user_id($_SESSION['user_id']) === false) {
            return false;
        }
        return true;
    }

    // Check token auth
    if (is_auth_token_authenticated()) {
        return true;
    }

    // HTTP BASIC AUTHENTICATION support
    if (is_http_basic_authenticated()) {
        return true;
    }

    return false;
}

/**
 * Checks if an auth token is valid and if we should log someone
 * in or not using it.
 *
 * @return  bool            True if user valid
 */
function is_auth_token_authenticated()
{
    $auth_token = grab_request_var("token", "");
    if (empty($auth_token)) {
        return false;
    }

    // Check token for validity
    if (user_is_valid_auth_token($auth_token)) {
        $user_id = user_get_auth_token_user_id($auth_token);
        $username = get_username($user_id);

        // Log user in
        $_SESSION["user_id"] = $user_id;
        $_SESSION["username"] = $username;

        // Set up the session in the db
        $sid = user_generate_session();
        $_SESSION["session_id"] = $sid;
        
        get_user_meta_session_vars(true);
        create_dashboards_if_none();

        log_info(LOG_TYPE_SECURITY, _("User logged in via auth_token"), 0, $user_id);

        // Set token as used and update session ID to current user's session
        //$session_id = user_generate_session();
        //$_SESSION["session_id"] = $session_id;
        //user_set_auth_token_session_id($session_id, $auth_token);
        user_set_auth_token_used($auth_token);

        // Set restrictions if there are any
        //user_restrict_session_token($auth_token);
        $_SESSION["auth_token"] = $auth_token;

        return true;
    }

    return false;
}

function is_http_basic_authenticated()
{
    $remote_user = '';
    if (isset($_SERVER['REMOTE_USER'])) {
        $remote_user = $_SERVER['REMOTE_USER'];
    }

    if ($remote_user != '') {

        $uid = get_user_id($remote_user);

        // user has authenticated, and they are configured in fusion!
        if ($uid > 0) {

            // set session variables
            $_SESSION['user_id'] = $uid;
            $_SESSION['username'] = $remote_user;

            // Set up session in db
            $sid = user_generate_session();
            $_SESSION["session_id"] = $sid;

            return true;

        } else {

            return false;
        }
    }
}

function is_autologin_enabled() {

    $opt_s = get_option('autologin_options');
    if ($opt_s == '') {
        return false;
    } else {
        $opts = unserialize($opt_s);
    }

    $enabled = grab_array_var($opts, 'autologin_enabled');
    $username = grab_array_var($opts, 'autologin_username');

    if ($enabled == 1 && $username != '' && is_valid_user($username)) {

        return true;
    }

    return false;
}
