/**
 * Get the users to display on the current page (fill the sortable-table)
 * @param   int     offset of first user to recover
 * @param   int     Number of users to get
 * @param   int     Column to sort on
 * @param   string  Order (ASC,DESC)
 * @see SortableTable#get_table_data($from)
 */
function get_user_data($from, $number_of_items, $column, $direction)
{
    $sql = prepare_user_sql_query(false);
    $checkPassStrength = isset($_GET['check_easy_passwords']) && $_GET['check_easy_passwords'] == 1 ? true : false;
    if ($checkPassStrength) {
        $easyPasswordList = api_get_easy_password_list();
        $easyPasswordList = array_map('api_get_encrypted_password', $easyPasswordList);
        $easyPasswordList = array_map(array('Database', 'escape_string'), $easyPasswordList);
        $easyPassword = implode("' OR password LIKE '", $easyPasswordList);
        $sql .= "AND password LIKE '{$easyPassword}' ";
    }
    if (!in_array($direction, array('ASC', 'DESC'))) {
        $direction = 'ASC';
    }
    $column = intval($column);
    $from = intval($from);
    $number_of_items = intval($number_of_items);
    global $_configuration;
    if (api_is_session_admin() && isset($_configuration['prevent_session_admins_to_manage_all_users']) && $_configuration['prevent_session_admins_to_manage_all_users'] == 'true') {
        $sql .= " WHERE u.creator_id = " . api_get_user_id();
    }
    $sql .= " ORDER BY col{$column} {$direction} ";
    $sql .= " LIMIT {$from},{$number_of_items}";
    $res = Database::query($sql);
    $users = array();
    $t = time();
    while ($user = Database::fetch_row($res)) {
        $image_path = UserManager::get_user_picture_path_by_id($user[0], 'web', false, true);
        $user_profile = UserManager::get_picture_user($user[0], $image_path['file'], 22, USER_IMAGE_SIZE_SMALL, ' width="22" height="22" ');
        if (!api_is_anonymous()) {
            $photo = '<center><a href="' . api_get_path(WEB_PATH) . 'whoisonline.php?origin=user_list&id=' . $user[0] . '" title="' . get_lang('Info') . '">
                            <img src="' . $user_profile['file'] . '" ' . $user_profile['style'] . ' alt="' . api_get_person_name($user[2], $user[3]) . '"  title="' . api_get_person_name($user[2], $user[3]) . '" /></a></center>';
        } else {
            $photo = '<center><img src="' . $user_profile['file'] . '" ' . $user_profile['style'] . ' alt="' . api_get_person_name($user[2], $user[3]) . '" title="' . api_get_person_name($user[2], $user[3]) . '" /></center>';
        }
        if ($user[7] == 1 && $user[10] != '0000-00-00 00:00:00') {
            // check expiration date
            $expiration_time = convert_sql_date($user[10]);
            // if expiration date is passed, store a special value for active field
            if ($expiration_time < $t) {
                $user[7] = '-1';
            }
        }
        // forget about the expiration date field
        $users[] = array($user[0], $photo, $user[1], $user[2], $user[3], $user[4], $user[5], $user[6], $user[7], api_get_local_time($user[9]), $user[0]);
    }
    return $users;
}
/**
 * Get the users to display on the current page (fill the sortable-table)
 * @param   int     offset of first user to recover
 * @param   int     Number of users to get
 * @param   int     Column to sort on
 * @param   string  Order (ASC,DESC)
 * @param   bool
 * @see SortableTable#get_table_data($from)
 */
