<?php
/* Copyright (C) 2002-2005	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
 * Copyright (C) 2004-2021	Laurent Destailleur		<eldy@users.sourceforge.net>
 * Copyright (C) 2005-2024	Regis Houssin			<regis.houssin@inodbox.com>
 * Copyright (C) 2015-2024  Alexandre Spangaro      <alexandre@inovea-conseil.com>
 * Copyright (C) 2016		Marcos García			<marcosgdf@gmail.com>
 * Copyright (C) 2024-2025	MDW						<mdeweerd@users.noreply.github.com>
 * Copyright (C) 2024		Benjamin Falière		<benjamin.faliere@altairis.fr>
 * Copyright (C) 2024		William Mead			<william.mead@manchenumerique.fr>
 * Copyright (C) 2024-2025  Frédéric France         <frederic.france@free.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

/**
 *      \file       htdocs/user/list.php
 * 		\ingroup	core
 *      \brief      Page of users
 */

// Load Dolibarr environment
require '../main.inc.php';
/**
 * @var Conf $conf
 * @var DoliDB $db
 * @var HookManager $hookmanager
 * @var Translate $langs
 * @var User $user
 */
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
if (isModEnabled('category')) {
	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
}

// Load translation files required by page
$langs->loadLangs(array('users', 'companies', 'hrm', 'salaries'));

$action     = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
$show_files = GETPOSTINT('show_files'); // Show files area generated by bulk actions ?
$confirm    = GETPOST('confirm', 'alpha'); // Result of a confirmation
$cancel     = GETPOST('cancel', 'alpha'); // We click on a Cancel button
$toselect   = GETPOST('toselect', 'array:int'); // Array of ids of elements selected into a list
$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)).basename(__FILE__, '.php')); // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
$optioncss  = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
$mode       = GETPOST("mode", 'aZ');

// Security check (for external users)
$socid = 0;
if ($user->socid > 0) {
	$socid = $user->socid;
}

// Load variable for pagination
$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
	// If $page is not defined, or '' or -1 or if we click on clear filters
	$page = 0;
}
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;

// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
$object = new User($db);
$extrafields = new ExtraFields($db);
$diroutputmassaction = $conf->user->dir_output.'/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('userlist'));

// Fetch optionals attributes and labels
$extrafields->fetch_name_optionals_label($object->table_element);

$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');

if (!$sortfield) {
	$sortfield = "u.login";
}
if (!$sortorder) {
	$sortorder = "ASC";
}

// Initialize array of search criteria
$search_all = trim(GETPOST('search_all', 'alphanohtml'));
$search = array();
foreach ($object->fields as $key => $val) {
	if (GETPOST('search_'.$key, 'alpha') !== '') {
		$search[$key] = GETPOST('search_'.$key, 'alpha');
	}
	if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
		$search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOSTINT('search_'.$key.'_dtstartmonth'), GETPOSTINT('search_'.$key.'_dtstartday'), GETPOSTINT('search_'.$key.'_dtstartyear'));
		$search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOSTINT('search_'.$key.'_dtendmonth'), GETPOSTINT('search_'.$key.'_dtendday'), GETPOSTINT('search_'.$key.'_dtendyear'));
	}
}

$userstatic = new User($db);
$companystatic = new Societe($db);
$form = new Form($db);

// List of fields to search into when doing a "search in all"
$fieldstosearchall = array(
	'u.login' => "Login",
	'u.lastname' => "Lastname",
	'u.firstname' => "Firstname",
	'u.accountancy_code' => "AccountancyCode",
	'u.office_phone' => "PhonePro",
	'u.user_mobile' => "PhoneMobile",
	'u.email' => "EMail",
	'co.label' => "Country",
	'u.note_public' => "NotePublic",
	'u.note_private' => "NotePrivate"
);
if (isModEnabled('api')) {
	$fieldstosearchall['u.api_key'] = "ApiKey";
}

$permissiontoreadhr = $user->hasRight('hrm', 'read_personal_information', 'read') || $user->hasRight('hrm', 'write_personal_information', 'write');
$permissiontowritehr = $user->hasRight('hrm', 'write_personal_information', 'write');

