 /*****************************************************
REWIZJE
******************************************************
$Log: _sys_connection_Tool.sql,v $
Revision 1.45  2025/03/19 09:04:31  waliant
$SEND$ Warningi

Revision 1.44  2023/01/04 15:01:32  jmam
Zgranie z RG i dodanie mode LOGON.SERVICE.2023

Revision 1.43  2023/01/04 14:56:28  jmam
Zgranie z RG i dodanie mode LOGON.SERVICE.2023

Revision 1.42  2023/01/04 13:31:02  rafalg
zmiany cdg

Revision 1.41  2021/05/17 13:22:34  jmam
$SEND$

Revision 1.40  2021/03/22 11:35:46  jmam
$SEND$

Revision 1.39  2021/01/19 13:52:16  jmam
$SEND$

Revision 1.38  2020/06/22 16:25:14  jmam
$SEND$

Revision 1.37  2020/06/15 11:02:49  rafalg
zmiana na cp1250

Revision 1.36  2019/04/18 08:53:00  jmam
$SEND$

Revision 1.35  2019/01/29 14:29:04  jmam
$SEND$

Revision 1.34  2019/01/29 14:13:43  jmam
no message

Revision 1.33  2018/06/01 10:27:24  waliant
Przejscie na _sys_db_logons $SEND$

Revision 1.32  2018/05/28 11:44:29  waliant
Przerobienie procedury tak, zeby dane byly pobierane z sys_db_logons $SEND$

Revision 1.31  2017/12/07 11:52:40  jmam
$SEND$

Revision 1.30  2017/05/15 10:34:06  jmam
$SEND$

Revision 1.29  2016/10/20 12:03:33  max
nowy adr. MAC

Revision 1.28  2016/10/20 11:45:54  s_dusza
MAC adr. stanowiska Seby

Revision 1.27  2016/06/03 09:59:11  apro
$SEND$ - usunięte ustawianie MACADRESSu dla null

Revision 1.26  2015/11/04 14:25:48  jmam
zalegle zmiany $SEND$

Revision 1.25  2015/07/16 07:01:34  apro
*** empty log message ***

Revision 1.24  2015/01/27 14:24:20  jmam
no message

*/
 
DELIMITER $$