function get_user_data($from, $number_of_items, $column, $direction, $get_count = false)
{
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
    $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
    $select = "SELECT\n                 u.user_id\t\t\t\tAS col0,\n                 u.official_code\t\tAS col2,\n\t\t\t\t " . (api_is_western_name_order() ? "u.firstname \t\t\tAS col3,\n                 u.lastname \t\t\tAS col4," : "u.lastname \t\t\tAS col3,\n                 u.firstname \t\t\tAS col4,") . "\n                 u.username\t\t\t\tAS col5,\n                 u.email\t\t\t\tAS col6,\n                 u.status\t\t\t\tAS col7,\n                 u.active\t\t\t\tAS col8,\n                 u.user_id\t\t\t\tAS col9,\n                 u.registration_date    AS col10,\n                 u.expiration_date      AS exp,\n                 u.password\n    ";
    if ($get_count) {
        $select = "SELECT count(u.user_id) as total_rows";
    }
    $sql = "{$select} FROM {$user_table} u ";
    // adding the filter to see the user's only of the current access_url
    if ((api_is_platform_admin() || api_is_session_admin()) && api_get_multiple_access_url()) {
        $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
        $sql .= " INNER JOIN {$access_url_rel_user_table} url_rel_user ON (u.user_id=url_rel_user.user_id)";
    }
    if (isset($_GET['keyword_extra_data'])) {
        $keyword_extra_data = Database::escape_string($_GET['keyword_extra_data']);
        if (!empty($keyword_extra_data)) {
            $extra_info = UserManager::get_extra_field_information_by_name($keyword_extra_data);
            $field_id = $extra_info['id'];
            $sql .= " INNER JOIN user_field_values ufv ON u.user_id=ufv.user_id AND ufv.field_id={$field_id} ";
        }
    }
    if (isset($_GET['keyword'])) {
        $keyword = Database::escape_string(trim($_GET['keyword']));
        $sql .= " WHERE (u.firstname LIKE '%" . $keyword . "%' OR u.lastname LIKE '%" . $keyword . "%' OR concat(u.firstname,' ',u.lastname) LIKE '%" . $keyword . "%' OR concat(u.lastname,' ',u.firstname) LIKE '%" . $keyword . "%' OR u.username LIKE '%" . $keyword . "%'  OR u.official_code LIKE '%" . $keyword . "%' OR u.email LIKE '%" . $keyword . "%' )";
    } elseif (isset($_GET['keyword_firstname'])) {
        $keyword_firstname = Database::escape_string($_GET['keyword_firstname']);
        $keyword_lastname = Database::escape_string($_GET['keyword_lastname']);
        $keyword_email = Database::escape_string($_GET['keyword_email']);
        $keyword_officialcode = Database::escape_string($_GET['keyword_officialcode']);
        $keyword_username = Database::escape_string($_GET['keyword_username']);
        $keyword_status = Database::escape_string($_GET['keyword_status']);
        $query_admin_table = '';
        $and_conditions = array();
        if ($keyword_status == SESSIONADMIN) {
            $keyword_status = '%';
            $query_admin_table = " , {$admin_table} a ";
            $and_conditions[] = ' a.user_id = u.user_id ';
        }
        if (isset($_GET['keyword_extra_data'])) {
            if (!empty($_GET['keyword_extra_data']) && !empty($_GET['keyword_extra_data_text'])) {
                $keyword_extra_data_text = Database::escape_string($_GET['keyword_extra_data_text']);
                $and_conditions[] = " ufv.field_value LIKE '%" . trim($keyword_extra_data_text) . "%' ";
            }
        }
        $keyword_active = isset($_GET['keyword_active']);
        $keyword_inactive = isset($_GET['keyword_inactive']);
        $sql .= $query_admin_table . " WHERE ( ";
        if (!empty($keyword_firstname)) {
            $and_conditions[] = "u.firstname LIKE '%" . $keyword_firstname . "%' ";
        }
        if (!empty($keyword_lastname)) {
            $and_conditions[] = "u.lastname LIKE '%" . $keyword_lastname . "%' ";
        }
        if (!empty($keyword_username)) {
            $and_conditions[] = "u.username LIKE '%" . $keyword_username . "%'  ";
        }
        if (!empty($keyword_email)) {
            $and_conditions[] = "u.email LIKE '%" . $keyword_email . "%' ";
        }
        if (!empty($keyword_officialcode)) {
            $and_conditions[] = "u.official_code LIKE '%" . $keyword_officialcode . "%' ";
        }
        if (!empty($keyword_status)) {
            $and_conditions[] = "u.status LIKE '" . $keyword_status . "' ";
        }
        if ($keyword_active && !$keyword_inactive) {
            $and_conditions[] = "  u.active='1' ";
        } elseif ($keyword_inactive && !$keyword_active) {
            $and_conditions[] = "  u.active='0' ";
        }
        if (!empty($and_conditions)) {
            $sql .= implode(' AND ', $and_conditions);
        }
        $sql .= " ) ";
    }
    // adding the filter to see the user's only of the current access_url
    if ((api_is_platform_admin() || api_is_session_admin()) && api_get_multiple_access_url()) {
        $sql .= " AND url_rel_user.access_url_id=" . api_get_current_access_url_id();
    }
    $checkPassStrength = isset($_GET['check_easy_passwords']) && $_GET['check_easy_passwords'] == 1 ? true : false;
    if ($checkPassStrength) {
        $easyPasswordList = api_get_easy_password_list();
        $easyPasswordList = array_map('api_get_encrypted_password', $easyPasswordList);
        $easyPasswordList = array_map(array('Database', 'escape_string'), $easyPasswordList);
        $easyPassword = implode("' OR password LIKE '", $easyPasswordList);
        $sql .= "AND password LIKE '{$easyPassword}' ";
    }
    if (!in_array($direction, array('ASC', 'DESC'))) {
        $direction = 'ASC';
    }
    $column = intval($column);
    $from = intval($from);
    $number_of_items = intval($number_of_items);
    // Returns counts and exits function.
    if ($get_count) {
        $res = Database::query($sql);
        $user = Database::fetch_array($res);
        return $user['total_rows'];
    }
    $sql .= " ORDER BY col{$column} {$direction} ";
    $sql .= " LIMIT {$from},{$number_of_items}";
    $res = Database::query($sql);
    $users = array();
    $t = time();
    while ($user = Database::fetch_row($res)) {
        $userInfo = api_get_user_info($user[0]);
        $image_path = UserManager::get_user_picture_path_by_id($user[0], 'web', false, true);
        $user_profile = UserManager::get_picture_user($user[0], $image_path['file'], 22, USER_IMAGE_SIZE_SMALL, ' width="22" height="22" ');
        if (!api_is_anonymous()) {
            $photo = '<center><a href="' . $userInfo['profile_url'] . '" title="' . get_lang('Info') . '">
                            <img src="' . $user_profile['file'] . '" ' . $user_profile['style'] . ' alt="' . $userInfo['complete_name'] . '" title="' . $userInfo['complete_name'] . '" /></a></center>';
        } else {
            $photo = '<center><img src="' . $user_profile['file'] . '" ' . $user_profile['style'] . ' alt="' . $userInfo['complete_name'] . '" title="' . $userInfo['complete_name'] . '" /></center>';
        }
        if ($user[7] == 1 && $user[10] != '0000-00-00 00:00:00') {
            // check expiration date
            $expiration_time = api_convert_sql_date($user[10]);
            // if expiration date is passed, store a special value for active field
            if ($expiration_time < $t) {
                $user[7] = '-1';
            }
        }
        // forget about the expiration date field
        $users[] = array($user[0], $photo, $user[1], Display::url($user[2], $userInfo['profile_url']), Display::url($user[3], $userInfo['profile_url']), $user[4], $user[5], $user[6], $user[7], api_get_local_time($user[9]), $user[0]);
    }
    return $users;
}