// Definition of fields for list
$arrayfields = array(
	'u.rowid' => array('label' => "TechnicalID", 'checked' => '-1', 'position' => 5),
	'u.login' => array('label' => "Login", 'checked' => '1', 'position' => 10),
	'u.lastname' => array('label' => "Lastname", 'checked' => '1', 'position' => 15),
	'u.firstname' => array('label' => "Firstname", 'checked' => '1', 'position' => 20),
	'u.entity' => array('label' => "Entity", 'checked' => '1', 'position' => 50, 'enabled' => (string) (int) (isModEnabled('multicompany') && !getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE'))),
	'u.gender' => array('label' => "Gender", 'checked' => '0', 'position' => 22),
	'u.employee' => array('label' => "Employee", 'checked' => ($contextpage == 'employeelist' ? '1' : '0'), 'position' => 25),
	'u.fk_user' => array('label' => "HierarchicalResponsible", 'checked' => '1', 'position' => 27, 'csslist' => 'maxwidth150'),
	'u.accountancy_code' => array('label' => "AccountancyCode", 'checked' => '0', 'position' => 30),
	'u.office_phone' => array('label' => "PhonePro", 'checked' => '1', 'position' => 31),
	'u.user_mobile' => array('label' => "PhoneMobile", 'checked' => '1', 'position' => 32),
	'u.email' => array('label' => "EMail", 'checked' => '1', 'position' => 35),
	'co.label' => array('label' => "Country", 'checked' => '0', 'position' => 37),
	'u.api_key' => array('label' => "ApiKey", 'checked' => '0', 'position' => 40, "enabled" => (string) (int) (isModEnabled('api') && $user->admin)),
	'u.fk_soc' => array('label' => "Company", 'checked' => ($contextpage == 'employeelist' ? '0' : '1'), 'position' => 45),
	'u.ref_employee' => array('label' => "RefEmployee", 'checked' => '-1', 'position' => 50, 'enabled' => (string) (int) (isModEnabled('hrm') && $permissiontoreadhr)),
	'u.national_registration_number' => array('label' => "NationalRegistrationNumber", 'checked' => '-1', 'position' => 51, 'enabled' => (string) (int) (isModEnabled('hrm') && $permissiontoreadhr)),
	'u.job' => array('label' => "PostOrFunction", 'checked' => '-1', 'position' => 60),
	'u.salary' => array('label' => "Salary", 'checked' => '-1', 'position' => 80, 'enabled' => (string) (int) (isModEnabled('salaries') && $user->hasRight("salaries", "readall")), 'isameasure' => 1),
	'u.thm' => array('label' => "THM", 'langs' => 'salaries', 'checked' => '-1', 'position' => 82, 'enabled' => '1', 'isameasure' => 1),
	'u.datec' => array('label' => "DateCreation", 'checked' => '0', 'position' => 500),
	'date_modification' => array('label' => "DateModificationShort", 'checked' => '0', 'position' => 500),
	'u.statut' => array('label' => "Status", 'checked' => '1', 'position' => 1000),
);

if (getDolGlobalInt('MAIN_ENABLE_LOGINS_PRIVACY') == 0) {
	$arrayfields['u.datelastlogin'] = array('label' => "LastConnexion", 'checked' => '1', 'position' => 100);
	$arrayfields['u.datepreviouslogin'] = array('label' => "PreviousConnexion", 'checked' => '0', 'position' => 110);
}

// Extra fields
include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';

$object->fields = dol_sort_array($object->fields, 'position');
$arrayfields = dol_sort_array($arrayfields, 'position');

// Init search fields
$search_all = trim(GETPOST('search_all', 'alphanohtml'));
$search_user = GETPOST('search_user', 'alpha');
$search_rowid = GETPOST('search_rowid', 'alpha');
$search_login = GETPOST('search_login', 'alpha');
$search_lastname = GETPOST('search_lastname', 'alpha');
$search_firstname = GETPOST('search_firstname', 'alpha');
$search_gender = GETPOST('search_gender', 'alpha');
$search_employee = GETPOST('search_employee', 'alpha');
$search_accountancy_code = GETPOST('search_accountancy_code', 'alpha');
$search_phonepro = GETPOST('search_phonepro', 'alpha');
$search_phonemobile = GETPOST('search_phonemobile', 'alpha');
$search_email = GETPOST('search_email', 'alpha');
$search_country = GETPOST('search_country', 'alpha');
$search_api_key = GETPOST('search_api_key', 'alphanohtml');
$search_status = GETPOST('search_status', 'intcomma');
$search_thirdparty = GETPOST('search_thirdparty', 'alpha');
$search_job = GETPOST('search_job', 'alpha');
$search_warehouse = GETPOST('search_warehouse', 'alpha');
$search_supervisor = GETPOST('search_supervisor', 'intcomma');
$search_categ = GETPOST("search_categ", 'intcomma');
$search_datelastlogin = GETPOSTDATE('search_datelastlogin', '', 'tzuserrel');
$search_datepreviouslogin = GETPOSTDATE('search_datepreviouslogin', '', 'tzuserrel');

$searchCategoryUserOperator = 0;
if (GETPOSTISSET('formfilteraction')) {
	$searchCategoryUserOperator = GETPOSTINT('search_category_user_operator');
} elseif (getDolGlobalString('MAIN_SEARCH_CAT_OR_BY_DEFAULT')) {
	$searchCategoryUserOperator = getDolGlobalString('MAIN_SEARCH_CAT_OR_BY_DEFAULT');
}
$searchCategoryUserList = GETPOST('search_category_user_list', 'array:int');
$catid = GETPOSTINT('catid');
if (!empty($catid) && empty($searchCategoryUserList)) {
	$searchCategoryUserList = array($catid);
}
$catid = GETPOSTINT('catid');
if (!empty($catid) && empty($search_categ)) {
	$search_categ = $catid;
}

// Default search
if ($search_status == '' && empty($search_all)) {
	$search_status = '1';
}
if ($contextpage == 'employeelist' && !GETPOSTISSET('search_employee')) {
	$search_employee = 1;
}

// Define value to know what current user can do on users
$permissiontoadd = (isModEnabled('multicompany') && !empty($user->entity) && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? false : (!empty($user->admin) || $user->hasRight("user", "user", "write")));
$canreaduser = (!empty($user->admin) || $user->hasRight("user", "user", "read"));
$canedituser = $permissiontoadd;
$candisableuser = (isModEnabled('multicompany') && !empty($user->entity) && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? false : (!empty($user->admin) || $user->hasRight("user", "user", "delete")));
$canreadgroup = $canreaduser;
$caneditgroup = $canedituser;
if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
	$canreadgroup = (!empty($user->admin) || $user->hasRight("user", "group_advance", "read"));
	$caneditgroup = (isModEnabled('multicompany') && !empty($user->entity) && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') ? false : (!empty($user->admin) || $user->hasRight("user", "group_advance", "write")));
}

$error = 0;

// Permission to list
if (isModEnabled('salaries') && $contextpage == 'employeelist' && $search_employee == 1) {
	if (!$user->hasRight("salaries", "read")) {
		accessforbidden();
	}
} else {
	if (!$user->hasRight("user", "user", "read") && empty($user->admin)) {
		accessforbidden();
	}
}

$childids = $user->getAllChildIds(1);


/*
 * Actions
 */

if (GETPOST('cancel', 'alpha')) {
	$action = 'list';
	$massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
	$massaction = '';
}

$parameters = array('arrayfields' => &$arrayfields);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) {
	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}

if (empty($reshook)) {
	// Selection of new fields
	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';

	// Purge search criteria
	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
		$search_user = "";
		$search_rowid = "";
		$search_login = "";
		$search_lastname = "";
		$search_firstname = "";
		$search_gender = "";
		$search_employee = "";
		$search_accountancy_code = "";
		$search_phonepro = "";
		$search_phonemobile = "";
		$search_email = "";
		$search_country = "";
		$search_status = "";
		$search_thirdparty = "";
		$search_job = "";
		$search_warehouse = "";
		$search_supervisor = "";
		$search_api_key = "";
		$search_categ = 0;
		$search_all = '';
		$toselect = array();
		$search_array_options = array();
		if (getDolGlobalInt('MAIN_ENABLE_LOGINS_PRIVACY') == 0) {
			$search_datelastlogin = "";
			$search_datepreviouslogin = "";
		}
	}
	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
		|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
	}

	// Mass actions
	$objectclass = 'User';
	$objectlabel = 'User';
	$uploaddir = $conf->user->dir_output;

	global $error;

	// Disable or Enable records
	if (!$error && ($massaction == 'disable' || $massaction == 'reactivate') && $permissiontoadd) {
		$objecttmp = new User($db);

		$db->begin();

		$nbok = 0;
		foreach ($toselect as $toselectid) {
			if ($toselectid == $user->id) {
				setEventMessages($langs->trans($massaction == 'disable' ? 'CantDisableYourself' : 'CanEnableYourself'), null, 'errors');
				$error++;
				break;
			}

			$result = $objecttmp->fetch($toselectid);
			if ($result > 0) {
				if ($objecttmp->admin) {
					setEventMessages($langs->trans($massaction == 'disable' ? 'CantDisableAnAdminUserWithMassActions' : 'CantEnableAnAdminUserWithMassActions', $objecttmp->login), null, 'errors');
					$error++;
					break;
				}

				$result = $objecttmp->setstatus($massaction == 'disable' ? 0 : 1);
				if ($result == 0) {
					// Nothing is done
				} elseif ($result < 0) {
					setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
					$error++;
					break;
				} else {
					$nbok++;
				}
			} else {
				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
				$error++;
				break;
			}
		}

		if (!$error && !empty($conf->file->main_limit_users)) {
			$nb = $object->getNbOfUsers("active");
			if ($nb >= $conf->file->main_limit_users) {
				$error++;
				setEventMessages($langs->trans("YourQuotaOfUsersIsReached"), null, 'errors');
			}
		}

		if (!$error) {
			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
			$db->commit();
		} else {
			$db->rollback();
		}

		$massaction = '';
	}

	// Generic mass actions
	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
}


