<?php
require_once(dirname(__FILE__) . '/../includes/base.inc.php');

block_non_admins();
block_demo(_('Manage Users'));

route_request();
function route_request() {

    $pageopt = get_pageopt();

    // if we chose a multi button, we just redirect the page opt based on the value
    $multi = grab_request_var('multi');
    $valid_multi_values = array('delete', 'unlock', 'enable', 'disable', 'email');
    if (in_array($multi, $valid_multi_values)) {
        $pageopt = $multi;
    }

    switch ($pageopt) {

        case 'update':
            update_user();
            break;

        case 'delete':
            delete_users();
            break;

        case 'edit':
            edit_user();
            break;

        case 'unlock':
            unlock_users();
            break;

        case 'enable':
            enable_users();
            break;

        case 'disable':
            disable_users();
            break;

        case 'masquerade':
            masquerade_as_user();
            break;

        case 'email':
            email_users();
            break;

        case 'new_api':
            generate_new_api_key();
            break;

        default:
            show_users();
            break;
    }
}


// Generate API Key for given user ID
function generate_new_api_key($user_id=null) {

    if (!isset($user_id)) {
        $user_id = users_get_request_user_id($return_int_only = true);    
    } else {
        $user_id = intval($user_id);
    }

    // Generate the API key
    $new_key = random_string(64);

    // Insert key into database
    users_set_user_attr('api_key', $new_key, $user_id);
    // Make sure that api access is enabled if the user is generating a key
    users_set_user_attr('api_enabled', 1, $user_id);

    echo $new_key;
}

// get the user id submitted and masquerade + redirect
function masquerade_as_user() {

    check_nagios_session_protector();

    $user_id = users_get_request_user_id($return_int_only = true);

    if (!is_valid_user_id($user_id))
        flash_message_cb_and_exit('show_users', _('Invalid specified user ID.'), 'error');

    masquerade_as_user_id($user_id);

    header("Location: " . get_base_url());
}


// send out an email to selected users
function email_users() {
    
    // no changes in demo
    demo_error('show_users');

    //TODO: this whole function
    flash_message_cb_and_exit('show_users', _('Users emailed.'));
}


// unlock selected user accounts
function unlock_users() {

    // no changes in demo
    demo_error('show_users');

    $count = 0;
    // TODO: unlock stuff - reset login_times and all that jazz
    flash_message_cb_and_exit('show_users', sprintf(_('%d user accounts unlocked successfully.'), $count));
}


// disable selected user accounts
function disable_users() {

    // no changes in demo
    demo_error('show_users');

    // Do not let the last administrator disable themselves
    if ((get_number_of_admins() == 1) && (is_admin($user_id)) && ($account_enabled == 0))
        $errmsg .= 'You cannot disable the last administrative account.';
    if (!empty($errmsg))
        flash_message_cb_and_exit('edit_user', $errmsg, 'error');

    $count = users_set_user_attr('enabled', 0);
    flash_message_cb_and_exit('show_users', sprintf(_('%d user accounts disabled successfully.'), $count));
}


// enable selected user accounts
function enable_users() {

    // no changes in demo
    demo_error('show_users');

    $count = users_set_user_attr('enabled', 1);
    

    $user_id = users_get_request_user_id();
    // clear the users failed attempts when manually re-enabled
    set_user_meta('failed_2fa_attempts', 0, false, $user_id);

    flash_message_cb_and_exit('show_users', sprintf(_('%d user accounts enabled successfully.'), $count));
}


// used to adjust user attributes in bulk via the user_id request var
function users_set_user_attr($attr, $value, $user_id=null) {

    check_nagios_session_protector();

    // no changes in demo
    demo_error('show_users');

    if (!isset($user_id)) {
        $user_id = users_get_request_user_id();
    } else {
        $user_id = intval($user_id);
    }

    $count = 0;

    // attempt to enable/disable
    if (is_array($user_id)) {
        foreach ($user_id as $this_user_id) {
            if (is_valid_user_id($this_user_id)) {
                set_user_attr($attr, $value, $this_user_id);
                $count++;
            }
        }
    } else {
        if (is_valid_user_id($user_id)) {
            set_user_attr($attr, $value, $user_id);
            $count++;
        }
    }

    // return the count so the calling function can print the message
    return $count;
}


// delete selected user accounts
function delete_users() {

    // no changes in demo
    demo_error('show_users');

    check_nagios_session_protector();

    $user_id = users_get_request_user_id();

    $deleted_user_count = 0;

    // attempt to delete
    if (is_array($user_id)) {
        foreach ($user_id as $this_user_id) {
            if (delete_user($this_user_id))
                $deleted_user_count++;
        }
    } else {
        if (delete_user($user_id))
            $deleted_user_count++;
    }

    flash_message_cb_and_exit('show_users', sprintf(_('%d users successfully deleted!'), $deleted_user_count));
}


