<?php

	#########################################################
	/*
	~~~~~~ LIST OF FUNCTIONS ~~~~~~
		getTableList() -- returns an associative array (tableName => tableData, tableData is array(tableCaption, tableDescription, tableIcon)) of tables accessible by current user
		get_table_groups() -- returns an associative array (table_group => tables_array)
		logInMember() -- checks POST login. If not valid, redirects to index.php, else returns TRUE
		getTablePermissions($tn) -- returns an array of permissions allowed for logged member to given table (allowAccess, allowInsert, allowView, allowEdit, allowDelete) -- allowAccess is set to true if any access level is allowed
		get_sql_fields($tn) -- returns the SELECT part of the table view query
		get_sql_from($tn[, true, [, false]]) -- returns the FROM part of the table view query, with full joins (unless third paramaeter is set to true), optionally skipping permissions if true passed as 2nd param.
		get_joined_record($table, $id[, true]) -- returns assoc array of record values for given PK value of given table, with full joins, optionally skipping permissions if true passed as 3rd param.
		get_defaults($table) -- returns assoc array of table fields as array keys and default values (or empty), excluding automatic values as array values
		htmlUserBar() -- returns html code for displaying user login status to be used on top of pages.
		showNotifications($msg, $class) -- returns html code for displaying a notification. If no parameters provided, processes the GET request for possible notifications.
		parseMySQLDate(a, b) -- returns a if valid mysql date, or b if valid mysql date, or today if b is true, or empty if b is false.
		parseCode(code) -- calculates and returns special values to be inserted in automatic fields.
		addFilter(i, filterAnd, filterField, filterOperator, filterValue) -- enforce a filter over data
		clearFilters() -- clear all filters
		loadView($view, $data) -- passes $data to templates/{$view}.php and returns the output
		loadTable($table, $data) -- loads table template, passing $data to it
		filterDropdownBy($filterable, $filterers, $parentFilterers, $parentPKField, $parentCaption, $parentTable, &$filterableCombo) -- applies cascading drop-downs for a lookup field, returns js code to be inserted into the page
		br2nl($text) -- replaces all variations of HTML <br> tags with a new line character
		htmlspecialchars_decode($text) -- inverse of htmlspecialchars()
		entitiesToUTF8($text) -- convert unicode entities (e.g. &#1234;) to actual UTF8 characters, requires multibyte string PHP extension
		func_get_args_byref() -- returns an array of arguments passed to a function, by reference
		permissions_sql($table, $level) -- returns an array containing the FROM and WHERE additions for applying permissions to an SQL query
		error_message($msg[, $back_url]) -- returns html code for a styled error message .. pass explicit false in second param to suppress back button
		toMySQLDate($formattedDate, $sep = datalist_date_separator, $ord = datalist_date_format)
		reIndex(&$arr) -- returns a copy of the given array, with keys replaced by 1-based numeric indices, and values replaced by original keys
		get_embed($provider, $url[, $width, $height, $retrieve]) -- returns embed code for a given url (supported providers: youtube, googlemap)
		check_record_permission($table, $id, $perm = 'view') -- returns true if current user has the specified permission $perm ('view', 'edit' or 'delete') for the given recors, false otherwise
		NavMenus($options) -- returns the HTML code for the top navigation menus. $options is not implemented currently.
		StyleSheet() -- returns the HTML code for included style sheet files to be placed in the <head> section.
		getUploadDir($dir) -- if dir is empty, returns upload dir configured in defaultLang.php, else returns $dir.
		PrepareUploadedFile($FieldName, $MaxSize, $FileTypes='jpg|jpeg|gif|png', $NoRename=false, $dir="") -- validates and moves uploaded file for given $FieldName into the given $dir (or the default one if empty)
		get_home_links($homeLinks, $default_classes, $tgroup) -- process $homeLinks array and return custom links for homepage. Applies $default_classes to links if links have classes defined, and filters links by $tgroup (using '*' matches all table_group values)
		quick_search_html($search_term, $label, $separate_dv = true) -- returns HTML code for the quick search box.
	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	*/

	#########################################################

	function getTableList($skip_authentication = false) {
		$arrAccessTables = array();
		$arrTables = array(
			/* 'table_name' => ['table caption', 'homepage description', 'icon', 'table group name'] */   
			'main' => array('Main', '', 'resources/table_icons/appgini-icon.png', 'ADMINISTRATION'),
			'clients' => array('CLIENTS', '', 'resources/table_icons/client_account_template.png', 'ADMINISTRATION'),
			'gestionnaires' => array('PERSONNELS', '', 'resources/table_icons/administrator.png', 'ADMINISTRATION'),
			'partenaires' => array('PARTENAIRES', '', 'resources/table_icons/small_business.png', 'ADMINISTRATION'),
			'paiements' => array('PAIEMENTS FACTURES', '', 'resources/table_icons/table_money.png', 'TRANSACTIONS'),
			'emetteurs' => array('EMETTEURS', '', 'resources/table_icons/home_page.png', 'ADMINISTRATION'),
			'bieleteries' => array('BILLETERIES', '', 'resources/table_icons/gei (81).png', 'TRANSACTIONS'),
			'tarifs' => array('LISTE BILLETERIES', '', 'resources/table_icons/gei (81).png', 'TRANSACTIONS'),
			'transferts_argent' => array('TRANSFERT D\'ARGENT', '', 'resources/table_icons/coins_in_hand.png', 'TRANSACTIONS'),
			'colis' => array('ENVOI DE COLI', '', 'resources/table_icons/box_closed.png', 'TRANSACTIONS'),
			'envois_colis' => array('LISTE ENVOIS COLI', '', 'resources/table_icons/lorry.png', 'TRANSACTIONS'),
			'parc_auto' => array('PARC AUTOMOBILE', '', 'resources/table_icons/car.png', 'TRANSACTIONS'),
			'location_vh' => array('LOCATION VEHICULE', '', 'resources/table_icons/small_car.png', 'TRANSACTIONS'),
			'liste_location' => array('LISTE LOCATION VH', '', 'resources/table_icons/small_car.png', 'TRANSACTIONS'),
			'fonctions' => array('FONCTIONS', '', 'resources/table_icons/chair.png', 'PARAMETRAGE'),
			'agences' => array('AGENCES', '', 'resources/table_icons/house_link.png', 'PARAMETRAGE'),
			'villes' => array('VILLES', '', 'resources/table_icons/world_go.png', 'PARAMETRAGE'),
			'banques' => array('BANQUES', '', 'resources/table_icons/card_bank.png', 'PARAMETRAGE'),
			'type_paiements' => array('TYPES DE PAIEMENT', '', 'resources/table_icons/american_express.png', 'PARAMETRAGE'),
			'compagnies' => array('COMPAGNIES AERIENNE', '', 'resources/table_icons/gei (69).png', 'PARAMETRAGE'),
			'statuts' => array('STATUS', '', 'resources/table_icons/flag_red.png', 'PARAMETRAGE'),
			'visas' => array('VISAS', '', 'resources/table_icons/locate.png', 'TRANSACTIONS'),
			'oumras' => array('OUMRA', '', 'resources/table_icons/heart.png', 'TRANSACTIONS'),
			'assurances' => array('ASSURANCES', '', 'resources/table_icons/color_wheel.png', 'TRANSACTIONS'),
			'type_visas' => array('TYPE VISAS', '', 'resources/table_icons/vcard_edit.png', 'PARAMETRAGE'),
			'facture' => array('FACTURATION', '', 'resources/table_icons/calculator_add.png', 'ADMINISTRATION'),
			'detail_facture' => array('LISTE DES FACTURES', '', 'resources/table_icons/blogs.png', 'ADMINISTRATION'),
			'recettes' => array('RECETTES', '', 'resources/table_icons/coins_add.png', 'CAISSE'),
			'depenses' => array('DEPENSES', '', 'resources/table_icons/coins_add.png', 'CAISSE'),
			'caisse' => array('CAISSE', '', 'resources/table_icons/table_money.png', 'CAISSE'),
			'tresorerie_caisse' => array('TRESORERIE CAISSE', '', 'resources/table_icons/marega.png', 'CAISSE'),
			'tresorerie_items' => array('LISTE TRESORERIE', '', 'resources/table_icons/marega.png', 'TRANSACTIONS'),
			'piece_reglements' => array('PIECE DE REGLEMENT', '', 'resources/table_icons/marega.png', 'TRANSACTIONS'),
			'autorisation_change' => array('AUTORISATION DE CHANGE', '', 'resources/table_icons/marega.png', 'TRANSACTIONS'),
			'bon_passage' => array('BON DE PASSAGE', '', 'resources/table_icons/marega.png', 'TRANSACTIONS'),
			'fiches_changes' => array('FICHES DE CHANGES', '', 'resources/table_icons/marega.png', 'TRANSACTIONS'),
			'fiches_changes_items' => array('LISTE FICHES DE CHANGES', '', 'resources/table_icons/marega.png', 'TRANSACTIONS'),
			'caisse_journaliere' => array('CAISSE JOURNALIERE', '', 'resources/table_icons/marega.png', 'CAISSE'),
			'item_caisse_journaliere' => array('ITEM CAISSE JOURNALIERE', '', 'resources/table_icons/marega.png', 'CAISSE'),
			'models' => array('MODELS', '', 'resources/table_icons/areachart.png', 'PARAMETRAGE'),
			'natures' => array('NATURES', '', 'resources/table_icons/application_view_tile.png', 'PARAMETRAGE'),
			'services' => array('SERVICES', '', 'resources/table_icons/application_view_gallery.png', 'PARAMETRAGE'),
			'liens' => array('APPLICATIONS', '', 'resources/table_icons/world_link.png', 'ADMINISTRATION'),
			'types_client' => array('TYPE DE CLIENT', '', 'resources/table_icons/set_security_question.png', 'PARAMETRAGE'),
			'cartes_fidelite' => array('CARTES FIDELITE', '', 'resources/table_icons/award_star_gold_3.png', 'PARAMETRAGE'),
			'designations' => array('DESIGNATIONS', '', 'resources/table_icons/align_center.png', 'PARAMETRAGE'),
			'parcours' => array('PARCOURS', '', 'resources/table_icons/paper_airplane.png', 'PARAMETRAGE'),
			'pays' => array('PAYS', '', 'resources/table_icons/pays.png', 'PARAMETRAGE'),
			'provenance' => array('PROVENANCE', '', 'resources/table_icons/align_center.png', 'PARAMETRAGE'),
			'programmes' => array('PROGRAMMES', '', 'resources/table_icons/application_view_icons.png', 'PARAMETRAGE'),
			'justificatifs' => array('JUSTIFICATIF', '', 'resources/table_icons/application_edit.png', 'PARAMETRAGE'),
			'devise' => array('DEVISE', '', 'resources/table_icons/table_money.png', 'PARAMETRAGE'),
			'intermediares' => array('INTERMEDIARES', '', 'resources/table_icons/ceo.png', 'PARAMETRAGE'),
			'formule' => array('FORMULES', '', 'resources/table_icons/color_swatch.png', 'PARAMETRAGE'),
			'operations' => array('OPERATIONS', '', 'resources/table_icons/align_right.png', 'PARAMETRAGE'),
			'pointages' => array('POINTAGES', '', 'resources/table_icons/timesheet.png', 'ADMINISTRATION'),
			'fichiers_partages' => array('FICHIERS PARTAGES', '', 'resources/table_icons/folder.png', 'ADMINISTRATION'),
			'note_de_service' => array('NOTE DE SERVICE', '', 'resources/table_icons/clipboard_empty.png', 'ADMINISTRATION')
		);
		if($skip_authentication || getLoggedAdmin()) return $arrTables;

		if(is_array($arrTables)) {
			foreach($arrTables as $tn => $tc) {
				$arrPerm = getTablePermissions($tn);
				if($arrPerm[0]) {
					$arrAccessTables[$tn] = $tc;
				}
			}
		}

		return $arrAccessTables;
	}

	#########################################################

	function get_table_groups($skip_authentication = false) {
		$tables = getTableList($skip_authentication);
		$all_groups = array('ADMINISTRATION', 'TRANSACTIONS', 'CAISSE', 'PARAMETRAGE');

		$groups = array();
		foreach($all_groups as $grp) {
			foreach($tables as $tn => $td) {
				if($td[3] && $td[3] == $grp) $groups[$grp][] = $tn;
				if(!$td[3]) $groups[0][] = $tn;
			}
		}

		return $groups;
	}

	#########################################################

	function getTablePermissions($tn) {
		static $table_permissions = array();
		if(isset($table_permissions[$tn])) return $table_permissions[$tn];

		$groupID = getLoggedGroupID();
		$memberID = makeSafe(getLoggedMemberID());
		$res_group = sql("select tableName, allowInsert, allowView, allowEdit, allowDelete from membership_grouppermissions where groupID='{$groupID}'", $eo);
		$res_user = sql("select tableName, allowInsert, allowView, allowEdit, allowDelete from membership_userpermissions where lcase(memberID)='{$memberID}'", $eo);

		while($row = db_fetch_assoc($res_group)) {
			$table_permissions[$row['tableName']] = array(
				1 => intval($row['allowInsert']),
				2 => intval($row['allowView']),
				3 => intval($row['allowEdit']),
				4 => intval($row['allowDelete']),
				'insert' => intval($row['allowInsert']),
				'view' => intval($row['allowView']),
				'edit' => intval($row['allowEdit']),
				'delete' => intval($row['allowDelete'])
			);
		}

		// user-specific permissions, if specified, overwrite his group permissions
		while($row = db_fetch_assoc($res_user)) {
			$table_permissions[$row['tableName']] = array(
				1 => intval($row['allowInsert']),
				2 => intval($row['allowView']),
				3 => intval($row['allowEdit']),
				4 => intval($row['allowDelete']),
				'insert' => intval($row['allowInsert']),
				'view' => intval($row['allowView']),
				'edit' => intval($row['allowEdit']),
				'delete' => intval($row['allowDelete'])
			);
		}

		// if user has any type of access, set 'access' flag
		foreach($table_permissions as $t => $p) {
			$table_permissions[$t]['access'] = $table_permissions[$t][0] = false;

			if($p['insert'] || $p['view'] || $p['edit'] || $p['delete']) {
				$table_permissions[$t]['access'] = $table_permissions[$t][0] = true;
			}
		}

		return $table_permissions[$tn];
	}

	#########################################################

	function get_sql_fields($table_name) {
		$sql_fields = array(
			'main' => "`main`.`id` as 'id', `main`.`main` as 'main'",
			'clients' => "`clients`.`matricule_client` as 'matricule_client', if(`clients`.`date_inscription`,date_format(`clients`.`date_inscription`,'%d/%m/%Y'),'') as 'date_inscription', IF(    CHAR_LENGTH(`types_client1`.`type_client`), CONCAT_WS('',   `types_client1`.`type_client`), '') as 'type', `clients`.`nom_prenom` as 'nom_prenom', IF(    CHAR_LENGTH(`pays1`.`pays`), CONCAT_WS('',   `pays1`.`pays`), '') as 'nationalite', `clients`.`sexe` as 'sexe', if(`clients`.`date_naissance`,date_format(`clients`.`date_naissance`,'%d/%m/%Y'),'') as 'date_naissance', `clients`.`age` as 'age', `clients`.`nni` as 'nni', IF(    CHAR_LENGTH(`fonctions1`.`fonction`), CONCAT_WS('',   `fonctions1`.`fonction`), '') as 'fonction', `clients`.`passport` as 'passport', IF(    CHAR_LENGTH(`pays2`.`pays`), CONCAT_WS('',   `pays2`.`pays`), '') as 'lieu', if(`clients`.`date_emis`,date_format(`clients`.`date_emis`,'%d/%m/%Y'),'') as 'date_emis', if(`clients`.`date_exp`,date_format(`clients`.`date_exp`,'%d/%m/%Y'),'') as 'date_exp', `clients`.`validite` as 'validite', `clients`.`adresse` as 'adresse', `clients`.`telephone` as 'telephone', `clients`.`email` as 'email', IF(    CHAR_LENGTH(`banques1`.`banque`), CONCAT_WS('',   `banques1`.`banque`), '') as 'banque', `clients`.`compte` as 'compte', IF(    CHAR_LENGTH(`cartes_fidelite1`.`carte_fidelite`), CONCAT_WS('',   `cartes_fidelite1`.`carte_fidelite`), '') as 'carte_fidelite', `clients`.`numero_cf` as 'numero_cf', REPLACE(FORMAT(`clients`.`total_entree`, 0), ',', ' ') as 'total_entree', REPLACE(FORMAT(`clients`.`total_sortie`, 0), ',', ' ') as 'total_sortie', REPLACE(FORMAT(`clients`.`solde`, 0), ',', ' ') as 'solde', `clients`.`photo` as 'photo', `clients`.`signature` as 'signature', IF(    CHAR_LENGTH(`agences1`.`agence`), CONCAT_WS('',   `agences1`.`agence`), '') as 'agence', `clients`.`dossier` as 'dossier', `clients`.`urgence` as 'urgence', `clients`.`observation` as 'observation'",
			'gestionnaires' => "`gestionnaires`.`matricule_gestionnaire` as 'matricule_gestionnaire', if(`gestionnaires`.`date_recrutement`,date_format(`gestionnaires`.`date_recrutement`,'%d/%m/%Y'),'') as 'date_recrutement', `gestionnaires`.`nom_prenom` as 'nom_prenom', `gestionnaires`.`telephone` as 'telephone', `gestionnaires`.`email` as 'email', `gestionnaires`.`adresse` as 'adresse', IF(    CHAR_LENGTH(`fonctions1`.`fonction`), CONCAT_WS('',   `fonctions1`.`fonction`), '') as 'fonction', IF(    CHAR_LENGTH(`agences1`.`agence`), CONCAT_WS('',   `agences1`.`agence`), '') as 'agence', `gestionnaires`.`photo` as 'photo', `gestionnaires`.`dossier` as 'dossier', `gestionnaires`.`observation` as 'observation'",
			'partenaires' => "`partenaires`.`matricule_partenaire` as 'matricule_partenaire', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'raison_sociale', `partenaires`.`contact` as 'contact', IF(    CHAR_LENGTH(`fonctions1`.`fonction`), CONCAT_WS('',   `fonctions1`.`fonction`), '') as 'fonction', IF(    CHAR_LENGTH(`clients1`.`adresse`), CONCAT_WS('',   `clients1`.`adresse`), '') as 'adresse', IF(    CHAR_LENGTH(`clients1`.`telephone`), CONCAT_WS('',   `clients1`.`telephone`), '') as 'telephone', IF(    CHAR_LENGTH(`clients1`.`email`), CONCAT_WS('',   `clients1`.`email`), '') as 'email', REPLACE(FORMAT(`partenaires`.`commission`, 0), ',', ' ') as 'commission', IF(    CHAR_LENGTH(`banques1`.`banque`), CONCAT_WS('',   `banques1`.`banque`), '') as 'banque', IF(    CHAR_LENGTH(`clients1`.`compte`), CONCAT_WS('',   `clients1`.`compte`), '') as 'compte', `partenaires`.`observation` as 'observation'",
			'paiements' => "`paiements`.`idpaiement` as 'idpaiement', `paiements`.`code` as 'code', IF(    CHAR_LENGTH(`clients1`.`matricule_client`), CONCAT_WS('',   `clients1`.`matricule_client`), '') as 'matricule', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'nom_prenom', IF(    CHAR_LENGTH(`banques1`.`banque`), CONCAT_WS('',   `banques1`.`banque`), '') as 'banque', IF(    CHAR_LENGTH(`clients1`.`compte`), CONCAT_WS('',   `clients1`.`compte`), '') as 'compte', IF(    CHAR_LENGTH(`type_paiements1`.`type_paiement`), CONCAT_WS('',   `type_paiements1`.`type_paiement`), '') as 'type_paiement', if(`paiements`.`date_paiement`,date_format(`paiements`.`date_paiement`,'%d/%m/%Y'),'') as 'date_paiement', `paiements`.`num_facture` as 'num_facture', `paiements`.`montant` as 'montant', IF(    CHAR_LENGTH(`partenaires1`.`matricule_partenaire`), CONCAT_WS('',   `partenaires1`.`matricule_partenaire`), '') as 'beneficiaire', IF(    CHAR_LENGTH(`clients5`.`nom_prenom`), CONCAT_WS('',   `clients5`.`nom_prenom`), '') as 'rs', IF(    CHAR_LENGTH(`partenaires1`.`banque`), CONCAT_WS('',   `partenaires1`.`banque`), '') as 'banque_beneficiaire', IF(    CHAR_LENGTH(`partenaires1`.`compte`), CONCAT_WS('',   `partenaires1`.`compte`), '') as 'compte_beneficiaire', `paiements`.`statut` as 'statut', `paiements`.`observation` as 'observation'",
			'emetteurs' => "`emetteurs`.`idemetteur` as 'idemetteur', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'emetteur', IF(    CHAR_LENGTH(`clients1`.`adresse`), CONCAT_WS('',   `clients1`.`adresse`), '') as 'adresse', IF(    CHAR_LENGTH(`clients1`.`email`), CONCAT_WS('',   `clients1`.`email`), '') as 'email', IF(    CHAR_LENGTH(`clients1`.`telephone`), CONCAT_WS('',   `clients1`.`telephone`), '') as 'telephone', `emetteurs`.`observation` as 'observation'",
			'bieleteries' => "`bieleteries`.`idbieleterie` as 'idbieleterie', `bieleteries`.`link_tarif` as 'link_tarif', `bieleteries`.`num_facture` as 'num_facture', if(`bieleteries`.`date`,date_format(`bieleteries`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'client', `bieleteries`.`statut` as 'statut'",
			'tarifs' => "`tarifs`.`idtarif` as 'idtarif', IF(    CHAR_LENGTH(`bieleteries1`.`link_tarif`), CONCAT_WS('',   `bieleteries1`.`link_tarif`), '') as 'link_bieleterie', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'passager', IF(    CHAR_LENGTH(`parcours1`.`parcour`), CONCAT_WS('',   `parcours1`.`parcour`), '') as 'parcours', IF(    CHAR_LENGTH(`compagnies1`.`compagnie`), CONCAT_WS('',   `compagnies1`.`compagnie`), '') as 'compagnie', IF(    CHAR_LENGTH(`provenance1`.`provenance`), CONCAT_WS('',   `provenance1`.`provenance`), '') as 'provenance', IF(    CHAR_LENGTH(`clients2`.`nom_prenom`), CONCAT_WS('',   `clients2`.`nom_prenom`), '') as 'emetteur', `tarifs`.`pnr` as 'pnr', `tarifs`.`numero` as 'numero', `tarifs`.`prix_achat` as 'prix_achat', `tarifs`.`commission` as 'commission', `tarifs`.`frais_service` as 'frais_service', `tarifs`.`total` as 'total'",
			'transferts_argent' => "`transferts_argent`.`idtransfert` as 'idtransfert', `transferts_argent`.`num_facture` as 'num_facture', `transferts_argent`.`code_transaction` as 'code_transaction', if(`transferts_argent`.`date`,date_format(`transferts_argent`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'emetteur', IF(    CHAR_LENGTH(`clients1`.`nni`), CONCAT_WS('',   `clients1`.`nni`), '') as 'nni_emetteur', IF(    CHAR_LENGTH(`clients1`.`telephone`), CONCAT_WS('',   `clients1`.`telephone`), '') as 'phone_emetteur', IF(    CHAR_LENGTH(`clients1`.`adresse`), CONCAT_WS('',   `clients1`.`adresse`), '') as 'adresse_emetteur', `transferts_argent`.`beneficiaire` as 'beneficiaire', `transferts_argent`.`nni_beneficiaire` as 'nni_beneficiaire', `transferts_argent`.`phone_beneficiaire` as 'phone_beneficiaire', `transferts_argent`.`adresse_beneficiaire` as 'adresse_beneficiaire', `transferts_argent`.`prix_achat` as 'prix_achat', `transferts_argent`.`commission` as 'commission', `transferts_argent`.`total` as 'total', `transferts_argent`.`statut` as 'statut', `transferts_argent`.`observation` as 'observation'",
			'colis' => "`colis`.`idcoli` as 'idcoli', `colis`.`num_facture` as 'num_facture', `colis`.`link_envoi_colis` as 'link_envoi_colis', `colis`.`code_transaction` as 'code_transaction', if(`colis`.`date_envoi`,date_format(`colis`.`date_envoi`,'%d/%m/%Y'),'') as 'date_envoi', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'emetteur', IF(    CHAR_LENGTH(`clients1`.`telephone`), CONCAT_WS('',   `clients1`.`telephone`), '') as 'phone_emetteur'",
			'envois_colis' => "`envois_colis`.`idenvois_coli` as 'idenvois_coli', IF(    CHAR_LENGTH(`colis1`.`link_envoi_colis`), CONCAT_WS('',   `colis1`.`link_envoi_colis`), '') as 'link_colis', `envois_colis`.`description` as 'description', IF(    CHAR_LENGTH(`pays1`.`pays`), CONCAT_WS('',   `pays1`.`pays`), '') as 'destination', IF(    CHAR_LENGTH(`agences1`.`agence`), CONCAT_WS('',   `agences1`.`agence`), '') as 'agence', IF(    CHAR_LENGTH(`villes1`.`ville`), CONCAT_WS('',   `villes1`.`ville`), '') as 'ville', `envois_colis`.`prix_unitaire` as 'prix_unitaire', `envois_colis`.`qts` as 'qts', `envois_colis`.`prix_total` as 'prix_total', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'beneficiaire', IF(    CHAR_LENGTH(`clients1`.`telephone`), CONCAT_WS('',   `clients1`.`telephone`), '') as 'telephone_beneficiaire', IF(    CHAR_LENGTH(`clients1`.`nni`), CONCAT_WS('',   `clients1`.`nni`), '') as 'nni_beneficiaire', if(`envois_colis`.`date_reception`,date_format(`envois_colis`.`date_reception`,'%d/%m/%Y'),'') as 'date_reception', `envois_colis`.`statut` as 'statut', `envois_colis`.`observation` as 'observation'",
			'parc_auto' => "`parc_auto`.`idparc` as 'idparc', `parc_auto`.`type` as 'type', IF(    CHAR_LENGTH(`models1`.`marque`), CONCAT_WS('',   `models1`.`marque`), '') as 'marque', IF(    CHAR_LENGTH(`models1`.`model`), CONCAT_WS('',   `models1`.`model`), '') as 'model', `parc_auto`.`immatriculation` as 'immatriculation', `parc_auto`.`places` as 'places', `parc_auto`.`observation` as 'observation'",
			'location_vh' => "`location_vh`.`idlocation` as 'idlocation', `location_vh`.`link_liste` as 'link_liste', `location_vh`.`num_facture` as 'num_facture', if(`location_vh`.`date_saisie`,date_format(`location_vh`.`date_saisie`,'%d/%m/%Y'),'') as 'date_saisie', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'client'",
			'liste_location' => "`liste_location`.`idlocations` as 'idlocations', IF(    CHAR_LENGTH(`location_vh1`.`link_liste`), CONCAT_WS('',   `location_vh1`.`link_liste`), '') as 'link_location', if(`liste_location`.`date_location`,date_format(`liste_location`.`date_location`,'%d/%m/%Y'),'') as 'date_location', if(`liste_location`.`date_fin_location`,date_format(`liste_location`.`date_fin_location`,'%d/%m/%Y'),'') as 'date_fin_location', IF(    CHAR_LENGTH(`models1`.`marque`), CONCAT_WS('',   `models1`.`marque`), '') as 'vehicule', IF(    CHAR_LENGTH(`models2`.`model`), CONCAT_WS('',   `models2`.`model`), '') as 'model', `liste_location`.`type` as 'type', `liste_location`.`prix_unitaire` as 'prix_unitaire', `liste_location`.`qts` as 'qts', `liste_location`.`prix_total` as 'prix_total', `liste_location`.`observation` as 'observation'",
			'fonctions' => "`fonctions`.`idfonction` as 'idfonction', `fonctions`.`fonction` as 'fonction', `fonctions`.`observation` as 'observation'",
			'agences' => "`agences`.`idagence` as 'idagence', `agences`.`agence` as 'agence', `agences`.`adresse` as 'adresse', IF(    CHAR_LENGTH(`villes1`.`ville`), CONCAT_WS('',   `villes1`.`ville`), '') as 'ville', `agences`.`observation` as 'observation'",
			'villes' => "`villes`.`idville` as 'idville', `villes`.`ville` as 'ville', `villes`.`observation` as 'observation'",
			'banques' => "`banques`.`idbanque` as 'idbanque', `banques`.`banque` as 'banque', `banques`.`adresse` as 'adresse', `banques`.`telephone` as 'telephone', `banques`.`email` as 'email', `banques`.`contact` as 'contact', `banques`.`observation` as 'observation'",
			'type_paiements' => "`type_paiements`.`idtype_payment` as 'idtype_payment', `type_paiements`.`type_paiement` as 'type_paiement', `type_paiements`.`observation` as 'observation'",
			'compagnies' => "`compagnies`.`idcompagnie` as 'idcompagnie', `compagnies`.`compagnie` as 'compagnie', `compagnies`.`observation` as 'observation'",
			'statuts' => "`statuts`.`idstatut` as 'idstatut', `statuts`.`statut` as 'statut'",
			'visas' => "`visas`.`idvisa` as 'idvisa', if(`visas`.`date_depot`,date_format(`visas`.`date_depot`,'%d/%m/%Y'),'') as 'date_depot', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'client', IF(    CHAR_LENGTH(`clients1`.`passport`), CONCAT_WS('',   `clients1`.`passport`), '') as 'num_passport', IF(    CHAR_LENGTH(`type_visas1`.`type_visa`), CONCAT_WS('',   `type_visas1`.`type_visa`), '') as 'type_visa', IF(    CHAR_LENGTH(`clients2`.`nom_prenom`), CONCAT_WS('',   `clients2`.`nom_prenom`), '') as 'emetteur', REPLACE(FORMAT(`visas`.`prix_achat`, 0), ',', ' ') as 'prix_achat', REPLACE(FORMAT(`visas`.`commission`, 0), ',', ' ') as 'commission', REPLACE(FORMAT(`visas`.`total`, 0), ',', ' ') as 'total', `visas`.`statut` as 'statut', `visas`.`dossier` as 'dossier', `visas`.`obs` as 'obs'",
			'oumras' => "`oumras`.`idoumra` as 'idoumra', if(`oumras`.`date`,date_format(`oumras`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'client', IF(    CHAR_LENGTH(`clients1`.`adresse`), CONCAT_WS('',   `clients1`.`adresse`), '') as 'adresse', IF(    CHAR_LENGTH(`clients1`.`passport`), CONCAT_WS('',   `clients1`.`passport`), '') as 'passeport', if(`oumras`.`date_depart`,date_format(`oumras`.`date_depart`,'%d/%m/%Y'),'') as 'date_depart', if(`oumras`.`date_retour`,date_format(`oumras`.`date_retour`,'%d/%m/%Y'),'') as 'date_retour', IF(    CHAR_LENGTH(`compagnies1`.`compagnie`), CONCAT_WS('',   `compagnies1`.`compagnie`), '') as 'compagnie', `oumras`.`billet` as 'billet', IF(    CHAR_LENGTH(`programmes1`.`programme`), CONCAT_WS('',   `programmes1`.`programme`), '') as 'programme', if(`oumras`.`debut_visa`,date_format(`oumras`.`debut_visa`,'%d/%m/%Y'),'') as 'debut_visa', if(`oumras`.`fin_visa`,date_format(`oumras`.`fin_visa`,'%d/%m/%Y'),'') as 'fin_visa', `oumras`.`duree_visa` as 'duree_visa', `oumras`.`statut` as 'statut', `oumras`.`dossier` as 'dossier', `oumras`.`obs` as 'obs'",
			'assurances' => "`assurances`.`idassurance` as 'idassurance', if(`assurances`.`date`,date_format(`assurances`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'nom_prenom', IF(    CHAR_LENGTH(`intermediares1`.`intermediare`), CONCAT_WS('',   `intermediares1`.`intermediare`), '') as 'intermediare', IF(    CHAR_LENGTH(`pays1`.`pays`), CONCAT_WS('',   `pays1`.`pays`), '') as 'pays_residence', IF(    CHAR_LENGTH(`clients2`.`adresse`), CONCAT_WS('',   `clients2`.`adresse`), '') as 'adresse', IF(    CHAR_LENGTH(`clients1`.`telephone`), CONCAT_WS('',   `clients1`.`telephone`), '') as 'telephone', IF(    CHAR_LENGTH(`clients1`.`email`), CONCAT_WS('',   `clients1`.`email`), '') as 'email', IF(    CHAR_LENGTH(`pays2`.`pays`), CONCAT_WS('',   `pays2`.`pays`), '') as 'destination', IF(    CHAR_LENGTH(`formule1`.`formule`), CONCAT_WS('',   `formule1`.`formule`), '') as 'formule', `assurances`.`certificat` as 'certificat', if(`assurances`.`date_depart`,date_format(`assurances`.`date_depart`,'%d/%m/%Y'),'') as 'date_depart', if(`assurances`.`date_retour`,date_format(`assurances`.`date_retour`,'%d/%m/%Y'),'') as 'date_retour', IF(    CHAR_LENGTH(`clients1`.`passport`), CONCAT_WS('',   `clients1`.`passport`), '') as 'passport', `assurances`.`beneficiaire` as 'beneficiaire', IF(    CHAR_LENGTH(`clients3`.`nom_prenom`), CONCAT_WS('',   `clients3`.`nom_prenom`), '') as 'nom_prenomb', IF(    CHAR_LENGTH(if(`clients1`.`date_naissance`,date_format(`clients1`.`date_naissance`,'%d/%m/%Y'),'')), CONCAT_WS('',   if(`clients1`.`date_naissance`,date_format(`clients1`.`date_naissance`,'%d/%m/%Y'),'')), '') as 'date_de_naissance', `assurances`.`dossier_pdf` as 'dossier_pdf', `assurances`.`dossier_zippe` as 'dossier_zippe', `assurances`.`statut` as 'statut', `assurances`.`questionnaire_medical` as 'questionnaire_medical', `assurances`.`question1` as 'question1', `assurances`.`question2` as 'question2', `assurances`.`question2a` as 'question2a', `assurances`.`question3` as 'question3', `assurances`.`question4` as 'question4', `assurances`.`question5` as 'question5', `assurances`.`prime_total` as 'prime_total'",
			'type_visas' => "`type_visas`.`idtype_visa` as 'idtype_visa', `type_visas`.`type_visa` as 'type_visa'",
			'facture' => "`facture`.`idfacture` as 'idfacture', `facture`.`num_facture` as 'num_facture', `facture`.`type` as 'type', if(`facture`.`date`,date_format(`facture`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'client', IF(    CHAR_LENGTH(`clients1`.`telephone`), CONCAT_WS('',   `clients1`.`telephone`), '') as 'societe', IF(    CHAR_LENGTH(`natures1`.`nature`), CONCAT_WS('',   `natures1`.`nature`), '') as 'travaux', `facture`.`statut` as 'statut'",
			'detail_facture' => "`detail_facture`.`dfid` as 'dfid', IF(    CHAR_LENGTH(`facture1`.`idfacture`), CONCAT_WS('',   `facture1`.`idfacture`), '') as 'factureid', IF(    CHAR_LENGTH(`designations1`.`designation`), CONCAT_WS('',   `designations1`.`designation`), '') as 'designation', `detail_facture`.`quantite` as 'quantite', `detail_facture`.`prixunitaire` as 'prixunitaire', `detail_facture`.`total` as 'total'",
			'recettes' => "`recettes`.`idrecette` as 'idrecette', if(`recettes`.`date`,date_format(`recettes`.`date`,'%d/%m/%Y'),'') as 'date', `recettes`.`num_piece` as 'num_piece', IF(    CHAR_LENGTH(`agences1`.`agence`), CONCAT_WS('',   `agences1`.`agence`), '') as 'agence', IF(    CHAR_LENGTH(`services1`.`service`), CONCAT_WS('',   `services1`.`service`), '') as 'service', IF(    CHAR_LENGTH(`natures1`.`nature`), CONCAT_WS('',   `natures1`.`nature`), '') as 'nature', REPLACE(FORMAT(`recettes`.`montant`, 0), ',', ' ') as 'montant', `recettes`.`obs` as 'obs'",
			'depenses' => "`depenses`.`iddepense` as 'iddepense', if(`depenses`.`date`,date_format(`depenses`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`natures1`.`nature`), CONCAT_WS('',   `natures1`.`nature`), '') as 'nature', IF(    CHAR_LENGTH(`justificatifs1`.`justificatif`), CONCAT_WS('',   `justificatifs1`.`justificatif`), '') as 'justificatif', IF(    CHAR_LENGTH(`agences1`.`agence`), CONCAT_WS('',   `agences1`.`agence`), '') as 'agence', IF(    CHAR_LENGTH(`services1`.`service`), CONCAT_WS('',   `services1`.`service`), '') as 'service', IF(    CHAR_LENGTH(`banques1`.`banque`), CONCAT_WS('',   `banques1`.`banque`), '') as 'banque', REPLACE(FORMAT(`depenses`.`montant`, 0), ',', ' ') as 'montant', `depenses`.`compte` as 'compte', `depenses`.`obs` as 'obs'",
			'caisse' => "`caisse`.`idcaisse` as 'idcaisse', IF(    CHAR_LENGTH(`recettes1`.`idrecette`), CONCAT_WS('',   `recettes1`.`idrecette`), '') as 'link_recettes', IF(    CHAR_LENGTH(`depenses1`.`iddepense`), CONCAT_WS('',   `depenses1`.`iddepense`), '') as 'link_depenses', if(`caisse`.`date`,date_format(`caisse`.`date`,'%d/%m/%Y'),'') as 'date', `caisse`.`recettes` as 'recettes', `caisse`.`depenses` as 'depenses', `caisse`.`caisse` as 'caisse', `caisse`.`obs` as 'obs'",
			'tresorerie_caisse' => "`tresorerie_caisse`.`idtresorerie_caisse` as 'idtresorerie_caisse', if(`tresorerie_caisse`.`date`,date_format(`tresorerie_caisse`.`date`,'%d/%m/%Y'),'') as 'date', `tresorerie_caisse`.`journee_du` as 'journee_du', `tresorerie_caisse`.`link_in` as 'link_in'",
			'tresorerie_items' => "`tresorerie_items`.`idtresorerie_item` as 'idtresorerie_item', IF(    CHAR_LENGTH(`tresorerie_caisse1`.`link_in`), CONCAT_WS('',   `tresorerie_caisse1`.`link_in`), '') as 'link_out', `tresorerie_items`.`justificatif` as 'justificatif', `tresorerie_items`.`libelles` as 'libelles', `tresorerie_items`.`montant` as 'montant', `tresorerie_items`.`commission_agence` as 'commission_agence', `tresorerie_items`.`net_compagnie` as 'net_compagnie', `tresorerie_items`.`observations` as 'observations'",
			'piece_reglements' => "`piece_reglements`.`idpiece` as 'idpiece', if(`piece_reglements`.`date`,date_format(`piece_reglements`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'beneficiaire', IF(    CHAR_LENGTH(`operations1`.`operation`), CONCAT_WS('',   `operations1`.`operation`), '') as 'operation', REPLACE(FORMAT(`piece_reglements`.`montant`, 0), ',', ' ') as 'montant', IF(    CHAR_LENGTH(`banques1`.`banque`), CONCAT_WS('',   `banques1`.`banque`), '') as 'banque', IF(    CHAR_LENGTH(`clients1`.`compte`), CONCAT_WS('',   `clients1`.`compte`), '') as 'compte', `piece_reglements`.`num_cheque` as 'num_cheque', if(`piece_reglements`.`date_cheque`,date_format(`piece_reglements`.`date_cheque`,'%d/%m/%Y'),'') as 'date_cheque', `piece_reglements`.`imputation` as 'imputation', `piece_reglements`.`statut` as 'statut', `piece_reglements`.`observations` as 'observations'",
			'autorisation_change' => "`autorisation_change`.`idautorisation` as 'idautorisation', if(`autorisation_change`.`date`,date_format(`autorisation_change`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'nom_prenom', IF(    CHAR_LENGTH(`pays1`.`pays`), CONCAT_WS('',   `pays1`.`pays`), '') as 'nationalite', IF(    CHAR_LENGTH(`fonctions1`.`fonction`), CONCAT_WS('',   `fonctions1`.`fonction`), '') as 'profession', IF(    CHAR_LENGTH(`clients1`.`adresse`), CONCAT_WS('',   `clients1`.`adresse`), '') as 'adresse', IF(    CHAR_LENGTH(`clients1`.`compte`), CONCAT_WS('',   `clients1`.`compte`), '') as 'num_compte', IF(    CHAR_LENGTH(`natures1`.`nature`), CONCAT_WS('',   `natures1`.`nature`), '') as 'nature_operation', `autorisation_change`.`piece_justificative` as 'piece_justificative', IF(    CHAR_LENGTH(`devise1`.`devise`), CONCAT_WS('',   `devise1`.`devise`), '') as 'nature_devises', REPLACE(FORMAT(`autorisation_change`.`montant_chiffre`, 0), ',', ' ') as 'montant_chiffre', `autorisation_change`.`cours` as 'cours', `autorisation_change`.`montant_fois_cours` as 'montant_fois_cours', `autorisation_change`.`commission` as 'commission', REPLACE(FORMAT(`autorisation_change`.`contre_valeur`, 0), ',', ' ') as 'contre_valeur', `autorisation_change`.`total` as 'total', `autorisation_change`.`statut` as 'statut'",
			'bon_passage' => "`bon_passage`.`idbon` as 'idbon', if(`bon_passage`.`date`,date_format(`bon_passage`.`date`,'%d/%m/%Y'),'') as 'date', `bon_passage`.`pnr` as 'pnr', `bon_passage`.`nous_prions` as 'nous_prions', `bon_passage`.`au_nom_de` as 'au_nom_de', `bon_passage`.`parcours` as 'parcours', if(`bon_passage`.`depart`,date_format(`bon_passage`.`depart`,'%d/%m/%Y'),'') as 'depart', if(`bon_passage`.`retour`,date_format(`bon_passage`.`retour`,'%d/%m/%Y'),'') as 'retour', REPLACE(FORMAT(`bon_passage`.`total_ht`, 0), ',', ' ') as 'total_ht', `bon_passage`.`commissions` as 'commissions', REPLACE(FORMAT(`bon_passage`.`total_ttc`, 0), ',', ' ') as 'total_ttc', REPLACE(FORMAT(`bon_passage`.`frais_pta`, 0), ',', ' ') as 'frais_pta', REPLACE(FORMAT(`bon_passage`.`net_payer`, 0), ',', ' ') as 'net_payer', `bon_passage`.`num_billet` as 'num_billet', `bon_passage`.`statut` as 'statut', `bon_passage`.`observations` as 'observations'",
			'fiches_changes' => "`fiches_changes`.`idfichechange` as 'idfichechange', if(`fiches_changes`.`date`,date_format(`fiches_changes`.`date`,'%d/%m/%Y'),'') as 'date', `fiches_changes`.`journee_du` as 'journee_du', `fiches_changes`.`link_in` as 'link_in', `fiches_changes`.`statut` as 'statut'",
			'fiches_changes_items' => "`fiches_changes_items`.`idfiche_change_item` as 'idfiche_change_item', IF(    CHAR_LENGTH(`fiches_changes1`.`link_in`), CONCAT_WS('',   `fiches_changes1`.`link_in`), '') as 'link_out', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'nom_prenom', IF(    CHAR_LENGTH(`clients1`.`nni`), CONCAT_WS('',   `clients1`.`nni`), '') as 'num_identite', `fiches_changes_items`.`montant` as 'montant', IF(    CHAR_LENGTH(`devise1`.`devise`), CONCAT_WS('',   `devise1`.`devise`), '') as 'devises', `fiches_changes_items`.`achats` as 'achats', `fiches_changes_items`.`ventes` as 'ventes', `fiches_changes_items`.`observations` as 'observations'",
			'caisse_journaliere' => "`caisse_journaliere`.`idcaisse_journaliere` as 'idcaisse_journaliere', if(`caisse_journaliere`.`date`,date_format(`caisse_journaliere`.`date`,'%d/%m/%Y'),'') as 'date', `caisse_journaliere`.`link_in` as 'link_in'",
			'item_caisse_journaliere' => "IF(    CHAR_LENGTH(`caisse_journaliere1`.`link_in`), CONCAT_WS('',   `caisse_journaliere1`.`link_in`), '') as 'link_out', `item_caisse_journaliere`.`iditem_caisse_journaliere` as 'iditem_caisse_journaliere', `item_caisse_journaliere`.`justificatif` as 'justificatif', `item_caisse_journaliere`.`nom_prenom` as 'nom_prenom', `item_caisse_journaliere`.`destination` as 'destination', `item_caisse_journaliere`.`compagnie` as 'compagnie', REPLACE(FORMAT(`item_caisse_journaliere`.`prix_ht`, 0), ',', ' ') as 'prix_ht', `item_caisse_journaliere`.`commission` as 'commission', REPLACE(FORMAT(`item_caisse_journaliere`.`prix_ttc`, 0), ',', ' ') as 'prix_ttc', `item_caisse_journaliere`.`observations` as 'observations'",
			'models' => "`models`.`idmodel` as 'idmodel', `models`.`marque` as 'marque', `models`.`model` as 'model'",
			'natures' => "`natures`.`idnature` as 'idnature', `natures`.`nature` as 'nature', `natures`.`obs` as 'obs'",
			'services' => "`services`.`idservice` as 'idservice', `services`.`service` as 'service', `services`.`obs` as 'obs'",
			'liens' => "`liens`.`id` as 'id', `liens`.`logo` as 'logo', `liens`.`nom` as 'nom', `liens`.`lien` as 'lien'",
			'types_client' => "`types_client`.`idtype_client` as 'idtype_client', `types_client`.`type_client` as 'type_client', `types_client`.`obs` as 'obs'",
			'cartes_fidelite' => "`cartes_fidelite`.`idcartecf` as 'idcartecf', `cartes_fidelite`.`carte_fidelite` as 'carte_fidelite', `cartes_fidelite`.`obs` as 'obs'",
			'designations' => "`designations`.`iddesignation` as 'iddesignation', `designations`.`designation` as 'designation', `designations`.`obs` as 'obs'",
			'parcours' => "`parcours`.`idparcour` as 'idparcour', `parcours`.`parcour` as 'parcour', `parcours`.`obs` as 'obs'",
			'pays' => "`pays`.`idpays` as 'idpays', `pays`.`pays` as 'pays', `pays`.`obs` as 'obs'",
			'provenance' => "`provenance`.`idprovenance` as 'idprovenance', `provenance`.`provenance` as 'provenance', `provenance`.`obs` as 'obs'",
			'programmes' => "`programmes`.`idprogramme` as 'idprogramme', `programmes`.`programme` as 'programme', `programmes`.`obs` as 'obs'",
			'justificatifs' => "`justificatifs`.`idjustificatif` as 'idjustificatif', `justificatifs`.`justificatif` as 'justificatif', `justificatifs`.`obs` as 'obs'",
			'devise' => "`devise`.`iddevise` as 'iddevise', `devise`.`devise` as 'devise'",
			'intermediares' => "`intermediares`.`idintermediaire` as 'idintermediaire', `intermediares`.`intermediare` as 'intermediare', `intermediares`.`obs` as 'obs'",
			'formule' => "`formule`.`idformule` as 'idformule', `formule`.`formule` as 'formule', `formule`.`obs` as 'obs'",
			'operations' => "`operations`.`idoperation` as 'idoperation', `operations`.`operation` as 'operation'",
			'pointages' => "`pointages`.`idpointage` as 'idpointage', if(`pointages`.`date`,date_format(`pointages`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`clients1`.`nom_prenom`), CONCAT_WS('',   `clients1`.`nom_prenom`), '') as 'nom_prenom', IF(    CHAR_LENGTH(`agences1`.`agence`), CONCAT_WS('',   `agences1`.`agence`), '') as 'agence', IF(    CHAR_LENGTH(`fonctions1`.`fonction`), CONCAT_WS('',   `fonctions1`.`fonction`), '') as 'fonction', `pointages`.`arrivee` as 'arrivee', `pointages`.`depart` as 'depart', `pointages`.`obs` as 'obs'",
			'fichiers_partages' => "`fichiers_partages`.`idfichier_partage` as 'idfichier_partage', if(`fichiers_partages`.`date`,date_format(`fichiers_partages`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`gestionnaires1`.`nom_prenom`), CONCAT_WS('',   `gestionnaires1`.`nom_prenom`), '') as 'agent', IF(    CHAR_LENGTH(`agences1`.`agence`), CONCAT_WS('',   `agences1`.`agence`), '') as 'agence', IF(    CHAR_LENGTH(`fonctions1`.`fonction`), CONCAT_WS('',   `fonctions1`.`fonction`), '') as 'service', `fichiers_partages`.`nom_du_fichier` as 'nom_du_fichier', `fichiers_partages`.`pdf` as 'pdf', `fichiers_partages`.`word` as 'word', `fichiers_partages`.`excel` as 'excel', `fichiers_partages`.`powerpoint` as 'powerpoint', `fichiers_partages`.`compresse` as 'compresse', `fichiers_partages`.`note` as 'note'",
			'note_de_service' => "`note_de_service`.`idnote_service` as 'idnote_service', if(`note_de_service`.`date`,date_format(`note_de_service`.`date`,'%d/%m/%Y'),'') as 'date', IF(    CHAR_LENGTH(`agences1`.`agence`), CONCAT_WS('',   `agences1`.`agence`), '') as 'agence', IF(    CHAR_LENGTH(`services1`.`service`), CONCAT_WS('',   `services1`.`service`), '') as 'service', `note_de_service`.`objet` as 'objet', `note_de_service`.`texte` as 'texte', `note_de_service`.`ampliation` as 'ampliation'",
		);

		if(isset($sql_fields[$table_name])) {
			return $sql_fields[$table_name];
		}

		return false;
	}

	#########################################################

	function get_sql_from($table_name, $skip_permissions = false, $skip_joins = false) {
		$sql_from = array(
			'main' => "`main` ",
			'clients' => "`clients` LEFT JOIN `types_client` as types_client1 ON `types_client1`.`idtype_client`=`clients`.`type` LEFT JOIN `pays` as pays1 ON `pays1`.`idpays`=`clients`.`nationalite` LEFT JOIN `fonctions` as fonctions1 ON `fonctions1`.`idfonction`=`clients`.`fonction` LEFT JOIN `pays` as pays2 ON `pays2`.`idpays`=`clients`.`lieu` LEFT JOIN `banques` as banques1 ON `banques1`.`idbanque`=`clients`.`banque` LEFT JOIN `cartes_fidelite` as cartes_fidelite1 ON `cartes_fidelite1`.`idcartecf`=`clients`.`carte_fidelite` LEFT JOIN `agences` as agences1 ON `agences1`.`idagence`=`clients`.`agence` ",
			'gestionnaires' => "`gestionnaires` LEFT JOIN `fonctions` as fonctions1 ON `fonctions1`.`idfonction`=`gestionnaires`.`fonction` LEFT JOIN `agences` as agences1 ON `agences1`.`idagence`=`gestionnaires`.`agence` ",
			'partenaires' => "`partenaires` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`partenaires`.`raison_sociale` LEFT JOIN `fonctions` as fonctions1 ON `fonctions1`.`idfonction`=`clients1`.`fonction` LEFT JOIN `banques` as banques1 ON `banques1`.`idbanque`=`clients1`.`banque` ",
			'paiements' => "`paiements` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`paiements`.`matricule` LEFT JOIN `type_paiements` as type_paiements1 ON `type_paiements1`.`idtype_payment`=`paiements`.`type_paiement` LEFT JOIN `partenaires` as partenaires1 ON `partenaires1`.`matricule_partenaire`=`paiements`.`beneficiaire` LEFT JOIN `banques` as banques1 ON `banques1`.`idbanque`=`clients1`.`banque` LEFT JOIN `clients` as clients5 ON `clients5`.`matricule_client`=`partenaires1`.`raison_sociale` ",
			'emetteurs' => "`emetteurs` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`emetteurs`.`emetteur` ",
			'bieleteries' => "`bieleteries` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`bieleteries`.`client` ",
			'tarifs' => "`tarifs` LEFT JOIN `bieleteries` as bieleteries1 ON `bieleteries1`.`idbieleterie`=`tarifs`.`link_bieleterie` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`tarifs`.`passager` LEFT JOIN `parcours` as parcours1 ON `parcours1`.`idparcour`=`tarifs`.`parcours` LEFT JOIN `compagnies` as compagnies1 ON `compagnies1`.`idcompagnie`=`tarifs`.`compagnie` LEFT JOIN `provenance` as provenance1 ON `provenance1`.`idprovenance`=`tarifs`.`provenance` LEFT JOIN `emetteurs` as emetteurs1 ON `emetteurs1`.`idemetteur`=`tarifs`.`emetteur` LEFT JOIN `clients` as clients2 ON `clients2`.`matricule_client`=`emetteurs1`.`emetteur` ",
			'transferts_argent' => "`transferts_argent` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`transferts_argent`.`emetteur` ",
			'colis' => "`colis` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`colis`.`emetteur` ",
			'envois_colis' => "`envois_colis` LEFT JOIN `colis` as colis1 ON `colis1`.`idcoli`=`envois_colis`.`link_colis` LEFT JOIN `pays` as pays1 ON `pays1`.`idpays`=`envois_colis`.`destination` LEFT JOIN `agences` as agences1 ON `agences1`.`idagence`=`envois_colis`.`agence` LEFT JOIN `villes` as villes1 ON `villes1`.`idville`=`envois_colis`.`ville` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`envois_colis`.`beneficiaire` ",
			'parc_auto' => "`parc_auto` LEFT JOIN `models` as models1 ON `models1`.`idmodel`=`parc_auto`.`marque` ",
			'location_vh' => "`location_vh` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`location_vh`.`client` ",
			'liste_location' => "`liste_location` LEFT JOIN `location_vh` as location_vh1 ON `location_vh1`.`idlocation`=`liste_location`.`link_location` LEFT JOIN `parc_auto` as parc_auto1 ON `parc_auto1`.`idparc`=`liste_location`.`vehicule` LEFT JOIN `models` as models1 ON `models1`.`idmodel`=`parc_auto1`.`marque` LEFT JOIN `models` as models2 ON `models2`.`idmodel`=`liste_location`.`model` ",
			'fonctions' => "`fonctions` ",
			'agences' => "`agences` LEFT JOIN `villes` as villes1 ON `villes1`.`idville`=`agences`.`ville` ",
			'villes' => "`villes` ",
			'banques' => "`banques` ",
			'type_paiements' => "`type_paiements` ",
			'compagnies' => "`compagnies` ",
			'statuts' => "`statuts` ",
			'visas' => "`visas` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`visas`.`client` LEFT JOIN `type_visas` as type_visas1 ON `type_visas1`.`idtype_visa`=`visas`.`type_visa` LEFT JOIN `emetteurs` as emetteurs1 ON `emetteurs1`.`idemetteur`=`visas`.`emetteur` LEFT JOIN `clients` as clients2 ON `clients2`.`matricule_client`=`emetteurs1`.`emetteur` ",
			'oumras' => "`oumras` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`oumras`.`client` LEFT JOIN `compagnies` as compagnies1 ON `compagnies1`.`idcompagnie`=`oumras`.`compagnie` LEFT JOIN `programmes` as programmes1 ON `programmes1`.`idprogramme`=`oumras`.`programme` ",
			'assurances' => "`assurances` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`assurances`.`nom_prenom` LEFT JOIN `intermediares` as intermediares1 ON `intermediares1`.`idintermediaire`=`assurances`.`intermediare` LEFT JOIN `pays` as pays1 ON `pays1`.`idpays`=`assurances`.`pays_residence` LEFT JOIN `clients` as clients2 ON `clients2`.`matricule_client`=`assurances`.`adresse` LEFT JOIN `pays` as pays2 ON `pays2`.`idpays`=`assurances`.`destination` LEFT JOIN `formule` as formule1 ON `formule1`.`idformule`=`assurances`.`formule` LEFT JOIN `clients` as clients3 ON `clients3`.`matricule_client`=`assurances`.`nom_prenomb` ",
			'type_visas' => "`type_visas` ",
			'facture' => "`facture` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`facture`.`client` LEFT JOIN `natures` as natures1 ON `natures1`.`idnature`=`facture`.`travaux` ",
			'detail_facture' => "`detail_facture` LEFT JOIN `facture` as facture1 ON `facture1`.`idfacture`=`detail_facture`.`factureid` LEFT JOIN `designations` as designations1 ON `designations1`.`iddesignation`=`detail_facture`.`designation` ",
			'recettes' => "`recettes` LEFT JOIN `agences` as agences1 ON `agences1`.`idagence`=`recettes`.`agence` LEFT JOIN `services` as services1 ON `services1`.`idservice`=`recettes`.`service` LEFT JOIN `natures` as natures1 ON `natures1`.`idnature`=`recettes`.`nature` ",
			'depenses' => "`depenses` LEFT JOIN `natures` as natures1 ON `natures1`.`idnature`=`depenses`.`nature` LEFT JOIN `justificatifs` as justificatifs1 ON `justificatifs1`.`idjustificatif`=`depenses`.`justificatif` LEFT JOIN `agences` as agences1 ON `agences1`.`idagence`=`depenses`.`agence` LEFT JOIN `services` as services1 ON `services1`.`idservice`=`depenses`.`service` LEFT JOIN `banques` as banques1 ON `banques1`.`idbanque`=`depenses`.`banque` ",
			'caisse' => "`caisse` LEFT JOIN `recettes` as recettes1 ON `recettes1`.`idrecette`=`caisse`.`link_recettes` LEFT JOIN `depenses` as depenses1 ON `depenses1`.`iddepense`=`caisse`.`link_depenses` ",
			'tresorerie_caisse' => "`tresorerie_caisse` ",
			'tresorerie_items' => "`tresorerie_items` LEFT JOIN `tresorerie_caisse` as tresorerie_caisse1 ON `tresorerie_caisse1`.`idtresorerie_caisse`=`tresorerie_items`.`link_out` ",
			'piece_reglements' => "`piece_reglements` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`piece_reglements`.`beneficiaire` LEFT JOIN `operations` as operations1 ON `operations1`.`idoperation`=`piece_reglements`.`operation` LEFT JOIN `banques` as banques1 ON `banques1`.`idbanque`=`clients1`.`banque` ",
			'autorisation_change' => "`autorisation_change` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`autorisation_change`.`nom_prenom` LEFT JOIN `natures` as natures1 ON `natures1`.`idnature`=`autorisation_change`.`nature_operation` LEFT JOIN `devise` as devise1 ON `devise1`.`iddevise`=`autorisation_change`.`nature_devises` LEFT JOIN `pays` as pays1 ON `pays1`.`idpays`=`clients1`.`nationalite` LEFT JOIN `fonctions` as fonctions1 ON `fonctions1`.`idfonction`=`clients1`.`fonction` ",
			'bon_passage' => "`bon_passage` ",
			'fiches_changes' => "`fiches_changes` ",
			'fiches_changes_items' => "`fiches_changes_items` LEFT JOIN `fiches_changes` as fiches_changes1 ON `fiches_changes1`.`idfichechange`=`fiches_changes_items`.`link_out` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`fiches_changes_items`.`nom_prenom` LEFT JOIN `devise` as devise1 ON `devise1`.`iddevise`=`fiches_changes_items`.`devises` ",
			'caisse_journaliere' => "`caisse_journaliere` ",
			'item_caisse_journaliere' => "`item_caisse_journaliere` LEFT JOIN `caisse_journaliere` as caisse_journaliere1 ON `caisse_journaliere1`.`idcaisse_journaliere`=`item_caisse_journaliere`.`link_out` ",
			'models' => "`models` ",
			'natures' => "`natures` ",
			'services' => "`services` ",
			'liens' => "`liens` ",
			'types_client' => "`types_client` ",
			'cartes_fidelite' => "`cartes_fidelite` ",
			'designations' => "`designations` ",
			'parcours' => "`parcours` ",
			'pays' => "`pays` ",
			'provenance' => "`provenance` ",
			'programmes' => "`programmes` ",
			'justificatifs' => "`justificatifs` ",
			'devise' => "`devise` ",
			'intermediares' => "`intermediares` ",
			'formule' => "`formule` ",
			'operations' => "`operations` ",
			'pointages' => "`pointages` LEFT JOIN `clients` as clients1 ON `clients1`.`matricule_client`=`pointages`.`nom_prenom` LEFT JOIN `agences` as agences1 ON `agences1`.`idagence`=`clients1`.`agence` LEFT JOIN `fonctions` as fonctions1 ON `fonctions1`.`idfonction`=`clients1`.`fonction` ",
			'fichiers_partages' => "`fichiers_partages` LEFT JOIN `gestionnaires` as gestionnaires1 ON `gestionnaires1`.`matricule_gestionnaire`=`fichiers_partages`.`agent` LEFT JOIN `gestionnaires` as gestionnaires2 ON `gestionnaires2`.`matricule_gestionnaire`=`fichiers_partages`.`service` LEFT JOIN `fonctions` as fonctions1 ON `fonctions1`.`idfonction`=`gestionnaires2`.`fonction` LEFT JOIN `agences` as agences1 ON `agences1`.`idagence`=`gestionnaires1`.`agence` ",
			'note_de_service' => "`note_de_service` LEFT JOIN `agences` as agences1 ON `agences1`.`idagence`=`note_de_service`.`agence` LEFT JOIN `services` as services1 ON `services1`.`idservice`=`note_de_service`.`service` ",
		);

		$pkey = array(
			'main' => 'id',
			'clients' => 'matricule_client',
			'gestionnaires' => 'matricule_gestionnaire',
			'partenaires' => 'matricule_partenaire',
			'paiements' => 'idpaiement',
			'emetteurs' => 'idemetteur',
			'bieleteries' => 'idbieleterie',
			'tarifs' => 'idtarif',
			'transferts_argent' => 'idtransfert',
			'colis' => 'idcoli',
			'envois_colis' => 'idenvois_coli',
			'parc_auto' => 'idparc',
			'location_vh' => 'idlocation',
			'liste_location' => 'idlocations',
			'fonctions' => 'idfonction',
			'agences' => 'idagence',
			'villes' => 'idville',
			'banques' => 'idbanque',
			'type_paiements' => 'idtype_payment',
			'compagnies' => 'idcompagnie',
			'statuts' => 'idstatut',
			'visas' => 'idvisa',
			'oumras' => 'idoumra',
			'assurances' => 'idassurance',
			'type_visas' => 'idtype_visa',
			'facture' => 'idfacture',
			'detail_facture' => 'dfid',
			'recettes' => 'idrecette',
			'depenses' => 'iddepense',
			'caisse' => 'idcaisse',
			'tresorerie_caisse' => 'idtresorerie_caisse',
			'tresorerie_items' => 'idtresorerie_item',
			'piece_reglements' => 'idpiece',
			'autorisation_change' => 'idautorisation',
			'bon_passage' => 'idbon',
			'fiches_changes' => 'idfichechange',
			'fiches_changes_items' => 'idfiche_change_item',
			'caisse_journaliere' => 'idcaisse_journaliere',
			'item_caisse_journaliere' => 'iditem_caisse_journaliere',
			'models' => 'idmodel',
			'natures' => 'idnature',
			'services' => 'idservice',
			'liens' => 'id',
			'types_client' => 'idtype_client',
			'cartes_fidelite' => 'idcartecf',
			'designations' => 'iddesignation',
			'parcours' => 'idparcour',
			'pays' => 'idpays',
			'provenance' => 'idprovenance',
			'programmes' => 'idprogramme',
			'justificatifs' => 'idjustificatif',
			'devise' => 'iddevise',
			'intermediares' => 'idintermediaire',
			'formule' => 'idformule',
			'operations' => 'idoperation',
			'pointages' => 'idpointage',
			'fichiers_partages' => 'idfichier_partage',
			'note_de_service' => 'idnote_service',
		);

		if(!isset($sql_from[$table_name])) return false;

		$from = ($skip_joins ? "`{$table_name}`" : $sql_from[$table_name]);

		if($skip_permissions) return $from . ' WHERE 1=1';

		// mm: build the query based on current member's permissions
		$perm = getTablePermissions($table_name);
		if($perm[2] == 1) { // view owner only
			$from .= ", membership_userrecords WHERE `{$table_name}`.`{$pkey[$table_name]}`=membership_userrecords.pkValue and membership_userrecords.tableName='{$table_name}' and lcase(membership_userrecords.memberID)='" . getLoggedMemberID() . "'";
		}elseif($perm[2] == 2) { // view group only
			$from .= ", membership_userrecords WHERE `{$table_name}`.`{$pkey[$table_name]}`=membership_userrecords.pkValue and membership_userrecords.tableName='{$table_name}' and membership_userrecords.groupID='" . getLoggedGroupID() . "'";
		}elseif($perm[2] == 3) { // view all
			$from .= ' WHERE 1=1';
		}else{ // view none
			return false;
		}

		return $from;
	}

	#########################################################

	function get_joined_record($table, $id, $skip_permissions = false) {
		$sql_fields = get_sql_fields($table);
		$sql_from = get_sql_from($table, $skip_permissions);

		if(!$sql_fields || !$sql_from) return false;

		$pk = getPKFieldName($table);
		if(!$pk) return false;

		$safe_id = makeSafe($id, false);
		$sql = "SELECT {$sql_fields} FROM {$sql_from} AND `{$table}`.`{$pk}`='{$safe_id}'";
		$eo['silentErrors'] = true;
		$res = sql($sql, $eo);
		if($row = db_fetch_assoc($res)) return $row;

		return false;
	}

	#########################################################

	function get_defaults($table) {
		/* array of tables and their fields, with default values (or empty), excluding automatic values */
		$defaults = array(
			'main' => array(
				'id' => '',
				'main' => ''
			),
			'clients' => array(
				'matricule_client' => '',
				'date_inscription' => '1',
				'type' => '',
				'nom_prenom' => '',
				'nationalite' => '',
				'sexe' => '',
				'date_naissance' => '',
				'age' => '',
				'nni' => '',
				'fonction' => '',
				'passport' => '',
				'lieu' => '',
				'date_emis' => '',
				'date_exp' => '',
				'validite' => '',
				'adresse' => '',
				'telephone' => '',
				'email' => '',
				'banque' => '',
				'compte' => '',
				'carte_fidelite' => '',
				'numero_cf' => '',
				'total_entree' => '0',
				'total_sortie' => '0',
				'solde' => '0',
				'photo' => '',
				'signature' => '',
				'agence' => '',
				'dossier' => '',
				'urgence' => '',
				'observation' => ''
			),
			'gestionnaires' => array(
				'matricule_gestionnaire' => '',
				'date_recrutement' => '1',
				'nom_prenom' => '',
				'telephone' => '',
				'email' => '',
				'adresse' => '',
				'fonction' => '',
				'agence' => '',
				'photo' => '',
				'dossier' => '',
				'observation' => ''
			),
			'partenaires' => array(
				'matricule_partenaire' => '',
				'raison_sociale' => '',
				'contact' => '',
				'fonction' => '',
				'adresse' => '',
				'telephone' => '',
				'email' => '',
				'commission' => '',
				'banque' => '',
				'compte' => '',
				'observation' => ''
			),
			'paiements' => array(
				'idpaiement' => '',
				'code' => '',
				'matricule' => '',
				'nom_prenom' => '',
				'banque' => '',
				'compte' => '',
				'type_paiement' => '',
				'date_paiement' => '1',
				'num_facture' => '',
				'montant' => '',
				'beneficiaire' => '',
				'rs' => '',
				'banque_beneficiaire' => '',
				'compte_beneficiaire' => '',
				'statut' => 'En cours',
				'observation' => ''
			),
			'emetteurs' => array(
				'idemetteur' => '',
				'emetteur' => '',
				'adresse' => '',
				'email' => '',
				'telephone' => '',
				'observation' => ''
			),
			'bieleteries' => array(
				'idbieleterie' => '',
				'link_tarif' => '',
				'num_facture' => '',
				'date' => '1',
				'client' => '',
				'statut' => ''
			),
			'tarifs' => array(
				'idtarif' => '',
				'link_bieleterie' => '',
				'passager' => '',
				'parcours' => '',
				'compagnie' => '',
				'provenance' => '',
				'emetteur' => '',
				'pnr' => '',
				'numero' => '',
				'prix_achat' => '0',
				'commission' => '0',
				'frais_service' => '0',
				'total' => ''
			),
			'transferts_argent' => array(
				'idtransfert' => '',
				'num_facture' => '',
				'code_transaction' => '',
				'date' => '1',
				'emetteur' => '',
				'nni_emetteur' => '',
				'phone_emetteur' => '',
				'adresse_emetteur' => '',
				'beneficiaire' => '',
				'nni_beneficiaire' => '',
				'phone_beneficiaire' => '',
				'adresse_beneficiaire' => '',
				'prix_achat' => '0',
				'commission' => '0',
				'total' => '',
				'statut' => 'En cours',
				'observation' => ''
			),
			'colis' => array(
				'idcoli' => '',
				'num_facture' => '',
				'link_envoi_colis' => '',
				'code_transaction' => '',
				'date_envoi' => '1',
				'emetteur' => '',
				'phone_emetteur' => ''
			),
			'envois_colis' => array(
				'idenvois_coli' => '',
				'link_colis' => '',
				'description' => '',
				'destination' => '',
				'agence' => '',
				'ville' => '',
				'prix_unitaire' => '0',
				'qts' => '0',
				'prix_total' => '0',
				'beneficiaire' => '',
				'telephone_beneficiaire' => '',
				'nni_beneficiaire' => '',
				'date_reception' => '',
				'statut' => '',
				'observation' => ''
			),
			'parc_auto' => array(
				'idparc' => '',
				'type' => '',
				'marque' => '',
				'model' => '',
				'immatriculation' => '',
				'places' => '',
				'observation' => ''
			),
			'location_vh' => array(
				'idlocation' => '',
				'link_liste' => '',
				'num_facture' => '',
				'date_saisie' => '1',
				'client' => ''
			),
			'liste_location' => array(
				'idlocations' => '',
				'link_location' => '',
				'date_location' => '1',
				'date_fin_location' => '',
				'vehicule' => '',
				'model' => '',
				'type' => '',
				'prix_unitaire' => '0',
				'qts' => '0',
				'prix_total' => '',
				'observation' => ''
			),
			'fonctions' => array(
				'idfonction' => '',
				'fonction' => '',
				'observation' => ''
			),
			'agences' => array(
				'idagence' => '',
				'agence' => '',
				'adresse' => '',
				'ville' => '',
				'observation' => ''
			),
			'villes' => array(
				'idville' => '',
				'ville' => '',
				'observation' => ''
			),
			'banques' => array(
				'idbanque' => '',
				'banque' => '',
				'adresse' => '',
				'telephone' => '',
				'email' => '',
				'contact' => '',
				'observation' => ''
			),
			'type_paiements' => array(
				'idtype_payment' => '',
				'type_paiement' => '',
				'observation' => ''
			),
			'compagnies' => array(
				'idcompagnie' => '',
				'compagnie' => '',
				'observation' => ''
			),
			'statuts' => array(
				'idstatut' => '',
				'statut' => ''
			),
			'visas' => array(
				'idvisa' => '',
				'date_depot' => '1',
				'client' => '',
				'num_passport' => '',
				'type_visa' => '',
				'emetteur' => '',
				'prix_achat' => '0',
				'commission' => '0',
				'total' => '',
				'statut' => 'En cours',
				'dossier' => '',
				'obs' => ''
			),
			'oumras' => array(
				'idoumra' => '',
				'date' => '1',
				'client' => '',
				'adresse' => '',
				'passeport' => '',
				'date_depart' => '',
				'date_retour' => '',
				'compagnie' => '',
				'billet' => '',
				'programme' => '',
				'debut_visa' => '',
				'fin_visa' => '',
				'duree_visa' => '',
				'statut' => 'En cours',
				'dossier' => '',
				'obs' => ''
			),
			'assurances' => array(
				'idassurance' => '',
				'date' => '1',
				'nom_prenom' => '',
				'intermediare' => '',
				'pays_residence' => '',
				'adresse' => '',
				'telephone' => '',
				'email' => '',
				'destination' => '',
				'formule' => '',
				'certificat' => '',
				'date_depart' => '',
				'date_retour' => '',
				'passport' => '',
				'beneficiaire' => '',
				'nom_prenomb' => '',
				'date_de_naissance' => '',
				'dossier_pdf' => '',
				'dossier_zippe' => '',
				'statut' => 'En cours',
				'questionnaire_medical' => '',
				'question1' => '',
				'question2' => '',
				'question2a' => '',
				'question3' => '',
				'question4' => '',
				'question5' => '',
				'prime_total' => ''
			),
			'type_visas' => array(
				'idtype_visa' => '',
				'type_visa' => ''
			),
			'facture' => array(
				'idfacture' => '',
				'num_facture' => '',
				'type' => '',
				'date' => '1',
				'client' => '',
				'societe' => '',
				'travaux' => '',
				'statut' => 'En cours'
			),
			'detail_facture' => array(
				'dfid' => '',
				'factureid' => '',
				'designation' => '',
				'quantite' => '1',
				'prixunitaire' => '0',
				'total' => ''
			),
			'recettes' => array(
				'idrecette' => '',
				'date' => '1',
				'num_piece' => '',
				'agence' => '',
				'service' => '',
				'nature' => '',
				'montant' => '0',
				'obs' => ''
			),
			'depenses' => array(
				'iddepense' => '',
				'date' => '1',
				'nature' => '',
				'justificatif' => '',
				'agence' => '',
				'service' => '',
				'banque' => '',
				'montant' => '0',
				'compte' => '',
				'obs' => ''
			),
			'caisse' => array(
				'idcaisse' => '',
				'link_recettes' => '',
				'link_depenses' => '',
				'date' => '1',
				'recettes' => '',
				'depenses' => '',
				'caisse' => '',
				'obs' => ''
			),
			'tresorerie_caisse' => array(
				'idtresorerie_caisse' => '',
				'date' => '1',
				'journee_du' => '',
				'link_in' => ''
			),
			'tresorerie_items' => array(
				'idtresorerie_item' => '',
				'link_out' => '',
				'justificatif' => '',
				'libelles' => '',
				'montant' => '0',
				'commission_agence' => '',
				'net_compagnie' => '',
				'observations' => ''
			),
			'piece_reglements' => array(
				'idpiece' => '',
				'date' => '1',
				'beneficiaire' => '',
				'operation' => '',
				'montant' => '0',
				'banque' => '',
				'compte' => '',
				'num_cheque' => '',
				'date_cheque' => '',
				'imputation' => '',
				'statut' => 'En cours',
				'observations' => ''
			),
			'autorisation_change' => array(
				'idautorisation' => '',
				'date' => '1',
				'nom_prenom' => '',
				'nationalite' => '',
				'profession' => '',
				'adresse' => '',
				'num_compte' => '',
				'nature_operation' => '',
				'piece_justificative' => '',
				'nature_devises' => '',
				'montant_chiffre' => '0',
				'cours' => '0',
				'montant_fois_cours' => '',
				'commission' => '0',
				'contre_valeur' => '0',
				'total' => '',
				'statut' => 'En cours'
			),
			'bon_passage' => array(
				'idbon' => '',
				'date' => '1',
				'pnr' => '',
				'nous_prions' => '',
				'au_nom_de' => '',
				'parcours' => '',
				'depart' => '',
				'retour' => '',
				'total_ht' => '0',
				'commissions' => '0',
				'total_ttc' => '',
				'frais_pta' => '',
				'net_payer' => '',
				'num_billet' => '',
				'statut' => 'En cours',
				'observations' => ''
			),
			'fiches_changes' => array(
				'idfichechange' => '',
				'date' => '1',
				'journee_du' => '',
				'link_in' => '',
				'statut' => 'En cours'
			),
			'fiches_changes_items' => array(
				'idfiche_change_item' => '',
				'link_out' => '',
				'nom_prenom' => '',
				'num_identite' => '',
				'montant' => '0',
				'devises' => '',
				'achats' => '0',
				'ventes' => '0',
				'observations' => ''
			),
			'caisse_journaliere' => array(
				'idcaisse_journaliere' => '',
				'date' => '1',
				'link_in' => ''
			),
			'item_caisse_journaliere' => array(
				'link_out' => '',
				'iditem_caisse_journaliere' => '',
				'justificatif' => '',
				'nom_prenom' => '',
				'destination' => '',
				'compagnie' => '',
				'prix_ht' => '0',
				'commission' => '0',
				'prix_ttc' => '0',
				'observations' => ''
			),
			'models' => array(
				'idmodel' => '',
				'marque' => '',
				'model' => ''
			),
			'natures' => array(
				'idnature' => '',
				'nature' => '',
				'obs' => ''
			),
			'services' => array(
				'idservice' => '',
				'service' => '',
				'obs' => ''
			),
			'liens' => array(
				'id' => '',
				'logo' => '',
				'nom' => '',
				'lien' => ''
			),
			'types_client' => array(
				'idtype_client' => '',
				'type_client' => '',
				'obs' => ''
			),
			'cartes_fidelite' => array(
				'idcartecf' => '',
				'carte_fidelite' => '',
				'obs' => ''
			),
			'designations' => array(
				'iddesignation' => '',
				'designation' => '',
				'obs' => ''
			),
			'parcours' => array(
				'idparcour' => '',
				'parcour' => '',
				'obs' => ''
			),
			'pays' => array(
				'idpays' => '',
				'pays' => '',
				'obs' => ''
			),
			'provenance' => array(
				'idprovenance' => '',
				'provenance' => '',
				'obs' => ''
			),
			'programmes' => array(
				'idprogramme' => '',
				'programme' => '',
				'obs' => ''
			),
			'justificatifs' => array(
				'idjustificatif' => '',
				'justificatif' => '',
				'obs' => ''
			),
			'devise' => array(
				'iddevise' => '',
				'devise' => ''
			),
			'intermediares' => array(
				'idintermediaire' => '',
				'intermediare' => '',
				'obs' => ''
			),
			'formule' => array(
				'idformule' => '',
				'formule' => '',
				'obs' => ''
			),
			'operations' => array(
				'idoperation' => '',
				'operation' => ''
			),
			'pointages' => array(
				'idpointage' => '',
				'date' => '1',
				'nom_prenom' => '',
				'agence' => '',
				'fonction' => '',
				'arrivee' => '',
				'depart' => '',
				'obs' => ''
			),
			'fichiers_partages' => array(
				'idfichier_partage' => '',
				'date' => '1',
				'agent' => '',
				'agence' => '',
				'service' => '',
				'nom_du_fichier' => '',
				'pdf' => '',
				'word' => '',
				'excel' => '',
				'powerpoint' => '',
				'compresse' => '',
				'note' => ''
			),
			'note_de_service' => array(
				'idnote_service' => '',
				'date' => '1',
				'agence' => '',
				'service' => '',
				'objet' => '',
				'texte' => '',
				'ampliation' => ''
			)
		);

		return isset($defaults[$table]) ? $defaults[$table] : array();
	}

	#########################################################

	function logInMember() {
		$redir = 'index.php';
		if($_POST['signIn'] != '') {
			if($_POST['username'] != '' && $_POST['password'] != '') {
				$username = makeSafe(strtolower($_POST['username']));
				$hash = sqlValue("select passMD5 from membership_users where lcase(memberID)='{$username}' and isApproved=1 and isBanned=0");
				$password = $_POST['password'];

				if(password_match($password, $hash)) {
					$_SESSION['memberID'] = $username;
					$_SESSION['memberGroupID'] = sqlValue("SELECT `groupID` FROM `membership_users` WHERE LCASE(`memberID`)='{$username}'");

					if($_POST['rememberMe'] == 1) {
						RememberMe::login($username);
					}else{
						RememberMe::delete();
					}

					// harden user's password hash
					password_harden($username, $password, $hash);

					// hook: login_ok
					if(function_exists('login_ok')) {
						$args=array();
						if(!$redir=login_ok(getMemberInfo(), $args)) {
							$redir='index.php';
						}
					}

					redirect($redir);
					exit;
				}
			}

			// hook: login_failed
			if(function_exists('login_failed')) {
				$args=array();
				login_failed(array(
					'username' => $_POST['username'],
					'password' => $_POST['password'],
					'IP' => $_SERVER['REMOTE_ADDR']
					), $args);
			}

			if(!headers_sent()) header('HTTP/1.0 403 Forbidden');
			redirect("index.php?loginFailed=1");
			exit;
		}

		/* do we have a JWT auth header? */
		jwt_check_login();

		if(!empty($_SESSION['memberID']) && !empty($_SESSION['memberGroupID'])) return;

		/* check if a rememberMe cookie exists and sign in user if so */
		if(RememberMe::check()) {
			$username = makeSafe(strtolower(RememberMe::user()));
			$_SESSION['memberID'] = $username;
			$_SESSION['memberGroupID'] = sqlValue("SELECT `groupID` FROM `membership_users` WHERE LCASE(`memberID`)='{$username}'");
		}
	}

	#########################################################

	function htmlUserBar() {
		global $adminConfig, $Translation;
		if(!defined('PREPEND_PATH')) define('PREPEND_PATH', '');

		ob_start();
		$home_page = (basename($_SERVER['PHP_SELF'])=='index.php' ? true : false);

		?>
		<nav class="navbar navbar-default navbar-fixed-top hidden-print" role="navigation">
			<div class="navbar-header">
				<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
					<span class="sr-only">Toggle navigation</span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
				</button>
				<!-- application title is obtained from the name besides the yellow database icon in AppGini, use underscores for spaces -->
				<a class="navbar-brand" href="<?php echo PREPEND_PATH; ?>index.php"><i class="glyphicon glyphicon-home"></i> MAREGA VOYAGES</a>
			</div>
			<div class="collapse navbar-collapse">
				<ul class="nav navbar-nav">
					<?php if(!$home_page) { ?>
						<?php echo NavMenus(); ?>
					<?php } ?>
				</ul>

				<?php if(getLoggedAdmin()) { ?>
					<ul class="nav navbar-nav">
						<a href="<?php echo PREPEND_PATH; ?>admin/pageHome.php" class="btn btn-danger navbar-btn hidden-xs" title="<?php echo html_attr($Translation['admin area']); ?>"><i class="glyphicon glyphicon-cog"></i> <?php echo $Translation['admin area']; ?></a>
						<a href="<?php echo PREPEND_PATH; ?>admin/pageHome.php" class="btn btn-danger navbar-btn visible-xs btn-lg" title="<?php echo html_attr($Translation['admin area']); ?>"><i class="glyphicon glyphicon-cog"></i> <?php echo $Translation['admin area']; ?></a>
					</ul>
				<?php } ?>

				<?php if(!$_GET['signIn'] && !$_GET['loginFailed']) { ?>
					<?php if(getLoggedMemberID() == $adminConfig['anonymousMember']) { ?>
						<p class="navbar-text navbar-right">&nbsp;</p>
						<a href="<?php echo PREPEND_PATH; ?>index.php?signIn=1" class="btn btn-success navbar-btn navbar-right"><?php echo $Translation['sign in']; ?></a>
						<p class="navbar-text navbar-right">
							<?php echo $Translation['not signed in']; ?>
						</p>
					<?php }else{ ?>
						<ul class="nav navbar-nav navbar-right hidden-xs" style="min-width: 330px;">
							<a class="btn navbar-btn btn-default" href="<?php echo PREPEND_PATH; ?>index.php?signOut=1"><i class="glyphicon glyphicon-log-out"></i> <?php echo $Translation['sign out']; ?></a>
							<p class="navbar-text">
								<?php echo $Translation['signed as']; ?> <strong><a href="<?php echo PREPEND_PATH; ?>membership_profile.php" class="navbar-link"><?php echo getLoggedMemberID(); ?></a></strong>
							</p>
						</ul>
						<ul class="nav navbar-nav visible-xs">
							<a class="btn navbar-btn btn-default btn-lg visible-xs" href="<?php echo PREPEND_PATH; ?>index.php?signOut=1"><i class="glyphicon glyphicon-log-out"></i> <?php echo $Translation['sign out']; ?></a>
							<p class="navbar-text text-center">
								<?php echo $Translation['signed as']; ?> <strong><a href="<?php echo PREPEND_PATH; ?>membership_profile.php" class="navbar-link"><?php echo getLoggedMemberID(); ?></a></strong>
							</p>
						</ul>
						<script>
							/* periodically check if user is still signed in */
							setInterval(function() {
								$j.ajax({
									url: '<?php echo PREPEND_PATH; ?>ajax_check_login.php',
									success: function(username) {
										if(!username.length) window.location = '<?php echo PREPEND_PATH; ?>index.php?signIn=1';
									}
								});
							}, 60000);
						</script>
					<?php } ?>
				<?php } ?>
			</div>
		</nav>
		<?php

		$html = ob_get_contents();
		ob_end_clean();

		return $html;
	}

	#########################################################

	function showNotifications($msg = '', $class = '', $fadeout = true) {
		global $Translation;

		$notify_template_no_fadeout = '<div id="%%ID%%" class="alert alert-dismissable %%CLASS%%" style="display: none; padding-top: 6px; padding-bottom: 6px;">' .
					'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' .
					'%%MSG%%</div>' .
					'<script> jQuery(function() { /* */ jQuery("#%%ID%%").show("slow"); }); </script>'."\n";
		$notify_template = '<div id="%%ID%%" class="alert %%CLASS%%" style="display: none; padding-top: 6px; padding-bottom: 6px;">%%MSG%%</div>' .
					'<script>' .
						'jQuery(function() {' .
							'jQuery("#%%ID%%").show("slow", function() {' .
								'setTimeout(function() { /* */ jQuery("#%%ID%%").hide("slow"); }, 4000);' .
							'});' .
						'});' .
					'</script>'."\n";

		if(!$msg) { // if no msg, use url to detect message to display
			if($_REQUEST['record-added-ok'] != '') {
				$msg = $Translation['new record saved'];
				$class = 'alert-success';
			}elseif($_REQUEST['record-added-error'] != '') {
				$msg = $Translation['Couldn\'t save the new record'];
				$class = 'alert-danger';
				$fadeout = false;
			}elseif($_REQUEST['record-updated-ok'] != '') {
				$msg = $Translation['record updated'];
				$class = 'alert-success';
			}elseif($_REQUEST['record-updated-error'] != '') {
				$msg = $Translation['Couldn\'t save changes to the record'];
				$class = 'alert-danger';
				$fadeout = false;
			}elseif($_REQUEST['record-deleted-ok'] != '') {
				$msg = $Translation['The record has been deleted successfully'];
				$class = 'alert-success';
				$fadeout = false;
			}elseif($_REQUEST['record-deleted-error'] != '') {
				$msg = $Translation['Couldn\'t delete this record'];
				$class = 'alert-danger';
				$fadeout = false;
			}else{
				return '';
			}
		}
		$id = 'notification-' . rand();

		$out = ($fadeout ? $notify_template : $notify_template_no_fadeout);
		$out = str_replace('%%ID%%', $id, $out);
		$out = str_replace('%%MSG%%', $msg, $out);
		$out = str_replace('%%CLASS%%', $class, $out);

		return $out;
	}

	#########################################################

	function parseMySQLDate($date, $altDate) {
		// is $date valid?
		if(preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/", trim($date))) {
			return trim($date);
		}

		if($date != '--' && preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/", trim($altDate))) {
			return trim($altDate);
		}

		if($date != '--' && $altDate && intval($altDate)==$altDate) {
			return @date('Y-m-d', @time() + ($altDate >= 1 ? $altDate - 1 : $altDate) * 86400);
		}

		return '';
	}

	#########################################################

	function parseCode($code, $isInsert=true, $rawData=false) {
		if($isInsert) {
			$arrCodes=array(
				'<%%creatorusername%%>' => $_SESSION['memberID'],
				'<%%creatorgroupid%%>' => $_SESSION['memberGroupID'],
				'<%%creatorip%%>' => $_SERVER['REMOTE_ADDR'],
				'<%%creatorgroup%%>' => sqlValue("select name from membership_groups where groupID='{$_SESSION['memberGroupID']}'"),

				'<%%creationdate%%>' => ($rawData ? @date('Y-m-d') : @date('j/n/Y')),
				'<%%creationtime%%>' => ($rawData ? @date('H:i:s') : @date('h:i:s a')),
				'<%%creationdatetime%%>' => ($rawData ? @date('Y-m-d H:i:s') : @date('j/n/Y h:i:s a')),
				'<%%creationtimestamp%%>' => ($rawData ? @date('Y-m-d H:i:s') : @time())
			);
		}else{
			$arrCodes=array(
				'<%%editorusername%%>' => $_SESSION['memberID'],
				'<%%editorgroupid%%>' => $_SESSION['memberGroupID'],
				'<%%editorip%%>' => $_SERVER['REMOTE_ADDR'],
				'<%%editorgroup%%>' => sqlValue("select name from membership_groups where groupID='{$_SESSION['memberGroupID']}'"),

				'<%%editingdate%%>' => ($rawData ? @date('Y-m-d') : @date('j/n/Y')),
				'<%%editingtime%%>' => ($rawData ? @date('H:i:s') : @date('h:i:s a')),
				'<%%editingdatetime%%>' => ($rawData ? @date('Y-m-d H:i:s') : @date('j/n/Y h:i:s a')),
				'<%%editingtimestamp%%>' => ($rawData ? @date('Y-m-d H:i:s') : @time())
			);
		}

		$pc=str_ireplace(array_keys($arrCodes), array_values($arrCodes), $code);

		return $pc;
	}

	#########################################################

	function addFilter($index, $filterAnd, $filterField, $filterOperator, $filterValue) {
		// validate input
		if($index < 1 || $index > 80 || !is_int($index)) return false;
		if($filterAnd != 'or')   $filterAnd = 'and';
		$filterField = intval($filterField);

		/* backward compatibility */
		if(in_array($filterOperator, $GLOBALS['filter_operators'])) {
			$filterOperator = array_search($filterOperator, $GLOBALS['filter_operators']);
		}

		if(!in_array($filterOperator, array_keys($GLOBALS['filter_operators']))) {
			$filterOperator = 'like';
		}

		if(!$filterField) {
			$filterOperator = '';
			$filterValue = '';
		}

		$_REQUEST['FilterAnd'][$index] = $filterAnd;
		$_REQUEST['FilterField'][$index] = $filterField;
		$_REQUEST['FilterOperator'][$index] = $filterOperator;
		$_REQUEST['FilterValue'][$index] = $filterValue;

		return true;
	}

	#########################################################

	function clearFilters() {
		for($i=1; $i<=80; $i++) {
			addFilter($i, '', 0, '', '');
		}
	}

	#########################################################

	if(!function_exists('str_ireplace')) {
		function str_ireplace($search, $replace, $subject) {
			$ret=$subject;
			if(is_array($search)) {
				for($i=0; $i<count($search); $i++) {
					$ret=str_ireplace($search[$i], $replace[$i], $ret);
				}
			}else{
				$ret=preg_replace('/'.preg_quote($search, '/').'/i', $replace, $ret);
			}

			return $ret;
		} 
	} 

	#########################################################

	/**
	* Loads a given view from the templates folder, passing the given data to it
	* @param $view the name of a php file (without extension) to be loaded from the 'templates' folder
	* @param $the_data_to_pass_to_the_view (optional) associative array containing the data to pass to the view
	* @return the output of the parsed view as a string
	*/
	function loadView($view, $the_data_to_pass_to_the_view=false) {
		global $Translation;

		$view = dirname(__FILE__)."/templates/$view.php";
		if(!is_file($view)) return false;

		if(is_array($the_data_to_pass_to_the_view)) {
			foreach($the_data_to_pass_to_the_view as $k => $v)
				$$k = $v;
		}
		unset($the_data_to_pass_to_the_view, $k, $v);

		ob_start();
		@include($view);
		$out=ob_get_contents();
		ob_end_clean();

		return $out;
	}

	#########################################################

	/**
	* Loads a table template from the templates folder, passing the given data to it
	* @param $table_name the name of the table whose template is to be loaded from the 'templates' folder
	* @param $the_data_to_pass_to_the_table associative array containing the data to pass to the table template
	* @return the output of the parsed table template as a string
	*/
	function loadTable($table_name, $the_data_to_pass_to_the_table = array()) {
		$dont_load_header = $the_data_to_pass_to_the_table['dont_load_header'];
		$dont_load_footer = $the_data_to_pass_to_the_table['dont_load_footer'];

		$header = $table = $footer = '';

		if(!$dont_load_header) {
			// try to load tablename-header
			if(!($header = loadView("{$table_name}-header", $the_data_to_pass_to_the_table))) {
				$header = loadView('table-common-header', $the_data_to_pass_to_the_table);
			}
		}

		$table = loadView($table_name, $the_data_to_pass_to_the_table);

		if(!$dont_load_footer) {
			// try to load tablename-footer
			if(!($footer = loadView("{$table_name}-footer", $the_data_to_pass_to_the_table))) {
				$footer = loadView('table-common-footer', $the_data_to_pass_to_the_table);
			}
		}

		return "{$header}{$table}{$footer}";
	}

	#########################################################

	function filterDropdownBy($filterable, $filterers, $parentFilterers, $parentPKField, $parentCaption, $parentTable, &$filterableCombo) {
		$filterersArray = explode(',', $filterers);
		$parentFilterersArray = explode(',', $parentFilterers);
		$parentFiltererList = '`' . implode('`, `', $parentFilterersArray) . '`';
		$res=sql("SELECT `$parentPKField`, $parentCaption, $parentFiltererList FROM `$parentTable` ORDER BY 2", $eo);
		$filterableData = array();
		while($row=db_fetch_row($res)) {
			$filterableData[$row[0]] = $row[1];
			$filtererIndex = 0;
			foreach($filterersArray as $filterer) {
				$filterableDataByFilterer[$filterer][$row[$filtererIndex + 2]][$row[0]] = $row[1];
				$filtererIndex++;
			}
			$row[0] = addslashes($row[0]);
			$row[1] = addslashes($row[1]);
			$jsonFilterableData .= "\"{$row[0]}\":\"{$row[1]}\",";
		}
		$jsonFilterableData .= '}';
		$jsonFilterableData = '{'.str_replace(',}', '}', $jsonFilterableData);     
		$filterJS = "\nvar {$filterable}_data = $jsonFilterableData;";

		foreach($filterersArray as $filterer) {
			if(is_array($filterableDataByFilterer[$filterer])) foreach($filterableDataByFilterer[$filterer] as $filtererItem => $filterableItem) {
				$jsonFilterableDataByFilterer[$filterer] .= '"'.addslashes($filtererItem).'":{';
				foreach($filterableItem as $filterableItemID => $filterableItemData) {
					$jsonFilterableDataByFilterer[$filterer] .= '"'.addslashes($filterableItemID).'":"'.addslashes($filterableItemData).'",';
				}
				$jsonFilterableDataByFilterer[$filterer] .= '},';
			}
			$jsonFilterableDataByFilterer[$filterer] .= '}';
			$jsonFilterableDataByFilterer[$filterer] = '{'.str_replace(',}', '}', $jsonFilterableDataByFilterer[$filterer]);

			$filterJS.="\n\n// code for filtering {$filterable} by {$filterer}\n";
			$filterJS.="\nvar {$filterable}_data_by_{$filterer} = {$jsonFilterableDataByFilterer[$filterer]}; ";
			$filterJS.="\nvar selected_{$filterable} = \$j('#{$filterable}').val();";
			$filterJS.="\nvar {$filterable}_change_by_{$filterer} = function() {";
			$filterJS.="\n\t$('{$filterable}').options.length=0;";
			$filterJS.="\n\t$('{$filterable}').options[0] = new Option();";
			$filterJS.="\n\tif(\$j('#{$filterer}').val()) {";
			$filterJS.="\n\t\tfor({$filterable}_item in {$filterable}_data_by_{$filterer}[\$j('#{$filterer}').val()]) {";
			$filterJS.="\n\t\t\t$('{$filterable}').options[$('{$filterable}').options.length] = new Option(";
			$filterJS.="\n\t\t\t\t{$filterable}_data_by_{$filterer}[\$j('#{$filterer}').val()][{$filterable}_item],";
			$filterJS.="\n\t\t\t\t{$filterable}_item,";
			$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false),";
			$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false)";
			$filterJS.="\n\t\t\t);";
			$filterJS.="\n\t\t}";
			$filterJS.="\n\t}else{";
			$filterJS.="\n\t\tfor({$filterable}_item in {$filterable}_data) {";
			$filterJS.="\n\t\t\t$('{$filterable}').options[$('{$filterable}').options.length] = new Option(";
			$filterJS.="\n\t\t\t\t{$filterable}_data[{$filterable}_item],";
			$filterJS.="\n\t\t\t\t{$filterable}_item,";
			$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false),";
			$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false)";
			$filterJS.="\n\t\t\t);";
			$filterJS.="\n\t\t}";
			$filterJS.="\n\t\tif(selected_{$filterable} && selected_{$filterable} == \$j('#{$filterable}').val()) {";
			$filterJS.="\n\t\t\tfor({$filterer}_item in {$filterable}_data_by_{$filterer}) {";
			$filterJS.="\n\t\t\t\tfor({$filterable}_item in {$filterable}_data_by_{$filterer}[{$filterer}_item]) {";
			$filterJS.="\n\t\t\t\t\tif({$filterable}_item == selected_{$filterable}) {";
			$filterJS.="\n\t\t\t\t\t\t$('{$filterer}').value = {$filterer}_item;";
			$filterJS.="\n\t\t\t\t\t\tbreak;";
			$filterJS.="\n\t\t\t\t\t}";
			$filterJS.="\n\t\t\t\t}";
			$filterJS.="\n\t\t\t\tif({$filterable}_item == selected_{$filterable}) break;";
			$filterJS.="\n\t\t\t}";
			$filterJS.="\n\t\t}";
			$filterJS.="\n\t}";
			$filterJS.="\n\t$('{$filterable}').highlight();";
			$filterJS.="\n};";
			$filterJS.="\n$('{$filterer}').observe('change', function() { /* */ window.setTimeout({$filterable}_change_by_{$filterer}, 25); });";
			$filterJS.="\n";
		}

		$filterableCombo = new Combo;
		$filterableCombo->ListType = 0;
		$filterableCombo->ListItem = array_slice(array_values($filterableData), 0, 10);
		$filterableCombo->ListData = array_slice(array_keys($filterableData), 0, 10);
		$filterableCombo->SelectName = $filterable;
		$filterableCombo->AllowNull = true;

		return $filterJS;
	}

	#########################################################
	function br2nl($text) {
		return  preg_replace('/\<br(\s*)?\/?\>/i', "\n", $text);
	}

	#########################################################

	if(!function_exists('htmlspecialchars_decode')) {
		function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT) {
			return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
		}
	}

	#########################################################

	function entitiesToUTF8($input) {
		return preg_replace_callback('/(&#[0-9]+;)/', '_toUTF8', $input);
	}

	function _toUTF8($m) {
		if(function_exists('mb_convert_encoding')) {
			return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
		}else{
			return $m[1];
		}
	}

	#########################################################

	function func_get_args_byref() {
		if(!function_exists('debug_backtrace')) return false;

		$trace = debug_backtrace();
		return $trace[1]['args'];
	}

	#########################################################

	function permissions_sql($table, $level = 'all') {
		if(!in_array($level, array('user', 'group'))) { $level = 'all'; }
		$perm = getTablePermissions($table);
		$from = '';
		$where = '';
		$pk = getPKFieldName($table);

		if($perm[2] == 1 || ($perm[2] > 1 && $level == 'user')) { // view owner only
			$from = 'membership_userrecords';
			$where = "(`$table`.`$pk`=membership_userrecords.pkValue and membership_userrecords.tableName='$table' and lcase(membership_userrecords.memberID)='".getLoggedMemberID()."')";
		}elseif($perm[2] == 2 || ($perm[2] > 2 && $level == 'group')) { // view group only
			$from = 'membership_userrecords';
			$where = "(`$table`.`$pk`=membership_userrecords.pkValue and membership_userrecords.tableName='$table' and membership_userrecords.groupID='".getLoggedGroupID()."')";
		}elseif($perm[2] == 3) { // view all
			// no further action
		}elseif($perm[2] == 0) { // view none
			return false;
		}

		return array('where' => $where, 'from' => $from, 0 => $where, 1 => $from);
	}

	#########################################################

	function error_message($msg, $back_url = '', $full_page = true) {
		$curr_dir = dirname(__FILE__);
		global $Translation;

		ob_start();

		if($full_page) include_once($curr_dir . '/header.php');

		echo '<div class="panel panel-danger">';
			echo '<div class="panel-heading"><h3 class="panel-title">' . $Translation['error:'] . '</h3></div>';
			echo '<div class="panel-body"><p class="text-danger">' . $msg . '</p>';
			if($back_url !== false) { // explicitly passing false suppresses the back link completely
				echo '<div class="text-center">';
				if($back_url) {
					echo '<a href="' . $back_url . '" class="btn btn-danger btn-lg vspacer-lg"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['< back'] . '</a>';
				}else{
					echo '<a href="#" class="btn btn-danger btn-lg vspacer-lg" onclick="history.go(-1); return false;"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['< back'] . '</a>';
				}
				echo '</div>';
			}
			echo '</div>';
		echo '</div>';

		if($full_page) include_once($curr_dir . '/footer.php');

		$out = ob_get_contents();
		ob_end_clean();

		return $out;
	}

	#########################################################

	function toMySQLDate($formattedDate, $sep = datalist_date_separator, $ord = datalist_date_format) {
		// extract date elements
		$de=explode($sep, $formattedDate);
		$mySQLDate=intval($de[strpos($ord, 'Y')]).'-'.intval($de[strpos($ord, 'm')]).'-'.intval($de[strpos($ord, 'd')]);
		return $mySQLDate;
	}

	#########################################################

	function reIndex(&$arr) {
		$i=1;
		foreach($arr as $n=>$v) {
			$arr2[$i]=$n;
			$i++;
		}
		return $arr2;
	}

	#########################################################

	function get_embed($provider, $url, $max_width = '', $max_height = '', $retrieve = 'html') {
		global $Translation;
		if(!$url) return '';

		$providers = array(
			'youtube' => array('oembed' => 'http://www.youtube.com/oembed?'),
			'googlemap' => array('oembed' => '', 'regex' => '/^http.*\.google\..*maps/i')
		);

		if(!isset($providers[$provider])) {
			return '<div class="text-danger">' . $Translation['invalid provider'] . '</div>';
		}

		if(isset($providers[$provider]['regex']) && !preg_match($providers[$provider]['regex'], $url)) {
			return '<div class="text-danger">' . $Translation['invalid url'] . '</div>';
		}

		if($providers[$provider]['oembed']) {
			$oembed = $providers[$provider]['oembed'] . 'url=' . urlencode($url) . "&maxwidth={$max_width}&maxheight={$max_height}&format=json";
			$data_json = request_cache($oembed);

			$data = json_decode($data_json, true);
			if($data === null) {
				/* an error was returned rather than a json string */
				if($retrieve == 'html') return "<div class=\"text-danger\">{$data_json}\n<!-- {$oembed} --></div>";
				return '';
			}

			return (isset($data[$retrieve]) ? $data[$retrieve] : $data['html']);
		}

		/* special cases (where there is no oEmbed provider) */
		if($provider == 'googlemap') return get_embed_googlemap($url, $max_width, $max_height, $retrieve);

		return '<div class="text-danger">Invalid provider!</div>';
	}

	#########################################################

	function get_embed_googlemap($url, $max_width = '', $max_height = '', $retrieve = 'html') {
		global $Translation;
		$url_parts = parse_url($url);
		$coords_regex = '/-?\d+(\.\d+)?[,+]-?\d+(\.\d+)?(,\d{1,2}z)?/'; /* https://stackoverflow.com/questions/2660201 */

		if(preg_match($coords_regex, $url_parts['path'] . '?' . $url_parts['query'], $m)) {
			list($lat, $long, $zoom) = explode(',', $m[0]);
			$zoom = intval($zoom);
			if(!$zoom) $zoom = 10; /* default zoom */
			if(!$max_height) $max_height = 360;
			if(!$max_width) $max_width = 480;

			$api_key = '';
			$embed_url = "https://www.google.com/maps/embed/v1/view?key={$api_key}&center={$lat},{$long}&zoom={$zoom}&maptype=roadmap";
			$thumbnail_url = "https://maps.googleapis.com/maps/api/staticmap?key={$api_key}&center={$lat},{$long}&zoom={$zoom}&maptype=roadmap&size={$max_width}x{$max_height}";

			if($retrieve == 'html') {
				return "<iframe width=\"{$max_width}\" height=\"{$max_height}\" frameborder=\"0\" style=\"border:0\" src=\"{$embed_url}\"></iframe>";
			}else{
				return $thumbnail_url;
			}
		}else{
			return '<div class="text-danger">' . $Translation['cant retrieve coordinates from url'] . '</div>';
		}
	}

	#########################################################

	function request_cache($request, $force_fetch = false) {
		$max_cache_lifetime = 7 * 86400; /* max cache lifetime in seconds before refreshing from source */

		/* membership_cache table exists? if not, create it */
		static $cache_table_exists = false;
		if(!$cache_table_exists && !$force_fetch) {
			$te = sqlValue("show tables like 'membership_cache'");
			if(!$te) {
				if(!sql("CREATE TABLE `membership_cache` (`request` VARCHAR(100) NOT NULL, `request_ts` INT, `response` TEXT NOT NULL, PRIMARY KEY (`request`))", $eo)) {
					/* table can't be created, so force fetching request */
					return request_cache($request, true);
				}
			}
			$cache_table_exists = true;
		}

		/* retrieve response from cache if exists */
		if(!$force_fetch) {
			$res = sql("select response, request_ts from membership_cache where request='" . md5($request) . "'", $eo);
			if(!$row = db_fetch_array($res)) return request_cache($request, true);

			$response = $row[0];
			$response_ts = $row[1];
			if($response_ts < time() - $max_cache_lifetime) return request_cache($request, true);
		}

		/* if no response in cache, issue a request */
		if(!$response || $force_fetch) {
			$response = @file_get_contents($request);
			if($response === false) {
				$error = error_get_last();
				$error_message = preg_replace('/.*: (.*)/', '$1', $error['message']);
				return $error_message;
			}elseif($cache_table_exists) {
				/* store response in cache */
				$ts = time();
				sql("replace into membership_cache set request='" . md5($request) . "', request_ts='{$ts}', response='" . makeSafe($response, false) . "'", $eo);
			}
		}

		return $response;
	}

	#########################################################

	function check_record_permission($table, $id, $perm = 'view') {
		if($perm != 'edit' && $perm != 'delete') $perm = 'view';

		$perms = getTablePermissions($table);
		if(!$perms[$perm]) return false;

		$safe_id = makeSafe($id);
		$safe_table = makeSafe($table);

		if($perms[$perm] == 1) { // own records only
			$username = getLoggedMemberID();
			$owner = sqlValue("select memberID from membership_userrecords where tableName='{$safe_table}' and pkValue='{$safe_id}'");
			if($owner == $username) return true;
		}elseif($perms[$perm] == 2) { // group records
			$group_id = getLoggedGroupID();
			$owner_group_id = sqlValue("select groupID from membership_userrecords where tableName='{$safe_table}' and pkValue='{$safe_id}'");
			if($owner_group_id == $group_id) return true;
		}elseif($perms[$perm] == 3) { // all records
			return true;
		}

		return false;
	}

	#########################################################

	function NavMenus($options = array()) {
		if(!defined('PREPEND_PATH')) define('PREPEND_PATH', '');
		global $Translation;
		$prepend_path = PREPEND_PATH;

		/* default options */
		if(empty($options)) {
			$options = array(
				'tabs' => 7
			);
		}

		$table_group_name = array_keys(get_table_groups()); /* 0 => group1, 1 => group2 .. */
		/* if only one group named 'None', set to translation of 'select a table' */
		if((count($table_group_name) == 1 && $table_group_name[0] == 'None') || count($table_group_name) < 1) $table_group_name[0] = $Translation['select a table'];
		$table_group_index = array_flip($table_group_name); /* group1 => 0, group2 => 1 .. */
		$menu = array_fill(0, count($table_group_name), '');

		$t = time();
		$arrTables = getTableList();
		if(is_array($arrTables)) {
			foreach($arrTables as $tn => $tc) {
				/* ---- list of tables where hide link in nav menu is set ---- */
				$tChkHL = array_search($tn, array('main','transferts_argent','colis','envois_colis','parc_auto','location_vh','liste_location'));

				/* ---- list of tables where filter first is set ---- */
				$tChkFF = array_search($tn, array());
				if($tChkFF !== false && $tChkFF !== null) {
					$searchFirst = '&Filter_x=1';
				}else{
					$searchFirst = '';
				}

				/* when no groups defined, $table_group_index['None'] is NULL, so $menu_index is still set to 0 */
				$menu_index = intval($table_group_index[$tc[3]]);
				if(!$tChkHL && $tChkHL !== 0) $menu[$menu_index] .= "<li><a href=\"{$prepend_path}{$tn}_view.php?t={$t}{$searchFirst}\"><img src=\"{$prepend_path}" . ($tc[2] ? $tc[2] : 'blank.gif') . "\" height=\"32\"> {$tc[0]}</a></li>";
			}
		}

		// custom nav links, as defined in "hooks/links-navmenu.php" 
		global $navLinks;
		if(is_array($navLinks)) {
			$memberInfo = getMemberInfo();
			$links_added = array();
			foreach($navLinks as $link) {
				if(!isset($link['url']) || !isset($link['title'])) continue;
				if($memberInfo['admin'] || @in_array($memberInfo['group'], $link['groups']) || @in_array('*', $link['groups'])) {
					$menu_index = intval($link['table_group']);
					if(!$links_added[$menu_index]) $menu[$menu_index] .= '<li class="divider"></li>';

					/* add prepend_path to custom links if they aren't absolute links */
					if(!preg_match('/^(http|\/\/)/i', $link['url'])) $link['url'] = $prepend_path . $link['url'];
					if(!preg_match('/^(http|\/\/)/i', $link['icon']) && $link['icon']) $link['icon'] = $prepend_path . $link['icon'];

					$menu[$menu_index] .= "<li><a href=\"{$link['url']}\"><img src=\"" . ($link['icon'] ? $link['icon'] : "{$prepend_path}blank.gif") . "\" height=\"32\"> {$link['title']}</a></li>";
					$links_added[$menu_index]++;
				}
			}
		}

		$menu_wrapper = '';
		for($i = 0; $i < count($menu); $i++) {
			$menu_wrapper .= <<<EOT
				<li class="dropdown">
					<a href="#" class="dropdown-toggle" data-toggle="dropdown">{$table_group_name[$i]} <b class="caret"></b></a>
					<ul class="dropdown-menu" role="menu">{$menu[$i]}</ul>
				</li>
EOT;
		}

		return $menu_wrapper;
	}

	#########################################################

	function StyleSheet() {
		if(!defined('PREPEND_PATH')) define('PREPEND_PATH', '');
		$prepend_path = PREPEND_PATH;

		$css_links = <<<EOT

			<link rel="stylesheet" href="{$prepend_path}resources/initializr/css/cerulean.css">
			<link rel="stylesheet" href="{$prepend_path}resources/lightbox/css/lightbox.css" media="screen">
			<link rel="stylesheet" href="{$prepend_path}resources/select2/select2.css" media="screen">
			<link rel="stylesheet" href="{$prepend_path}resources/timepicker/bootstrap-timepicker.min.css" media="screen">
			<link rel="stylesheet" href="{$prepend_path}dynamic.css.php">
EOT;

		return $css_links;
	}

	#########################################################

	function getUploadDir($dir) {
		global $Translation;

		if($dir=="") {
			$dir=$Translation['ImageFolder'];
		}

		if(substr($dir, -1)!="/") {
			$dir.="/";
		}

		return $dir;
	}

	#########################################################

	function PrepareUploadedFile($FieldName, $MaxSize, $FileTypes = 'jpg|jpeg|gif|png', $NoRename = false, $dir = '') {
		global $Translation;
		$f = $_FILES[$FieldName];
		if($f['error'] == 4 || !$f['name']) return '';

		$dir = getUploadDir($dir);

		/* get php.ini upload_max_filesize in bytes */
		$php_upload_size_limit = trim(ini_get('upload_max_filesize'));
		$last = strtolower($php_upload_size_limit[strlen($php_upload_size_limit) - 1]);
		switch($last) {
			case 'g':
				$php_upload_size_limit *= 1024;
			case 'm':
				$php_upload_size_limit *= 1024;
			case 'k':
				$php_upload_size_limit *= 1024;
		}

		$MaxSize = min($MaxSize, $php_upload_size_limit);

		if($f['size'] > $MaxSize || $f['error']) {
			echo error_message(str_replace('<MaxSize>', intval($MaxSize / 1024), $Translation['file too large']));
			exit;
		}
		if(!preg_match('/\.(' . $FileTypes . ')$/i', $f['name'], $ft)) {
			echo error_message(str_replace('<FileTypes>', str_replace('|', ', ', $FileTypes), $Translation['invalid file type']));
			exit;
		}

		$name = str_replace(' ', '_', $f['name']);
		if(!$NoRename) $name = substr(md5(microtime() . rand(0, 100000)), -17) . $ft[0];

		if(!file_exists($dir)) @mkdir($dir, 0777);

		if(!@move_uploaded_file($f['tmp_name'], $dir . $name)) {
			echo error_message("Couldn't save the uploaded file. Try chmoding the upload folder '{$dir}' to 777.");
			exit;
		}

		@chmod($dir . $name, 0666);
		return $name;
	}

	#########################################################

	function get_home_links($homeLinks, $default_classes, $tgroup = '') {
		if(!is_array($homeLinks) || !count($homeLinks)) return '';

		$memberInfo = getMemberInfo();

		ob_start();
		foreach($homeLinks as $link) {
			if(!isset($link['url']) || !isset($link['title'])) continue;
			if($tgroup != $link['table_group'] && $tgroup != '*') continue;

			/* fall-back classes if none defined */
			if(!$link['grid_column_classes']) $link['grid_column_classes'] = $default_classes['grid_column'];
			if(!$link['panel_classes']) $link['panel_classes'] = $default_classes['panel'];
			if(!$link['link_classes']) $link['link_classes'] = $default_classes['link'];

			if($memberInfo['admin'] || @in_array($memberInfo['group'], $link['groups']) || @in_array('*', $link['groups'])) {
				?>
				<div class="col-xs-12 <?php echo $link['grid_column_classes']; ?>">
					<div class="panel <?php echo $link['panel_classes']; ?>">
						<div class="panel-body">
							<a class="btn btn-block btn-lg <?php echo $link['link_classes']; ?>" title="<?php echo preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", html_attr(strip_tags($link['description']))); ?>" href="<?php echo $link['url']; ?>"><?php echo ($link['icon'] ? '<img src="' . $link['icon'] . '">' : ''); ?><strong><?php echo $link['title']; ?></strong></a>
							<div class="panel-body-description"><?php echo $link['description']; ?></div>
						</div>
					</div>
				</div>
				<?php
			}
		}

		$html = ob_get_contents();
		ob_end_clean();

		return $html;
	}

	#########################################################

	function quick_search_html($search_term, $label, $separate_dv = true) {
		global $Translation;

		$safe_search = html_attr($search_term);
		$safe_label = html_attr($label);
		$safe_clear_label = html_attr($Translation['Reset Filters']);

		if($separate_dv) {
			$reset_selection = "document.myform.SelectedID.value = '';";
		}else{
			$reset_selection = "document.myform.writeAttribute('novalidate', 'novalidate');";
		}
		$reset_selection .= ' document.myform.NoDV.value=1; return true;';

		$html = <<<EOT
		<div class="input-group" id="quick-search">
			<input type="text" id="SearchString" name="SearchString" value="{$safe_search}" class="form-control" placeholder="{$safe_label}">
			<span class="input-group-btn">
				<button name="Search_x" value="1" id="Search" type="submit" onClick="{$reset_selection}" class="btn btn-default" title="{$safe_label}"><i class="glyphicon glyphicon-search"></i></button>
				<button name="ClearQuickSearch" value="1" id="ClearQuickSearch" type="submit" onClick="\$j('#SearchString').val(''); {$reset_selection}" class="btn btn-default" title="{$safe_clear_label}"><i class="glyphicon glyphicon-remove-circle"></i></button>
			</span>
		</div>
EOT;
		return $html;
	}

	#########################################################