/*
 * View
 */

$formother = new FormOther($db);
$user2 = new User($db);

$help_url = 'EN:Module_Users|FR:Module_Utilisateurs|ES:M&oacute;dulo_Usuarios|DE:Modul_Benutzer';
if ($contextpage == 'employeelist' && $search_employee == 1) {
	$title = $langs->trans("Employees");
} else {
	$title = $langs->trans("Users");
}
$morejs = array();
$morecss = array();
$morehtmlright = "";

// Build and execute select
// --------------------------------------------------------------------
$sql = "SELECT DISTINCT u.rowid, u.lastname, u.firstname, u.admin, u.fk_soc, u.login, u.office_phone, u.user_mobile, u.email, u.api_key, u.accountancy_code, u.gender, u.employee, u.photo,";
$sql .= " u.fk_user,";
$sql .= " u.ref_employee, u.national_registration_number, u.job, u.salary, u.thm, u.datelastlogin, u.datepreviouslogin,";
$sql .= " u.datestartvalidity, u.dateendvalidity,";
$sql .= " u.ldap_sid, u.statut as status, u.entity,";
$sql .= " GREATEST(u.tms, ef.tms) as date_modification, u.datec as date_creation,";
$sql .= " u2.rowid as id2, u2.login as login2, u2.firstname as firstname2, u2.lastname as lastname2, u2.admin as admin2, u2.fk_soc as fk_soc2, u2.office_phone as ofice_phone2, u2.user_mobile as user_mobile2, u2.email as email2, u2.gender as gender2, u2.photo as photo2, u2.entity as entity2, u2.statut as status2,";
$sql .= " s.nom as name, s.canvas,";
$sql .= " co.code as country_code, co.label as country_label";
// Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) {
	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
	}
}
// Add fields from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$sql = preg_replace('/,\s*$/', '', $sql);

$sqlfields = $sql; // $sql fields to remove for count total

$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as u";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (u.rowid = ef.fk_object)";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_soc = s.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u2 ON u.fk_user = u2.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON u.fk_country = co.rowid";
// Add table from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
if ($reshook > 0) {
	$sql .= $hookmanager->resPrint;
}
$sql .= " WHERE u.entity IN (".getEntity($object->element).")";
if ($socid > 0) {
	$sql .= " AND u.fk_soc = ".((int) $socid);
}
//if ($search_user != '')       $sql.=natural_search(array('u.login', 'u.lastname', 'u.firstname'), $search_user);
if ($search_supervisor > 0) {
	$sql .= " AND u.fk_user IN (".$db->sanitize($search_supervisor).")";
}
if ($search_thirdparty != '') {
	$sql .= natural_search(array('s.nom'), $search_thirdparty);
}
if ($search_warehouse > 0) {
	$sql .= natural_search(array('u.fk_warehouse'), $search_warehouse);
}
if ($search_rowid != '') {
	$sql .= natural_search("u.rowid", $search_rowid, 1);
}
if ($search_login != '') {
	$sql .= natural_search("u.login", $search_login);
}
if ($search_lastname != '') {
	$sql .= natural_search("u.lastname", $search_lastname);
}
if ($search_firstname != '') {
	$sql .= natural_search("u.firstname", $search_firstname);
}
if ($search_gender != '' && $search_gender != '-1') {
	$sql .= " AND u.gender = '".$db->escape($search_gender)."'"; // Cannot use natural_search as looking for %man% also includes woman
}
if (is_numeric($search_employee) && $search_employee >= 0) {
	$sql .= ' AND u.employee = '.(int) $search_employee;
}
if ($search_accountancy_code != '') {
	$sql .= natural_search("u.accountancy_code", $search_accountancy_code);
}
if ($search_phonepro != '') {
	$sql .= natural_search("u.office_phone", $search_phonepro);
}
if ($search_phonemobile != '') {
	$sql .= natural_search("u.user_mobile", $search_phonemobile);
}
if ($search_email != '') {
	$sql .= natural_search("u.email", $search_email);
}
if ($search_country != '') {
	$sql .= " AND u.fk_country IN (".$db->sanitize($search_country).')';
}
if ($search_api_key != '') {
	$sql .= natural_search("u.api_key", $search_api_key);
}
if ($search_job != '') {
	$sql .= natural_search(array('u.job'), $search_job);
}
if ($search_status != '' && $search_status >= 0) {
	$sql .= " AND u.statut IN (".$db->sanitize($search_status).")";
}
if ($search_all) {
	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
}
// Search for tag/category ($searchCategoryUserList is an array of ID)
$searchCategoryUserList = array($search_categ);
if (!empty($searchCategoryUserList)) {
	$searchCategoryUserSqlList = array();
	$listofcategoryid = '';
	foreach ($searchCategoryUserList as $searchCategoryUser) {
		if (intval($searchCategoryUser) == -2) {
			$searchCategoryUserSqlList[] = "NOT EXISTS (SELECT ck.fk_user FROM ".MAIN_DB_PREFIX."categorie_user as ck WHERE u.rowid = ck.fk_user)";
		} elseif (intval($searchCategoryUser) > 0) {
			if ($searchCategoryUserOperator == 0) {
				$searchCategoryUserSqlList[] = " EXISTS (SELECT ck.fk_user FROM ".MAIN_DB_PREFIX."categorie_user as ck WHERE u.rowid = ck.fk_user AND ck.fk_categorie = ".((int) $searchCategoryUser).")";
			} else {
				$listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryUser);
			}
		}
	}
	if ($listofcategoryid) {
		$searchCategoryUserSqlList[] = " EXISTS (SELECT ck.fk_user FROM ".MAIN_DB_PREFIX."categorie_user as ck WHERE u.rowid = ck.fk_user AND ck.fk_categorie IN (".$db->sanitize($listofcategoryid)."))";
	}
	if ($searchCategoryUserOperator == 1) {
		if (!empty($searchCategoryUserSqlList)) {
			$sql .= " AND (".implode(' OR ', $searchCategoryUserSqlList).")";
		}
	} else {
		if (!empty($searchCategoryUserSqlList)) {
			$sql .= " AND (".implode(' AND ', $searchCategoryUserSqlList).")";
		}
	}
}
if ($search_warehouse > 0) {
	$sql .= " AND u.fk_warehouse = ".((int) $search_warehouse);
}
if (isModEnabled('salaries') && $contextpage == 'employeelist' && !$user->hasRight("salaries", "readall")) {
	$sql .= " AND u.rowid IN (".$db->sanitize(implode(',', $childids)).")";
}
// Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;