// create or update a user account
function update_user() {

    check_nagios_session_protector();

    // if we aren't updating or we pressed cancel then just go ahead and show_users
    $update = grab_request_var('update', false);
    $cancel = grab_request_var('cancel', false);
    if (!$update || $cancel)
        flash_message_cb_and_exit('show_users');

    // grab the user id, but intval it to be safe
    $user_id = intval(grab_request_var('user_id', -1));
    $add_user = ($user_id == -1);

    // get our submitted data
    $username = grab_request_var('username');
    $password1 = grab_request_var('password1');
    $password2 = grab_request_var('password2');
    $force_password_change = grab_request_var('force_password_change');
    $email_account_info = grab_request_var('email_account_info');
    $name = filter_var(grab_request_var('name'), FILTER_SANITIZE_STRING);
    $email = filter_var(grab_request_var('email'), FILTER_SANITIZE_STRING);
    $language = grab_request_var('language');
    $date_format = grab_request_var('date_format');
    $number_format = grab_request_var('number_format');
    $account_enabled = intval(grab_request_var('account_enabled'));
    $api_enabled = intval(grab_request_var('api_enabled'));
    $user_mapping = grab_request_var('user_mapping');
    $server_exclusion = grab_request_var('server_exclusion');
    
    // Grab authentication settings
    $auth_type = grab_request_var('auth_type', 'local');
    $ad_server = grab_request_var('ad_server', '');
    $ldap_server = grab_request_var('ldap_server', '');
    $ldap_ad_username = grab_request_var('ldap_ad_username', '');
    $dn = grab_request_var('dn', '');
    $allow_local = checkbox_binary(grab_request_var('allow_local', 0));

    $level = grab_request_var('level');

    // no changes in demo
    demo_error('edit_user');

    $errmsg = '';

    if (empty($username))
        $errmsg .= _('You must enter a username.') . '<br>';
    if (empty($name))
        $errmsg .= _('You must enter a name.') . '<br>';
    if (empty($email))
        $errmsg .= _('You must enter an email address.') . '<br>';
    if (!array_key_exists($language, get_languages_as_array()))
        $errmsg .= _('You must select a valid language.') . '<br>';
    if (!array_key_exists($date_format, get_date_formats_as_array()))
        $errmsg .= _('You must select a valid date format.') . '<br>';
    if (!array_key_exists($number_format, get_number_formats_as_array()))
        $errmsg .= _('You must select a valid number format.') . '<br>';
    if ($add_user && empty($password1))
        $errmsg .= _('You must enter a valid password.') . '<br>';
    if ($password1 != $password2)
        $errmsg .= _('Passwords must match.') . '<br>';

    $illegal_chars = "/[`~!$%^&*|'<>?,=\"\(\)]/";
    if (empty($username) || preg_match($illegal_chars, $username))
        $errmsg .= _("Usernames may only contain alphanumeric characters, or the following special characters: + - _ .");

    if ($user_id === 1 && ($level !== "1" || is_array($server_exclusion)))
        $errmsg .= _('Authorization demotion error.');
    else if (is_v2_license_type('cloud') && $user_id === 2 && ($level !== "1" || is_array($server_exclusion)))
        $errmsg .= _('Authorization demotion error.');
    else if ($user_id === $_SESSION['user_id'] && $level !== "1")
        $errmsg .= _('Authorization demotion error.');

    if (!empty($errmsg))
        flash_message_cb_and_exit('edit_user', $errmsg, 'error');

    if ($add_user) {

        if (!empty($username) && get_user_id($username))
            $errmsg .= _('User with that username already exists.') . '<br>';
        if (!empty($errmsg))
            flash_message_cb_and_exit('edit_user', $errmsg, 'error');

        $user_id = add_user($username, $password1, $name, $email, $account_enabled, $level);

        if ($api_enabled == 1) {
            set_user_attr('api_enabled', 1, $user_id);
            generate_new_api_key($user_id);
        }

        if ($user_id !== false) {
            set_user_meta('force_password_change', $force_password_change, false, $user_id);
            set_user_meta('language', $language, false, $user_id);
            set_user_meta('theme', '', false, $user_id);
            set_user_meta('date_format', $date_format, false, $user_id);
            set_user_meta('number_format', $number_format, false, $user_id);

            // Set authentication settings
            set_user_meta("auth_type", $auth_type, false, $user_id);
            set_user_meta("allow_local", $allow_local, false, $user_id);
            if ($auth_type == 'ad') {
                set_user_meta("auth_server_id", $ad_server, false, $user_id);
                set_user_meta("ldap_ad_username", $ldap_ad_username, false, $user_id);
            } else if ($auth_type == 'ldap') {
                set_user_meta("auth_server_id", $ldap_server, false, $user_id);
                set_user_meta("ldap_ad_dn", $dn, false, $user_id);
            }

            flash_message(_('User added successfully!'));

        } else {
            flash_message(_('Something went wrong adding user.'), 'error');
        }

    } else {

        $current_username = get_username($user_id);
        if (is_v2_license_type('cloud') && $current_username == 'nagiosadmin' && $current_username != $username) {
            $errmsg .= _('You cannot edit the nagiosadmin account username.');
        }

        if (!empty($username) && ($current_username != $username) && get_user_id($username))
            $errmsg .= _('User with that username already exists.') . '<br>';

        // Do not allow the last active administrator to disable themselves
        if ((get_number_of_admins() == 1) && (is_admin($user_id)) && ($account_enabled == 0))
            $errmsg .= 'You cannot disable the last administrative account.';

        if (!empty($errmsg))
            flash_message_cb_and_exit('edit_user', $errmsg, 'error');

        set_user_attr('username', $username, $user_id);

        if (!empty($password1) && $password1 == $password2) {
            set_user_attr('password', hash('sha256', $password1), $user_id);
            set_user_attr('password_set_time', date("Y-m-d H:i:s", time()), $user_id);
        }

        set_user_attr('name', $name, $user_id);
        set_user_attr('email', $email, $user_id);
        set_user_attr('enabled', $account_enabled, $user_id);
        set_user_attr('api_enabled', $api_enabled, $user_id);
        set_user_attr('level', $level, $user_id);

        set_user_meta('force_password_change', $force_password_change, false, $user_id);
        set_user_meta('language', $language, false, $user_id);
        set_user_meta('date_format', $date_format, false, $user_id);
        set_user_meta('number_format', $number_format, false, $user_id);

        // Set authentication settings
        set_user_meta("auth_type", $auth_type, false, $user_id);
        set_user_meta("allow_local", $allow_local, false, $user_id);
        if ($auth_type == 'ad') {
            set_user_meta("auth_server_id", $ad_server, false, $user_id);
            set_user_meta("ldap_ad_username", $ldap_ad_username, false, $user_id);
        } else if ($auth_type == 'ldap') {
            set_user_meta("auth_server_id", $ldap_server, false, $user_id);
            set_user_meta("ldap_ad_dn", $dn, false, $user_id);
        }

        flash_message(_('User Updated!'));
    }

    // if not false or 0
    if (!empty($user_id)) {

        // user mapping
        if (is_array($user_mapping) && count($user_mapping) > 0) {

            foreach ($user_mapping as $server_id => $server_username) {
                if ($server_username == 'none') {
                    delete_current_mapped_user($server_id, $user_id);
                } else {
                    set_current_mapped_user($server_id, $server_username, $user_id);
                }
            }
        }

        // server exclusions
        // $server_exclusion may or may not be an array, if all checkboxes are
        // unchecked it won't be - so the empty checks that and removes as needed
        $all_servers = get_servers(true, $include_exclusions = false);
        foreach ($all_servers as $server) {
            $server_id = $server['server_id'];

            if (empty($server_exclusion[$server_id])) {
                remove_user_server_exclusion($server_id, $user_id);
            } else {
                set_user_server_exclusion($server_id, $user_id);
            }
        }
    }

    // send email if required
    if (!empty($email_account_info)) {
        // User email Defaults
        $default_email_subject = _("%product% Account Created");
        $default_email_body = _("An account has been created for you to access %product%. You can login using the following information:\n\nUsername: %username%\nPassword: %password%\nURL: %url%\n\n");

        $password = $password1;
        $adminname = get_option('admin_name');
        $adminemail = get_option('admin_email');
        $internal_url = get_option('internal_url');


        // Array of %options% to replace
        $args = array('product' => get_product_name(),
            'username' => $username,
            'password' => $password,
            'url' => $internal_url
        );

        // Get email template
        $email_subject = get_option('user_new_account_email_subject', $default_email_subject);
        $email_body = get_option('user_new_account_email_body', $default_email_body);

        // Process the macros
        $email_subject = replace_array_macros($email_subject, $args);
        $email_body = replace_array_macros($email_body, $args);

        // Use this for debug output in PHPmailer log
        $debugmsg = "";
        // Set where email is coming from for PHPmailer log
        $send_mail_referer = "admin/users.php > Account Creation";

        $opts = array(
            'from' => $adminname . ' <' . $adminemail . ">\r\n",
            "to" => $email,
            "subject" => $email_subject,
            "message" => $email_body,
        );

        send_email($opts, $debugmsg, $send_mail_referer);
    }

    header("Location: users.php");
}