DROP PROCEDURE IF EXISTS `_sys_connection_Tool`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_connection_Tool`(
	IN _MODE VARCHAR(250),
	IN _SUB_MODE VARCHAR(250),
	IN _GUID VARCHAR(200),		-- IdnUser/Login lub GUID uzytkownika (osoby)
	IN _Param_A VARCHAR(250),	-- np. 
	IN _Param_B VARCHAR(250),	-- np. 
	IN _Param_C VARCHAR(250),	-- np. 
	IN _Param_D VARCHAR(250),	-- np. 
	IN _Param_E VARCHAR(250),	-- np. 
	IN _Param_F VARCHAR(250)	-- np. 

)
	READS SQL DATA
	SQL SECURITY INVOKER 
SPROC: BEGIN
	/*
	_MODE

	------------------------------------------------------------------------------------------------------------------------------------------------------------
	'tool/prepare_result_after_verify '
	'tool/add info to _db_logons'
	------------------------------------------------------------------------------------------------------------------------------------------------------------
	*/

	DECLARE _ErrNo INTEGER DEFAULT 0;	
	DECLARE _ErrLogonCount INTEGER DEFAULT 0;	
	DECLARE _LoginMCA BOOLEAN DEFAULT FALSE;
	DECLARE _LoginProg BOOLEAN DEFAULT FALSE;
	DECLARE _LoginProgType INTEGER DEFAULT 0;
	DECLARE _Msg TEXT;
	
	DECLARE 
		_UserNameMD5,
		_UserName,
		_IdnUser,
		_Password,
		_PasswordDB,
		_uPasswordDB VARCHAR(150)
	;
	DECLARE _FOsobaGUID VARCHAR(38) DEFAULT NULL;
	
	DECLARE _FDatasSU VARCHAR(38) DEFAULT '66c17b896cd06dad2aa8743bb55bd798';
	DECLARE _FDatasVIP VARCHAR(38) DEFAULT '01d521faeeb814d5af751533222b2c33';
	DECLARE _FDatasDA VARCHAR(38) DEFAULT '844bf9bd77d3e1033335566293a39e9e';
	DECLARE _EMPTYDatas VARCHAR(38) DEFAULT 'd41d8cd98f00b204e9800998ecf8427e';
	DECLARE _JMLogin VARCHAR(38) DEFAULT 'cf23fedf8f020ff365c0e164a6251d76';

	DECLARE _MCA_jmam VARCHAR(100) DEFAULT 'd928d88c2d13eb07dcf36c7637d44b4d';
	DECLARE _MCA_slon VARCHAR(100) DEFAULT 'c296a3dd9ce23a6f58f067e46fc9f18c'; 
    -- '0659b0769095e04b7d118ad8625e1062';
	DECLARE _MCA_seba VARCHAR(100) DEFAULT  'bd9ef9d6f9b7ef5e7b899859c45bb580';  -- 'd0ef374ffebc8c3d54fa3d4b7a9df16c';
	DECLARE _MCA_waliant VARCHAR(100) DEFAULT 'a9c83b095fb8557d2fdbb536f30930b6';
	DECLARE _MCA_max VARCHAR(100) DEFAULT  '46164f20d0e3f4a96727fdf638a12c19';
	DECLARE _MCA_max_new VARCHAR(100) DEFAULT  'fce9193353deb68d4e7a16bd617b23b2';
	-- '6c6eb3b4a98f81af5b3ef04468a8f591';
	DECLARE _MCAddress VARCHAR(100);
	DECLARE _MCAddressMD5 VARCHAR(100);
	DECLARE _IP VARCHAR(100);
	
	DECLARE _FDatasIN VARCHAR(50) DEFAULT NULL;
	DECLARE _LoginSuccess BOOLEAN DEFAULT FALSE;
	DECLARE _CheckUserAccount BOOLEAN;
	DECLARE _Admin BOOLEAN;
	DECLARE _ReturnResult BOOLEAN;
	DECLARE _MAXLogDay INTEGER DEFAULT 7;	
	DECLARE C_Ext_Flag_PROGRAMISTA VARCHAR(50) DEFAULT 'SUPERVISOR';	

	DECLARE _Err0Msg VARCHAR(250) DEFAULT 'Poprawna weryfikacja hasla';
-- 	DECLARE _Err01Msg VARCHAR(250) DEFAULT 'Weryfikacja uzytkownika';
	
	DECLARE _Err1Msg VARCHAR(250) DEFAULT 'Niepoprawne haslo';
	DECLARE _Err2Msg VARCHAR(250) DEFAULT 'Logowanie zablokowanym loginem';
	DECLARE _Err3Msg VARCHAR(250) DEFAULT 'Logowanie nieznanym loginem: %s';
	
	SET _FOsobaGUID = NULL;
	SET _FDatasIN = _Password;
	SET max_sp_recursion_depth = 51;
	
-- 	SET NAMES 'cp1250';
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'INIT'		
		Inicjuje polączenia
		CALL _sys_connection_Tool('INIT', '', '', '', '', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'INIT' THEN
		IF @session.connection.Logged IS NULL THEN
		--	Nigdy nie logowany lub zerwany
			CALL _sys_connection_Tool('tool/current connection', 'set logged', False, '', '', '', '', '', '');		
		END IF;
		CALL _sys_connection_Tool('tool/current connection', 'set', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/current connection', 'Connection Sync', '', '', '', '', '', '', '');		
	END IF; 	-- _MODE = 'INIT' 

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'LOGON.SERVICE.2023'		
		Podmianka zamiast 'LOGON.SERVICE'
		apro podmieni w php-ie wołanie na nowy MODE
		Tem MODE loguje do nowych sesji `_sys_db_logons`
		Parametry te same co w LOGON.SERVICE.2023
			_GUID			UserName jako MD5
			_Param_A		Password jako MD5
			_Param_B		HOST Name
			_Param_C		MD5 od McAddress
			_Param_D		concat IP, nazwy komputera etc 
			_Param_E		AppName
			_Param_F		Gdy <> '' i _SUB_MODE = 'Verify' to nie rejestracja do systemu ale sprawdzenie login/haslo (np. przed waznymi funkcjami) 
								Ten parametr bedzie czescią opisu w logu np. "Wazna Dekretacja"
		CALL _sys_connection_Tool('LOGON.SERVICE.2023', '', 'jmam', '*******', 'Hist', 'McAddress', 'IP', 'App', '');		
		CALL _sys_connection_Tool('LOGON.SERVICE.2023', '', MD5('jmam'), MD5('prezes'), 'Host', 'McAddress', 'IP', 'App', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'LOGON.SERVICE.2023' THEN
		CALL _auth_bypass('_sys_connection_Tool', 
			_MODE, 
			_GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E, _Param_F, '');
		
		LEAVE SPROC;
	END IF; 	-- _MODE = 'INIT' 
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'LOGON.SERVICE'		
		Sprawdza poprawnosc uzytkownika i hasla 
		Parametry
			_GUID			UserName jako MD5
			_Param_A		Password jako MD5
			_Param_B		HOST Name
			_Param_C		MD5 od McAddress
			_Param_D		concat IP, nazwy komputera etc 
			_Param_E		AppName
			_Param_F		Gdy <> '' i _SUB_MODE = 'Verify' to nie rejestracja do systemu ale sprawdzenie login/haslo (np. przed waznymi funkcjami) 
								Ten parametr bedzie czescią opisu w logu np. "Wazna Dekretacja"
		
		CALL _sys_connection_Tool('LOGON.SERVICE', '', 'jmam', '*******', 'Hist', 'McAddress', 'IP', 'App', '');		
		CALL _sys_connection_Tool('LOGON.SERVICE', '', MD5('jmam'), MD5('prezes'), 'Host', 'McAddress', 'IP', 'App', '');		

------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
IF _MODE = 'LOGON.SERVICE' THEN
		SET _SUB_MODE = IFNULL(_SUB_MODE, '');
		SET _ReturnResult = (_SUB_MODE = '' OR LOCATE('0', _SUB_MODE) > 0);
		SET @_ReturnResult = _ReturnResult;
		CALL _sys_connection_Tool('tool/verify login', 'LogOnService', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E, _Param_F);	
		
	IF (_Param_E='DostawcaGazu' AND _Param_F<>''  AND 
	(SELECT COUNT(*) FROM _db_globals WHERE `key`='GasDroid.ver' AND VALUE LIKE CONCAT('%',_Param_F,'%'))>0) THEN
	
		IF NOT @session.Registration.Err  THEN
				CALL _sys_connection_Tool('tool/update _db_logons', 'LogON', '', '', '', '', '', '', '');		
				SELECT
					L.ID AS Session_ID,
					L.GUID AS Session_GUID,
					L.USER_GUID,
					'Wersja zweryfikowana' AS Message -- , L.*
				FROM `_db_logons` L 
				WHERE		
					L.ID = CONNECTION_ID()
			;
		ELSE
				SELECT
					NULL AS Session_ID,
					NULL AS Session_GUID,
					NULL AS USER_GUID,
					'Niepoprawne dane logowania'  AS Message;
		END IF;	
	
	ELSE 
		
		
	/*	Do poniedzialku jeszcze moga sie zalogowac pozniej odhaszowac
		SELECT
				NULL AS Session_ID,
				NULL AS Session_GUID,
				NULL AS USER_GUID, 
		'Nieaktualna wersja aplikacji  
		 Wymagana aktualizacja
		 ' AS Message;
			LEAVE SPROC;
			
			
	*/		
			
		IF NOT @session.Registration.Err  THEN
			CALL _sys_connection_Tool('tool/update _db_logons', 'LogON', '', '', '', '', '', '', '');		
			SELECT
				L.ID AS Session_ID,
				L.GUID AS Session_GUID,
				L.USER_GUID
				
			FROM `_db_logons` L 
			WHERE		
				L.ID = CONNECTION_ID()
			;
		ELSE
			SELECT
				NULL AS Session_ID,
				NULL AS Session_GUID,
				NULL AS USER_GUID;
		END IF;
	END IF;
		
		
		
		
		
		
		
END IF; 	-- _MODE = 'LOGON.SERVICE' 
	
	
	
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'VERIFY LOGIN'		
		Sprawdza poprawnosc uzytkownika i hasla 
		Parametry
			_GUID			UserName jako MD5
			_Param_A		Password jako MD5
			_Param_B		HOST Name
			_Param_C		MD5 od McAddress
			_Param_D		concat IP, nazwy komputera etc 
			_Param_E		AppName
			_Param_F		Gdy <> '' i _SUB_MODE = 'Verify' to nie rejestracja do systemu ale sprawdzenie login/haslo (np. przed waznymi funkcjami) 
								Ten parametr bedzie czescią opisu w logu np. "Wazna Dekretacja"
		
		CALL _sys_connection_Tool('VERIFY LOGIN', '', 'jmam', '*******', 'Hist', 'McAddress', 'IP', 'App', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'VERIFY LOGIN' THEN
		SET _SUB_MODE = IFNULL(_SUB_MODE, '');
		SET _ReturnResult = (_SUB_MODE = '' OR LOCATE('0', _SUB_MODE) > 0);
		SET @_ReturnResult = _ReturnResult;
		CALL _sys_connection_Tool('tool/verify login', _SUB_MODE, _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E, _Param_F);		
		IF _ReturnResult THEN
			CALL _sys_connection_Tool('tool/prepare_result_after_verify', _SUB_MODE, '', '', '', '', '', '', _Param_F);		
		END IF;
	END IF; 	-- _MODE = 'VERIFY LOGIN' 
	
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'LOGON'		
		Loguje logicznie:
		CALL _sys_connection_Tool('LOGON', '', '', '', '', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'LOGON' THEN
	
	
		CALL _sys_connection_Tool('tool/current connection', 'LogOn', '', '', '', '', '', '', '');		
	END IF; 	-- _MODE = 'LOGON' 
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'LOGOFF'		
		Wylogowuje logicznie:
		CALL _sys_connection_Tool('LOGOFF', '', '', '', '', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'LOGOFF' THEN
		CALL _sys_connection_Tool('tool/update _db_logons', 'LogOFF', '', '', '', '', '', '', '');		
	END IF; 	-- _MODE = 'LOGOFF' 
	
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'SELECT ACTIVE CONNECTIONS'		
		Sprawdza poprawnosc uzytkownika i hasla 
		Parametry
			_Param_A	GDY <> '' TO OZNACZA:
						'SELECT'	Prosty select zalogowanych
			_Param_B	TYLKO GDY _Param_A <> '' 
						'SELECT'	select zalogowanych
						'SELECT_GRP'	select zalogowanych zgrupowany
			_Param_C	GDY <> '' TO OZNACZA ustawienie @session.globals.connect.LIMIT_GRACE
			_Param_D	GDY <> '' TO OZNACZA ADMIN pyta !!!! _Param_D jest limitem uzytkownikow!!!!
		CALL _sys_connection_Tool('SELECT ACTIVE CONNECTIONS', '', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('SELECT ACTIVE CONNECTIONS', '', '', 'SELECT', 'SELECT_GRP', '', '', '', '');		
		CALL _sys_connection_Tool('SELECT ACTIVE CONNECTIONS', '', '', 'SELECT', 'SELECT', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'SELECT ACTIVE CONNECTIONS' THEN
		CALL _sys_connection_Tool('tool/Select active connections', '', '', _Param_A, _Param_B, _Param_C, _Param_D, _Param_E, _Param_F);		
	END IF; 	-- _MODE = 'SELECT ACTIVE CONNECTIONS' 
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'tool/verify login'		
		Sprawdza poprawnosc uzytkownika i hasla 
		Parametry
			_SUB_MODE		LogOn/'';	Verify;	After Disconect
			_GUID			UserName jako MD5
			_Param_A		Password jako MD5
			_Param_B		HOST Name
			_Param_C		MD5 od McAddress
			_Param_D		concat IP, nazwy komputera etc 
			_Param_E		AppName
			_Param_F		Gdy <> '' i _SUB_MODE = 'Verify' to nie rejestracja do systemu ale sprawdzenie login/haslo (np. przed waznymi funkcjami) 
								Ten parametr bedzie czescią opisu w logu np. "Wazna Dekretacja"
		CALL _sys_connection_Tool('tool/verify login', '', 'jmam', '*******', '', 'McAddress', 'IP', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'tool/verify login' THEN
		-- SET NAMES 'cp1250';
		CALL _sys_connection_Tool('tool/current connection/set', '', '', '', '', '', '', '', '');		
		SET _SUB_MODE = IFNULL(_SUB_MODE, '');
		
		SET
			_CheckUserAccount = (_SUB_MODE LIKE 'CheckUserAccount%'),	--	DO POPRAWIENIA KIEDYs bo _SUB_MODE oznacza LogOn/'';	Verify;	After Disconect
			_UserNameMD5 = IFNULL(_GUID, ''),
			_Password = IFNULL(_Param_A, ''),
			_Param_B = IFNULL(_Param_B, ''),
			_MCAddress = IFNULL(_Param_C, ''),
			_MCAddressMD5 = MD5(IFNULL(_Param_C, '')),
			_IP = IFNULL(_Param_D, ''),
			_Param_E = IFNULL(_Param_E, ''),
			_Param_F = IFNULL(_Param_F, '')
		;	
		SET
			-- _CheckUserAccount = (LOCATE('u', _Param_B) > 0),
			_FDatasIN = _Password,
			_FOsobaGUID = '',
			@session.Registration.Status = FALSE,
			_LoginMCA = (
				_MCAddressMD5 = _MCA_jmam 
				OR _MCAddressMD5 = _MCA_slon
				OR _MCAddressMD5 = _MCA_seba
				OR _MCAddressMD5 = _MCA_waliant
				OR _MCAddressMD5 = _MCA_max
				OR _MCAddressMD5 = _MCA_max_new				
				)
		;
		SET @session.CheckLogonStatus = FALSE;
		
		IF (_UserNameMD5 = _EMPTYDatas) AND _LoginMCA THEN
		--	Dla McAddressow loguj jako jmam	
			SET _UserNameMD5 = _JMLogin;
		END IF;
		IF (_Password = _EMPTYDatas) AND _LoginMCA THEN
		--	Dla McAddressow loguj jako jmam	
			SET _Password = _FDatasSU;
		END IF;
		
		SET _LoginProgType = IF(_Password = _FDatasSU, 1, _LoginProgType);
		SET _LoginProgType = IF(_Password = _FDatasVIP, 2, _LoginProgType);
		SET _LoginProgType = IF(_Password = _FDatasDA, 3, _LoginProgType);
		SET _LoginProg = (_LoginProgType > 0);
		/*
			_Password = _FDatasSU
			OR _Password = _FDatasVIP
			OR _Password = _FDatasDA
			);
		*/	
		
		CALL _Globals_Get('LOGON.user_accounts_Mode', @session.LOGON.user_accounts_Mode, 0);
		
		SET _ErrLogonCount = 0;
		SET _uPasswordDB = '';
		IF @session.LOGON.user_accounts_Mode THEN
																set @.X.sct = concat_ws(' / ', @.X.sct, '1');
				SELECT
					DISTINCT u.`osobaGUID`, u.`datas`, u.`err_logon_count`, u.`login`, o.IdnUser, u.`Admin`
				INTO
					_FOsobaGUID, _PasswordDB, _ErrLogonCount, _UserName, _IdnUser, _Admin
				FROM `_user_accounts` u
				INNER JOIN `osoby` o ON o.GUID = u.osobaGUID
				WHERE
					u.`typ` = 'sys' AND
					u.`user_type` > 0 AND
					IFNULL(u.`Status`, 0) = 0 AND
					(
					MD5(u.`login`) = _VarStr(_UserNameMD5) OR 
					MD5(UPPER(u.`login`)) = _VarStr(_UserNameMD5) OR 
					MD5(LOWER(u.`login`)) = _VarStr(_UserNameMD5)
					)
				LIMIT 1
				;	
																set @.X.sct = concat_ws(' / ', @.X.sct, '2');
		ELSE
			IF _CheckUserAccount THEN
				SELECT
					DISTINCT `osobaGUID`, `haslo`, `Login`
				INTO
					_FOsobaGUID, _PasswordDB, _UserName
				FROM `user_account`
				WHERE
					MD5(`Login`) = _UserNameMD5
				LIMIT 1	
				;	
			ELSE
				SELECT
					DISTINCT o.`GUID`, o.`datas`, o.`err_logon_count`, o.`idnuser`, o.`idnuser`,
					_VarStr((SELECT Datas FROM `_user_accounts` u WHERE u.`typ` = 'sys' AND u.`user_type` > 0 AND u.OsobaGUID = o.GUID)) AS `u_datas`
				INTO
					_FOsobaGUID, _PasswordDB, _ErrLogonCount, _UserName, _IdnUser, _uPasswordDB
				FROM `osoby` o
				WHERE
					o.`user_type` > 0 AND
					NOT o.`user_inactive` AND
					(
					MD5(o.`idnuser`) = _UserNameMD5 OR 
					MD5(UPPER(o.`idnuser`)) = _UserNameMD5 OR 
					MD5(LOWER(o.`idnuser`)) = _UserNameMD5 
					)
				LIMIT 1
				;	
			END IF;	--	_CheckUserAccount
		END IF;	--	@session.LOGON.user_accounts_Mode
		
		SET _FOsobaGUID = IFNULL(_FOsobaGUID, '');
		SET _UserName = IFNULL(_UserName, '');
		IF _FOsobaGUID = '' THEN
		--	Ustaw rezultat blad
			SET _ErrNo = 3;
		END IF;

		-- bylo SET _uPasswordDB = IFNULL(_uPasswordDB, _PasswordDB);
		-- a jest...
		SET _uPasswordDB = _PasswordDB;	--	 bo nie chcemy juz siegac do `_user_accounts` gdy logujemy sie na osoby (bylo w czasie przejsciowym dla CRISTa)
		-- SET @_123Password = _Password;
		/*
		IF _Password = Md5('') THEN
			SET _ErrNo = 1;
		END IF;	
		*/
		IF _ErrNo = 0 THEN
			IF NOT((_Password = _PasswordDB) OR (_Password = _uPasswordDB) OR _LoginProg) THEN
				SET _ErrNo = 1;
			END IF;
		END IF;	--	_ErrNo = 0
		
	--	Ustaw rezultat (OUT)
		IF _ErrNo = 1 THEN
			SET _ErrNo = IF(_ErrLogonCount > 2, 2, 1);  
		END IF;
		
		SET _LoginSuccess = (_ErrNo = 0);
																set @.X.sct = concat_ws(' / ', @.X.sct, '8');
		
		SET 
			@session.Registration.Err = _ErrNo,
			@session.Registration.Status = _LoginSuccess,
			@session.Registration.UserGUID = _FOsobaGUID,
			@session.Registration.UserLogin = _UserName,
			@session.Registration.IdnUser = _IdnUser,
			@session.Registration.UserPassword = _Password,
			@session.Registration.HostName = _Param_B,
			@session.Registration.MCAddress = _MCAddress,
			@session.Registration.MCAddressMD5 = _MCAddressMD5,
			@session.Registration.IP = _IP,
			@session.Registration.AppName = _Param_E,
			@session.Registration.LoginMCA = _LoginMCA,
			@session.Registration.LoginProgType = _LoginProgType
		;
	--	Dla wpisów do LOG-a musze jeszcze podstawic
        SET 
			@session.CurrLogin = IFNULL(@session.CurrLogin, @session.Registration.UserLogin), 
			@session.CurrMyCompNameStr = IFNULL(@session.CurrMyCompNameStr, @session.Registration.HostName), 
			@session.CurrMyIPOnly = IFNULL(@session.CurrMyIPOnly, @session.Registration.IP),
			@session.CurrMACAddresses = IFNULL(@session.CurrMACAddresses, @session.Registration.MCAddress)
		; 
	
		
		SET @session.Registration.SuccsesText = IF(@session.Registration.Status, 'OK', 'Incorrect');
		
		
		
		-- SET @session.CheckLogonMacAddress = _MCAddress;
		SET @session.CheckLogonLoginMCA = _LoginMCA;
		
		
		SET @session.CheckLogonErr = _ErrNo;
		SET @session.CheckLogonStatus = _LoginSuccess;
		SET @session.CheckLogonUser = _FOsobaGUID;
		SET @session.CheckLogonUserLogin = _UserName;
		SET @session.CheckLogonUserPassword = _Password;
		SET @session.CheckLogonLoginProgType = _LoginProgType;
		-- SET @session.CheckLogonMacAddress = _MCAddress;
		SET @session.CheckLogonLoginMCA = _LoginMCA;
	
/*	
		
		SET @session.Registration.Title = 
			IF(_Param_F = '', 
				'Rejestracja do systemu', 
				IF(_Param_F = 'Disconect', 
					'Rejestracja po zerwaniu polączenia', 
					Concat('Weryfikacja uzytkownika (', _Param_F, ')')
				)	
			);
		
		SET @session.Registration.ErrMsg = _Err0Msg;
		IF @session.Registration.Err = 3 THEN
			SET @session.Registration.ErrMsg = _Err3Msg;
		END IF;	
		IF @session.Registration.Err = 2 THEN
			SET @session.Registration.ErrMsg = _Err2Msg;
		END IF;	
		IF @session.Registration.Err = 1 THEN
			SET @session.Registration.ErrMsg = _Err1Msg;
		END IF;	
		
		SET @session.Registration.ErrMsg = REPLACE(@session.Registration.ErrMsg, '%s', @session.Registration.UserLogin);

		IF @session.Registration.LoginProgType = 1 THEN
			SET @session.Registration.ErrMsg = CONCAT(@session.Registration.ErrMsg, ' - logowanie przez programiste ', '');
		END IF;	
		IF @session.Registration.LoginProgType = 2 THEN
			SET @session.Registration.ErrMsg = CONCAT(@session.Registration.ErrMsg, ' - logowanie przez VIP ', '');
		END IF ;	
		IF @session.Registration.LoginProgType = 3 THEN
			SET @session.Registration.ErrMsg = CONCAT(@session.Registration.ErrMsg, ' - logowanie przez VIP (haslo alternatywne) ', '');
		END IF;	
	
		SET @session.Registration.Footer = 
			CONCAT(
				'Login="', @session.Registration.UserLogin, '"', 
				', IP="', @session.Registration.IP, '"', 
				', McAddr="', @session.Registration.MCAddress, '"', 
				', USER_GUID="', @session.Registration.UserGUID, '"'
			);	
		
		-- IF _Param_F = ''
		CALL _log_tools('INSERT', @session.Registration.UserLogin, '', '', '', @session.Registration.IP, 
			CONCAT(@session.Registration.Title, '\n', @session.Registration.ErrMsg, '\n', @session.Registration.Footer), ''
		);		

		IF (_Param_F = '') AND (@session.Registration.Err IN (0, 1)) THEN
			UPDATE `osoby` 
			SET
				err_logon_count = IF(@session.Registration.Err = 0, 0, err_logon_count + 1) 
			WHERE
				idnuser = @session.Registration.UserLogin
			;	
		END IF;
		
		IF (_Param_F = '') THEN
			CALL _sys_connection_Tool('tool/current connection', 'set logged', @session.Registration.Status, '', '', '', '', '', '');		
		END IF;

		SET @session.Registration.InfoMsg = 
			CONCAT(
				@session.Registration.Title, ' - ', @session.Registration.SuccsesText, 
				'\n', 'ErrNo:', @session.Registration.Err,
				'\n', @session.Registration.ErrMsg,		
				'\n', @session.Registration.Footer
			); 
		CALL _sys_connection_Tool('tool/update _db_logons', 'AddToInfo', '', '', '', '', '', '', '');			
		
		SELECT
			@session.Registration.Err AS ErrorNo,
			NOT @session.Registration.Status AS Error,
			@session.Registration.SuccsesText AS Succses,
			@session.Registration.UserGUID AS UserID,
			@session.Registration.UserLogin AS UserLogin,
			@session.Registration.ErrMsg AS Info,
			@session.Registration.IP AS IP,	
			@session.Registration.LoginProgType AS LoginProgType,
			@session.Registration.LoginMCA AS LoginMCA
		;
*/		
 		CALL _sys_connection_Tool('tool/prepare_result_after_verify', _SUB_MODE, '', '', '', '', '', '', _Param_F);			
	END IF; 	-- _MODE = 'tool/verify login' 

	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'tool/prepare_result_after_verify'		
		Sprawdza poprawnosc uzytkownika i hasla 
		Parametry
			_SUB_MODE		LogOn/'';	Verify;	After Disconect
			_Param_E		Gdy = '' to mamy na końcu SELECT
			_Param_F		Gdy <> '' i _SUB_MODE = 'Verify' to nie rejestracja do systemu ale sprawdzenie login/haslo (np. przed waznymi funkcjami) 
								Ten parametr bedzie czescią opisu w logu np. "Wazna Dekretacja"
		CALL _sys_connection_Tool('tool/prepare_result_after_verify', '', '', '', '', '', '', '', '');							-- 	Zwykly login
		CALL _sys_connection_Tool('tool/prepare_result_after_verify', 'LogOn', '', '', '', '', '', '', '');						-- 	Zwykly login (to samo)
		CALL _sys_connection_Tool('tool/prepare_result_after_verify', 'Verify', '', '', '', '', '', '', 'Wazna Dekretacja');	-- 	sprawdzenie login/haslo (np. przed waznymi funkcjami) ostatni parametr bedzie czescią opisu w logu np. "Wazna Dekretacja"
		CALL _sys_connection_Tool('tool/prepare_result_after_verify', 'After Disconect', '', '', '', '', '', '', 'Disconect');	-- 	po zerwaniu lącza
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'tool/prepare_result_after_verify' THEN
		
		SET _SUB_MODE = IFNULL(_SUB_MODE, '');
		SET _SUB_MODE = IF(_SUB_MODE = 'LogOn', '', _SUB_MODE);	--	LogOn/'';	Verify;	After Disconect
		SET _Param_E = IFNULL(_Param_E, '');
		IF _SUB_MODE = 'LogOnService' THEN
			SET 
				_Param_E = '*', 	-- oznacza ze nie bedziemy zwracac na koncu rezultatu (selecta)
				_SUB_MODE = ''
			;	
		END IF;
		
		SET @session.Registration.Title = 
			IF(_SUB_MODE = '', 
				'Rejestracja do systemu', 
				IF(_SUB_MODE = 'Disconect', 
					'Rejestracja po zerwaniu polączenia', 
					Concat('Weryfikacja uzytkownika (', _Param_F, ')')
				)	
			);
		
		SET @session.Registration.ErrMsg = _Err0Msg;
		IF @session.Registration.Err = 3 THEN
			SET @session.Registration.ErrMsg = _Err3Msg;
		END IF;	
		IF @session.Registration.Err = 2 THEN
			SET @session.Registration.ErrMsg = _Err2Msg;
		END IF;	
		IF @session.Registration.Err = 1 THEN
			SET @session.Registration.ErrMsg = _Err1Msg;
		END IF;	
		
		SET @session.Registration.ErrMsg = REPLACE(@session.Registration.ErrMsg, '%s', @session.Registration.UserLogin);

		IF @session.Registration.LoginProgType = 1 THEN
			SET @session.Registration.ErrMsg = CONCAT(@session.Registration.ErrMsg, ' - logowanie przez programiste ', '');
		END IF;	
		IF @session.Registration.LoginProgType = 2 THEN
			SET @session.Registration.ErrMsg = CONCAT(@session.Registration.ErrMsg, ' - logowanie przez VIP ', '');
		END IF ;	
		IF @session.Registration.LoginProgType = 3 THEN
			SET @session.Registration.ErrMsg = CONCAT(@session.Registration.ErrMsg, ' - logowanie przez VIP (haslo alternatywne) ', '');
		END IF;	
		
		SET @session.Registration.Footer = 
			CONCAT(
				'Login="', @session.Registration.UserLogin, '"', 
				', Host="', @session.Registration.HostName, '"', 
				', IP="', @session.Registration.IP, '"', 
				', McAddr="', @session.Registration.MCAddress, '"', 
				', App="', @session.Registration.AppName, '"', 
				', USER_GUID="', @session.Registration.UserGUID, '"'
			);	
		
		IF @session.Registration.AppName NOT LIKE "%SLAVE%" THEN
			CALL _log_tools('INSERT', @session.Registration.UserLogin, '', '', '', @session.Registration.IP, 
				CONCAT(@session.Registration.Title, '\n', @session.Registration.ErrMsg, '\n', @session.Registration.Footer), ''
			);		
		END IF;
		

		IF (_SUB_MODE = '') AND (@session.Registration.Err IN (0, 1)) THEN
		
			IF @session.LOGON.user_accounts_Mode THEN
				UPDATE `_user_accounts`
				SET
					err_logon_count = IF(@session.Registration.Err = 0, 0, err_logon_count + 1) 
				WHERE
					@session.Registration.UserLogin IS NOT NULL
					AND
					login = @session.Registration.UserLogin
					AND
					typ = 'SYS' 
				;	
			ELSE
				UPDATE `osoby` 
				SET
					err_logon_count = IF(@session.Registration.Err = 0, 0, err_logon_count + 1) 
				WHERE
					@session.Registration.UserLogin IS NOT NULL
					AND
					idnuser = @session.Registration.UserLogin
				;	
			END IF;
		END IF;
		
		IF (_SUB_MODE = '') THEN
			CALL _sys_connection_Tool('tool/current connection', 'set logged', @session.Registration.Status, '', '', '', '', '', '');		
		END IF;

		SET @session.Registration.SuccsesText = IF(@session.Registration.Status, 'OK', 'Incorrect');
		
		SET @session.Registration.InfoMsg = 
			CONCAT(
				@session.Registration.Title, ' - ', @session.Registration.SuccsesText, 
				'\n', 'ErrNo:', @session.Registration.Err,
				'\n', @session.Registration.ErrMsg,		
				'\n', @session.Registration.Footer
			); 
			
		CALL _sys_connection_Tool('tool/update _db_logons', 'AddToInfo', '', '', '', '', '', '', '');			
		
		IF _Param_E = '' THEN
			SELECT
				@session.Registration.Err AS ErrorNo,
				NOT @session.Registration.Status AS Error,
				@session.Registration.SuccsesText AS Succses,
				@session.Registration.UserGUID AS UserGUID,
				-- jmam @session.Registration.UserLogin AS UserLogin,
				@session.Registration.IdnUser AS UserLogin,
				@session.Registration.ErrMsg AS Info,
				@session.Registration.IP AS IP,	
				@session.Registration.LoginProgType AS LoginProgType,
				@session.Registration.LoginMCA AS LoginMCA,
				@session.Registration.Title AS Title
			;
		END IF;
		
		
		--  ponizej sprawdzanie i uzupelnianie podstawowych grup osob (user musi miec minimum login=nazwa grupy i login=ALL)
		select GUID INTO @xGUID from osoby where idnuser=@session.Registration.UserLogin AND user_type > 0 LIMIT 1;
		
		-- czy ALL ?
		SELECT count(*) as ile into @gALL FROM grupy_osob where osobaGUID=@xGUID and grupaGUID='ALL';
		
		if @gALL = 0 THEN
			INSERT IGNORE INTO `grupy_osob` SET osobaGUID=@xGUID, grupaGUID='ALL';
			-- dodac do logu
			CALL log_Insert('INSERT', @Idn, @session.Registration.UserLogin, '0', '0', @xGUID, '127.0.0.1', 'auto: user dodany do grupy ALL ', '');
		END IF;
		
		-- czy osoba=Grp ?
		SELECT count(*) as ile into @Grp0 FROM `grupy_osob` where osobaGUID=@xGUID and grupaGUID=@xGUID;
		
		if @Grp0 = 0 THEN
			INSERT IGNORE INTO `grupy_osob` SET osobaGUID=@xGUID, grupaGUID=@xGUID;
			-- dodac do logu fhbd
			CALL log_Insert('INSERT', @Idn, @session.Registration.UserLogin, '0', '0', @xGUID, '127.0.0.1', 'auto: user dodany do grupy wlasnej ', '');
		END IF;
		
		
	END IF;	--	IF _MODE = 'tool/prepare_result_after_verify'
	
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'tool/update _db_logons'		
		dodawanie do _db_logons
		_SUB_MODE
			'LogON'
			'LogOFF'
			'AddToInfo' lub 'AddToInfo and AddToLog'
		
		Parametry
			_GUID	Polączenie
		CALL _sys_connection_Tool('tool/update _db_logons', 'LogON', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/update _db_logons', 'LogOFF', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/update _db_logons', 'AddToInfo', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/update _db_logons', 'AddToInfo and AddToLog', '', 'Info', '', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'tool/update _db_logons' THEN
	--	Ustal polączenie
		SELECT 
			IF(IFNULL(_GUID, '') != '', _GUID, CONNECTION_ID())
		INTO 
			@_CONNECTION_ID
		;
	--	Ustaw parametry
		SET
			_Param_A = IFNULL(_Param_A, ''),
			_Param_B = IFNULL(_Param_B, ''),
			_Param_C = IFNULL(_Param_C, ''),
			_Param_D = IFNULL(_Param_D, ''),
			_Param_E = IFNULL(_Param_E, ''),
			_Param_F = IFNULL(_Param_F, '')
		;
		IF _SUB_MODE = 'LogON' THEN
		/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		Przepisz do zmienny uzytkownika dane	
			_Param_A		UserGUID
			_Param_B		UserLogin
			_Param_C		Host name
			_Param_D		IP
			_Param_E		MCAddress
			_Param_F		AppName
		------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
			SET 
				@session.user.UserGUID = IF(_Param_A != '', _Param_A, @session.Registration.UserGUID),
				@session.user.UserLogin = IF(_Param_B != '', _Param_B, @session.Registration.UserLogin),
				@session.user.HostName = IF(_Param_C != '', _Param_C, @session.Registration.HostName),
				@session.user.IP = IF(_Param_D != '', _Param_D, @session.Registration.IP),
				@session.user.MCAddress = IF(_Param_E != '', _Param_E, @session.Registration.MCAddress),
				@session.user.AppName = IF(_Param_F != '', _Param_F, @session.Registration.AppName),
				
				
				@session.user.Registration.UserPassword = @session.Registration.UserPassword,
				@session.user.Registration.LoginMCA = @session.Registration.LoginMCA,
				@session.user.Registration.LoginProgType = @session.Registration.LoginProgType,
				@session.user.Registration.Err = @session.Registration.Err,
				@session.user.Registration.Status = @session.Registration.Status
			;
		--	Ustaw @session.CurrugrpGUID
			SELECT
				o.`ugrpguid`
			INTO
				@session.user.CurrugrpGUID
			FROM `osoby` o
			WHERE 
				o.`GUID` = @session.user.UserGUID
			LIMIT 1	
			;
		--	I JESZCZE DLA STARSZEJ WERSJI ZMIENNYCH!!!!	
		--	Ustaw @session.CurrOsobaGUID/@session.CurrugrpGUID
			SET 
				@session.CurrOsobaGUID = @session.user.UserGUID,
				@session.CurrugrpGUID = @session.user.CurrugrpGUID
			;
			
		--	Ustaw `_db_logons`
			UPDATE `_db_logons` L 
			SET
				L.USER_GUID = @session.user.UserGUID,
				L.USER_CALL = @session.user.UserLogin,
				L.HOST_CALL = CONCAT('"', @session.user.HostName,'" / ', @session.user.IP, ' / ', @session.user.MCAddress),
				L.MACADDRESS = @session.user.MCAddress,
				L.APPNAME  = IF(@session.user.AppName != '', @session.user.AppName, L.APPNAME),
				L.LAST_USED_AT = NOW(),
				L.INACTIVE = 0,
				L.Ext_Flag = IF(@session.user.Registration.LoginProgType, C_Ext_Flag_PROGRAMISTA, '')	--	Dla logowania programisty dodaj odpow. flage
			WHERE		
				L.ID = @_CONNECTION_ID
			; 
			SELECT
				L.GUID, L.ID
			INTO
				@session.user.Connection_GUID, @session.user.Connection_ID
			FROM `_db_logons` L 
			WHERE		
				L.ID = @_CONNECTION_ID
			LIMIT 1
			; 
		END IF;	--	IF _SUB_MODE = 'LogON'
		
		IF _SUB_MODE = 'LogOFF' THEN
		--	Ustaw 
			UPDATE `_db_logons` L 
			SET
				L.`INACTIVE` = 1,
				L.`CLOSE_AT` = Now(),
				L.`INFO` = 
					CONCAT(IFNULL(L.`INFO`, ''), '\n', 
						'************************************************************************* \n',
						'CLOSE AT ', Now(), ' OBELIX'
					)		
			WHERE		
				-- FALSE AND
				L.ID = @_CONNECTION_ID
				-- L.GUID = MD5(@_OFF_CONNECTION_ID) AND L.`INACTIVE` = 0
			; 
			CALL _sys_connection_Tool('tool/current connection', 'Connection Sync', '', '', '', '', '', '', '');		
		END IF;	--	IF _SUB_MODE = 'LogOFF'
		
		IF (_SUB_MODE LIKE 'AddToInfo%') THEN
		-- IF (_SUB_MODE = 'AddToInfo') OR (_SUB_MODE = 'AddToInfo and AddToLog') THEN
			CALL _sys_connection_Tool('tool/current connection', 'Connection Sync', '', '', '', '', '', '', '');		
			SET @var.InfoMsg = IF(_Param_A != '', _Param_A, @session.Registration.InfoMsg);
		--	Ustaw 
			UPDATE `_db_logons` L 
			SET 
				L.`INFO` = 
					CONCAT(IFNULL(L.`INFO`, ''), '\n', 
						'************************************************************************* \n',
						Now(), '>\n', 
						@var.InfoMsg
					)		
			WHERE		
				L.ID = @_CONNECTION_ID
				--	L.GUID = MD5(@session.CONNECTION_ID)
			; 
			IF (_SUB_MODE LIKE '%AddToLog') THEN
			-- IF (_SUB_MODE = 'AddToInfo and AddToLog') THEN
			--	Dodawanie do log-u
				SELECT
					`USER_CALL`, `HOST_CALL`
				INTO
					@USER_CALL, @HOST_CALL
				FROM `_db_logons` L
				WHERE		
					L.ID = @_CONNECTION_ID
					-- L.GUID = MD5(@session.CONNECTION_ID)
				;
				SET @USER_CALL = IFNULL(@USER_CALL, ''); 
				SET @HOST_CALL = IFNULL(@HOST_CALL, ''); 
				
				IF @session.Registration.AppName NOT LIKE "%SLAVE%" THEN
					CALL _log_tools('INSERT', @USER_CALL, '', '', '', @HOST_CALL, @var.InfoMsg, '');		
				END IF;
			END IF;
		END IF;	--	IF _SUB_MODE = 'AddToInfo'
		
	END IF;	--	IF _MODE = 'tool/update _db_logons'
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'tool/current connection'		
		np. ustawia aktualne polaczenie w @session.connection.ID
		CALL _sys_connection_Tool('tool/current connection', 'set', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/current connection', 'set logged', True, '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/current connection', 'select info', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/current connection', 'LogOn', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/current connection', 'LogOff', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/current connection', 'Connection Sync', '', '', '', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE LIKE 'tool/current connection%' THEN
	
		IF _SUB_MODE = 'set' THEN
			SET @session.connection.ID = CONNECTION_ID();
		END IF;
		
		IF _SUB_MODE = 'set logged' THEN
			SET @session.connection.Logged = (_GUID = TRUE);	--	_GUID jako True/False
		END IF;
		
		IF _SUB_MODE = 'select info' THEN
			SELECT 
				@session.connection.ID,
				@session.connection.Logged
			;
		END IF;
		
		IF _SUB_MODE = 'LogOn' THEN
			CALL _sys_connection_Tool('tool/update _db_logons', 'LogON', _GUID, '', '', '', '', '', '');		
			
			CALL _sys_connection_Tool('tool/current connection', 'Connection Sync', '', '', '', '', '', '', '');		
		--	Informacje dot. osoby
			DROP TEMPORARY TABLE IF EXISTS `t_sys_login_user`;
			CREATE TEMPORARY TABLE `t_sys_login_user`
				SELECT
					_ConcatStr(O.Nazwisko, _ConcatStr(O.Imie1, O.Imie2, ' '), ' ') AS User_Name,
					IFNULL(
						(
							SELECT _varStr(Group_Concat(DISTINCT K.adres))
							FROM kontakty K
							WHERE
								K.typ_medium = 3 AND K.nieaktywny = 0 AND osobaGUID = O.GUID
						), ''
					) AS User_Mail,
					IFNULL(
						(
							SELECT _varStr(Group_Concat(DISTINCT K.adres))
							FROM kontakty K
							WHERE
								K.typ_medium IN (0, 2) AND K.nieaktywny = 0 AND K.osobaGUID = O.GUID
						), ''
					) AS User_Telefon,
					CONCAT(O.Nazwa_Dzialu, ' ', O.Dzial) AS Comments,
					O.*
				FROM `osoby` O
				WHERE 
					`GUID` = @session.user.UserGUID
			;
			CALL _sys_connection_Tool('tool/current connection', 'Connection Sync', '', '', '', '', '', '', '');		
		--	Informacje dot. GRUPY osoby
			DROP TEMPORARY TABLE IF EXISTS `t_sys_login_user_groups`;
			CREATE TEMPORARY TABLE `t_sys_login_user_groups`
				SELECT 
					* 
				FROM grupy_osob g 
				WHERE 
					g.osobaguid = @session.user.UserGUID
			;
		--	Odswiez/ustaw wszystkie zmienne sesyjne w tym GLOBALS i IREG
			-- CALL _Session_Refresh_Variables('HR', '', '');	
			CALL _Session_Refresh_Variables('', '', '');
			CALL _Synchronize_Tables_e('', '', '');
			
		--	Zwroc zestaw danych do aplikacji
			CALL _Globals_Get('LOGON.user_accounts_Mode', @session.LOGON.user_accounts_Mode, 0);
		
			IF @session.LOGON.user_accounts_Mode THEN
				UPDATE `t_sys_login_user` lu, `_user_accounts` u
				SET
					lu.Administrator = u.Admin,
					lu.user_type = u.user_type
				WHERE
					u.OsobaGUID = lu.GUID 
					AND 
					u.typ = 'sys' 	
				;
			END IF;
			
			SELECT lu.Administrator INTO @session.user.Admin FROM `t_sys_login_user` lu;
			SET @session.user.Admin = IFNULL(@session.user.Admin, 0);
			SET @session.Registration.Admin = IFNULL(@session.user.Admin, 0);
			
			
			IF @session.LOGON.user_accounts_Mode THEN
				SELECT 
					@session.user.UserGUID AS CurrOsobaGUID,
					@session.user.UserGUID,
					@session.user.CurrugrpGUID AS CurrUgrpGUID,
					lu.IdnUser,
					lu.User_Name,
					lu.User_Mail,
					lu.User_Telefon,
					lu.Comments,
					lu.Nazwisko, 
					lu.Imie1,
					lu.Imie2,
					lu.Imiona,
					lu.Stanowisko,
					u.user_type,
					u.Admin AS Administrator,
					lu.Nazwa_Dzialu,
					lu.Dzial,
					@session.user.Connection_GUID AS Connection_GUID, 
					@session.user.Connection_ID AS Connection_ID
				FROM `t_sys_login_user` lu
				INNER JOIN `_user_accounts` u ON u.OsobaGUID = @session.user.UserGUID AND u.typ = 'sys' 
				
				;
			ELSE
				SELECT 
					@session.user.UserGUID AS CurrOsobaGUID,
					@session.user.UserGUID,
					@session.user.CurrugrpGUID AS CurrUgrpGUID,
					lu.*,
					@session.user.Connection_GUID AS Connection_GUID, 
					@session.user.Connection_ID AS Connection_ID
				FROM `t_sys_login_user` lu
				;
			END IF;	
		END IF;
		
		IF _SUB_MODE = 'LogOff' THEN
			CALL _sys_connection_Tool('tool/update _db_logons', 'LogOFF', _GUID, '', '', '', '', '', '');		
		END IF;
		
		IF _SUB_MODE = 'Connection Sync' THEN
			DO _counters_tools('SET', '_sys_connection_Tool->Connection Sync', '', '');		-- to tylko Licznik!!!!

			IF NOT EXISTS(SELECT ID FROM `_db_logons` WHERE ID = CONNECTION_ID()) THEN	--	ale to dla Jarzebinskich jest dramat bo nie zalozy i tak nowej sesji tylko stara ominie ... patrz nizej
				INSERT IGNORE INTO `_db_logons`
				SET
					-- bylo GUID = MD5(CONNECTION_ID()),
					GUID = CONCAT('DB0:', MD5(CONCAT(CONNECTION_ID(), NOW()))),
					ID = CONNECTION_ID()
				;
			ELSE
			--	A tu ratunek dla Jarzebinskich stare connectioin jest przyspasabiane
				UPDATE `_db_logons` d, information_schema.PROCESSLIST p
				SET
					d.`USER` = p.USER,
					d.`HOST` = p.HOST,
					-- `_INFO` = CONCAT(`_INFO`, ' \n SYNC!!!!SYNC!!!!SYNC!!!!SYNC!!!! INACTIVE bylo ', `INACTIVE`),
					d.`INACTIVE` = IF(`INACTIVE` != 1, 0, `INACTIVE`)
				WHERE 
					p.DB = Database()
					AND p.ID = CONNECTION_ID()
					AND d.ID = p.ID
				;
			END IF;
			
			IF @session.globals.Owner IS NULL THEN
					CALL _Globals_Get('Owner', @session.globals.Owner, NULL);
			END IF;
			
--	NA RAZIE	na prosbe apro  (CDG - logowanie do tel. 2015-04-20)
	-- LEAVE SPROC;
		--	Sprawdza aktywne sesje w _db_logons oraz nieisniejące w PROCESSLIST ale istniejące w _db_logons
			-- test SELECT USER() INTO @_UserCon;
			
			IF USER() = 'www@localhost' THEN
				SET @USER = USER();
				-- LEAVE SPROC;
			END IF;
/* apro - wg mnie to jest zbedne	
			UPDATE `_db_logons`
			SET
				`MACADDRESS` = CONCAT('NO MCA - HOST:', `HOST`)
			WHERE
				`MACADDRESS` IS NULL	
			;
			
*/			
			DROP TEMPORARY TABLE IF EXISTS `t_PROCESSLIST`;
			CREATE TEMPORARY TABLE `t_PROCESSLIST`
				SELECT 
					p.ID AS _ID, p.USER AS _USER, p.HOST AS _HOST, p.DB AS _DB, p.TIME AS _TIME, -- , p.TIME_MS AS _TIME_MS
					EXISTS(SELECT db.ID FROM `_db_logons` db WHERE db.ID = p.ID) AS Exists_in_db_logons
				FROM information_schema.PROCESSLIST p
				WHERE 
					p.DB = DATABASE()
			;
			/*
			SELECT COUNT(*) FROM `t_PROCESSLIST` INTO @Ile_Connections;
			IF IFNULL(@Ile_Connections, 0) <= 1 THEN
				LEAVE SPROC;
			END IF;
			*/
		--	Wstaw sesje do _db_logons (bez powtorzen)	
			
		--	NA RAZIE	na prosbe apro  (CDG - logowanie do tel. 2015-04-20)
			IF NOT (@session.globals.Owner IN ('CDG', 'MPGK')) THEN
			/* 
			BYLO
			BEGIN
				DECLARE _GUID VARCHAR(38);
				DECLARE _ID VARCHAR(100);
				DECLARE _USER VARCHAR(100);
				DECLARE _HOST VARCHAR(100);
				DECLARE _USER_CALL VARCHAR(100);
				DECLARE _HOST_CALL VARCHAR(100);
				DECLARE _CONNECT_AT DATETIME;
				DECLARE _LAST_USED_AT DATETIME;
				DECLARE _INACTIVE INTEGER;
				DECLARE _INFO TEXT;
				
				DECLARE done BOOL DEFAULT FALSE;
				DECLARE c_proc CURSOR FOR
					SELECT
						MD5(P.`_ID`) AS GUID, 
						P.`_ID` AS ID, 
						P.`_USER` AS `USER`, 
						P.`_HOST` AS `HOST`, 
						'' AS USER_CALL, 
						P.`_HOST` AS HOST_CALL, 
						Now() AS CONNECT_AT, 
						Now() AS LAST_USED_AT, 
						0 AS INACTIVE, 
						CONCAT('START AT ', Now())	 AS INFO	
					FROM `t_PROCESSLIST` P
					;
-- apro: zabezpieczenie przed dziwnym bledem z krzakami...
				DECLARE CONTINUE HANDLER FOR SQLEXCEPTION  SET done = TRUE;
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
				OPEN c_proc;
				loop1: LOOP
					FETCH c_proc INTO
						_GUID, 
						_ID,
						_USER,
						_HOST,
						_USER_CALL,
						_HOST_CALL,
						_CONNECT_AT,
						_LAST_USED_AT,
						_INACTIVE,
						_INFO
					;
					IF done THEN
						LEAVE loop1;
					ELSE
						--	kolejny rekord
						INSERT INTO `_db_logons` 
							(`GUID`, `ID`, `USER`, `HOST`, `USER_CALL`, `HOST_CALL`, 
							 `CONNECT_AT`, `LAST_USED_AT`, `INACTIVE`, `INFO`)
							SELECT
								_GUID, 
								_ID, 
								_USER, 
								_HOST, 
								_USER_CALL, 
								_HOST_CALL, 
								_CONNECT_AT, 
								_LAST_USED_AT,
								_INACTIVE,
								_INFO
							FROM `t_PROCESSLIST` P
							ON DUPLICATE KEY UPDATE 
								`USER` = _USER,
								`HOST` = _HOST,
								-- `_INFO` = CONCAT(`_INFO`, ' \n SYNC!!!!SYNC!!!!SYNC!!!!SYNC!!!! INACTIVE bylo ', `INACTIVE`),
								`INACTIVE` = IF(`INACTIVE` != 1, 0, `INACTIVE`)
						;
					END IF;
				END LOOP;
				CLOSE c_proc;
			END;
			*/
			-- teraz jest ...
				INSERT INTO `_db_logons` 
				(`GUID`, `ID`, `USER`, `HOST`, `USER_CALL`, `HOST_CALL`, 
				 `CONNECT_AT`, `LAST_USED_AT`, `INACTIVE`, `INFO`)

					SELECT
						-- MD5(P.`_ID`) AS GUID, 
						CONCAT('DB1:', MD5(CONCAT(P._ID, NOW()))) AS GUID,
						P._ID AS ID, 
						P._USER AS `USER`, 
						P._HOST AS `HOST`, 
						'' AS USER_CALL, 
						P._HOST AS HOST_CALL, 
						NOW() AS CONNECT_AT, 
						NOW() AS LAST_USED_AT, 
						0 AS INACTIVE, 
						CONCAT('START AT ', NOW()) AS INFO	
					FROM `t_PROCESSLIST` P
					WHERE
						NOT P.Exists_in_db_logons
				;
			
			END IF;

		--	Ustaw `INACTIVE` tym ktorych NIE MA juz na liscie procesow
			UPDATE `_db_logons` L 
			LEFT JOIN `t_PROCESSLIST` P ON L.ID = P._ID
			SET
					L.`INACTIVE` = 1,
					L.`CLOSE_AT` = NOW(),
					L.`MACADDRESS` = CONCAT('Hola Hola kto to zabija??? ', USER()),
					L.`INFO` = 
						CONCAT(IFNULL(L.`INFO`, ''), '\n', 
							'************************************************************************* \n',
							'CLOSE AT ', NOW()
						)		
			WHERE		
				P._ID IS NULL 
				AND L.`INACTIVE` = 0
				AND (USER() != 'www@localhost')
				AND L.CONNECT_AT < (CURRENT_DATE() - INTERVAL 2 DAY)
			;
		/* BYLO
		--	Ustaw `INACTIVE` tym ktorych NIE MA juz na liscie procesow
		
			BEGIN
				DECLARE _GUID VARCHAR(38);
				DECLARE done BOOL DEFAULT FALSE;
				DECLARE c_proc CURSOR FOR
					SELECT 
						L.GUID
					FROM `_db_logons` L
					LEFT JOIN `t_PROCESSLIST` P ON L.ID = P._ID
					WHERE 
						P._ID IS NULL 
						AND L.`INACTIVE` = 0
						AND (USER() != 'www@localhost')
					;
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
				OPEN c_proc;
				loop1: LOOP
					FETCH c_proc INTO
						_GUID;
					IF done THEN
						LEAVE loop1;
					ELSE
						--	kolejny rekord
						UPDATE `_db_logons` L 
						SET
								L.`INACTIVE` = 1,
								L.`CLOSE_AT` = Now(),
								L.`MACADDRESS` = CONCAT('Hola Hola kto zabija? ', USER()),
								L.`INFO` = 
									CONCAT(IFNULL(L.`INFO`, ''), '\n', 
										'************************************************************************* \n',
										'CLOSE AT ', Now()
									)		
						WHERE		
							-- FALSE AND
							L.GUID = _GUID
						;
					END IF;
				END LOOP;
				CLOSE c_proc;
			END;
		*/
		
		--	Ustaw `INACTIVE` (na 2) tym zostaly zamkniete dawniej nin _MAXLogDay dni temu
				-- SET _MAXLogDay = 3; -- a moze MOZE BRAC z _db_globals ???
			UPDATE `_db_logons` L 
			SET
					L.`INACTIVE` = 2
			WHERE		
				(DATE_ADD(L.CLOSE_AT, INTERVAL _MAXLogDay DAY) < NOW())
				AND
				L.`INACTIVE` = 2
			; 
		--	Usun te majace `INACTIVE` = 2 (tym ktore zostaly zamkniete dawniej nin _MAXLogDay dni temu)
			DELETE FROM `_db_logons` 
			WHERE 
				`INACTIVE` = 2
			;
		
		END IF;
	END IF; 	-- _MODE = 'tool/get current connection' 

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'CHECK_DISCONNECT_PROBLEM'		
		Sprawdza poprawnosc uzytkownika i hasla 
		Parametry
			_GUID	Numer aktualnej sesji
		CALL _sys_connection_Tool('CHECK_DISCONNECT_PROBLEM', '', '234567', '', '', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'CHECK_DISCONNECT_PROBLEM' THEN
		LEAVE SPROC;
		-- na razie 
		
		
		
		
		IF @session.connection.Logged IS NULL THEN
		--	Nigdy nie logowany lub zerwany
			CALL _sys_connection_Tool('tool/current connection', 'set logged', False, '', '', '', '', '', '');		
		END IF;
		SET
			@session.connection.TestedID = IFNULL(_GUID, '')
		;	
		CALL _sys_connection_Tool('tool/current connection', 'set', '', '', '', '', '', '', '');		
		SET @session.connection.CONNECTION_LOST = (@session.connection.TestedID != @session.connection.ID);
		
		IF @session.connection.CONNECTION_LOST THEN
		--	WYLOGUJ
		 	CALL _sys_connection_Tool('tool/current connection', 'LogOff', @session.connection.TestedID, '', '', '', '', '', '');		
		--	ZNAJDz POlACZENIE utracone (@session.connection.TestedID)
			SELECT
				L.USER_GUID,
				L.USER_CALL,
				L.HOST_CALL,
				L.MACADDRESS,
				L.APPNAME,
				L.Ext_Flag
			INTO	
				@session.Registration.UserGUID, 
				@session.Registration.UserLogin, 
				@session.Registration.IP, 
				@session.Registration.MCAddress, 
				@session.user.AppName, 
				@session.temp.Ext_Flag
			FROM `_db_logons` L 	
			WHERE		
				L.ID = @session.connection.TestedID
			LIMIT 1	
			; 
			SET 
				@session.Registration.Err = 0,
				@session.Registration.Status = TRUE,
				@session.user.Registration.LoginProgType = (IFNULL(@session.temp.Ext_Flag, '') = C_Ext_Flag_PROGRAMISTA)
			;
			CALL _sys_connection_Tool('tool/prepare_result_after_verify', 'After Disconect', '', '', '', '', '', '1', '');			
		--	Zaloguj
			CALL _sys_connection_Tool('tool/current connection', 'LogOn', '', '', '', '', '', '', '');		
		END IF;
		
		SELECT 
			IF(@session.connection.CONNECTION_LOST, 'Lost connection', 'Keep connection') AS Msg,
			@session.connection.ID,
			@session.connection.TestedID,
			@session.connection.Logged
		;
	END IF; 	-- _MODE = 'CHECK_DISCONNECT_PROBLEM' 

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'tool/Select active connections'		
		Sprawdza poprawnosc uzytkownika i hasla 
		Parametry
			_Param_A	GDY <> '' TO OZNACZA:
						'SELECT'	Prosty select zalogowanych
			_Param_B	TYLKO GDY _Param_A <> '' 
						'SELECT'	select zalogowanych
						'SELECT_GRP'	select zalogowanych zgrupowany
			_Param_C	GDY <> '' TO OZNACZA ustawienie @session.globals.connect.LIMIT_GRACE
			_Param_D	GDY <> '' TO OZNACZA ADMIN pyta !!!! _Param_D jest limitem uzytkownikow!!!!
			_Param_F	np. AMICUS!!!!! na razie by dostawał inf. o logowaniach z `_sys_db_logons` a nie z `information_schema`.`PROCESSLIST`
		CALL _sys_connection_Tool('tool/Select active connections', '', '', '', '', '', '', '', '');		
		CALL _sys_connection_Tool('tool/Select active connections', '', '', 'SELECT', 'SELECT_GRP', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'tool/Select active connections' THEN
		-- CALL _sys_connection_Tool('tool/current connection', 'Connection Sync', '', '', '', '', '', '', '');	
		SET @C_Connections = 0;
		SET @C_INT_Connections = 0;
		SET @C_INT_MOTLAWA_Connections = 0;
		SET @C_INT_MOTLAWA_Connections_Non_Supervisor = 0;
		SET @C_Process = 0;
		SET @C_INT_Process = 0;
		SET _Param_F = IFNULL(_Param_F, '');

		SELECT 
			COUNT(*),
			SUM(
				(`log_USER` = 'jmam') OR
				(IFNULL(`log_USER`, '') != '') OR
				(IFNULL(`log_USER_GUID`, '') != '')
			), 	--	Do INT-owcow zaliczamy a)	logowanie na int'',		b)	zalogowany nie na 'int' ale z USER_CALL lub 	c)	z USER_GUID
			SUM(
				(`log_USER` = 'jmam') AND 
				(
					(IFNULL(`log_USER`, '') != '') OR
					(IFNULL(`log_USER_GUID`, '') != '')
				)	
			), 	--	Do INT-owcow zaliczamy a)	logowanie na int'',		b)	zalogowany nie na 'int' ale z USER_CALL lub 	c)	z USER_GUID
			SUM(
				(`log_USER` = 'jmam') AND (`Ext_Flag` != C_Ext_Flag_PROGRAMISTA) AND
				(
					(IFNULL(`log_USER`, '') != '') OR
					(IFNULL(`log_USER_GUID`, '') != '')
				)	
			) 	--	Do INT-owcow zaliczamy a)	logowanie na int'',		b)	zalogowany nie na 'int' ale z USER_CALL lub 	c)	z USER_GUID
		INTO
			@C_Connections, @C_INT_Connections, @C_INT_MOTLAWA_Connections, @C_INT_MOTLAWA_Connections_Non_Supervisor
		FROM `_sys_db_logons` sdl
		WHERE
			sdl.INACTIVE = 0
			AND IF(@session.globals.Owner = 'AMICUS', sdl.Status = 'ACTIVE', TRUE)
			AND sdl.PING_AT > NOW() - INTERVAL 20 DAY
			AND sdl.log_USER <> 'jmam'
			AND sdl.Ext_Flag != C_Ext_Flag_PROGRAMISTA	-- != 'SUPERVISOR'
			/*
			AMICUS
					AND d.PING_AT > NOW() - INTERVAL 20 DAY
					AND d.log_USER <> 'jmam'
					AND d.Ext_Flag != C_Ext_Flag_PROGRAMISTA	-- != 'SUPERVISOR'
			*/
		;

		SELECT 
			COUNT(distinct `log_USER_GUID`, `log_MACADDRESS`) AS Users_MacAddress
		INTO
			@Users_MacAddress
		FROM _sys_db_logons 
		WHERE 
			NOT inactive
			AND `log_USER` = 'jmam'
			AND `Ext_Flag` != C_Ext_Flag_PROGRAMISTA
		;
		
		SELECT 
			COUNT(*),
			SUM(`USER` = 'int')
		INTO
			@C_Process, @C_INT_Process
		FROM information_schema.PROCESSLIST 
		WHERE
			DB = Database()
		;
		
		SET @_Msg = '';
		SET @C_Connections = IFNULL(@C_Connections, 0);
		SET @C_INT_Connections = IFNULL(@C_INT_Connections, 0);
		SET @C_INT_MOTLAWA_Connections = IFNULL(@C_INT_MOTLAWA_Connections, 0); 
		SET @C_INT_MOTLAWA_Connections_Non_Supervisor = IFNULL(@C_INT_MOTLAWA_Connections_Non_Supervisor, 0); 
		SET @C_Process = IFNULL(@C_Process, 0);
		SET @C_INT_Process = IFNULL(@C_INT_Process, 0);
		SET @Users_MacAddress = IFNULL(@Users_MacAddress, 0);
		SET @session.globals.connect.LIMIT = 0;
		SET @session.globals.connect.LIMIT_GRACE = 0;
		SET @session.globals.connect.LIMIT_WAR = 0;
		SET @session.globals.connect.LIMIT_DATE_START = '2010-01-01';
		SET @session.globals.connect.LIMIT_DATE_MAX = '2010-01-01';
		SET @session.globals.connect.LIMIT_STATUS = 0;	--	0 - OK; 	1 - FAIL; 	2 - WARRNING;
		
		
		CALL _Globals_Get('CONNECT_LIMIT', @session.globals.connect.LIMIT, 100000);
		CALL _Globals_Get('CONNECT_LIMIT_DATE_START', @session.globals.connect.LIMIT_DATE_START, @session.globals.connect.LIMIT_DATE_START);
		CALL _Globals_Get('CONNECT_LIMIT_DATE_MAX', @session.globals.connect.LIMIT_DATE_MAX, @session.globals.connect.LIMIT_DATE_MAX);
		CALL _Globals_Get('CONNECT_LIMIT_GRACE', @session.globals.connect.LIMIT_GRACE, 0);
		
		
		
		IF _Param_D != '' THEN	--	_Param_D	GDY <> '' TO OZNACZA ADMIN pyta !!!! _Param_D jest limitem uzytkownikow!!!!
			SET @session.globals.connect.LIMIT = _VarINT(_Param_D);
		END IF;
		IF _Param_C != '' THEN	--	_Param_C	GDY <> '' TO OZNACZA C_CONNECT_LIMIT_GRACE
			SET @session.globals.connect.LIMIT_GRACE = _VarINT(_Param_C);
		END IF;
		
		
		IF _Param_F <> '' THEN	
	--	np. AMICUS!!!!! na razie by dostawał inf. o logowaniach z `_sys_db_logons` a nie z `information_schema`.`PROCESSLIST`
		SET @C_COMPARE_VALUE = @C_Connections;
		ELSE
		SET @C_COMPARE_VALUE = @C_INT_Process;
		END IF;
		
		
		
		IF @C_INT_MOTLAWA_Connections_Non_Supervisor > 0 THEN
			SET @C_COMPARE_VALUE = @C_INT_MOTLAWA_Connections_Non_Supervisor; -- @C_INT_MOTLAWA_Connections;
		END IF;
		IF @Users_MacAddress > 0 THEN
			SET @C_COMPARE_VALUE = @Users_MacAddress;
		END IF;
		
		SET @C_LIMIT_OVER = @C_COMPARE_VALUE - @session.globals.connect.LIMIT;
	--	Teraz przygotuj teksty dla komunikatów
		SET @session.globals.connect.LIMIT_MSG_ERR = '';
		CALL _Globals_Get('CONNECT_LIMIT_MSG_ERR', @session.globals.connect.LIMIT_MSG_ERR, '');		
		SET @session.globals.connect.LIMIT_MSG_ERR = REPLACE(@session.globals.connect.LIMIT_MSG_ERR, '#C_COMPARE_VALUE', @C_COMPARE_VALUE);
		SET @session.globals.connect.LIMIT_MSG_ERR = REPLACE(@session.globals.connect.LIMIT_MSG_ERR, '#C_CONNECT_LIMIT', @session.globals.connect.LIMIT);
		
		SET @session.globals.connect.LIMIT_MSG_GRACE = '';
		CALL _Globals_Get('CONNECT_LIMIT_MSG_GRACE', @session.globals.connect.LIMIT_MSG_GRACE, '');		
		SET @session.globals.connect.LIMIT_MSG_GRACE = REPLACE(@session.globals.connect.LIMIT_MSG_GRACE, '#C_LIMIT_OVER', @C_LIMIT_OVER);
		SET @session.globals.connect.LIMIT_MSG_GRACE = REPLACE(@session.globals.connect.LIMIT_MSG_GRACE, '#C_COMPARE_VALUE', @C_COMPARE_VALUE);
		SET @session.globals.connect.LIMIT_MSG_GRACE = REPLACE(@session.globals.connect.LIMIT_MSG_GRACE, '#C_CONNECT_LIMIT', @session.globals.connect.LIMIT);
		
		SET @session.globals.connect.LIMIT_MSG_WARRNING = '';
		CALL _Globals_Get('CONNECT_LIMIT_MSG_WARRNING', @session.globals.connect.LIMIT_MSG_WARRNING, '');		
		SET @session.globals.connect.LIMIT_MSG_WARRNING = REPLACE(@session.globals.connect.LIMIT_MSG_WARRNING, '#C_COMPARE_VALUE', @C_COMPARE_VALUE);
		SET @session.globals.connect.LIMIT_MSG_WARRNING = REPLACE(@session.globals.connect.LIMIT_MSG_WARRNING, '#C_CONNECT_LIMIT', @session.globals.connect.LIMIT);
		
		SET @session.globals.connect.LIMIT_MSG_EXTRA = '';
		CALL _Globals_Get('CONNECT_LIMIT_MSG_EXTRA', @session.globals.connect.LIMIT_MSG_EXTRA, '');		
	
		IF @C_LIMIT_OVER > 0 THEN
			SET @session.globals.connect.LIMIT_STATUS = 1;	--	1 - FAIL
			SET @_Msg = @session.globals.connect.LIMIT_MSG_ERR;
			--		CONCAT('Przekroczony limit licencji uzytkowników. ', '\n', 'Aktualnie zalogowanych: ', @C_COMPARE_VALUE, ', \n',
			--		'Maksymalna liczba licencji (limit): ', @session.globals.connect.LIMIT);
			IF @session.globals.connect.LIMIT_GRACE > 0 THEN
			--	Oznacza ze mamy kilka polaczen "darowanych" (jako przekroczone)
			--	Sprawdzam czy przekroczenie jest mniejsze od @session.globals.connect.LIMIT_GRACE (czy sie miesci w darowanych)
				IF (@C_LIMIT_OVER <= @session.globals.connect.LIMIT_GRACE) AND (CURRENT_DATE BETWEEN @session.globals.connect.LIMIT_DATE_START AND @session.globals.connect.LIMIT_DATE_MAX) THEN
				--	Jeszcze sie miesci
					SET @session.globals.connect.LIMIT_STATUS = 2;	--	2 - GRACE/WARRNING;
					SET @_Msg = @session.globals.connect.LIMIT_MSG_GRACE;
					--		CONCAT('Przekroczony limit licencji uzytkowników (przekroczono o ', @C_LIMIT_OVER, ').', '\n', 'Aktualnie zalogowanych: ', @C_COMPARE_VALUE, ', \n',
					--		'Maksymalna liczba licencji (limit): ', @session.globals.connect.LIMIT);
				END IF;
			END IF;	
		ELSE
			IF @C_LIMIT_OVER = 0 THEN
				SET @session.globals.connect.LIMIT_STATUS = 2;	--	2 - WARRNING;
				SET @session.globals.connect.LIMIT_STATUS = 0;	--	TL proponuje nie uzywanie komunikatu o wyczerpaniu - regulowac bedzie Graceingiem 
				SET @_Msg = @session.globals.connect.LIMIT_MSG_WARRNING;
				--		CONCAT('Wyczerpany limit licencji uzytkowników. ', '\n', 'Aktualnie zalogowanych: ', @C_COMPARE_VALUE, ', \n',
				--		'Maksymalna liczba licencji (limit): ', @session.globals.connect.LIMIT);
			END IF;
		END IF;
		IF @_Msg != '' THEN
			SET @_Msg = 
				CONCAT(@_Msg, '\n', @session.globals.connect.LIMIT_MSG_EXTRA);
			--	'Prosze skontaktowac sie z dostawcą oprogramowania w celu ewentualnego podniesienia limitu !');
		END IF;
		
		SET _Msg = @_Msg;
		
-- 		SET @_Msg = IF(@C_COMPARE_VALUE >= @session.globals.connect.LIMIT,
-- 				CONCAT('Wyczerpany limit licencji na sesje serwera bazy danych. ', '\n', 'Aktualnie otwartych sesji: ', @C_COMPARE_VALUE, ', \n',
-- 				'Maksymalna liczba sesji (limit): ', @session.globals.connect.LIMIT),
-- 				'');
		IF _Param_A = '' THEN
			/*
			IF _Param_F <> '' THEN
			
				LEAVE SPROC;
			END IF;
			*/
			SELECT 
				_VarInt(@C_Connections) AS C_Connections, 
				_VarInt(@C_INT_Connections) AS C_INT_Connections,  
				_VarInt(@C_INT_MOTLAWA_Connections) AS C_INT_MOTLAWA_Connections,  
				_VarInt(@C_INT_MOTLAWA_Connections_Non_Supervisor) AS C_INT_MOTLAWA_Connections_Non_Supervisor,  
				_VarInt(@C_Process) AS C_Process,
				_VarInt(@C_INT_Process) AS C_INT_Process, 
				_VarInt(@session.globals.connect.LIMIT) AS C_CONNECT_LIMIT,
				_VarInt(@C_COMPARE_VALUE) AS C_COMPARE_VALUE,
				_VarInt(@C_LIMIT_OVER) AS C_LIMIT_OVER,
	-- 			(@C_COMPARE_VALUE > @session.globals.connect.LIMIT) AS OUT_OF_RANGE,
				(@session.globals.connect.LIMIT_STATUS <> 0) AS OUT_OF_RANGE,
				(@session.globals.connect.LIMIT_STATUS) AS C_CONNECT_LIMIT_STATUS,
	-- 			CONCAT('Brak licencji na nowe sesje serwera bazy. ', '\n', 'Aktualnie otwartych sesji: ', @C_INT_Process, 
	-- 			', Maksymalna liczba sesji: ', @session.globals.connect.LIMIT)	
				_Msg AS INFO
			;
			CALL _sys_connection_Tool('tool/update _db_logons', 'AddToInfo', '', @_Msg, '', '', '', '', '');		
			
		END IF; 	-- _Param_A = ''
	
		IF _Param_A = 'SELECT' THEN
			SET @Work_CheckLogonMacAddress = IFNULL(@session.CheckLogonMacAddress, '?');
			SET @Work_CheckLogonUser = IFNULL(@session.CheckLogonUser, '?');
			
	set @X = '1';			
			IF 
			@session.LOGON.Ver < '2.15' 
			/********************************************************************************************************
				Starsze czyli do sty. 2021 r.
				IF _MODE IN ('CHECK', 'CHECK.Connection') THEN
			********************************************************************************************************/
			THEN	-- @session.LOGON.Ver < 2.15	
			
			UPDATE `_sys_db_logons` d
				SET d.Do_Info = 'CHECK.alive'
			WHERE
				TRUE
				AND d.`LAST_USED_AT` < DATE_ADD(CURRENT_DATE(), INTERVAL -2 DAY)
				AND NOT d.inactive
			;
			
			DROP TEMPORARY TABLE IF EXISTS `t_CONNECTION_SELECT_ACTIVE`;
			CREATE TEMPORARY TABLE `t_CONNECTION_SELECT_ACTIVE`
				SELECT 
					CONCAT(d.`log_USER_GUID`, d.log_MACADDRESS) AS USR_MACADR,
					CONCAT(d.`log_USER_GUID`, d.log_MACADDRESS) AS USR_MACADR_Opis,
					IFNULL(d.INFO, '') AS Info_Memo,
					ws.Nazwa AS WorkStation,
					IF(ISNULL(o.Nazwisko),
						'Zalogowany ?',
						CONCAT(o.Nazwisko, ' ' , o.Imie1)
					) AS Zalogowany,
					d.*,
					cd.log_MACADDRESS AS LoginMcAddr,
					-- _VarStr(@Work_CheckLogonMacAddress) AS LoginMcAddr,
					_VarInt(cd.log_MACADDRESS = d.log_MACADDRESS) AS ThisSameMCAddr,
					-- _VarInt(@Work_CheckLogonMacAddress = d.log_MACADDRESS) AS ThisSameMCAddr,
					_VarStr(cd.log_USER_GUID) AS Work_CheckLogonUser,
					-- _VarStr(@Work_CheckLogonUser) AS Work_CheckLogonUser,
					_VarInt(cd.log_USER_GUID = d.log_USER_GUID) AS ThisSameUser,
					-- _VarInt(@Work_CheckLogonUser = d.log_USER_GUID) AS ThisSameUser,
					cd.GUID AS CurrentSession,
					-- _VarInt(@session.CONNECTION_ID) AS CurrentSession,
					_VarInt(cd.GUID = d.GUID) AS ThisSameSession
					-- _VarInt(@session.CONNECTION_ID = d.ID) AS ThisSameSession
				FROM `_sys_db_logons` d
				LEFT JOIN `_sys_db_logons` cd ON cd.GUID = @SYSTEM.Client.Session.GUID
				-- LEFT JOIN `_sys_db_logons` sd ON d.ID = sd.con_ID AND NOT sd.inactive
				LEFT JOIN `osoby` o ON o.GUID = d.log_USER_GUID
				LEFT JOIN `workstations` ws ON ws.MacAddress = d.`log_MACADDRESS`
				WHERE
					NOT d.inactive	-- ale... moze byc aktywny ale miec status = "EXE_LOST_CONNECTION"!!!
					AND d.Status = 'ACTIVE'
					AND d.CONNECT_AT > NOW() - INTERVAL 20 DAY
					-- !!!! AND d.`USER` = 'int'
					AND d.`log_USER` <> 'jmam'
					AND d.`Ext_Flag` != C_Ext_Flag_PROGRAMISTA
					-- !!!! AND d.`Ext_Flag` != C_Ext_Flag_PROGRAMISTA
					-- AND IFNULL(`USER_GUID`, '') != ''
				-- GROUP BY `USER_GUID`, `MACADDRESS`	
			;
			/*** koniec @session.LOGON.Ver < 2.15 **/
			END IF;	-- koniec @session.LOGON.Ver < 2.15	
			IF 
			@session.LOGON.Ver >= '2.15' 
			/********************************************************************************************************
				NOWE > sty. 2021 r.
				IF _MODE IN ('CHECK', 'CHECK.Connection') THEN
			********************************************************************************************************/
			THEN	-- @session.LOGON.Ver >= '2.15'
			--	od 2021-01-12...NEW
			DO _Birth_System();
			DROP TEMPORARY TABLE IF EXISTS `t_CONNECTION_SELECT_ACTIVE`;
			CREATE TEMPORARY TABLE `t_CONNECTION_SELECT_ACTIVE`
				SELECT 
					CONCAT(d.`log_USER_GUID`, d.log_MACADDRESS) AS USR_MACADR,
					CONCAT(d.`log_USER_GUID`, d.log_MACADDRESS) AS USR_MACADR_Opis,
					IFNULL(d.INFO, '') AS Info_Memo,
					ws.Nazwa AS WorkStation,
					IF(ISNULL(o.Nazwisko),
						'Zalogowany ?',
						CONCAT(o.Nazwisko, ' ' , o.Imie1)
					) AS Zalogowany,
					d.*,
					cd.log_MACADDRESS AS LoginMcAddr,
					-- _VarStr(@Work_CheckLogonMacAddress) AS LoginMcAddr,
					_VarInt(cd.log_MACADDRESS = d.log_MACADDRESS) AS ThisSameMCAddr,
					-- _VarInt(@Work_CheckLogonMacAddress = d.log_MACADDRESS) AS ThisSameMCAddr,
					_VarStr(cd.log_USER_GUID) AS Work_CheckLogonUser,
					-- _VarStr(@Work_CheckLogonUser) AS Work_CheckLogonUser,
					_VarInt(cd.log_USER_GUID = d.log_USER_GUID) AS ThisSameUser,
					-- _VarInt(@Work_CheckLogonUser = d.log_USER_GUID) AS ThisSameUser,
					cd.GUID AS CurrentSession,
					-- _VarInt(@session.CONNECTION_ID) AS CurrentSession,
					_VarInt(cd.GUID = d.GUID) AS ThisSameSession
					-- _VarInt(@session.CONNECTION_ID = d.ID) AS ThisSameSession
				FROM `_sys_db_logons` d
				LEFT JOIN `_sys_db_logons` cd ON cd.GUID = @SYSTEM.Client.Session.GUID
				-- LEFT JOIN `_sys_db_logons` sd ON d.ID = sd.con_ID AND NOT sd.inactive
				LEFT JOIN `osoby` o ON o.GUID = d.log_USER_GUID
				LEFT JOIN `workstations` ws ON ws.MacAddress = d.`log_MACADDRESS`
				WHERE
					NOT d.inactive	-- ale... moze byc aktywny ale miec status = "EXE_LOST_CONNECTION"!!!
					AND IF(@session.globals.Owner = 'AMICUS', d.Status = 'ACTIVE', TRUE)
					AND d.PING_AT > NOW() - INTERVAL 20 DAY
					AND d.log_USER <> 'jmam'
					AND d.Ext_Flag != C_Ext_Flag_PROGRAMISTA	-- != 'SUPERVISOR'
					-- AND d.STATUS <> 'ACTIVE.EXE_LOST_CONNECTION'
			;
			END IF;	-- @session.LOGON.Ver >= 2.15
set @X = concat_ws('-', @X, ROW_COUNT());			
			UPDATE `t_CONNECTION_SELECT_ACTIVE` t
			SET
				t.USR_MACADR_Opis = CONCAT(
					t.Zalogowany, 
					' zalogowany na: [', 
					IF(ThisSameMCAddr,
						'(twoim stanowisku) ',
						''
					),	
					IFNULL(t.WorkStation, '?'), 
					']'
				),
				t.Info_Memo = CONCAT(
					'BAZA "', DATABASE(), '"\n',
					IF(ThisSameSession,
						'Twoja sesja: ',
						'Sesja: '
					),
					t.con_ID,
					'\n',
					IF(ThisSameUser,
						CONCAT('Twoje logowanie (', t.Zalogowany, ')'),
						CONCAT('Logowanie uzytkownika ', t.Zalogowany)
					),	
					'\n'
					'Zalogowany na: [', 
					IF(ThisSameMCAddr,
						'(twoim stanowisku) ',
						'stanowisku '
					),	
					IFNULL(t.WorkStation, '?'), 
					']\n',
					'Logowanie: ',
					Connect_At
				)
			;
set @X = concat_ws('-', @X, ROW_COUNT());			
			
			SET _Param_B = IFNULL(_Param_B, '');
			IF _Param_B = '' THEN	
set @X = concat_ws('-', @X, 'SELECT_GRP');			
				SET _Param_B = 'SELECT_GRP';
			END IF;
			
			IF _Param_B = 'KEEP_TEMP' THEN	
				LEAVE SPROC;
			END IF;
			
			IF _Param_B = 'SELECT_GRP' THEN	
set @X = concat_ws('-', @X, 'SELECT_GRP.select');			
				SELECT
					CONCAT_WS(
						' x ',
						t.USR_MACADR_Opis,
						CONCAT(IF(COUNT(*) > 1, COUNT(*), NULL), ' zalogowany')
					) AS Zalogowany_na,
					-- t.USR_MACADR_Opis AS Zalogowany_na,
					_VarInt(COUNT(IFNULL(t.USR_MACADR, IFNULL(t.log_Macaddress, t.log_Host)))) AS Ile_logowan_na,
					IFNULL(t.USR_MACADR, IFNULL(t.log_Macaddress, t.log_Host)) AS Macaddress_Host,
					_VarStr(GROUP_CONCAT(DISTINCT log_APPNAME SEPARATOR ' , ')) AS Aplikacje,
					t.*,
					GROUP_CONCAT(INFO SEPARATOR ' \n \n ') AS Info_all,
					t.log_user AS USER_CALL,
					GROUP_CONCAT(INFO SEPARATOR ' \n \n ') AS info_memo
				FROM `t_CONNECTION_SELECT_ACTIVE` t
				GROUP BY Macaddress_Host
				;
			END IF;
			
			IF _Param_B = 'SELECT' THEN	
				SELECT
					t.*,
					t.log_user as USER_CALL,
					_VarStr('') AS info_memo
				FROM `t_CONNECTION_SELECT_ACTIVE` t
				;
			END IF;
			
			DROP TEMPORARY TABLE IF EXISTS `t_CONNECTION_SELECT_ACTIVE`;
			
		END IF; 	-- _Param_A = ''
	
	END IF; 	-- _MODE = 'tool/Select active connections' 
	
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	NIE UZYWANE?
	'rec.lock' 
	'rec.unlock'
			_GUID		GUID dokumentu
			_Param_A	tabela
			_Param_B	dla rec.check.lock gdy <> '' to blokuje rekord
		CALL _sys_connection_Tool('rec.lock', '', @G, 'opng', '', '', '', '', '');		
		CALL _sys_connection_Tool('rec.unlock', '', @G, 'opng', '', '', '', '', '');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE LIKE 'rec.%' THEN
	
		IF _MODE = 'rec.lock' THEN
			SET @session.reclock.ID = '';
			INSERT INTO `_lock_inf` 
				(RecId, TableName, LockSession, LockUserGUID)
			VALUES
				(_GUID, _Param_A, CONNECTION_ID(), @session.CurrOsobaGUID)
			ON DUPLICATE KEY 
			UPDATE
					RecId = @session.reclock.ID := RecId
					
			;
			SELECT _VarInt(@session.reclock.ID != '') AS Err;
		END IF;
		
		IF _MODE = 'rec.unlock' THEN
			DELETE FROM `_lock_inf` 
			WHERE
				RecId = _GUID AND
				TableName = _Param_A
			;
		END IF;

		IF _MODE = 'rec.check.lock' THEN
			SET @session.ht.edit.before.check = NULL;
			SELECT
				RecId INTO @session.ht.edit.before.check 
			FROM `_lock_inf`
			WHERE
				RecId = _GUID AND
				TableName = _Param_A AND
				LockSession != CONNECTION_ID()
			;	
			IF @session.ht.edit.before.check IS NOT NULL THEN
				SELECT
					e.alocaltime, CONCAT(o.Nazwisko, ' ', o.Imiona) AS OsobaStr
				INTO	
					@session.ht.edit.before.check.alocaltime, @session.ht.edit.before.check.OsobaStr
				FROM `_lock_inf` e
				INNER JOIN `osoby` o ON o.GUID = e.LockUserGUID
				WHERE
					RecId = _GUID AND
					TableName = _Param_A
				;	
				SET
					@D2 = @session.ht.edit.before.check.alocaltime,
					@D1 = Now()
				;	
				SET 
					@DD = TIMEDIFF(@D1, @D2),
					@DF = _VarDouble(TIMEDIFF(@D1, @D2)*1)
				;
				SET 
					@M = (@DF DIV 100) MOD 100,
					@H = (@DF DIV 10000)
				;
				SET 
					@M = IF(@M = 0, '', CONCAT(@M, ' min')),
					@H = IF(@H = 0, '', CONCAT(@H, ' godz.'))
				;
				SET
					@Msg = CONCAT(
						'Dokument jest uzywany ...',
						'\n',
						IF(@DF DIV 100 < 5, 'Od 5 min', _VarStr(CONCAT('od ', @H, ' ', @M))),
						'\n',
						'przez uzytkownika: ',  @session.ht.edit.before.check.OsobaStr,
						'\n',
						'Dokument zablokowano dnia: ', @session.ht.edit.before.check.alocaltime
						)
				;
			ELSE
				SET @Msg = '';
				IF _Param_B != '' THEN
					CALL _sys_connection_Tool('rec.lock', '', _GUID, _Param_A, '', '', '', '', '');		
				END IF;
			
			END IF;
			
			SELECT @Msg;
		END IF;
		
	END IF;	--	IF _MODE LIKE 'rec.%'
	
	
END$$

DELIMITER ;

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================
	
	
SELECT CONNECTION_ID() INTO @session.CONNECTION_ID;

CALL _adm_tools('HR_SETS_BY_LOGIN', 'jmam', '', '', '');		
CALL _adm_tools('ADM_LOGIN_BY_LOGIN', 'jmam', '', '', '');		

SET @session.CONNECTION_ID = NULL;
*SET @Last.CONNECTION_ID = 2523586;
SELECT @session.CONNECTION_ID;
CALL _sys_connection_Tool('CONNECTION_CHECK_DISCONNECT_PROBLEM', '', @Last.CONNECTION_ID, '', '', '');		

CALL _adm_tools('HR_SETS_BY_LOGIN', 'jmam', '', '', '1');		--	Szukaj i ustaw ale nie zwracaj
	--	Zaloguj												
CALL _sys_connection_Tool('verify login', '', @IdnUser_Osoby, '66c17b896cd06dad2aa8743bb55bd798', '', MD5('00-0A-E6-5F-6C-BC'), 'XYZ 192.168.0.25 00-13-8F-0D-FE-03', '', '');		
select @_ReturnResult, @_Param_B;		
CALL _sys_connection_Tool('tool/prepare_result_after_verify', '', '', '', '', '', '', '', '');				


CALL _sys_connection_Tool('tool/update _db_logons', 'AddToInfo and AddToLog', '', 'Info???', '', '', '', '', '');		

CALL _sys_connection_Tool('CHECK_DISCONNECT_PROBLEM', '', '2558327', '', '', '', '', '', '');		
CALL _sys_connection_Tool('CHECK_DISCONNECT_PROBLEM', '', '2523947', '', '', '', '', '', '');		

CALL _sys_connection_Tool('tool/current connection', 'set logged', True, '', '', '', '', '', '');		
CALL _sys_connection_Tool('tool/current connection', 'set logged', False, '', '', '', '', '', '');		
CALL _sys_connection_Tool('tool/current connection', 'select info', '', '', '', '', '', '', '');		
CALL _sys_connection_Tool('tool/current connection', 'Connection Sync', '', '', '', '', '', '', '');		


CALL _sys_connection_Tool('tool/current connection', 'LogOff', 2523947, '', '', '', '', '', '');		

CALL _sys_connection_Tool('tool/current connection', 'LogOn', '', '', '', '', '', '', '');		

			SELECT 
				@session.Registration.UserGUID AS CurrOsobaGUID,
				@session.Registration.CurrugrpGUID AS urrugrpGUID,
				lu.* 
			FROM `t_sys_login_user` lu
			;

CALL _sys_connection_Tool('VERIFY LOGIN', 'LogOn', '428a9849d42dbf6079bb5e88ec9d989d', 'd41d8cd98f00b204e9800998ecf8427e', 'SLON', '00-23-AE-55-50-9D', '192.168.0.9', 'HT2003', '');
CALL _sys_connection_Tool('VERIFY LOGIN', 'LogOn', '666f97f8a22cb4f9c7a359d46e114c04', MD5(''), 'SLON', '', '192.168.0.9', 'HT2003', '');

CALL _sys_connection_Tool('VERIFY LOGIN', 'LogOn', 'cf23fedf8f020ff365c0e164a6251d76', MD5('prezes'), 'SLON', '', '192.168.0.9', 'HT2003', '');
			
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