// Count total nb of records
$nbtotalofrecords = '';
if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
	/* The fast and low memory method to get and count full list converts the sql into a sql count */
	$sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
	$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
	$resql = $db->query($sqlforcount);
	if ($resql) {
		$objforcount = $db->fetch_object($resql);
		$nbtotalofrecords = $objforcount->nbtotalofrecords;
	} else {
		dol_print_error($db);
	}

	if (($page * $limit) > (int) $nbtotalofrecords) {	// if total resultset is smaller then paging size (filtering), goto and load page 0
		$page = 0;
		$offset = 0;
	}
	$db->free($resql);
}

// Complete request and execute it with limit
$sql .= $db->order($sortfield, $sortorder);
if ($limit) {
	$sql .= $db->plimit($limit + 1, $offset);
}

$resql = $db->query($sql);
if (!$resql) {
	dol_print_error($db);
	exit;
}

$num = $db->num_rows($resql);

// Direct jump if only one record found
if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all && !$page) {
	$obj = $db->fetch_object($resql);
	$id = $obj->rowid;
	header("Location: ".DOL_URL_ROOT.'/user/card.php?id='.$id);
	exit;
}

// Output page
// --------------------------------------------------------------------

llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'bodyforlist mod-user page-list');

$arrayofselected = is_array($toselect) ? $toselect : array();

$param = '';
if (!empty($mode)) {
	$param .= '&mode='.urlencode($mode);
}
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
	$param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
	$param .= '&limit='.((int) $limit);
}
if ($optioncss != '') {
	$param .= '&optioncss='.urlencode($optioncss);
}
if ($search_all != '') {
	$param .= '&search_all='.urlencode($search_all);
}
if ($search_user != '') {
	$param .= "&search_user=".urlencode($search_user);
}
if ($search_rowid != '') {
	$param .= "&search_rowid=".urlencode($search_rowid);
}
if ($search_login != '') {
	$param .= "&search_login=".urlencode($search_login);
}
if ($search_lastname != '') {
	$param .= "&search_lastname=".urlencode($search_lastname);
}
if ($search_firstname != '') {
	$param .= "&search_firstname=".urlencode($search_firstname);
}
if ($search_gender != '' && $search_gender != '-1') {
	$param .= "&search_gender=".urlencode($search_gender);
}
if ($search_employee != '' && $search_employee != '-1') {
	$param .= "&search_employee=".urlencode($search_employee);
}
if ($search_accountancy_code != '') {
	$param .= "&search_accountancy_code=".urlencode($search_accountancy_code);
}
if ($search_phonepro != '') {
	$param .= "&search_phonepro=".urlencode($search_phonepro);
}
if ($search_phonemobile != '') {
	$param .= "&search_phonemobile=".urlencode($search_phonemobile);
}
if ($search_email != '') {
	$param .= "&search_email=".urlencode($search_email);
}
if ($search_country != '') {
	$param .= "&search_country=".urlencode($search_country);
}
if ($search_api_key != '') {
	$param .= "&search_api_key=".urlencode($search_api_key);
}
if ($search_supervisor > 0) {
	$param .= "&search_supervisor=".urlencode($search_supervisor);
}
if ($search_status != '') {
	$param .= "&search_status=".urlencode($search_status);
}
if ($search_categ > 0) {
	$param .= '&search_categ='.urlencode((string) ($search_categ));
}
if ($search_warehouse > 0) {
	$param .= '&search_warehouse='.urlencode($search_warehouse);
}
// Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';

// List of mass actions available
$arrayofmassactions = array();
if ($permissiontoadd) {
	$arrayofmassactions['disable'] = img_picto('', 'close_title', 'class="pictofixedwidth"').$langs->trans("DisableUser");
}
if ($permissiontoadd) {
	$arrayofmassactions['reactivate'] = img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Reactivate");
}
if (isModEnabled('category') && $permissiontoadd) {
	$arrayofmassactions['preaffecttag'] = img_picto('', 'category', 'class="pictofixedwidth"').$langs->trans("AffectTag");
}
if ($permissiontoadd) {
	$arrayofmassactions['presetsupervisor'] = img_picto('', 'user', 'class="pictofixedwidth"').$langs->trans("SetSupervisor");
}
//if ($permissiontodelete) $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");

if (GETPOSTINT('nomassaction') || in_array($massaction, array('presend', 'predelete', 'preaffecttag', 'presetsupervisor'))) {
	$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions);