// show the users list and buttons to manipulate user accounts
function show_users() {

    $title = _('Manage Users');
    child_page($title);
    echo well_top_page_header($title);
    ?>

    <div class="page-buttons">
        <a href="?edit" class="btn btn-sm btn-primary">
            <i class="fa fa-user-plus"></i>
            <span><?php echo _('Add New User'); ?></span>
        </a>
        <?php if (is_component_installed("ldap_ad_integration")) { ?>
        <a href="<?php echo get_component_url_base('ldap_ad_integration')?>" class="btn btn-sm btn-primary" id="add-adldap-user">
            <i class="fa"></i>
            <span><?php echo _('Add User From AD/LDAP'); ?></span>
        </a>
        <?php } ?>
    </div>

    <?php
    $select_statement = "SELECT user_id, username, name, email, enabled, account_locked FROM users";

    // Add to select statement to hide nagioscloud user if we are a cloud license
    if (is_v2_license_type('cloud')) {
        $select_statement .= " WHERE user_id != 1 OR username != 'nagioscloud'";
    }

    $opts = array(
        'display_footer' => false,
        'table_class' => 'table table-condensed table-hover table-bordered table-striped',
        'pre_table_html' => 
            '<script>
                $(function() { 
                    $("#select_all").click(function() { 
                        $("input.users_checkbox").prop("checked", $(this).prop("checked")); 
                    }); 
                    $("input.users_checkbox").closest("tr").click(function(ev) {                        
                        // cancel if click is on an input or on a th
                        if (ev.target.nodeName === "INPUT" || ev.target.nodeName === "TH" || ev.target.nodeName === "IMG" || ev.target.nodeName == "SPAN")
                            return;

                        $(this).find("input.users_checkbox").click();
                    });
                    $("a.action_button.delete.user").click(function() {
                        return confirm("' . _('Are you sure you want to delete this user?') . '");
                    });
                    $("button.delete").click(function() {
                        return confirm("' . _('Are you sure you want to delete these users?') . '");
                    });
                });
            </script>',

        'columns' => array(
            'checkbox' => array(
                'th' => '<input type="checkbox" id="select_all" class="users_checkbox" />',
                'td' => '<input type="checkbox" name="user_id[]" value="%user_id%" class="users_checkbox" />',
                'replace_macros' => true,
                'width' => '16px',
                ),
            'username' => array(
                'th' =>  _('Username'),
                'sortable' => true,
                'width' => '25%',
                ), 
            'name' => array(
                'th' =>  _('Name'),
                'sortable' => true,
                ),
            'email' => array(
                'sortable' => true,
                'th' => _('Email'),
                ),
            'authtype' => array(
                'sortable' => true,
                'th' => _('Authentication Type'),
                'transform' => 'users_build_authtype_td',
                ),
            'actions' => array(
                'th' => _('Actions'),
                'transform' => 'users_build_action_td',
                'replace_macros' => true,
                ),
            ),
        'with_selected' => array(
            array(
                'value' => 'delete',
                'class' => 'delete',
                'title' => _('Delete'),
                'img' => get_icon_url('cross.png'),
                ),
            /*array(
                'type' => 'button',
                'title' => _('Send Emails'),
                'img' => get_icon_url('email_go.png'),
                'onclick' => 'users_display_email_selected(false);',
                ),*/
            array(
                'value' => 'enable',
                'title' => _('Enable'),
                'img' => get_icon_url('user_add.png'),
                ),
            array(
                'value' => 'disable',
                'title' => _('Disable'),
                'img' => get_icon_url('user_disable.png'),
                ),
            /*array(
                'value' => 'unlock',
                'title' => _('Unlock'),
                'img' => get_icon_url('lock_open.png'),
                ),*/
            ),
        );
    echo '<form method="post">';
    echo get_paged_table($select_statement, null, $opts);
    echo '</form>';
}