print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
if ($optioncss != '') {
	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="page" value="'.$page.'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
print '<input type="hidden" name="page_y" value="">';
print '<input type="hidden" name="mode" value="'.$mode.'">';

$url = DOL_URL_ROOT.'/user/card.php?action=create'.($contextpage == 'employeelist' ? '&search_employee=1' : '').'&leftmenu=';
if (!empty($socid)) {
	$url .= '&socid='.urlencode((string) ($socid));
}

$newcardbutton = '';
$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars paddingleft imgforviewmode', DOL_URL_ROOT.'/user/list.php?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition'));
$newcardbutton .= dolGetButtonTitle($langs->trans('HierarchicView'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/user/hierarchy.php?mode=hierarchy'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', (($mode == 'hierarchy') ? 2 : 1), array('morecss' => 'reposition'));
$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition'));
$newcardbutton .= dolGetButtonTitleSeparator();
$newcardbutton .= dolGetButtonTitle($langs->trans('NewUser'), '', 'fa fa-plus-circle', $url, '', (int) $permissiontoadd);

/*$moreparam = array('morecss'=>'btnTitleSelected');
$morehtmlright = dolGetButtonTitle($langs->trans("List"), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/user/list.php'.(($search_status != '' && $search_status >= 0) ? '?search_status='.$search_status : ''), '', 1, $moreparam);
$moreparam = array('morecss'=>'marginleftonly');
$morehtmlright .= dolGetButtonTitle($langs->trans("HierarchicView"), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/user/hierarchy.php'.(($search_status != '' && $search_status >= 0) ? '?search_status='.$search_status : ''), '', 1, $moreparam);
*/
print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'user', 0, $morehtmlright.' '.$newcardbutton, '', $limit, 0, 0, 1);



// Add code for pre mass action (confirmation or email presend form)
$topicmail = "SendUserRef";
$modelmail = "user";
$objecttmp = new User($db);
$trackid = 'use'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';

if (!empty($catid)) {
	print "<div id='ways'>";
	$c = new Categorie($db);
	$ways = $c->print_all_ways('auto', 'user/list.php');
	print " &gt; ".$ways[0]."<br>\n";
	print "</div><br>";
}

if ($search_all) {
	$setupstring = '';
	foreach ($fieldstosearchall as $key => $val) {
		$fieldstosearchall[$key] = $langs->trans($val);
		$setupstring .= $key."=".$val.";";
	}
	print '<!-- Search done like if USER_QUICKSEARCH_ON_FIELDS = '.$setupstring.' -->'."\n";
	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).implode(', ', $fieldstosearchall).'</div>';
}

$moreforfilter = '';
/*$moreforfilter.='<div class="divsearchfield">';
 $moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
 $moreforfilter.= '</div>';*/

// Filter on categories
if (isModEnabled('category') && $user->hasRight("categorie", "read")) {
	$moreforfilter .= '<div class="divsearchfield">';
	$tmptitle = $langs->trans('Category');
	$moreforfilter .= img_picto($langs->trans("Category"), 'category', 'class="pictofixedwidth"').$formother->select_categories(Categorie::TYPE_USER, $search_categ, 'search_categ', 1, $tmptitle);
	$moreforfilter .= '</div>';
}
// Filter on warehouse
if (isModEnabled('stock') && getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER')) {
	require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
	$formproduct = new FormProduct($db);
	$moreforfilter .= '<div class="divsearchfield">';
	$tmptitle = $langs->trans('Warehouse');
	$moreforfilter .= img_picto($tmptitle, 'stock', 'class="pictofixedwidth"').$formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', 1, 0, 0, $tmptitle);
	$moreforfilter .= '</div>';
}

$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) {
	$moreforfilter .= $hookmanager->resPrint;
} else {
	$moreforfilter = $hookmanager->resPrint;
}

if (!empty($moreforfilter)) {
	print '<div class="liste_titre liste_titre_bydiv centpercent">';
	print $moreforfilter;
	print '</div>';
}

$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$htmlofselectarray = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')); // This also change content of $arrayfields
$selectedfields = ($mode != 'kanban' ? $htmlofselectarray : '');
$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');

print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";

// Fields title search
// --------------------------------------------------------------------
print '<tr class="liste_titre_filter">';
// Action column
if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print '<td class="liste_titre center maxwidthsearch">';
	$searchpicto = $form->showFilterButtons('left');
	print $searchpicto;
	print '</td>';
}
if (!empty($arrayfields['u.rowid']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_rowid" class="maxwidth50" value="'.$search_rowid.'"></td>';
}
if (!empty($arrayfields['u.login']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_login" class="maxwidth50" value="'.$search_login.'"></td>';
}
if (!empty($arrayfields['u.lastname']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_lastname" class="maxwidth50" value="'.$search_lastname.'"></td>';
}
if (!empty($arrayfields['u.firstname']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_firstname" class="maxwidth50" value="'.$search_firstname.'"></td>';
}
if (!empty($arrayfields['u.gender']['checked'])) {
	print '<td class="liste_titre center">';
	$arraygender = array('man' => $langs->trans("Genderman"), 'woman' => $langs->trans("Genderwoman"), 'other' => $langs->trans("Genderother"));
	print $form->selectarray('search_gender', $arraygender, $search_gender, 1);
	print '</td>';
}
if (!empty($arrayfields['u.employee']['checked'])) {
	print '<td class="liste_titre">';
	print $form->selectyesno('search_employee', $search_employee, 1, false, 1);
	print '</td>';
}
// Supervisor
if (!empty($arrayfields['u.fk_user']['checked'])) {
	print '<td class="liste_titre">';
	print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, array(), 0, '', '', '0', 0, 0, '', 0, '', 'maxwidth125');
	print '</td>';
}
if (!empty($arrayfields['u.accountancy_code']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_accountancy_code" class="maxwidth50" value="'.$search_accountancy_code.'"></td>';
}
if (!empty($arrayfields['u.office_phone']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_phonepro" class="maxwidth50" value="'.$search_phonepro.'"></td>';
}
if (!empty($arrayfields['u.user_mobile']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_phonemobile" class="maxwidth50" value="'.$search_phonemobile.'"></td>';
}
if (!empty($arrayfields['u.email']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_email" class="maxwidth75" value="'.$search_email.'"></td>';
}
if (!empty($arrayfields['co.label']['checked'])) {
	print '<td class="liste_titre">';
	print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100');
	print '</td>';
}
if (!empty($arrayfields['u.api_key']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_api_key" class="maxwidth50" value="'.$search_api_key.'"></td>';
}
if (!empty($arrayfields['u.fk_soc']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_thirdparty" class="maxwidth75" value="'.$search_thirdparty.'"></td>';
}
if (!empty($arrayfields['u.entity']['checked'])) {
	print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['u.ref_employee']['checked'])) {
	print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['u.national_registration_number']['checked'])) {
	print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['u.job']['checked'])) {
	print '<td class="liste_titre"><input type="text" name="search_job" class="maxwidth75" value="'.$search_job.'"></td>';
}
if (!empty($arrayfields['u.salary']['checked'])) {
	print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['u.thm']['checked'])) {
	print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['u.datelastlogin']['checked']) && getDolGlobalInt('MAIN_ENABLE_LOGINS_PRIVACY') == 0) {
	print '<td class="liste_titre"></td>';
}
if (!empty($arrayfields['u.datepreviouslogin']['checked']) && getDolGlobalInt('MAIN_ENABLE_LOGINS_PRIVACY') == 0) {
	print '<td class="liste_titre"></td>';
}
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
// Fields from hook
$parameters = array('arrayfields' => $arrayfields);
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
if (!empty($arrayfields['u.datec']['checked'])) {
	// Date creation
	print '<td class="liste_titre">';
	print '</td>';
}
if (!empty($arrayfields['date_modification']['checked'])) {
	// Date modification
	print '<td class="liste_titre">';
	print '</td>';
}
if (!empty($arrayfields['u.statut']['checked'])) {
	// Status
	print '<td class="liste_titre center parentonrightofpage">';
	print $form->selectarray('search_status', array('-1' => '', '0' => $langs->trans('Disabled'), '1' => $langs->trans('Enabled')), $search_status, 0, 0, 0, '', 0, 0, 0, '', 'search_status width100 onrightofpage');
	print '</td>';
}
// Action column
if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print '<td class="liste_titre maxwidthsearch">';
	$searchpicto = $form->showFilterButtons();
	print $searchpicto;
	print '</td>';
}
print '</tr>'."\n";

$totalarray = array();
$totalarray['nbfield'] = 0;

// Fields title label
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.rowid']['checked'])) {
	// @phan-suppress-next-line PhanTypeInvalidDimOffset
	print_liste_field_titre($arrayfields['u.rowid']['label'], $_SERVER['PHP_SELF'], "u.rowid", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.login']['checked'])) {
	print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER['PHP_SELF'], "u.login", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.lastname']['checked'])) {
	print_liste_field_titre("Lastname", $_SERVER['PHP_SELF'], "u.lastname", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.firstname']['checked'])) {
	print_liste_field_titre("FirstName", $_SERVER['PHP_SELF'], "u.firstname", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.gender']['checked'])) {
	print_liste_field_titre("Gender", $_SERVER['PHP_SELF'], "u.gender", "", $param, "", $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.employee']['checked'])) {
	print_liste_field_titre("Employee", $_SERVER['PHP_SELF'], "u.employee", "", $param, "", $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.fk_user']['checked'])) {
	print_liste_field_titre("HierarchicalResponsible", $_SERVER['PHP_SELF'], "u.fk_user", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.accountancy_code']['checked'])) {
	print_liste_field_titre("AccountancyCode", $_SERVER['PHP_SELF'], "u.accountancy_code", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.office_phone']['checked'])) {
	print_liste_field_titre("PhonePro", $_SERVER['PHP_SELF'], "u.office_phone", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.user_mobile']['checked'])) {
	print_liste_field_titre("PhoneMobile", $_SERVER['PHP_SELF'], "u.user_mobile", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.email']['checked'])) {
	print_liste_field_titre("EMail", $_SERVER['PHP_SELF'], "u.email", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['co.label']['checked'])) {
	print_liste_field_titre("Country", $_SERVER['PHP_SELF'], "co.label", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.api_key']['checked'])) {
	print_liste_field_titre("ApiKey", $_SERVER['PHP_SELF'], "u.api_key", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.fk_soc']['checked'])) {
	print_liste_field_titre("Company", $_SERVER['PHP_SELF'], "u.fk_soc", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.entity']['checked'])) {
	print_liste_field_titre($arrayfields['u.entity']['label'], $_SERVER['PHP_SELF'], "u.entity", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.ref_employee']['checked'])) {
	print_liste_field_titre("RefEmployee", $_SERVER['PHP_SELF'], "u.ref_employee", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.national_registration_number']['checked'])) {
	print_liste_field_titre("NationalRegistrationNumber", $_SERVER['PHP_SELF'], "u.national_registration_number", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.job']['checked'])) {
	print_liste_field_titre($arrayfields['u.job']['label'], $_SERVER['PHP_SELF'], "u.job", "", $param, "", $sortfield, $sortorder);
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.salary']['checked'])) {
	print_liste_field_titre("Salary", $_SERVER['PHP_SELF'], "u.salary", "", $param, "", $sortfield, $sortorder, 'right ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.thm']['checked'])) {
	print_liste_field_titre("THM", $_SERVER['PHP_SELF'], "u.thm", '', $param, "", $sortfield, $sortorder, 'right ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.datelastlogin']['checked']) && getDolGlobalInt('MAIN_ENABLE_LOGINS_PRIVACY') == 0) {
	print_liste_field_titre("LastConnexion", $_SERVER['PHP_SELF'], "u.datelastlogin", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.datepreviouslogin']['checked']) && getDolGlobalInt('MAIN_ENABLE_LOGINS_PRIVACY') == 0) {
	print_liste_field_titre("PreviousConnexion", $_SERVER['PHP_SELF'], "u.datepreviouslogin", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
// Extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
// Hook fields
$parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'totalarray' => &$totalarray);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
if (!empty($arrayfields['u.datec']['checked'])) {
	print_liste_field_titre("DateCreationShort", $_SERVER["PHP_SELF"], "u.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['date_modification']['checked'])) {
	print_liste_field_titre("DateModificationShort", $_SERVER["PHP_SELF"], "date_modification", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
	$totalarray['nbfield']++;
}
if (!empty($arrayfields['u.statut']['checked'])) {
	print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "u.statut", "", $param, '', $sortfield, $sortorder, 'center ');
	$totalarray['nbfield']++;
}
// Action column
if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
	print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
	$totalarray['nbfield']++;
}
print '</tr>'."\n";


// Detect if we need a fetch on each output line
$needToFetchEachLine = 0;
if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
		if (!is_null($val) && preg_match('/\$object/', $val)) {
			$needToFetchEachLine++; // There is at least one compute field that use $object
		}
	}
}


// Loop on record
// --------------------------------------------------------------------
$i = 0;
$savnbfield = $totalarray['nbfield'];
$totalarray = array('val' => array('u.salary' => 0));
$totalarray['nbfield'] = 0;
$imaxinloop = ($limit ? min($num, $limit) : $num);
while ($i < $imaxinloop) {
	$obj = $db->fetch_object($resql);
	if (empty($obj)) {
		break; // Should not happen
	}

	// Store properties in $object
	$object->setVarsFromFetchObj($obj);

	$object->id = $obj->rowid;
	$object->admin = $obj->admin;
	$object->ref = (string) $obj->rowid;
	$object->login = $obj->login;
	$object->statut = $obj->status;
	$object->status = $obj->status;
	$object->office_phone = $obj->office_phone;
	$object->user_mobile = $obj->user_mobile;
	$object->job = $obj->job;
	$object->email = $obj->email;
	$object->gender = $obj->gender;
	$object->socid = $obj->fk_soc;
	$object->firstname = $obj->firstname;
	$object->lastname = $obj->lastname;
	$object->employee = $obj->employee;
	$object->photo = $obj->photo;
	$object->datestartvalidity = $db->jdate($obj->datestartvalidity);
	$object->dateendvalidity = $db->jdate($obj->dateendvalidity);
	$object->country_code = $obj->country_code;
	$object->country = $obj->country_label;

	$li = $object->getNomUrl(-1, '', 0, 0, 24, 1, 'login', '', 1);

	$canreadhrmdata = 0;
	if ((isModEnabled('salaries') && $user->hasRight("salaries", "read") && in_array($obj->rowid, $childids))
		|| (isModEnabled('salaries') && $user->hasRight("salaries", "readall"))
		|| (isModEnabled('hrm') && $user->hasRight("hrm", "employee", "read"))) {
		$canreadhrmdata = 1;
	}
	$canreadsecretapi = 0;
	if ($user->id == $obj->rowid || !empty($user->admin)) {	// Current user or admin
		$canreadsecretapi = 1;
	}

	if ($mode == 'kanban') {
		if ($i == 0) {
			print '<tr class="trkanban"><td colspan="'.$savnbfield.'">';
			print '<div class="box-flex-container kanban">';
		}

		// Output Kanban
		$selected = -1;
		if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
			$selected = 0;
			if (in_array($object->id, $arrayofselected)) {
				$selected = 1;
			}
		}
		print $object->getKanbanView('', array('selected' => $selected));
		if ($i == ($imaxinloop - 1)) {
			print '</div>';
			print '</td></tr>';
		}
	} else {
		// Show here line of result
		$j = 0;
		print '<tr data-rowid="'.$object->id.'" class="oddeven row-with-select">';
		// Action column
		if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
			print '<td class="nowrap center">';
			if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
				$selected = 0;
				if (in_array($object->id, $arrayofselected)) {
					$selected = 1;
				}
				print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// TechnicalID
		if (!empty($arrayfields['u.rowid']['checked'])) {
			print '<td class="nowraponall">'.dolPrintHTML((string) $obj->rowid).'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Login
		if (!empty($arrayfields['u.login']['checked'])) {
			print '<td class="nowraponall tdoverflowmax150">';
			print $li;
			if (isModEnabled('multicompany') && $obj->admin && !$obj->entity) {
				print img_picto($langs->trans("SuperAdministratorDesc"), 'superadmin', 'class="valignmiddle paddingright paddingleft"');
			} elseif ($obj->admin) {
				print img_picto($langs->trans("AdministratorDesc"), 'admin', 'class="valignmiddle paddingright paddingleft"');
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Lastname
		if (!empty($arrayfields['u.lastname']['checked'])) {
			print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($obj->lastname).'">'.dol_escape_htmltag($obj->lastname).'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Fistname
		if (!empty($arrayfields['u.firstname']['checked'])) {
			print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($obj->lastname).'">'.dol_escape_htmltag($obj->firstname).'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Gender
		if (!empty($arrayfields['u.gender']['checked'])) {
			print '<td class="center">';
			if ($obj->gender) {
				// Preparing gender's display if there is one
				$addgendertxt = '';
				switch ($obj->gender) {
					case 'man':
						$addgendertxt .= '<i class="fas fa-mars" title="'.dol_escape_htmltag($langs->trans("Gender".$obj->gender)).'"></i>';
						break;
					case 'woman':
						$addgendertxt .= '<i class="fas fa-venus" title="'.dol_escape_htmltag($langs->trans("Gender".$obj->gender)).'"></i>';
						break;
					case 'other':
						$addgendertxt .= '<i class="fas fa-transgender" title="'.dol_escape_htmltag($langs->trans("Gender".$obj->gender)).'"></i>';
						break;
				}
				print $addgendertxt;
				//print $langs->trans("Gender".$obj->gender);
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Employee yes/no
		if (!empty($arrayfields['u.employee']['checked'])) {
			print '<td class="center">'.yn($obj->employee).'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Supervisor
		if (!empty($arrayfields['u.fk_user']['checked'])) {
			print '<td class="tdoverflowmax125">';
			if ($obj->login2) {
				$user2->id = $obj->id2;
				$user2->login = $obj->login2;
				$user2->lastname = $obj->lastname2;
				$user2->firstname = $obj->firstname2;
				$user2->gender = $obj->gender2;
				$user2->photo = $obj->photo2;
				$user2->admin = $obj->admin2;
				$user2->office_phone = $obj->office_phone;
				$user2->user_mobile = $obj->user_mobile;
				$user2->email = $obj->email2;
				$user2->socid = $obj->fk_soc2;
				$user2->statut = $obj->status2;
				$user2->status = $obj->status2;
				if (isModEnabled('multicompany') && $obj->admin2 && !$obj->entity2) {
					print img_picto($langs->trans("SuperAdministratorDesc"), 'superadmin', 'class="valignmiddle paddingright"');
				} elseif ($obj->admin2) {
					print img_picto($langs->trans("AdministratorDesc"), 'admin', 'class="valignmiddle paddingright"');
				}
				print $user2->getNomUrl(-1, '', 0, 0, 24, 0, '', '', 1);
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Accountancy code
		if (!empty($arrayfields['u.accountancy_code']['checked'])) {
			print '<td>'.$obj->accountancy_code.'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Phone
		if (!empty($arrayfields['u.office_phone']['checked'])) {
			print '<td class="tdoverflowmax125">'.dol_print_phone($obj->office_phone, $obj->country_code, 0, $obj->rowid, 'AC_TEL', ' ', 'phone')."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Phone mobile
		if (!empty($arrayfields['u.user_mobile']['checked'])) {
			print '<td class="tdoverflowmax125">'.dol_print_phone($obj->user_mobile, $obj->country_code, 0, $obj->rowid, 'AC_TEL', ' ', 'mobile')."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Email
		if (!empty($arrayfields['u.email']['checked'])) {
			print '<td class="tdoverflowmax150" title="'.dolPrintHTMLForAttribute($obj->email).'">'.dol_print_email($obj->email, $obj->rowid, $obj->fk_soc, 1, 0, 0, 1)."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Country
		if (!empty($arrayfields['co.label']['checked'])) {
			print '<td class="tdoverflowmax150">'.$obj->country_label."</td>\n";
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Api key
		if (!empty($arrayfields['u.api_key']['checked'])) {
			$api_key = dolDecrypt($obj->api_key);
			print '<td class="tdoverflowmax125" title="'.dol_escape_htmltag($api_key).'">';
			if ($api_key) {
				if ($canreadsecretapi) {
					print '<span class="opacitymedium">';
					print showValueWithClipboardCPButton($object->api_key, 1, dol_trunc($api_key, 3));		// TODO Add an option to also reveal the hash, not only copy paste
					print '</span>';
				} else {
					print '<span class="opacitymedium">'.$langs->trans("Hidden").'</span>';
				}
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// User
		if (!empty($arrayfields['u.fk_soc']['checked'])) {
			print '<td class="tdoverflowmax150">';
			if ($obj->fk_soc > 0) {
				$companystatic->id = $obj->fk_soc;
				$companystatic->name = $obj->name;
				$companystatic->canvas = $obj->canvas;
				print $companystatic->getNomUrl(1);
			} elseif ($obj->ldap_sid) {
				print '<span class="opacitymedium">'.$langs->trans("DomainUser").'</span>';
			} else {
				print '<span class="opacitymedium">'.$langs->trans("InternalUser").'</span>';
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Multicompany enabled
		if (isModEnabled('multicompany') && is_object($mc) && !getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
			if (!empty($arrayfields['u.entity']['checked'])) {
				if (!$obj->entity) {
					$labeltouse = $langs->trans("AllEntities");
				} else {
					$mc->getInfo($obj->entity);
					$labeltouse = $mc->label;
				}
				print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($labeltouse).'">';
				print $labeltouse;
				print '</td>';
				if (!$i) {
					$totalarray['nbfield']++;
				}
			}
		}

		// Ref employee
		if (!empty($arrayfields['u.ref_employee']['checked'])) {
			print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($obj->ref_employee).'">';
			print dol_escape_htmltag($obj->ref_employee);
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// National number
		if (!empty($arrayfields['u.national_registration_number']['checked'])) {
			print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($obj->national_registration_number).'">';
			print dol_escape_htmltag($obj->national_registration_number);
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Job position
		if (!empty($arrayfields['u.job']['checked'])) {
			print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($obj->job).'">';
			print dol_escape_htmltag($obj->job);
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Salary
		if (!empty($arrayfields['u.salary']['checked'])) {
			print '<td class="nowraponall right amount">';
			if ($obj->salary) {
				if ($canreadhrmdata) {
					print price($obj->salary);
				} else {
					print '<span class="opacitymedium">'.$langs->trans("Hidden").'</span>';
				}
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
			if (!$i) {
				$totalarray['pos'][$totalarray['nbfield']] = 'u.salary';
			}
			if (!isset($totalarray['val'])) {
				$totalarray['val'] = array();
			}
			if (!isset($totalarray['val']['u.salary'])) {
				$totalarray['val']['u.salary'] = 0;
			}
			$totalarray['val']['u.salary'] += $obj->salary;
		}

		// Hourly rate
		if (!empty($arrayfields['u.thm']['checked'])) {
			print '<td class="nowraponall right amount">';
			if (!is_null($obj->thm)) {
				print price($obj->thm);
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Date last login
		if (!empty($arrayfields['u.datelastlogin']['checked']) && getDolGlobalInt('MAIN_ENABLE_LOGINS_PRIVACY') == 0) {
			print '<td class="nowraponall center">'.dol_print_date($db->jdate($obj->datelastlogin), "dayhour").'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Date previous login
		if (!empty($arrayfields['u.datepreviouslogin']['checked']) && getDolGlobalInt('MAIN_ENABLE_LOGINS_PRIVACY') == 0) {
			print '<td class="nowraponall center">'.dol_print_date($db->jdate($obj->datepreviouslogin), "dayhour").'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		// Extra fields
		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
		// Fields from hook
		$parameters = array('arrayfields' => $arrayfields, 'object' => $object, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray);
		$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
		print $hookmanager->resPrint;
		// Date creation
		if (!empty($arrayfields['u.datec']['checked'])) {
			print '<td class="center nowraponall">';
			print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Date modification
		if (!empty($arrayfields['date_modification']['checked'])) {
			print '<td class="center nowraponall">';
			print dol_print_date($db->jdate($obj->date_modification), 'dayhour', 'tzuser');
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Status
		if (!empty($arrayfields['u.statut']['checked'])) {
			print '<td class="center">'.$object->getLibStatut(5).'</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}
		// Action column
		if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
			print '<td class="nowrap center">';
			if ($massactionbutton || $massaction) {   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
				$selected = 0;
				if (in_array($object->id, $arrayofselected)) {
					$selected = 1;
				}
				print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
			}
			print '</td>';
			if (!$i) {
				$totalarray['nbfield']++;
			}
		}

		print '</tr>'."\n";
	}

	$i++;
}

// Show total line
include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';

// If no record found
if ($num == 0) {
	$colspan = 1;
	foreach ($arrayfields as $key => $val) {
		if (!empty($val['checked'])) {
			$colspan++;
		}
	}
	print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
}


$db->free($resql);

$parameters = array('arrayfields' => $arrayfields, 'sql' => $sql);
$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;

print '</table>'."\n";
print '</div>'."\n";

print '</form>'."\n";


// End of page
llxFooter();
$db->close();