// edit/add user account
function edit_user() {

    $title = _('Manage User');
    child_page($title);

    // i just met you, and this is crazy, but heres a valid user_id, or add me maybe?
    // user_id of -1 means add, otherwise edit
    $user_id = users_get_request_user_id($return_int_only = true);

    // just to help with readability
    // If user_id = -1, set add_user to true, otherwise set to false
    $add_user = $user_id == -1 ? true : false;

    // set some of the displays based on whether we're adding or editing
    $page_header = $add_user ? _('Create User') : _('Edit User');
    $submit_button_value = $add_user ? _('Add User') : _('Update User');

    // get our user data or defaults
    $username = get_user_attr('username', $user_id, '');
    $username = grab_request_var('username', $username);

    // get our user data or defaults
    $api_key = get_user_attr('api_key', $user_id);
    
    // force password change only when adding new user by default
    $force_password_change = intval($add_user);
    $force_password_change = grab_request_var('force_password_change', $force_password_change);
    
    $name = get_user_attr('name', $user_id, '');
    $name = grab_request_var('name', $name);
    
    $email = get_user_attr('email', $user_id, '');
    $email = grab_request_var('email', $email);

    $email_account_info = grab_request_var('email_account_info', false);
    
    $language = get_option('default_language', 'en_US');
    $language = get_user_meta('language', $language, $user_id);
    $language = grab_request_var('language', $language);
    
    $date_format = get_option('default_date_format', DF_ISO8601);
    $date_format = get_user_meta('date_format', $date_format, $user_id);
    $date_format = grab_request_var('date_format', $date_format);    

    $number_format = get_option('default_number_format', NF_2);
    $number_format = get_user_meta('number_format', $number_format, $user_id);
    $number_format = grab_request_var('number_format', $number_format);
    
    $account_enabled = get_user_attr('enabled', $user_id, 1);
    $account_enabled = grab_request_var('account_enabled', $account_enabled);

    $api_enabled = get_user_attr('api_enabled', $user_id, 1);
    $api_enabled = grab_request_var('api_enabled', $api_enabled);

    $level = get_user_attr('level', $user_id, USER_LEVEL_NONPRIV);
    $level = grab_request_var('level', $level);

    $timezone = get_user_meta('timezone', get_current_timezone(), $user_id);
    $timezone = grab_request_var('timezone', $timezone);
    
    $auth_type = grab_request_var('auth_type', 'local');
    $ldap_ad_username = grab_request_var('ldap_ad_username', '');
    $ldap_ad_dn = grab_request_var('ldap_ad_dn', '');
    $allow_local = grab_request_var('allow_local', 0);

    get_timezones_and_selected($timezones, $timezone);

    $password = '';
    if ($add_user)
        $password = random_string(10);

    echo well_top_page_header($page_header);

    $req = '';
    if ($add_user) 
        $req = 'required="true"';
    ?>

<?php if (!$add_user) { ?>
<script type="text/javascript">
    $(function() {
        $('#password1').change(function() {
            if ($(this).val() == '') {
                remove_dynamic_required($('#password2'));
            } else {
                set_dynamic_required($('#password2'));
            }
        });
        $('#password2').change(function() {
            if ($(this).val() == '') {
                remove_dynamic_required($('#password1'));
            } else {
                set_dynamic_required($('#password1'));
            }
        });
    });
</script>
<?php } ?>
<form method="post" action="?update" class="formbuilder" >
    <input name="update"  value="1"  type="hidden"  />

    <?php
    if (!$add_user) {

        $auth_type = grab_request_var("auth_type", get_user_meta("auth_type", '', $user_id));
        $auth_server_id = grab_request_var("auth_server_id", get_user_meta("auth_server_id", '', $user_id));
        $ldap_ad_username = grab_request_var("ldap_ad_username", get_user_meta("ldap_ad_username", '', $user_id));
        $ldap_ad_dn = grab_request_var("ldap_ad_dn", get_user_meta("ldap_ad_dn", '', $user_id));
        $allow_local = grab_request_var("allow_local", get_user_meta("allow_local", 0, $user_id));

    ?>
        <input name="user_id"  value="<?php echo $user_id; ?>"  type="hidden"  />
    <?php
    } // if !add_user
    ?>

    <div class="formbuilder-div formbuilder" >
        <h5 class="ul" >
            <?php echo _('General Settings'); ?>
        </h5>
        <table class="formbuilder-table formbuilder" >
            <tr>
                <td>
                    <label for="username" >
                        <?php echo _('Username'); ?>:
                    </label>
                </td>
                <td>
                    <input name="username"  placeholder="Username"  value="<?php echo encode_html($username); ?>"  type="text"  id="username" <?php if ($username == 'nagiosadmin' && is_v2_license_type('cloud')) { echo 'readonly'; } ?>  class="form-control textfield" required="true" /><i class="fa fa-question-circle pop" style="font-size: 13px; line-height: 20px; vertical-align: middle; margin-left: 10px;" title="<?php echo _('Username Format'); ?>" data-placement="top" data-content="<?php echo _("Usernames may only contain alphanumeric characters, or the following special characters: + - _ ."); ?>"></i>
                    <div class="subtext">
                        
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="password1" >
                        <?php echo _('Password'); ?>:
                    </label>
                </td>
                <td>
                    <input name="password1"  type="password"  id="password1"  class="form-control textfield" <?php echo encode_html($req); ?> />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="password2" >
                        <?php echo _('Repeat Password'); ?>:
                    </label>
                </td>
                <td>
                    <input name="password2"  type="password"  id="password2"  class="form-control textfield" <?php echo encode_html($req); ?> />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="name" >
                        <?php echo _('Name'); ?>:
                    </label>
                </td>
                <td>
                    <input name="name"  placeholder="First Last"  value="<?php echo encode_html($name); ?>"  type="text"  id="name"  class="form-control textfield"  required="true"  />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="email" >
                        <?php echo _('Email Address'); ?>:
                    </label>
                </td>
                <td>
                    <input name="email"  placeholder="email@address.com"  value="<?php echo encode_html($email); ?>"  type="email"  id="email"  class="form-control textfield"  required="true"   />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="level" >
                        <?php echo _('Administrator'); ?>:
                    </label>
                </td>
                <td>
                    <input name="level"  type="checkbox"  value="1" <?php is_checked($level); ?> id="level"  class="checkbox"  />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="account_enabled" >
                        <?php echo _('Account Enabled'); ?>:
                    </label>
                </td>
                <td>
                    <input name="account_enabled"  type="checkbox"  value="1" <?php is_checked($account_enabled); ?> id="account_enabled"  class="checkbox"  />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="api_enabled" >
                        <?php echo _('API Access'); ?>:
                    </label>
                </td>
                <td>
                    <input name="api_enabled"  type="checkbox"  value="1" <?php is_checked($api_enabled); ?> id="api_enabled"  class="checkbox"  />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="email_account_info" >
                        <?php echo _('Email User Account Information'); ?>:
                    </label>
                </td>
                <td>
                    <input name="email_account_info"  type="checkbox"  value="1" <?php is_checked($email_account_info); ?> id="email_account_info"  class="checkbox"  />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="force_password_change" >
                        <?php echo _('Force Password Change at Next Login'); ?>:
                    </label>
                </td>
                <td>
                    <input name="force_password_change"  type="checkbox"  value="1" <?php is_checked($force_password_change); ?> id="force_password_change"  class="checkbox"  />
                </td>
            </tr>
        </table>
    </div>

    <?php if (is_component_installed('ldap_ad_integration')): ?>
            <div class="formbuilder-div formbuilder">
                <h5 class="ul" >
                    <?php echo _('Authentication Settings'); ?>
                </h5>

                <?php
                    // Grab LDAP/AD servers
                    $ad = array();
                    $ldap = array();
                    $servers_raw = get_option("ldap_ad_integration_component_servers");
                    if ($servers_raw == "") { $servers = array(); } else {
                        $servers = unserialize(base64_decode($servers_raw));
                    }
                    foreach ($servers as $server) {
                        if ($server['conn_method'] == 'ldap') {
                            $ldap[] = $server;
                        } else if ($server['conn_method'] == 'ad') {
                            $ad[] = $server;
                        }
                    }
                ?>

                <table class="formbuilder-table formbuilder" >
                    <table class="formbuilder-table formbuilder">
                        <tbody>
                            <tr>
                                <td style="width: 110px;"><label><?php echo _("Auth Type"); ?>:</label></td>
                                <td>
                                    <select name="auth_type" id="auth_type" class="form-control">
                                        <option value="local" <?php echo is_selected($auth_type, "local"); ?>><?php echo _("Local (Default)"); ?></option>
                                        <option value="ad" <?php echo is_selected($auth_type, "ad"); ?>><?php echo _("Active Directory"); ?></option>
                                        <option value="ldap" <?php echo is_selected($auth_type, "ldap"); ?>><?php echo _("LDAP"); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr class="hide auth-ad">
                                <td><label><?php echo _("AD Server"); ?>:</label></td>
                                <td>
                                    <select name="ad_server" class="form-control">
                                        <?php foreach ($ad as $s) { ?>
                                        <option value="<?php echo $s['id']; ?>" <?php echo is_selected($auth_server_id, $s['id']); ?>><?php echo $s['ad_domain_controllers']; if (!$s['enabled']) { echo _('(Disabled)'); } ?></option>
                                        <?php } ?>
                                    </select>
                                </td>
                            </tr>
                            <tr class="hide auth-ad">
                                <td><label><?php echo _("AD Username"); ?>:</label></td>
                                <td>
                                    <input type="text" name="ldap_ad_username" style="width: 240px;" class="form-control" value="<?php echo $ldap_ad_username; ?>">
                                </td>
                            </tr>
                            <tr class="hide auth-ldap">
                                <td><label><?php echo _("LDAP Server"); ?>:</label></td>
                                <td>
                                    <select name="ldap_server" class="form-control">
                                        <?php foreach ($ldap as $s) { ?>
                                        <option value="<?php echo $s['id']; ?>" <?php echo is_selected($auth_server_id, $s['id']); ?>><?php echo $s['ldap_host']; if (!$s['enabled']) { echo _('(Disabled)'); } ?></option>
                                        <?php } ?>
                                    </select>
                                </td>
                            </tr>
                            <tr class="hide auth-ldap">
                                <td><label><?php echo _("User's Full DN"); ?>:</label></td>
                                <td>
                                    <input type="text" style="width: 400px;" class="form-control" name="dn" value="<?php echo $ldap_ad_dn; ?>" placeholder="cn=John Smith,dn=nagios,dc=com">
                                </td>
                            </tr>
                            <tr class="hide auth-ldap auth-ad">
                                <td></td>
                                <td>
                                    <div class="checkbox">
                                        <label>
                                            <input class="checkbox" name="allow_local" id="allow_local" value="1" type="checkbox" <?php if ($user_id == 1) { echo 'disabled'; } ?> <?php echo is_checked($allow_local, 1); ?>> <?php echo _("Allow local login if auth server login fails"); ?>
                                        </label>
                                        <i class="fa fa-question-circle pop" style="font-size: 13px; line-height: 20px; vertical-align: middle;" title="<?php echo _('Fallback to Local Password'); ?>" data-placement="top" data-content="<?php echo _('By checking this box you will allow the user to use the local password created for this user (if the password is not blank) when the auth server cannot be connected to, times out, or the password provided is incorrect. This allows a secondary means of authentication in case the auth server is unreachable.'); ?>"></i>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </table>
            </div>
    <?php endif;?>

    <?php if (!$add_user): ?>
        
    <?php endif;?>

    <script type="text/javascript">
        function generate_new_api_key() {
            var nsp = $('input[name="nsp"]').val();

            user_id = $('input[name="user_id"]').val();

            $.ajax({
                url: '<?php echo get_base_url(false); ?>admin/users.php',
                dataType: 'text',
                data: {
                    pageopt: 'new_api',
                    user_id: user_id,
                    nsp: nsp
                },
                success: function(data) {
                    $('#api_key').val(data);
                }
            });
        }
    </script>
    <?php

    // server user mapping!
    $count_servers = count_servers(false);
    if ($count_servers !== false && $count_servers > 0) {

        ?>
        <div class="formbuilder-div formbuilder" style="min-height: 370px;">
            <h5 class="ul" >
                <?php echo _('Server User Mapping'); ?>
            </h5>
            <table class="formbuilder-table formbuilder" >
        <?php

        $servers = get_servers(false);

        foreach ($servers as $server) {

            $users = false;
            $selected_user = false;
            $server_excluded = get_user_server_exclusion($server, $user_id);

            $element_id = random_string(10);
            $exclude_id = random_string(10);

            // we only give them a mapping option if they are using fusekey
            if ($server['authentication_type'] == AUTH_TYPE_FUSEKEY) {

                $users = get_server_users($server['server_id'], 'none', _('No Mapping'));
                if ($users !== false) {

                    $selected_user = get_current_mapped_user($server['server_id'], $user_id);
                    if (is_null($selected_user))
                        $selected_user = 'none';
                }
            }

            ?>

            <tr>
                <td>
                    <label for="<?php echo $element_id; ?>" >
                        <?php echo $server['name']; ?>
                    </label>
                </td>
                <td>
                    <?php
                    if (is_array($users)) {
                    ?>
                        <select name="user_mapping[<?php echo $server['server_id'] ?>]"  id="<?php echo $element_id; ?>"  class="dropdown form-control" >
                            <?php echo get_users_options_from_array($users, $selected_user); ?>
                        </select>
                    <?php
                    } else {
                    ?>
                        <input disabled="disabled"  value="<?php echo $server['username']; ?>"  type="text"  id="<?php echo $element_id; ?>"  class="form-control textfield"  />
                        <div class="subtext">
                            <?php
                                // we output a little bit of information depending on the server type here
                                if ($server['server_type'] == SERVER_TYPE_XI) {
                                    echo _("You are only able map specific users on XI servers that have utilize a Fusekey.");
                                } else if ($server['server_type'] == SERVER_TYPE_CORE) {
                                    echo _("You are not able to map users on Core servers.");
                                } else if ($server['server_type'] == SERVER_TYPE_NLS) {
                                    echo _("You are not able to map users on Log Servers.");
                                }
                            ?>
                        </div>
                    <?php
                    } // if is_array(users) or ELSE..
                    ?>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input id="<?php echo $exclude_id; ?>"  value="1"  name="server_exclusion[<?php echo $server['server_id'] ?>]"  style="float: left; margin-top: 3px" 
                        type="checkbox"  class="checkbox" <?php is_checked($server_excluded); ?> />
                    <label for="<?php echo $exclude_id; ?>" style="font-weight: normal; display: inline-block; margin-top: 1px;">&nbsp;Exclude user from seeing server data</span>
                </td>
            </tr>
            <tr>
                <td colspan="2"></td>
            </tr>

            <?php

        } // foreach servers
        ?>

            </table>
        </div>
        <?php
    } // if count servers > 0

    ?>

    <div class="formbuilder-div formbuilder" >
        <h5 class="ul" >
            <?php echo _('Preferences'); ?>
        </h5>
        <table class="formbuilder-table formbuilder" >
            <tr>
                <td>
                    <label for="language" >
                        <?php echo _('Language'); ?>:
                    </label>
                </td>
                <td>
                    <select name="language"  id="language"  class="dropdown form-control" >
                        <?php echo get_options_from_array(get_languages_as_array(), $language); ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="date_format" >
                        <?php echo _('Date Format'); ?>:
                    </label>
                </td>
                <td>
                    <select name="date_format"  id="date_format"  class="dropdown form-control" >
                        <?php echo get_options_from_array(get_date_formats_as_array(), $date_format); ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="timezone" >
                        <?php echo _('Timezone'); ?>:
                    </label>
                </td>
                <td>
                    <select name="timezone"  id="timezone"  class="dropdown form-control" >
                        <?php echo get_options_from_array($timezones, $timezone); ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="number_format" >
                        <?php echo _('Number Format'); ?>:
                    </label>
                </td>
                <td>
                    <select name="number_format"  id="number_format"  class="dropdown form-control" >
                        <?php echo get_options_from_array(get_number_formats_as_array(), $number_format); ?>
                    </select>
                </td>
            </tr>
        </table>
    </div>

    <!-- Took this directly from XI -->
    <script type="text/javascript" language="JavaScript">

    // Disables authorization checkboxes when Admin is selected as Admins can do everything -SW
    $(document).ready(function() {
        var arrVal = [ "255" ];

        $(".ss-table select").change(function () {
            var valToCheck = String($(this).val());

            if ($.inArray(valToCheck, arrVal) != -1) {
                $(".authcheckbox").attr("disabled", "true");
                $("#rou").attr("disabled", "true");
                $(".authcheckbox").attr("checked", "checked");
            } else {
                $(".authcheckbox").removeAttr("disabled");
                $("#rou").removeAttr("disabled");
                $(".authcheckbox").attr("checked", false);
            }
        });

        $('#auth_type').change(function() {
            var type = $(this).val();
            if (type == 'ldap') {
                $('.auth-ad').hide();
                $('.auth-ldap').show();
                $('.lo').hide();
            } else if (type == 'ad') {
                $('.auth-ldap').hide();
                $('.auth-ad').show();
                $('.lo').hide();
            } else {
                $('.auth-ad').hide();
                $('.auth-ldap').hide();
                $('.lo').show();
            }
            verify_allow_local();
        });

        $('#allow_local').click(function() {
            verify_allow_local();
        })

        $('#auth_type').trigger('change');
        verify_allow_local();

    });

    function verify_allow_local() {
        if ($('#allow_local').is(':checked') || $('#allow_local').is(':disabled') || $('#auth_type').val() == 'local') {
            $('.lo').show();
            $('.pw').show();
        } else {
            $('.lo').hide();
            $('.pw').hide();
        }
    }
    </script>

    <div class="formbuilder-div formbuilder" >
        <h5 class="ul" >
            <?php echo _('API Settings'); ?>
        </h5>
        <table class="formbuilder-table formbuilder" >
            <tr>
                <td>
                    <label for="api_key" >
                        <?php echo _('API Key'); ?>:
                    </label>
                </td>
                <td>
                    <input name="api_key"  style="cursor: pointer;" onclick="this.select();" value="<?php echo $api_key; ?>"  type="text"  id="api_key"  class="form-control textfield" readonly />
                </td>
            </tr>
            <tr>    
                <td></td>
                <td>
                    <button type="button" onclick="generate_new_api_key();" class="btn btn-xs btn-default"><?php echo _('Generate new API key'); ?></button>
                </td>
            </tr>
        </table>
    </div>
    <div class="clear"></div>
    
    <div class="formbuilder-buttons">
        <input name="submit"  value="<?php echo $submit_button_value; ?>"  class="btn btn-primary btn-sm"  type="submit"  />
        <input name="cancel"  value="<?php echo _('Cancel'); ?>"  class="btn btn-default btn-sm cancel-validator"  type="submit"  />
    </div>

</form>
    <?php
}


// generic function for grabbing the user_id request var
// you can either get a single integer or an array for editting
// this function checks for user_id validity
function users_get_request_user_id($return_int_only = false) {

    // get the request user_id
    $user_id = grab_request_var('user_id', -1);

    // if we only want an int, that means we want the first of the array
    if ($return_int_only && is_array($user_id)) {

        $user_id = current($user_id);
 
    } else if (is_array($user_id)) {

        // check for valid user ids
        foreach ($user_id as $key => $uid) {

            if (!is_valid_user_id($uid))
                unset($user_id[$key]);
        }

        return $user_id;
    }

    // if we made it this far we need to double check that its a valid user_id
    if (is_valid_user_id($user_id))
        return $user_id;

    // return a -1 for all other cases
    return -1;
}
