 DELIMITER $$

/* ************************************************************************************************************************************************************************
	_sessions_APP
	kiedyś w _authorization.SQL
************************************************************************************************************************************************************************ */	

DROP PROCEDURE IF EXISTS `_sessions_APP`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_sessions_APP`(
	IN _MODE VARCHAR(250), 
	IN _GUID VARCHAR(255),
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200),
	IN _Param_C VARCHAR(200),
	IN _Param_D VARCHAR(200),
	IN _Params MEDIUMTEXT
)
S_sessions_APP: BEGIN
	DECLARE _Need_Select BOOLEAN;
	DECLARE _UserGUID, _Md5_UserGUID VARCHAR(150); 
	-- DECLARE _UserGUID, _Md5_SESSION_GUID, _Md5_UserGUID, _Md5_Login, _Md5_Pswd, _Md5_log_DEV_ID, _Md5_log_APP_ID VARCHAR(150); 
	DO _Birth_System(); -- było DO _TriggerDisabled();	--	aby miec @session.globals.INPUT_SALT_Hash

	SET _Need_Select = (_Params LIKE '%<select%>%');
	SET _Params = REPLACE(_Params, '<select>', '');
	SET
		@._sessions_APP.Result = 'OK',
		@._sessions_APP.Result.Msg = ''
	;
				/*********************************************************************************************************************************
					Dla zew. starych wywołań
					KOMPATYBILNOŚĆ!!!! +
					ALISY typu NEW -> INSERT
				*********************************************************************************************************************************/
				IF _MODE LIKE 'NEW%' OR _MODE LIKE 'SESSION.Born%' OR _MODE LIKE 'Born%' OR _MODE LIKE 'SESSION.NEW%' THEN
					SET 
						_MODE = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(_MODE, 
							'SESSION.Born.As.Clone.From', 'INSERT.Clone.From'),
							'SESSION.Born.EVENT', 'INSERT.for.EVENT'),
							'SESSION.Born', 'INSERT'),
							'SESSION.NEW', 'INSERT'),
							'NEW.EVENT', 'INSERT.for.EVENT'),
							'NEW', 'INSERT') 
					;
					
					IF _MODE LIKE '%.for.User%' THEN
						SET @SYSTEM.Client.Session.GUID = NULL;		-- PO CO? !!!!
						IF _Param_A LIKE '%jmam%' THEN
						--	Dla jmama
							SET 
								_MODE = 'INSERT.for.UserLogin',
								_Param_A = 'jmam'
							;
						END IF;
						SET _MODE = CONCAT_WS('', REPLACE(_MODE, '+LogON', ''), '+LogON');
					END IF;
					
					IF _MODE LIKE '%.for.EVENT%' THEN
					/*********************************************************************************************************************************
						I jeszcze mały dodatek .. Sesja serwerowa np. dla eventow
					*********************************************************************************************************************************/
						SET _MODE = CONCAT_WS('', REPLACE(_MODE, '+LogON', ''), '+LogON');
					END IF;
				END IF;
	IF 
		_MODE LIKE 'INSERT%'
		OR
		_MODE LIKE 'sdl.INSERT%' 
	THEN
		SET _MODE = REPLACE(_MODE, 'sdl.', '');
	/************************************************************************************************
		CALL _sessions_APP('sdl.INSERT[...]', [GUID], '', '', '', '', _Params);
		_MODE ma postać
			'INSERT								wstawianie zwykłej sesji
			[
				.for.UserLogin[(+LOG?)] | 		dla loginu Usera 	
				.for.UserGUID[{+LOG?})] | 		dla GUID-a Usera
				.for.#UserGUID[{+LOG?}] | 		dla #Usera czyli Md5(Usera) - zahaszowanego GUID-a Usera
				.for.EVENT | 					dla Eventów
				.Clone.From | 					jako clone sesji źródłowej
				.for.authorization[{+LOG?}]		po nowej! autoryzacji
			]
			[-SET.Client.Session]
			'
		gdzie 
			{+LOG?} <=>	
			'+LogON | +LOG.OK | +LOG.ERR'
				określa zmienne @.sdl.LogON i @.sdl.LogERR
				uwaga @.sdl.LogON jest na TRUE dla 'INSERT.%for.EVENT%', '%INSERT.Clone.From%'
			-SET.Client.Session		oznacza że nie aktualizujemy sesji gdy brak tego fragm, zawsze jest aktualizowana przy wstawianiu
			
		NOWE wstawianie
		--	zwykłe
			CALL _sessions_APP('sdl.INSERT', GUID/NULL, 'USER_GUID', 'log_APPNAME', 'log_APP_ID', 'log_DEV_ID' , '');
		--	po nowej! autoryzacji
			CALL _sessions_APP('sdl.INSERTfor.authorization', GUID/NULL, '', '', '', '' , '');
		--	dla logina Usera 
			CALL _sessions_APP('sdl.INSERT.for.UserLogin', GUID/NULL, 'USER_GUID', 'log_APPNAME', 'log_APP_ID', 'log_DEV_ID' , '');
				@.sdl.IN.User!!!	musi mieć w sznurku "..IN.User=xxx&..." ALBO w _Param_A
		--	dla Usera 
			CALL _sessions_APP('sdl.INSERT.for.UserGUID', GUID/NULL, 'USER_GUID', 'log_APPNAME', 'log_APP_ID', 'log_DEV_ID' , '');
		--	dla #Usera czyli Md5(Usera)
			CALL _sessions_APP('sdl.INSERT.for.#UserGUID', GUID/NULL, 'USER_GUID', 'log_APPNAME', 'log_APP_ID', 'log_DEV_ID' , '');
		--	dla Eventów
			CALL _sessions_APP('sdl.INSERT.for.EVENT', GUID/NULL, 'USER_GUID', 'log_APPNAME', 'log_APP_ID', 'log_DEV_ID' , '');
		_GUID			Sesja (moze byc ''/null 
		_Param_A	@.sdl.UserGUID / NULL
		_Param_B	log_APPNAME / NULL
		_Param_C	log_APP_ID / NULL
		_Param_D	log_DEV_ID / NULL
	************************************************************************************************/
		-- SET @SYSTEM.Client.Session.GUID = @SYSTEM.Current.Session.GUID;
		IF _MODE LIKE '%INSERT.Clone.From%' THEN
		--	Klonowanie sesji - sprawdz war. pocz. - pusty GUID lub gdy istnieje juz klon
			SET @.sdl.CLONE.SRC.GUID = _Param_A;
			IF NULLIF(@.sdl.CLONE.SRC.GUID, '') IS NULL THEN
			--	Coś baaardzo nie tak :( !!!!
				LEAVE S_sessions_APP;
			END IF;
			
		END IF;
		
		SET @.NEW.Session.NOT.Set.Client.Session = (_MODE LIKE '%-SET.Client.Session%');
		SET @.NEW.Session.Set.Client.Session = NOT @.NEW.Session.NOT.Set.Client.Session;
		-- SET @.sdl.Sznurek = _Params;
									SET @.jestem = CONCAT_WS('\n', @.jestem, CONCAT_WS('/', _MODE, _Params));
	--	W _GUID jest coś czyl sesja albo ''/NULL wtedy trzeba zainicjować
	--	ale zanim zainicjujemy _GUID to ...
	--	spr. czy _GUID = "NEW" bo jeśli to tak to pobieramy zupełnie nowy a nie z @.SYSTEM.Session.GUID.Default !!!!!
	/*	ALE !!! to spr. "NEW" robi już sama funkcja `Get_Session_GUID`
		IF _GUID = 'NEW' THEN
		--	czyśc polaczenie domyślne i _GUID
			SET 
				@.SYSTEM.Session.GUID.Default = NULL,
				_GUID = NULL
			;
		END IF;
	--	teraz GUID zainicjowany wyżej z _GUID	
	*/
		SET @.G.1 = _GUID;
		SET _GUID = Get_Session_GUID(_MODE, _GUID, @.sdl.CLONE.SRC.GUID, '');
		SET @.G.2 = _GUID;
		
	--	Pozostale parametry	w _Params - zapisz do zmiennej @.sdl.Params
		SET @.sdl.Params = _Params;
	--	Pobierz ze sznurka @	
		CALL _sessions_APP('@.LET.@.auth.CLEAR%<-Sznurek', '', '', '', '', '', @.sdl.Params);
		SET 
			_GUID = NULLIF(_GUID, ''),
			@.sdl.GUID = NULLIF(_GUID, ''),	-- powt. te zmienna wykorzystuje
			@.sdl.con_ID = CONNECTION_ID(),
		--	Uwaga w _Param_A lub paramsach podajemy W zaleznosci od inserta #UserGUID/UserGUID zahaszowany/jawny GUID
			@.sdl.kind = IF(_MODE LIKE 'INSERT.%for.EVENT%', 'EVENT', NULL),
			@.sdl.Ins_Mode = CONCAT_WS('.',
				@.sdl.Ins_Mode.Pre,		-- dla starych logowań które przechodzą przez nową procke w tej zmienne jest mode funkcji wywoł.
				REPLACE(_MODE, 'INSERT.for.', ''),
				NULLIF(_Params2('_FetchParams', '&', @.sdl.Params, 'Ins_Mode', ''), '')
			),
			@.sdl.Log_Mode = CONCAT_WS('->',
				@.sdl.Log_Mode.Pre,		-- dla starych logowań które przechodzą przez nową procke w tej zmienne jest mode funkcji wywoł.
				REPLACE(_MODE, 'INSERT.for.', ''),
				NULLIF(_Params2('_FetchParams', '&', @.sdl.Params, 'log_Mode', ''), ''),
				CONCAT('ver:', IFNULL(@session.LOGON.Ver, '?'))
			),
			@.sdl.GUID.Exists = FALSE
		;
		SET 
			@.sdl.Ins_Mode.Pre = NULL,	-- koniecznie - dla starych wstawień które przechodzą przez nową procke w tej zmienne jest mode funkcji wywoł.
			@.sdl.Log_Mode.Pre = NULL	-- koniecznie - dla starych logowań które przechodzą przez nową procke w tej zmienne jest mode funkcji wywoł.
		;
									-- set @.jestem = CONCAT_WS('\n', @.jestem, concat_ws('/', _MODE,'po parametrach'));
	--	teraz inne parametry np. User GUID 
		IF _MODE LIKE 'INSERT.for.%User%' THEN
		--	dla usera INSERT.for.User[Login | UserGUID | #UserGUID]]
		--	UWAGA 
		--	potrzebujemy @.sdl.IN.User!!!	musi być w sznurku "..IN.User=xxx&..." ALBO w _Param_A - jeśli _Param_A <> '' to on jest ważniejszy
			SET @.sdl.IN.User =	IFNULL(NULLIF(_Param_A, ''), @.sdl.IN.User);
			SET @.sdl.UserGUID = 
				IF(_MODE LIKE 'INSERT.for.UserGUID%', 
					(
					SELECT ua.OsobaGUID FROM `_user_accounts` ua WHERE ua.OsobaGUID = @.sdl.IN.User
					),
					IF(_MODE LIKE 'INSERT.for.#UserGUID%', 
						(
						SELECT ua.OsobaGUID FROM `_user_accounts` ua WHERE _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, MD5(ua.OsobaGUID), '', '', '') = (@_Md5_UserGUID := @.sdl.IN.User)
						),
						IF(_MODE LIKE 'INSERT.for.UserLogin%', 
							(
							SELECT ua.OsobaGUID FROM `_user_accounts` ua WHERE  ua.Login = @.sdl.IN.User
							),
							@.sdl.IN.User
						)
					)
				)
			;
		ELSEIF _MODE LIKE 'INSERT.%for.EVENT%' THEN
		--	dla EVENTów
									-- set @.jestem = CONCAT_WS('\n', @.jestem, concat_ws('/', 'jestem w evencie'));
			SET 
				@.sdl.UserGUID = 'System',
				@.sdl.log_APPNAME = IFNULL(NULLIF(_Param_A, ''), 'Sys.Alg')
			;
		ELSEIF _MODE LIKE 'INSERT.%for.authorization%' THEN
		--	po nowej autoryzacji
			SET 
				@.sdl.UserGUID = @.auth.Final.USER_GUID, 	 	-- zmienna z nowej autoryzacji itd kolejne 
				@.sdl.log_APPNAME = @.auth.Final.APP_ID_GRP_Dost_Name,
				@.sdl.log_APP_ID = @.auth.Final.APP_ID,
				@.sdl.log_DEV_ID = @.auth.Final.DEV_ID
			;	
		ELSEIF _MODE LIKE '%INSERT.Clone.From%' THEN
		--	Klonowanie sesji
		--	Nie ustawiamy żadnych zmiennych
			SET @.sdl.GUID.Exists = 
				EXISTS(
					SELECT 
						sdl.GUID
					FROM `_sys_db_logons` sdl 
					WHERE
						sdl.GUID = _GUID
				)
			;
		ELSE
		--	dla pozostałych - czyść
			SET 
				@.sdl.UserGUID = NULL
			;
		
		--	dla pozostałych - stadardowo z param. _Param_A
			-- SET @.sdl.UserGUID = _Param_A;	
			/*
			CALL _sessions_APP('@.LET.@.CLEAR%<-Sznurek', '', '', '', '', '', @.insert.we.Params);
			SET 
				@.sdl.log_APPNAME = @.auth.Final.APP_ID_GRP_Dost_Name,
				@.sdl.log_APP_ID = @.auth.Final.APP_ID
			;
			*/			
			SET @.X = '1';
		END IF;
	--	Pozostale parametry	z _Params czyli z zainicjowanej wyzaj @.sdl.Params
		/*
		SET
			@.sdl.log_HOST = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Params, 'log_HOST', ''), ''), 
			@.sdl.log_HOST_NAME = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Params, 'log_HOST_NAME', ''), ''), 
			@.sdl.log_MACADDRESS = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Params, 'log_MACADDRESS', ''), '') 
		;
		*/
	--	Dla zgodn. z poprzed zmiennymi
		SET
			-- _CONNECTION_ID = @.sdl.con_ID
			_GUID = @.sdl.GUID,
			_UserGUID = @.sdl.UserGUID
		;
	
		DROP TEMPORARY TABLE IF EXISTS `t_sys_db_logons`;
		-- CREATE TEMPORARY TABLE IF NOT EXISTS `t_sys_db_logons` LIKE `_sys_db_logons`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_sys_db_logons` SELECT * FROM `_sys_db_logons` WHERE FALSE;
									--	set @.jestem = CONCAT_WS('\n', @.jestem, concat_ws('/', 'jestem w A'));
		IF NOT _MODE LIKE '%INSERT.Clone.From%' THEN
		--	Wstawianie - wszystkie _MODE z wyjatkiem ...INSERT.Clone.From...
										-- set @.jestem = CONCAT_WS('\n', @.jestem, concat_ws('/', _MODE,'IF _MODE = ''INSERT'' THEN'));
			INSERT IGNORE INTO `t_sys_db_logons`
			SET
				IDN = NULL,
				GUID = @.sdl.GUID,
				con_ID = @.sdl.con_ID,
				kind = @.sdl.kind,
				log_APPNAME = @.sdl.log_APPNAME,
				log_APP_ID = @.sdl.log_APP_ID,		
				log_APP_VER = @.sdl.log_APP_VER,
				log_DEV_ID = @.sdl.log_DEV_ID,

				log_HOST = @.sdl.log_HOST,
				log_HOST_NAME = @.sdl.log_HOST_NAME,
				log_MACADDRESS = @.sdl.log_MACADDRESS,
				Ext_Flag = CONCAT('<', @.sdl.Ins_Mode, '>'),
				Do_Info = CONCAT('Insert mode: ', @.sdl.Ins_Mode)
			;
		END IF;	
			
		IF _MODE LIKE '%INSERT.Clone.From%' THEN
		--	Klonowanie sesji o ile nie istnieje
			IF NOT @.sdl.GUID.Exists THEN
			
			
				INSERT INTO `t_sys_db_logons` 
					SELECT
						dl.*
					FROM `_sys_db_logons` dl
					WHERE
						dl.GUID = @.sdl.CLONE.SRC.GUID
				;
				SET @.sdl.GUID.COUNT = ROW_COUNT();
				IF @.sdl.GUID.COUNT > 0 THEN
					UPDATE `t_sys_db_logons` dl
					SET	
						IDN = NULL,
						dl.GUID = @.sdl.GUID,
						dl.CONNECT_AT = NOW(),
						dl.LOGGED_AT = NOW(),
						dl.LAST_USED_AT = NOW(),
						dl.Ext_Flag = CONCAT('<', @.sdl.Ins_Mode, '>'),
						dl.Do_Info = CONCAT_WS('', 'SESSION AS CLONE from GUID = "', @.sdl.GUID, '"'),
									
						dl.con_ID = @.sdl.con_ID,
						dl.kind = IFNULL(@.sdl.kind, dl.kind),
						dl.log_APPNAME = IFNULL(@.sdl.log_APPNAME, dl.log_APPNAME),
						dl.log_APP_ID = IFNULL(@.sdl.log_APP_ID, dl.log_APP_ID),
						dl.log_APP_VER = IFNULL(@.sdl.log_APP_VER, dl.log_APP_VER),
						dl.log_DEV_ID = IFNULL(@.sdl.log_DEV_ID, dl.log_DEV_ID),

						dl.log_HOST = IFNULL(@.sdl.log_HOST, dl.log_HOST),
						dl.log_HOST_NAME = IFNULL(@.sdl.log_HOST_NAME, dl.log_HOST_NAME),
						dl.log_MACADDRESS = IFNULL(@.sdl.log_MACADDRESS, dl.log_MACADDRESS)

						-- dl.INFO = ''
					WHERE
						TRUE
					;
					/*
					INSERT IGNORE INTO `_sys_db_logons` 
						SELECT * FROM `t_sys_db_logons`
					;
					SET @.sdl.GUID.COUNT = ROW_COUNT();
					IF @.sdl.GUID.COUNT > 0 THEN
						UPDATE `_sys_db_logons` sdl, `t_sys_db_logons` t
						SET	
							sdl.Info = CONCAT_WS('\n',
								'************************************************************************************************************',
								CONCAT_WS('', 'SESSION AS CLONE from GUID = "', t.GUID, '"'),
								'............................................................................................................',
								sdl.Info
							)
						WHERE
							t.GUID = @.sdl.GUID
							AND sdl.GUID = @.sdl.GUID
						;
					END IF;
					*/
					/*
					SET @.SYSTEM.Last_Insert.Session.GUID = @.SYSTEM.Last_Insert.Session.GUID;	--	to samo do tego samego
					*/
				
				END IF;
			END IF;
		END IF;
	--	teraz jeszcze wstaw do @.SYSTEM.Last_Insert.Session.GUID
		SET 
			@.SYSTEM.Last_Insert.Session.GUID = @.sdl.GUID
		;
		
		IF NOT _MODE LIKE '%INSERT.Clone.From%' THEN
		--	Wszystkie _MODE z wyjatkiem ...INSERT.Clone.From...
			UPDATE `t_sys_db_logons` sdl, `_user_accounts` ua
			SET
				-- sdl.log_Mode = @.sdl.Log_Mode,
				sdl.log_USER = ua.Login,
				sdl.log_USER_GUID = ua.OsobaGUID
			WHERE
				sdl.GUID = @.sdl.GUID 	-- to samo co @.auth.Final.Session_GUID
				AND ua.OsobaGUID = @.sdl.UserGUID
			;
		END IF;
		--	Tutaj ostatecznie ustalana jest nazwa aplikacji
			UPDATE `t_sys_db_logons` sdl
			LEFT JOIN `_sys_app_reg` a ON 
				IF(sdl.log_APP_ID LIKE '#%', 
				--	#APP_ID - dla log_APP_ID zaczyn. na #APP_ID... - szukaj MD5 używając ...
					(
						--	... sól + ID
						_MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, a.ID, '', '', '') = SUBSTR(sdl.log_APP_ID, 2, 255)
						OR
						--	... sól + pieprz + ID
						_MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, sdl.GUID, a.ID, '', '') = SUBSTR(sdl.log_APP_ID, 2, 255)
					),	
				--	APP_ID - dla log_APP_ID zwykłego szukaj wprost ID
					a.ID = sdl.log_APP_ID
				)
			SET 
				-- sdl.log_APP_ID = IFNULL(a.ID, sdl.log_APP_ID),
				sdl.log_APP_ID = a.ID,
				-- było sdl.log_APPNAME = IFNULL(c.Descr, '?'),
				sdl.log_APPNAME = _VarStr(IFNULL(a.APP_Name, sdl.log_APPNAME)),
				sdl.Kind = 
					IFNULL(
						a.Kind,
						IF(sdl.log_APPNAME LIKE '%2003',
							'EXE',
							sdl.Kind
						)
					),
				-- sdl.TIME_IDLE = IFNULL(a.TIME_IDLE, sdl.TIME_IDLE),
				sdl.TIME_IDLE = a.TIME_IDLE,
				-- sdl.TIME_OUT = IFNULL(a.TIME_OUT, sdl.TIME_OUT)
				sdl.TIME_OUT = a.TIME_OUT
			WHERE 
				sdl.GUID = _GUID
			;
			
			
			UPDATE `t_sys_db_logons` sdl
			SET 
				sdl.log_DEV_ID = IFNULL(
					(
					SELECT id.ID FROM `_sys_Id_Device` id WHERE _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, id.ID, '', '', '') = SUBSTR(sdl.log_DEV_ID, 2, 255)
					)
				, '?')
			WHERE 
				sdl.GUID = _GUID
				AND sdl.log_DEV_ID LIKE '#%'
			;
			
		-- END IF;
		
		IF _MODE LIKE 'INSERT.%for.authorization%' THEN
			SET @bla = NULL;
			
		END IF;
		
		INSERT IGNORE INTO `_sys_db_logons`
		SELECT
			tsdl.*
		FROM `t_sys_db_logons` tsdl
		;
									-- set @.jestem = CONCAT_WS('\n', @.jestem, concat_ws('/', 'po insert'));
	--	Ustaw zmienna która decyduje czy w UPDATE `t_sys_db_logons` ustawic że jest zalogowanie
	--	mozl.iwe dodatki to ...
	--	+LogON / +LOG.OK / +LOG.ERR
		SET 
			@.sdl.LogON = (
			_MODE LIKE '%+LOG.OK%' OR _MODE LIKE '%+LogON%' OR _MODE LIKE 'INSERT.%for.EVENT%' OR _MODE LIKE '%INSERT.Clone.From%'
			),
			@.sdl.LogERR = (
			_MODE LIKE '%+LOG.ERR%'
			)
		;			
	/* 	było 
		IF _MODE LIKE 'INSERT.%for.EVENT' THEN
		teraz jest zmienna @.sdl.LogON
	*/
		IF @.sdl.LogON OR @.sdl.LogERR THEN
			UPDATE `t_sys_db_logons` sdl
			SET
				sdl.log_Mode = @.sdl.Log_Mode,
				sdl.Do_Info = 
					CONCAT_WS('\n', 
						CONCAT_WS('', 
							IF(@.sdl.LogON AND sdl.log_USER_GUID IS NOT NULL, 
							--	logowanie OK - to jest logowanie prawdziwe z Auth albo sztuczne
								'LOG.OK', 
							--	logowanie ERR
								'LOG.ERR'
							),
							IF(_MODE LIKE 'INSERT.%for.EVENT%', 
								'Autoryzacja systemowa',
								IF(_MODE LIKE 'INSERT.%for.authorization%',
									IF(@.sdl.LogON, 'User logon', NULLIF(@.auth.Final.MSG, '')),
									NULL	-- tutaj ew. cos o delfinku
								)	
							)
						),
						IF(_MODE LIKE 'INSERT.%for.authorization%',
							CONCAT('Verify status: ', @.auth.Final.Verify_Status),
							IF(_MODE LIKE 'INSERT.for.%User%',
								CONCAT('Verify status: ', IF(sdl.log_USER_GUID IS NULL, 'ERR.No.user', 'OK')),
								NULL
							)
						),
						IF(_MODE LIKE 'INSERT.%for.authorization%',
							CONCAT('XXX: ', @.auth.Final.MSG_LONG),
							NULL
						),
						IF(_MODE LIKE 'INSERT.%for.authorization%',
							CONCAT('Auth. mode: ', @.auth.Final.IN_Mode),
							NULL
						),
						-- CONCAT('Insert mode: ', @.sdl.Ins_Mode),
						CONCAT('Log. mode: ', @.sdl.Log_Mode),
						NULL
					),
				sdl.LAST_MSG = 
					IF(_MODE LIKE 'INSERT.%for.EVENT%', 
						'Autoryzacja systemowa',
						IF(_MODE LIKE 'INSERT.%for.authorization%',
							@.auth.Final.MSG,
							NULL	-- tutaj ew. cos o delfinku
						)	
					),
				sdl.Ext_flag = CONCAT_WS('', sdl.Ext_flag, CONCAT('<', @.auth.Final.IN_Mode, '>'))
			WHERE
				sdl.GUID = _GUID
			;
		END IF;
									--	set @.jestem = CONCAT_WS('\n', @.jestem, concat_ws('/', '25'));
		
		UPDATE `_sys_db_logons` sdl, `t_sys_db_logons` tsdl
		SET
			sdl.log_USER = IFNULL(tsdl.log_USER, sdl.log_USER),
			sdl.log_USER_GUID = IFNULL(tsdl.log_USER_GUID, sdl.log_USER_GUID),		
			
			sdl.Kind = tsdl.Kind,
			sdl.log_APPNAME = IFNULL(tsdl.log_APPNAME, sdl.log_APPNAME),
			sdl.log_APP_ID = IFNULL(tsdl.log_APP_ID, sdl.log_APP_ID),		
			sdl.TIME_IDLE = IFNULL(tsdl.TIME_IDLE, sdl.TIME_IDLE),
			sdl.TIME_OUT = IFNULL(tsdl.TIME_OUT, sdl.TIME_OUT),
			
			sdl.log_DEV_ID = IFNULL(tsdl.log_DEV_ID, sdl.log_DEV_ID),
						
			sdl.log_HOST = IFNULL(tsdl.log_HOST, sdl.log_HOST),
			sdl.log_HOST_NAME = IFNULL(tsdl.log_HOST_NAME, sdl.log_HOST_NAME),
			sdl.log_MACADDRESS = IFNULL(tsdl.log_MACADDRESS, sdl.log_MACADDRESS),
			sdl.Ext_flag = IFNULL(tsdl.Ext_flag, sdl.Ext_flag),
			sdl.LAST_MSG = IFNULL(tsdl.LAST_MSG, sdl.LAST_MSG),
		--	.. i cz. z logowania
			sdl.log_Mode = IFNULL(tsdl.log_Mode, sdl.log_Mode),
			sdl.Do_Info = tsdl.Do_Info,
			sdl.LAST_MSG = IFNULL(tsdl.LAST_MSG, sdl.LAST_MSG),
			sdl.Ext_flag = IFNULL(tsdl.Ext_flag, sdl.Ext_flag)
		WHERE
			sdl.GUID = tsdl.GUID
		;
		
	--	Insert zwykly do autoryzacji aplikacji jako SET ...
		IF @.NEW.Session.Set.Client.Session THEN
									-- set @.jestem = CONCAT_WS('\n', @.jestem, concat_ws('/', 'przes SET.Client.Session'));
			CALL _sessions_APP('SET.Client.Session', _GUID, '', '', '', '', '');
									-- set @.jestem = CONCAT_WS('\n', @.jestem, concat_ws('/', 'po SET.Client.Session'));
		END IF;
		IF _Need_Select THEN
            /*  od 1 IV 2025 używamy _sessions_SEL
			CALL _sessions_APP('SELECT.SHORT', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params); */
            CALL _sessions_SEL('SELECT.SHORT', _GUID, '', '', '');
		END IF;
		
		IF NOT IFNULL(@session.Delfinek, FALSE) THEN
			DROP TEMPORARY TABLE IF EXISTS `t_sys_db_logons`;
		END IF;

	END IF;
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		IF _MODE IN ('APP.REGISTER') THEN
			IF IFNULL(_GUID, '') = '' THEN
				SET @.APP.Sznurek = _Params;
				SET
					_GUID =  
						IFNULL(
							NULLIF(_Params2('_FetchParams', @._ModeParam, @.APP.Sznurek, 'log_APP_ID', ''), ''),
							NULLIF(_Params2('_FetchParams', @._ModeParam, @.APP.Sznurek, 'A.ID', ''), '')
						)
				;
			ELSE
				/*
					_GUID		APP.ID
					_PARAM_A	APP.NAME
					_PARAM_B	APP.DESCR
					_PARAM_C 	APP.PROG.NAME
					_PARAM_D 	APP.HREF
				*/
				SET
					@.REG.APP.ID = _GUID,
					@.REG.APP.NAME = _PARAM_A,	--  Descr to app_name - niestety :( juz nie zmienię tego
					@.REG.APP.DESCR = _PARAM_B,
					@.REG.APP.PROG.NAME = _PARAM_C,
					@.REG.APP.HREF = _PARAM_D
				;
				SET _Params = CONCAT_WS('&',
						CONCAT('A.NAME=', @.REG.APP.NAME),
						CONCAT('A.ACCESS=', @.REG.APP.ACCESS),
						CONCAT('A.DESCR=', @.REG.APP.DESCR),
						CONCAT('A.PROG.NAME=', @.REG.APP.PROG.NAME),
						CONCAT('A.HREF=', @.REG.APP.HREF),
						CONCAT('A.OLD_APPNAME=', @.REG.APP.Old_APPNAME)
					);
			END IF;
			SET @_GUID = _GUID;
			-- CALL _Moduly_Grupy('APP.REGISTER.Modul', '', _GUID, '', '', _Params);
			CALL _sys_app('APP.REGISTER.Modul', '', _GUID, '', '', _Params);
			/*
			wieczorem 16 V 2022
			... wychodzimy
			*/
			LEAVE S_sessions_APP;
			
		END IF;
	
		IF _MODE LIKE '@.LET.%' THEN
			IF _MODE LIKE '@.LET.Sznurek<-%' THEN
		--	Do sznurka <-
				SET
					@.sdl.Sznurek = IF(_MODE LIKE '@.LET.Sznurek<-Sznurek+%@', @.sdl.Sznurek, NULL)
				;
				IF _MODE LIKE '@.LET.Sznurek<-%@%' THEN
					SET
						@.sdl.Sznurek = 
						CONCAT_WS('&',
							@.sdl.Sznurek,
						--	@.auth.xxx	
							CONCAT('S.ID=', @.auth.S.ID),				-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
							CONCAT('S.ID.Zlec#=', @.auth.S.ID.Zlec.5),	-- sesja zlecająca haszowana
							CONCAT('U.L#=', @.auth.U.L.5),				-- USER_LOGIN.Hash
							CONCAT('U.P#=', @.auth.U.P.5),				-- USER_PSWD.Hash
							CONCAT('U.G#=', @.auth.U.G.5),				-- USER_GUID.Hash
							CONCAT('D.ID#=', @.auth.D.ID.5),			-- DEV_ID.Hash
							CONCAT('A.ID#=', @.auth.A.ID.5),			-- APP_ID.Hash
						--	@.sdl.xxx	
							CONCAT('D.ID=', @.sdl.D.ID),				-- DEV_ID
							CONCAT('A.ID=', @.sdl.A.ID)					-- APP_ID
						)
					;
				END IF;
				IF _MODE LIKE '@.LET.Sznurek<-%auth%' THEN
				--	 to nie jest dokonczony concat !!!! ale na razie nigdzie nie jest to wołane
					SET
						@.sdl.Sznurek = 
						CONCAT_WS('&',
							@.sdl.Sznurek,
						--	@.auth.Final.xxx
							@.auth.Final.IN_Mode,
							@.auth.Final.Need_INS_Session,
							@.auth.Final.Session_GUID,
							@.auth.Final.Verify_Status,
							@.auth.Final.Verify_OK, 
							@.auth.Final.USER_GUID, @.auth.Final.OsobaGUID, 
							@.auth.Final.APP_ID_GRP_Dost_Name, 
							@.auth.Final.APP_ID, 
							@.auth.Final.DEV_ID,
							@.auth.Final.MSG, 
							@.auth.Final.MSG_LONG
						)
					;
				END IF;
			END IF;
			
			IF _MODE LIKE '@.LET.@%<-%' THEN
			/************************************************************************************
				@.LET.@[.auth|.sdl][.CLEAR]<-Sznurek
				@.LET.@[.auth|.sdl][.CLEAR]<-Auth.rec
			************************************************************************************/
				IF _MODE LIKE '@.LET.@%.CLEAR%' THEN
				/************************************************************************************
					@.LET.@.auth.CLEAR
					@.LET.@.sdl.CLEAR
					@.LET.@.CLEAR = @.LET.CLEAR.ALL - wszystko
				************************************************************************************/
					IF _MODE LIKE '@.LET.@.sdl.CLEAR%' OR _MODE LIKE '@.LET.@.CLEAR<-%' THEN
						SET
							@.sdl.log_DEV_ID = NULL,
							@.sdl.log_APP_ID =  NULL,
							@.sdl.log_APPNAME = NULL,
							@.sdl.log_APP_VER = NULL,
							@.sdl.log_HOST = NULL,
							@.sdl.log_HOST_NAME = NULL,
							@.sdl.log_MACADDRESS = NULL
						;
					END IF;
					IF _MODE LIKE '@.LET.@.auth.CLEAR%' OR _MODE LIKE '@.LET.@.CLEAR<-%' THEN
						SET
							@.auth._IN_Session_GUID = NULL,
							@.auth.S.ID = NULL,
							@.auth.U.L.5 = NULL,
							@.auth.U.P.5 = NULL,
							@.auth.U.G.5 = NULL,
							@.auth.D.ID.5 = NULL,
							@.auth.D.ID = NULL,
							@.auth.A.ID.5 = NULL,
							@.auth.S.ID.Zlec.5 = NULL
						;
					END IF;
				END IF;
				IF _MODE LIKE '@.LET.@%<-Sznurek%' THEN
			--	Do zmiennych <- Ze sznurka
					SET @.sdl.Sznurek = _Params;

					IF _MODE LIKE '@.LET.@.auth%<-Sznurek%' THEN
						SET
							@.auth._IN_Session_GUID = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'IN_Session_GUID', ''), ''),
							@.auth.S.ID = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'S.ID', ''), ''),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
							@.auth.U.L.5 = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'U.L#', ''), ''),	-- USER_LOGIN.Hash
							@.auth.U.P.5 = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'U.P#', ''), ''),	-- USER_PSWD.Hash
							@.auth.U.G.5 = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'U.G#', ''), ''),	-- USER_GUID.Hash
							@.auth.D.ID.5 = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'D.ID#', ''), ''),	-- DEV_ID.Hash
							@.auth.D.ID = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'D.ID', ''), ''),		-- DEV_ID
							@.auth.A.ID.5 = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'A.ID#', ''), ''),	-- APP_ID.Hash
							@.auth.S.ID.Zlec.5 = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'S.ID.Zlec#', ''), '')
						;
					END IF;
					IF TRUE THEN
						SET
							@.sdl.log_DEV_ID = 
											IFNULL(
												NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'log_DEV_ID', ''), ''), 
												NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'D.ID', ''), '')
											),
							@.sdl.log_APP_ID =  
											IFNULL(
												NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'log_APP_ID', ''), ''),
												NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'A.ID', ''), '')
											),
							@.sdl.log_APPNAME =  
											IFNULL(
												NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'log_APPNAME', ''), ''),
												NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'A.NAME', ''), '')
											),
							@.sdl.log_APP_VER =  
											IFNULL(
												NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'log_APP_VER', ''), ''),
												NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'A.APP_VER', ''), '')
											),
							@.sdl.log_APP_ACCESS =  
									NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'A.ACCESS', ''), ''),
							-- @.sdl.log_APPNAME = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'log_APPNAME', ''), ''), 
							@.sdl.log_HOST = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'log_HOST', ''), ''), 
							@.sdl.log_HOST_NAME = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'log_HOST_NAME', ''), ''), 
							@.sdl.log_MACADDRESS = NULLIF(_Params2('_FetchParams', @._ModeParam, @.sdl.Sznurek, 'log_MACADDRESS', ''), ''),
							@.sdl.IN.User = NULLIF(_Params2('_FetchParams', '&', @.sdl.Sznurek, 'IN.User', ''), '')
						;
					END IF;
					
				END IF;
			END IF;
		END IF;
								
		IF _MODE LIKE 'SELECT%' THEN
        /*  z dnia 1 IV 2025 !!! 2 etapy wywalenia kodu typu select 
            1. na razie robimy calla do docelowej proc. `_sessions_SEL`
            2. wszędzie w kodzie zamieniamy CALL _sessions_app('SELECT... na  CALL _sessions_SEL('SELECT... na 
        */
            CALL _sessions_SEL(_MODE, _GUID, '', '', '');
            LEAVE S_sessions_APP;
            
            
            
            /*   od 1 IV 2025         
			IF _MODE LIKE 'SELECT' THEN
				SET @.s.g.2.1 := _GUID;
				SELECT
				-- 	sdl.*,
					sdl.GUID, sdl.log_USER, sdl.log_USER_GUID, 
					sdl.LAST_MSG, 
					IF(sdl.LAST_MSG LIKE 'ERR%' OR sdl.LAST_MSG LIKE '%.RODO.Need.Change.PSWD',
						sdl.LAST_MSG,
						''
					) AS VIEW_MSG,
					sdl.STATUS, 
					u.Administrator, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
					NazwiskoImie AS NazwiskoImiona,
					u.User_account_Type,
					IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
					IFNULL(
						IFNULL(
							(SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
							,
							(SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
						),
						''
					) AS KontrGUID
				FROM `_sys_db_logons` sdl
				LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
				WHERE 
					sdl.GUID = _GUID
					-- sdl.GUID = @.SYSTEM.Last_Insert.Session.GUID
				;
			END IF;
		
			IF _MODE IN ('SELECT.SHORT', 'SELECT.CHECK') THEN
				SET @.s.g.2.1 := _GUID;
				SELECT
					IFNULL(sdl.GUID, _GUID) AS GUID,
					IFNULL(sdl.log_USER, '?') AS log_USER,
					IFNULL(sdl.log_USER_GUID, '?') AS log_USER_GUID,
					IFNULL(sdl.LAST_MSG, ses_err.LAST_MSG) AS LAST_MSG,
					IFNULL(sdl.STATUS, ses_err.STATUS) AS STATUS,
					IFNULL(sdl.INACTIVE, 1) AS INACTIVE
				FROM
					(
					SELECT
						_VarStr(IF(_GUID = '{prohibited}', 'Sesja jest własnością innego użytkownika', 'Sesja nie istnieje')) AS LAST_MSG,
						_VarStr(IF(_GUID = '{prohibited}', 'ERR.PROHIBITED', 'ERR.NOT.EXISTS!!!')) AS STATUS
					) ses_err
				LEFT JOIN
					(
					SELECT
					-- 	sdl.*,
						sdl.GUID, sdl.log_USER, sdl.log_USER_GUID, 
						IFNULL(sdl.LAST_MSG, '') AS LAST_MSG, 
						sdl.STATUS,
						sdl.INACTIVE
					FROM `_sys_db_logons` sdl
					WHERE 
						sdl.GUID = _GUID
					) sdl ON TRUE 
				;
			END IF;

			IF _MODE LIKE 'SELECT.AUTH' THEN
				SELECT
					tui.Session_GUID,
					tui.Oper_Status AS Verify_Status, --  AS Inf_Status, 
					tui.Oper_Status LIKE 'OK%' AS Verify_OK, --  AS Inf_Status_OK,  
					tui.Oper_Status LIKE 'OK%' AS _Verify_OK,	-- kompatybilnośc z poprz. 
					-- tar.USER_GUID, -- tar.OsobaGUID,
					tui.Oper_Status_Msg AS Msg,
					tui.Oper_Status_Msg AS _MSG,	-- kompatybilnośc z poprz. 
					CONCAT_WS('\n',
						NULLIF(tui.Msg_Warn, ''),
						tui.Msg_Log
					) AS MSG_LONG,
					tui.Msg_Warn AS Msg_Warning,
					(IFNULL(tui.Msg_Warn, '') <> '') AS IS_Warning,
					tui.Status_N_Warn AS Verify_Status_All,
					-- tar.Add_MSG AS Inf_MsgEx,
					-- było ale zabrałem tui.Verify_Access_available, --  AS Inf_Access_available,
					-- było ale zabrałem tui.MSG_APP_ID_Err, -- tekst o braku dostepy
					-- było ale zabrałem tui.MSG_APP_ID_OK,	 -- tekst o dostepach (dodatk.)
					IFNULL(u.err_logon_count, 0) AS err_logon_count,
					(@.auth.Max_User_Err_logon_count - IFNULL(u.err_logon_count, 0)) AS logon_tries, 
					sdl.GUID, 
					sdl.log_USER, 
					sdl.log_USER_GUID, 
					sdl.LAST_MSG, 
					sdl.STATUS, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
					u.User_account_Type,
					u.Administrator, 
					-- IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
					u.Ad_mail,
					IFNULL(
						IFNULL(
							(SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
							,
							(SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
						),
						''
					) AS KontrGUID
				FROM `t_ua_inf` tui
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tui.Session_GUID
				-- LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
				-- LEFT JOIN `v_user_accounts` u ON u.GUID = sdl.log_USER_GUID
				LEFT JOIN `v_user_accounts_short` u ON u.GUID = sdl.log_USER_GUID
				WHERE 
					tui.Session_GUID = _GUID
					-- tui.Session_GUID = @.SYSTEM.Last_Insert.Session.GUID
				;
			END IF;
			
			IF _MODE LIKE 'SELECT.old.AUTH' THEN
				SELECT
					Session_GUID,
					tar.Verify_Status, --  AS Inf_Status, 
					tar.Verify_OK, --  AS Inf_Status_OK,  
					-- tar.USER_GUID, -- tar.OsobaGUID,
					tar.MSG, --  AS Inf_Msg, 
					tar.MSG_LONG, --  AS Inf_Msg_Long,
					-- tar.Add_MSG AS Inf_MsgEx,
					tar.Verify_Access_available, --  AS Inf_Access_available,
					tar.MSG_APP_ID_Err,
					tar.MSG_APP_ID_OK,
					sdl.GUID, 
					sdl.log_USER, 
					sdl.log_USER_GUID, 
					sdl.LAST_MSG, 
					sdl.STATUS, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
					-- u.NazwiskoImie AS NazwiskoImiona,
					u.User_account_Type,
					u.Administrator, 
					-- IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
					IFNULL(
						IFNULL(
							(SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
							,
							(SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
						),
						''
					) AS KontrGUID
				FROM `t_auth_rec` tar
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tar.Session_GUID
				LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
				WHERE 
					tar.Session_GUID = _GUID
					-- tar.Session_GUID = @.SYSTEM.Last_Insert.Session.GUID
				;
			END IF;

			IF _MODE LIKE 'SELECT.AUTH._sys_db_logons_Tools' THEN
			--	_sys_db_logons_Tools
				SELECT 
					l.GUID, l.log_USER, l.log_USER_GUID, 
					-- l.LAST_MSG, 
					IFNULL(NULLIF(@.auth.Final.MSG, ''), @.auth.Final.Verify_Status) AS LAST_MSG,
					l.STATUS, u.Administrator, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, u.User_account_Type, u.user_type,
					-- IF(l.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
					IF(@.auth.Final.Verify_Status = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
				FROM `_sys_db_logons` l
				LEFT JOIN `v_intnet_users` u ON u.GUID = l.log_USER_GUID
				WHERE 
					l.GUID = _GUID
				;
			END IF;
			
			IF _MODE LIKE 'SELECT.AUTH._sys_authorization' THEN
			--	_sys_authorization
				SELECT
					-- tui.*,
					sdl.GUID AS _Session_GUID, 
					tui.IN_Mode AS L_Mode,
					tui.UserGUID AS USER_GUID,
						-- sdl.log_USER AS User_login,
					u.login AS User_login,
					tui.Oper_Status LIKE 'OK%' AS _Verify_OK,
					tui.Oper_Status AS _Verify_Status,
					tui.Oper_Status_Msg AS _MSG,	-- kompatybilnośc z poprz. 
					u.User_account_Type AS User_type,
					u.Administrator AS admin, 
					u.Status,
					u.Ad_Mail,
					u.date_from,
					u.date_to,
					IFNULL(u.err_logon_count, 0) AS err_logon_count,
					u.GUID AS OsobaGUID,
					tui.Owner,
					tui.APP_ID,
					
					u.User_account_Type AS Typ,
					IF(@session.globals.RODO.Days = 0, '2100-01-01', DATE(DATE_ADD(u.Last_Change_Pswd, INTERVAL @session.globals.RODO.Days DAY))) AS USER_First_Day_to_Change_Pswd,
					u.Last_Change_Pswd AS USER_Last_Change_Pswd,
					tui.Salt AS _INPUT_SALT_Hash,

					CONCAT_WS(' ', IFNULL(u.Nazwisko, 'Nie ustalony'), u.Imiona) AS USER_Str
				FROM `t_ua_inf` tui
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tui.Session_GUID
				-- LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
				-- LEFT JOIN `v_user_accounts` u ON u.GUID = sdl.log_USER_GUID
				LEFT JOIN `v_user_accounts_short` u ON u.GUID = tui.UserGUID -- sdl.log_USER_GUID
				WHERE 
					TRUE
					-- and tui.Session_GUID = 'CON:20221214.084903:3111'
					-- tui.Session_GUID = @.SYSTEM.Last_Insert.Session.GUID
					-- l.GUID = _GUID
                    
				;
			END IF;
			
			IF _MODE LIKE 'SELECT.AUTH._sys_connection_Tool' THEN
			--	_sys_connection_Tool
				SELECT tui.Msg INTO @.tui.Msg FROM `t_ua_inf` tui;
				SELECT
					IF(sdl.Status LIKE '%ERR%', NULL, sdl.con_ID) AS Session_ID, 
					-- sdl.con_ID AS Session_ID, 
					IF(sdl.Status LIKE '%ERR%', NULL, sdl.GUID) AS Session_GUID, 
					-- sdl.GUID AS Session_GUID,
					IF(sdl.Status LIKE '%ERR%', NULL, sdl.log_USER_GUID) AS USER_GUID, 
					-- sdl.log_USER_GUID AS USER_GUID,
					IF(sdl.Status LIKE '%ERR%', @.tui.Msg, 'Wersja zweryfikowana') AS Message
				FROM (
					SELECT
						CONNECTION_ID() AS Session_ID, '' AS Session_GUID, '' AS USER_GUID
					) n
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = _GUID
				;
			END IF;
			
			IF _MODE LIKE 'SELECT.ALL.@' THEN
				SELECT
					@SYSTEM.Client.Session.GUID,
				-- 	zmienne	po logowaniu
					@SYSTEM.Client.Session.Kind,
					@SYSTEM.Client.Session.Status,
					@SYSTEM.Client.Session.IS.System,
					@SYSTEM.Client.Session.log_USER_GUID,
					@SYSTEM.Client.Session.log_USER,
					@SYSTEM.Client.Session.log_USER.user_type, 
					@SYSTEM.Client.Session.log_USER.admin,
					@SYSTEM.Client.Session.log_USER.ugrpguid,
					@SYSTEM.Client.Session.log_Host,
					@SYSTEM.Client.Session.log_HOST_NAME,
					@SYSTEM.Client.Session.log_MACAddress,
					@SYSTEM.Client.Session.log_AppName,
					@SYSTEM.Client.Session.log_APP_ID,
					@SYSTEM.Client.Session.log_DEV_ID,							
				-- 	starsze
					@session.INFO.User_GUID,
					@session.INFO.User_Login,
					@session.INFO.User_user_type,
					@session.INFO.User_UgrpGUID,
					@session.INFO.User_Admin,
					@session.INFO.Host_IP,
					@session.INFO.Host_Name,
					@session.INFO.AppName,
					@session.INFO.MACAddress,
					@session.INFO.INSERT.LOG.ip,
				-- 	i jeszcze starsze
					@session.Registration.UserGUID,
					@session.Registration.UserLogin,
					@session.Registration.Admin,
					@session.Registration.IP,
					
					@session.user.CurrugrpGUID,
					@session.user.Admin,
					@session.CheckLogonUser					,
					@session.CheckLogonUserLogin,
					@session.CurrMyCompNameStr, 
					@session.CurrMyIPOnly,
					@session.CurrMACAddresses,
					
					@X
				;
			END IF;
			
				*/
			IF _MODE LIKE 'SELECT.ALL.@.Table' THEN
				DROP TEMPORARY TABLE IF EXISTS `t_malpy`;
				CREATE TEMPORARY TABLE `t_malpy` (
					`Var_Name` VARCHAR(150) NOT NULL DEFAULT '',
					`Var_Inf` VARCHAR(150) NOT NULL DEFAULT '',
					`Var_Value` VARCHAR(250) NOT NULL DEFAULT '',
					PRIMARY KEY (`Var_Name`)
				);
				TRUNCATE `t_malpy`;
				INSERT IGNORE INTO `t_malpy` 
				(Var_Name, Var_Inf, Var_Value)
				VALUES
				('@SYSTEM.Client.Session.GUID', 'Sesja', IFNULL(@SYSTEM.Client.Session.GUID, 'NULL')),
				('@SYSTEM.Client.Session.Kind', 'Typ sesji', @SYSTEM.Client.Session.Kind),
				('@SYSTEM.Client.Session.log_USER_GUID', 'USER GUID', @SYSTEM.Client.Session.log_USER_GUID),
				('@SYSTEM.Client.Session.log_USER', 'USER login', @SYSTEM.Client.Session.log_USER),
				('@SYSTEM.Client.Session.log_USER.user_type', 'user_type', @SYSTEM.Client.Session.log_USER.user_type),
				('@SYSTEM.Client.Session.log_USER.admin', 'USER admin', @SYSTEM.Client.Session.log_USER.admin),
				('@SYSTEM.Client.Session.log_USER.ugrpguid', 'UgrpGUID', @SYSTEM.Client.Session.log_USER.ugrpguid),
				('@SYSTEM.Client.Session.log_Host', 'log_Host', @SYSTEM.Client.Session.log_Host),
				('@SYSTEM.Client.Session.log_HOST_NAME', 'HOST_NAME', @SYSTEM.Client.Session.log_HOST_NAME),
				('@SYSTEM.Client.Session.log_MACAddress', 'MACAddress', @SYSTEM.Client.Session.log_MACAddress),
				('@SYSTEM.Client.Session.log_AppName', 'AppName', @SYSTEM.Client.Session.log_AppName),
				('@SYSTEM.Client.Session.log_APP_ID', 'log_APP_ID', @SYSTEM.Client.Session.log_APP_ID),
				('@SYSTEM.Client.Session.log_DEV_ID', 'log_DEV_ID', @SYSTEM.Client.Session.log_DEV_ID),
			/* 	starsze	*/
				('@session.INFO.User_GUID', 'USER GUID', @session.INFO.User_GUID),
				('@session.INFO.User_Login', 'USER login', @session.INFO.User_Login),
				('@session.INFO.User_user_type', 'user_type', @session.INFO.User_user_type),
				('@session.INFO.User_UgrpGUID', 'UgrpGUID', @session.INFO.User_UgrpGUID),
				('@session.INFO.User_Admin', 'USER admin', @session.INFO.User_Admin),
				('@session.INFO.Host_IP', 'Host_IP', @session.INFO.Host_IP),
				('@session.INFO.Host_Name', 'HOST_NAME', @session.INFO.Host_Name),
				('@session.INFO.AppName', 'AppName', @session.INFO.AppName),
				('@session.INFO.MACAddress', 'MACAddress', @session.INFO.MACAddress),
				('@session.INFO.INSERT.LOG.ip', 'Host_IP', @session.INFO.INSERT.LOG.ip),
			/* 	i jeszcze starsze	*/
				('@session.Registration.UserGUID', 'USER GUID', @session.Registration.UserGUID),
				('@session.Registration.UserLogin', 'USER login', @session.Registration.UserLogin),
				('@session.Registration.Admin', 'USER admin', @session.Registration.Admin),
				('@session.Registration.IP', 'Host_IP', @session.Registration.IP),
				('@session.user.CurrugrpGUID', 'UgrpGUID', @session.user.CurrugrpGUID),
				('@session.user.Admin', 'USER admin', @session.user.Admin),

				('@session.CheckLogonUser', 'USER admin', @session.CheckLogonUser),
				('@session.CheckLogonUserLogin', 'USER login', @session.CheckLogonUserLogin),
				('@session.CurrMyCompNameStr', 'Comp.Name', @session.CurrMyCompNameStr),
				('@session.CurrMyIPOnly', 'IP', @session.CurrMyIPOnly),
				('@session.CurrMACAddresses', 'MACAddress', @session.CurrMACAddresses)
				;
				SELECT 
					tm.*
				FROM `t_malpy` tm
				;
				IF NOT IFNULL(@session.Delfinek, FALSE) THEN
					DROP TEMPORARY TABLE IF EXISTS `t_malpy`;
				END IF;
			END IF;
			
			
		END IF;
	
	
	IF (_MODE LIKE 'Close%') OR (_MODE LIKE 'SESSION.Close%') OR (_MODE LIKE 'SESSION.LOG%OFF')  OR (_MODE LIKE 'SESSION.LOG%OUT') THEN	
	/**********************************************************************************************************************************************************************
		CLOSE SESSION
		Secja zwykła
			CALL _sessions_APP('SESSION.Close', '', '', '', '', '', '');
		Secja serwerowa np. dla eventow 
			CALL _sessions_APP('SESSION.Close.EVENT', '', '', '', '', '', '');
			_Param_D ???
	**********************************************************************************************************************************************************************/
						SET @.rec.debug = CONCAT_WS('/', @.rec.debug, _MODE);
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa 
							CALL _sessions_APP('SESSION.Close.EVENT', '', '', '', '', 'inf:e_deptak_HT_A', '');
							???
						*/
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('START.SEQ', 'test.SESSION.Close', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.log);
						END IF;
		IF _Param_A IN ('', 'EVENT', 'SERVER') OR _MODE LIKE '%CLOSE%EVENT%' THEN
		--	do _GUID GUID sesji lub domyslny
			SET _GUID = IFNULL(NULLIF(_GUID, ''), Get_Var_Connection('Session.GUID.EVENT', '', '', ''));
		END IF;

		IF NULLIF(_GUID, '') IS NOT NULL THEN
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('START.SEQ', 'test.SESSION.Close.UPDATE...', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.IN.log);
						END IF;
			
			SET _GUID = _GUID;
		--	Close
			UPDATE `_sys_db_logons` sdl 
			SET 
				sdl.Do_Info = 'CLOSE',
				sdl.LAST_MSG = 'Zamykanie sesji'
			WHERE 
				sdl.GUID = _GUID
				AND NOT sdl.Inactive
			;
			SET @._sys_db_logons.RC = ROW_COUNT();
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('END.SEQ', '', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.IN.log);
						END IF;
			/* ***************************************************************************************************************************
				Jeszcze zapis do logu o wyrejestrowaniu z systemy ...
				a ponieważ sesja juz jest i jest juz ustawiona głowna sesja możemy korzystac z 
					CALL log_Ins('Spec.Prog.LogOut', ...
			****************************************************************************************************************************/
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('START.SEQ', 'test.SESSION.Close.Zapis do logu...', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.IN.log);
						END IF;
		--	Zapis w logu
			IF @._sys_db_logons.RC > 0 THEN
				IF FALSE AND NOT (@session.globals.Owner IN ('CDG', 'MPGK', 'KONKOL', 'SIMEX')) THEN
					DO _counters_tools('INC', CONCAT('_sessions_APP: ', _MODE), '', '');		-- to tylko Licznik!!!!
				END IF;
				CALL _sessions_APP('LOG.session.Close', '', '', '', '', '', '');
			END IF;
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('END.SEQ', '', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.IN.log);
						END IF;
		--	2022-04-20 - apro w phytonie connection jest teraz stałe  
		--	czyśćmy więc co się da bo zaraz na tym połączeniu zaloguje sie ktoś inny
		--	czyść polaczenie domyślne
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('START.SEQ', 'test.SESSION.Close.CLEAR.VAR...', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.IN.log);
						END IF;
			SET @.SYSTEM.Session.GUID.Default = NULL;
		--	czyść zmienne	
			CALL _sessions_APP('CLEAR.VAR', '', '', '', '', '', '');
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('END.SEQ', '', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.IN.log);
						END IF;
			
		END IF;
		
		IF _Need_Select THEN
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('START.SEQ', 'test.SESSION.Close.SELECT.SHORT...', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.IN.log);
						END IF;
            /*  od 1 IV 2025 używamy _sessions_SEL
			CALL _sessions_APP('SELECT.SHORT', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params); */
            CALL _sessions_SEL('SELECT.SHORT', _GUID, '', '', '');
						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('END.SEQ', '', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.IN.log);
						END IF;
		END IF;

						/*	Uwaga test jmam-a dla KONKOLA dlaczego długo trwa */
						IF _MODE = 'SESSION.Close.EVENT' AND IFNULL(@session.Delfinek, FALSE) THEN
							CALL _exproc_LOG('END.SEQ', 'test.SESSION.Close', 'jmam_test', @SYSTEM.Client.Session.GUID, '', @.test.SESSION.Close.log);
						END IF;
		
	--	WYCHODZIMY bo ponizej są like-i% do _MODE 	
		LEAVE S_sessions_APP;
	END IF;

	IF _MODE LIKE 'LOG.session.%' THEN
	/* ***************************************************************************************************************************
		Zapis do logu związany z sesją
			o zalogowaniu 	LOG.session.LOG.OK
				CALL _sessions_APP('LOG.session.LOG.OK', '', '', '', '', '', '');
			lub próbie błędnego logowania	LOG.session.LOG.ERR
				CALL _sessions_APP('LOG.session.LOG.ERR', '', '', '', '', '', '');
			o zamknięciu - wyrejestrowaniu z systemu ... LOG.session.LOG.OFF/LOG.session.CLOSE
				CALL _sessions_APP('LOG.session.Close', '', '', '', '', '', ''); albo
				CALL _sessions_APP('LOG.session.LOG.OFF', '', '', '', '', '', '');
			ewent. inne ?
			o autoryzacji - np. potw. operacji loginem i hasłem	 LOG.session.AUTH.OK
				CALL _sessions_APP('LOG.session.AUTH.OK', '', '', '', '', '', '');
			lub próbie błędnej autoryzacji	LOG.session.AUTH.ERR
				CALL _sessions_APP('LOG.session.AUTH.ERR', '', '', '', '', '', '');
		Woła
			CALL log_Ins('Spec.Prog.Log...', ...
	****************************************************************************************************************************/
		SET 
			@.AUTH.LOG.LogIDN = NULL,
			@.AUTH.LOG.MODE = REPLACE(_MODE, 'LOG.session.LOG.OFF', 'LOG.session.CLOSE')
		;
		CALL log_Ins(@.AUTH.LOG.MODE, @.AUTH.LOG.LogIDN, '', '', '', '', '', '', '', NULL, NULL, '', '');
												SET @.rec.debug = CONCAT_WS('/', @.rec.debug, _MODE, '@.AUTH.LOG.MODE');			
		IF @.AUTH.LOG.MODE = 'LOG.session.LOG.OK' THEN
												SET @.rec.debug = CONCAT_WS('/', @.rec.debug, 'WE');			
			SET _GUID = IFNULL(NULLIF(_GUID, ''), @SYSTEM.Client.Session.GUID);
												SET @.rec.debug = CONCAT_WS('/', @.rec.debug, _GUID);			
			UPDATE `_user_accounts` ua, `_sys_db_logons` sdl
			SET
				ua.Last_auth_info = 
					CONCAT_WS('',
						-- concat(_VarStr(sdl.LOGGED_AT), ': '),
						CONCAT(sdl.LOGGED_AT, ': '),
						CONCAT_WS(' ',
							CONCAT(sdl.log_App_ID, ' (', sdl.con_DB, ')'),
							-- CONCAT('(', sdl.con_DB, ')'),
							CONCAT(_varStr('Host: '), sdl.log_HOST, ' ', sdl.log_HOST_NAME, ' (', sdl.log_MACADDRESS, ')'),
							CONCAT(_varStr('Dev: '), sdl.log_DEV_ID),
							CONCAT(sdl.log_mode, ''),
							NULL
						)
					)
			WHERE
				TRUE
				AND sdl.GUID = _GUID
				AND ua.OsobaGUID = sdl.log_USER_GUID
			;
			
		END IF;
	END IF;
	
	IF _MODE LIKE 'SESSION.%' THEN
--	TODO UWAGA!!!!!!!!! RACZEJ SIĘ WYCOFAĆ z www/mob z tych wywołań!!!!	wołane jest tylko 'SESSION.CHECK' !!!! WYWAL
	/*
		CALL _sessions_APP();
		przykład
		CALL _sessions_APP('SESSION.CHECK', 'sesja', '', '', '', '', '<select>');
		wołana jest 
			CALL _sessions('SESSION.CHECK', 'sesja', '', '', '', '', 'GO');
	*/
		/* 	było do sty 2022
	
		IF _MODE = 'SESSION.CHECK' THEN
			CALL _sessions(_MODE, _GUID, 'CHECK.TIME+PING', _Param_B, _Param_C, _Param_D, 'GO');
			SET _Need_Select = TRUE;
		ELSE
			CALL _sessions(_MODE, _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params);
		END IF;
		*/
		IF _MODE = 'SESSION.CHECK' THEN
			CALL _sessions_APP('Check.and.SET.Client.Session', _GUID, 'CHECK.TIME+PING', _Param_B, _Param_C, _Param_D, '<FULL>');
		ELSE
		--	jakie tu mogą jeszcze być????
			CALL _sessions(_MODE, _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params);
		END IF;
		IF _Need_Select THEN
            /*  od 1 IV 2025 używamy _sessions_SEL
			CALL _sessions_APP('SELECT.SHORT', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params); */
            CALL _sessions_SEL('SELECT.SHORT', _GUID, '', '', '');
		END IF;
		
	END IF;
	
	IF _MODE LIKE 'rec.%' THEN
--	TODO UWAGA!!!!!!!!! RACZEJ SIĘ WYCOFAĆ z www/mob z tych wywołań!!!!	
		IF _MODE LIKE 'rec.INSERT.UPDATE%' THEN	
											SET @.rec.debug = CONCAT_WS('/', @.rec.debug, _MODE);
			/*
		--	Uwaga dla Wstawiania - pobierz GUID by przekazać go niżej
			SET @.G.1 = _GUID;
			SET _GUID = Get_Session_GUID(_MODE, _GUID, '', '');
			SET @.G.2 = _GUID;
			CALL _sessions(_MODE, _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params);
			*/
			-- CALL _sessions('rec.INSERT.UPDATE', GUID/NULL, 'USER_GUID', 'log_APPNAME', 'log_APP_ID', 'log_DEV_ID' , '');
			SET _Params = 
			CONCAT_WS('&',
				CONCAT('log_APPNAME=', _Param_B),
				CONCAT('log_APP_ID=', _Param_C), 
				CONCAT('log_DEV_ID=', _Param_D),
				'<select>'
			);			
			-- CALL _sessions_APP('sdl.INSERT', '', '', 'SystemB2B', 'M.WWW.VOLTB2B', '172.20.0.1', '<select>')
			CALL _sessions_APP('INSERT', '', '', '', '', '', _Params);
			SET
				_GUID = @.sdl.GUID,
				_UserGUID = @.sdl.UserGUID
			;
			IF _Need_Select THEN
			--	Select po ...
                /*  od 1 IV 2025 używamy _sessions_SEL
                CALL _sessions_APP('SELECT.SHORT', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params); */
                CALL _sessions_SEL('SELECT.SHORT', _GUID, '', '', '');
			END IF;
		ELSEIF _MODE LIKE 'rec.INSERT.for.%' THEN
		/*********
			Spr. ile jest takich wywołań
		*********/
		--	Uwaga dla Wstawiania - pbierz GUID by przekazać go niżej
											SET @.rec.debug = CONCAT_WS('/', @.rec.debug, _MODE);
			SET _GUID = Get_Session_GUID(_MODE, _GUID, '', '');
			CALL _sessions(_MODE, _GUID, _Param_A, _Param_B, _Param_C, _Param_D, 'NEW');	-- ten NEW to na razie
		ELSEIF _MODE LIKE 'rec.CLOSE%' THEN	
			CALL _sessions_APP('CLOSE', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params);
		ELSE
		--	pozostałe rec.... JAKIE ?????????? POPRAWIĆ KOD!!!!!
											SET @.rec.debug = CONCAT_WS('/', @.rec.debug, _MODE);
			CALL _sessions(_MODE, _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params);
		END IF;
		
		IF _Need_Select THEN
		--	Select po wstawianiu!!!
            /*  od 1 IV 2025 używamy _sessions_SEL
			CALL _sessions_APP('SELECT', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params); */
            CALL _sessions_SEL('SELECT', _GUID, '', '', '');
		END IF;
	END IF;

	IF _MODE IN ('CHECK.Session', 'PING.Session') THEN
		SET 
			_MODE = CONCAT(_MODE, '.SET.Client.Session')
		;
	END IF;
	
	IF 
		_MODE LIKE '%SET.Client.Session%'
		OR
		_MODE LIKE 'Check.%'
		OR
		_MODE LIKE 'Ping.%'
	--	de facto ... IF _MODE IN ('SET.Client.Session', 'Check.SET.Client.Session', 'Check.and.SET.Client.Session') THEN	
	THEN
	-- IF _MODE IN ('SET.Client.Session', 'Check.SET.Client.Session', 'Check.and.SET.Client.Session') THEN
	/************************************************************************************************
		zawsze - ustawia sesje na sesję wejściową (może pozosta martwą!)
		CALL _sessions_APP('SET.Client.Session', 'EVENT:2737:20220120:localhost:47130', '', '', '', '', '<select>');
		dla "Check.SET.Client.Session..."
		CALL _sessions_APP('Check.and.SET.Client.Session', 'EVENT:2737:20220120:localhost:47130', '', '', '', '', '<select>');
			a dla Grzesia - EXE choc to to samo!!!
		CALL _sessions_APP('PING.and.SET.Client.Session', 'EVENT:2737:20220120:localhost:47130', '', '', '', '', '<select>');
		-- po co??? w _Param_A jest np. 'CHECK.TIME+PING' 
		od 12 V 2022 n prośbe apro
		w _Param_B możemy (nie musimy) mieć login usera (dod. zabezp.) gdy jest taki login to spr. dodatk. w WHERE
	************************************************************************************************/
				IF FALSE AND NOT (@session.globals.Owner IN ('CDG', 'MPGK', 'KONKOL', 'SIMEX')) THEN
					DO _counters_tools('INC', CONCAT('_sessions_APP: ', _MODE, '.1.PRE'), '', '');	
				END IF;
		SET 
		--	Czy ost. sprawdz. było 4 min - 240 sec. temu? Jeśli tak to nie sprawdzaj!
		--	Dla EXE i nie zerw. poł. zmienne (np. @SYSTEM.Current.Session.Last.Check) są
		--	uzupełnione i mozna porównywać ale dla
		--	WWW/MOB nie są ustawione i mogą być NULL (z PHP) i wtedy @.sa.Check.Valid prawie zawsze ejst TRUE
			@.sa.Check.Valid := ((@.sa.diff := 
				TIMESTAMPDIFF(SECOND, IFNULL(@SYSTEM.Current.Session.Last.Check, CURRENT_DATE()), NOW())
				) > 300)
		;
							set @.s.app.log = concat_WS('/', @.s.app.log, 'WE.1');
		SET @SYSTEM.Current.Session.Last.Check = IF(@.sa.Check.Valid, NOW(), @SYSTEM.Current.Session.Last.Check);
		
		SET @.sa._MODE = _MODE, @.sa._Need_Select = _Need_Select;
		IF 
			@.sa.Check.Valid 
			AND
			(
			_MODE LIKE 'Check.%'
			OR
			_MODE LIKE 'Ping.%'
			)
		THEN
							set @.s.app.log = concat_WS('/', @.s.app.log, 'PING');
					-- DO _counters_tools('INC', CONCAT('_sessions_APP: ', _MODE, '.2.TRY.PING'), '', '');	
		--	Ważne!!!!	
			SET @.PING.Session = NULL, @.PING.Make.Sense = NULL, @._sys_db_logons.RC = 0;
		/*	16 VI 2023 było ale deadlocki
			UPDATE 
			(
				SELECT 
					sdlwe.GUID 
				FROM `_sys_db_logons` sdlwe
				WHERE
					sdlwe.GUID = _GUID
					AND IFNULL(_Param_B, '') IN (sdlwe.Log_USER, '')
			) sdlwe,
			`_sys_db_logons` sdl 
			SET 
				sdl.Do_Info = 'CHECK.TIME+PING'
			WHERE
				sdl.GUID = (@.PING.Session := sdlwe.GUID)
				AND (@.PING.Make.Sense := TIMESTAMPDIFF(MINUTE, sdl.PING_AT, NOW()) >= LEAST(5, sdl.TIME_OUT DIV 2))
			;
		jest ...
		*/
			SELECT 
				sdl.GUID,
				TIMESTAMPDIFF(MINUTE, sdl.PING_AT, NOW()) >= LEAST(5, sdl.TIME_OUT DIV 2) AS PING_Make_Sense
			INTO
				@.PING.Session, @.PING.Make.Sense
			FROM `_sys_db_logons` sdl
			WHERE
				sdl.GUID = _GUID
				AND IFNULL(_Param_B, '') IN (sdl.Log_USER, '')
			;
			IF @.PING.Session IS NOT NULL AND @.PING.Make.Sense THEN
				UPDATE `_sys_db_logons` sdl 
				SET 
					sdl.Do_Info = 'CHECK.TIME+PING'
				WHERE
					sdl.GUID = @.PING.Session
				;
				SET @._sys_db_logons.RC = ROW_COUNT();
			END IF;
		
			
			IF @._sys_db_logons.RC > 0 AND @.PING.Session IS NOT NULL AND @.PING.Make.Sense THEN
				IF FALSE AND NOT (@session.globals.Owner IN ('CDG', 'MPGK', 'KONKOL', 'SIMEX')) THEN
					DO _counters_tools('INC', CONCAT('_sessions_APP: ', _MODE, '.3.PING'), '', '');	
				END IF;
				set @.sdfsdfx = 1;
			END IF;
			
			/*	było
			IF IFNULL(_Param_B, '')  = '' THEN
				UPDATE `_sys_db_logons` sdl 
				SET 
					sdl.Do_Info = 'CHECK.TIME+PING',
					sdl.GUID = (@.Do_Info.Session := _GUID)
				WHERE 
					sdl.GUID = _GUID
				; 
				SET @._sys_db_logons.RC = ROW_COUNT();
				-- SET @._sys_db_logons.RC = 1;
			ELSE
			--	od 12 V 2022 n prośbe apro
			--	w _Param_B możemy (nie musimy) mieć login usera (dod. zabezp.) gdy jest taki login to spr. dodatk. w WHERE
				UPDATE `_sys_db_logons` sdl 
				SET 
					sdl.Do_Info = 'CHECK.TIME+PING',
					sdl.GUID = (@.Do_Info.Session := _GUID)
				WHERE 
					sdl.GUID = _GUID
					AND sdl.Log_USER = _Param_B
				; 
				SET @._sys_db_logons.RC = ROW_COUNT();
				-- SET @._sys_db_logons.RC = 1;
				-- IF @._sys_db_logons.RC < 1 THEN
				IF @.Do_Info.Session IS NULL THEN
				--	to nie twoja sesja !!!
					-- na razie bo to groźne 
					SET _GUID = '{prohibited}';
				END IF;
			END IF;
			*/
			IF IFNULL(_Param_B, '')  != '' AND @.PING.Session IS NULL THEN
			--	PING z userem a nie ma takiej sesji ...
			--	to nie twoja sesja !!!
			-- 	na razie ustaw cokolwiek bo to groźne 
				SET _GUID = '{prohibited}';
			END IF;
					-- IF _MODE LIKE '%SET.Client.Session%' AND @._sys_db_logons.RC < 1 THEN
			IF _MODE LIKE '%SET.Client.Session%' AND @.PING.Session IS NULL THEN
			--	Jesli dodatkowo ustawiamy sesję to sprawdzmy czy w ogóle istnieje albo czy dało sie ustawic PING (bo może jest close)
				-- na razie bo to groźne 
				SET _MODE = REPLACE(_MODE, 'SET.Client.Session', '');
				-- SET _MODE = _MODE;
			END IF;
		--	Ważne!!!!	
			SET @.PING.Session = NULL;
			-- SET _Need_Select = _Need_Select OR (_MODE LIKE 'Check.%'); 	-- Select zawsze gdy CHECK z WWW
		END IF;
		
							set @.s.app.log = concat_WS('/', @.s.app.log, '2');
		IF _MODE LIKE '%SET.Client.Session%' THEN -- AND @.sa.Check.Valid THEN
							set @.s.app.log = concat_WS('/', @.s.app.log, 'SET.Client.Session');
		--	Zawsze ustaw (zapamietaj) starą zmienną przed zmianą ...
			SET @SYSTEM.Current.Session.GUID.OLD = @SYSTEM.Current.Session.GUID;
		--	... Ustaw nową wartość
			SET @SYSTEM.Current.Session.GUID = _GUID;
		--	Ustaw słynną sesję klienta	
			SET @SYSTEM.Client.Session.GUID = @SYSTEM.Current.Session.GUID;
		--	Czy sesja sie zmieniła ? - porównanie starej i nowej ...
			SET @SYSTEM.Current.Session.GUID.Changed = !(@SYSTEM.Current.Session.GUID.OLD <=> @SYSTEM.Current.Session.GUID);
		--	Czy sesja sie zmieniła ? - porównanie starej i nowej ...
			IF @SYSTEM.Current.Session.GUID.Changed OR IFNULL(@SYSTEM.Client.Session.log_USER_GUID, '') = '' THEN	-- ten OR dopisałem bo jednak czasem usera nie czyli innych małp takze - wtedy zawsze pobierz
			--	zmieniono sesję zatem ustaw zmienne
							set @.s.app.log = concat_WS('/', @.s.app.log, 'SET.VAR');
				CALL _sessions_APP('SET.VAR', @SYSTEM.Current.Session.GUID, '', '', '', '', '<select>');
			END IF;
		END IF;
		--	DO _counters_tools('SET', _MODE, '', '');		-- to tylko Licznik!!!!
		
		IF _Need_Select THEN
							set @.s.app.log = concat_WS('/', @.s.app.log, 'Need_Select');
		--	Select po ...
            /*  od 1 IV 2025 używamy _sessions_SEL
			CALL _sessions_APP('SELECT.SHORT', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params); */
            CALL _sessions_SEL('SELECT.SHORT', _GUID, '', '', '');
		END IF;
	END IF;

	IF _MODE IN ('Use.Session') THEN
	/************************************************************************************************
		Ponownie użyj sesji istniejacej sesji.
		Dla połączeń typu pooling!!!
		Sprawdza istnienie robi ping - generalnie taki Ping/Check ale 
		uwzglednia że małpy moga być po "kims innym"
		CALL _sessions_APP('Use.Session', 'EVENT:2737:20220120:localhost:47130', '', '', '', '', ''['']['<select>']);
	************************************************************************************************/
		SET 
			@.sdl.check.SID = _GUID,
			@.sdl.check.Exists = FALSE, @.sdl.check.Active = FALSE, @.sdl.check.Make.Sense = FALSE
		;
	--	Ten update zwraca przy okazji czy istnieje i czy jest active	
		UPDATE `_sys_db_logons` sdl 
		SET 
			sdl.Do_Info = 
				IF(
				--	jeśli wymagane ...
					(@.sdl.check.Exists := (sdl.GUID = @.sdl.check.SID))
					AND
					(@.sdl.check.Active := NOT sdl.Inactive)
					AND
					(@.sdl.check.Make.Sense := (TIMESTAMPDIFF(MINUTE, sdl.PING_AT, NOW()) >= LEAST(5, sdl.TIME_OUT DIV 2))),
					'CHECK.TIME+PING',
				--	nie ruszaj
					sdl.Do_Info
				)
		WHERE
			sdl.GUID = @.sdl.check.SID 
			AND IFNULL(_Param_B, '') IN (sdl.Log_USER, '')	--	Dodatek dla apro z userem w _Param_B
		;
			--	SELECT @.sdl.check.SID, @.sdl.check.RC, @.sdl.check.Exists, @.sdl.check.Active, @.sdl.check.Make.Sense;
		SET @.sdl.check.RC = ROW_COUNT();
		IF @.sdl.check.Exists AND @.sdl.check.Active THEN
		--	Sesja istnieje i nie jest jeszcze zamknięta - ale... 
		--	...może PING juz ja zamknął i jest TimeOut?
		--	@.sdl.check.Active jest teraz TRUE ale jeśli ten update wyżej się wykonał to onacza że miał sens i mógł zmienic Active!!
		--	inaczej mówiac był juz czas na PINGA - zatem teraz sprawdz czy jest Active?
			IF @.sdl.check.Make.Sense THEN
			--	Ten update wyżej miał sens tzn. był juz czas na PINGA - zatem teraz sprawdz czy jest Active?
				SELECT 
					NOT sdl.Inactive
				INTO
					@.sdl.check.Active
				FROM `_sys_db_logons` sdl
				WHERE
					sdl.GUID = @.sdl.check.SID -- @.PING.Session
					-- sdl.GUID = _GUID
					-- AND IFNULL(_Param_B, '') IN (sdl.Log_USER, '')
				;
				--	SELECT @.sdl.check.SID, @.sdl.check.RC, @.sdl.check.Exists, @.sdl.check.Active, @.sdl.check.Make.Sense;
			END IF;
		--	@.sdl.check.Active może być nadal TRUE ale może być teraz już FALSE!!!	...
			IF @.sdl.check.Active AND !(_GUID <=> @SYSTEM.Current.Session.GUID) THEN
			--	Jeśli jest Active i sesja wchodząca _GUID (@.sdl.check.SID) jest różna od aktualnej ...
			--	... Ustaw nową wartość
				SET @SYSTEM.Current.Session.GUID = _GUID;
			--	Ustaw słynną sesję klienta	
				SET @SYSTEM.Client.Session.GUID = @SYSTEM.Current.Session.GUID;
			--	zmieniono sesję zatem ustaw zmienne
				CALL _sessions_APP('SET.VAR', @SYSTEM.Current.Session.GUID, '', '', '', '', '<select>');
			END IF;
		END IF;
	--	Dodatek dla apro z userem w _Param_B
		IF IFNULL(_Param_B, '')  != '' AND NOT @.sdl.check.Exists THEN
		--	PING z userem a nie ma takiej sesji ...
		--	to nie twoja sesja !!!
		-- 	na razie ustaw cokolwiek bo to groźne 
			SET _GUID = '{prohibited}';
		END IF;
		IF _Need_Select THEN
		--	Select po ...
            /*  od 1 IV 2025 używamy _sessions_SEL
			CALL _sessions_APP('SELECT.SHORT', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params); */
            CALL _sessions_SEL('SELECT.SHORT', _GUID, '', '', '');
		END IF;
		
	END IF;
	
	IF _MODE LIKE '%Do_Info%' THEN
	/************************************************************************************************
		zawsze - ustawia sesje na sesję wejściową (może pozosta martwą!)
		CALL _sessions_APP('Do_Info', 'CON:124242434234', 'SLEEP', 'Uśpienie sesji', '', '', '<select>');
		CALL _sessions_APP('Do_Info', 'CON:124242434234', 'WAKE.UP', 'Obudzenie sesji', '', '', '<select>');
		w _Param_A 	jest np. 'CHECK.TIME+PING' 
		w _Param_B 	ew. LAST_MSG
	************************************************************************************************/
				IF FALSE AND NOT (@session.globals.Owner IN ('CDG', 'MPGK', 'KONKOL', 'SIMEX')) THEN
					DO _counters_tools('INC', CONCAT('_sessions_APP: ', _MODE), '', '');		-- to tylko Licznik!!!!
				END IF;
		
		UPDATE `_sys_db_logons` sdl 
		SET 
			sdl.Do_Info = _Param_A,
			sdl.LAST_MSG = _Param_B	--	np 'Zamykanie sesji'
		WHERE 
			sdl.GUID = _GUID
		; 
		IF _Need_Select THEN
		--	Select po ...
            /*  od 1 IV 2025 używamy _sessions_SEL
			CALL _sessions_APP('SELECT.SHORT', _GUID, _Param_A, _Param_B, _Param_C, _Param_D, _Params); */
            CALL _sessions_SEL('SELECT.SHORT', _GUID, '', '', '');
		END IF;
	END IF;

	IF _MODE IN ('CLEAR.VAR', 'CLEAR.VAR.FULL') THEN
		SET
			@SYSTEM.Client.Session.Kind = NULL,
			@SYSTEM.Client.Session.log_USER_GUID = NULL,
			@SYSTEM.Client.Session.log_USER = NULL,
			@SYSTEM.Client.Session.log_USER.user_type = NULL, 
			@SYSTEM.Client.Session.log_USER.admin = NULL,
			@SYSTEM.Client.Session.log_USER.ugrpguid = NULL,
			@SYSTEM.Client.Session.log_Host = NULL,
			@SYSTEM.Client.Session.log_HOST_NAME = NULL,
			@SYSTEM.Client.Session.log_MACAddress = NULL,
			@SYSTEM.Client.Session.log_AppName = NULL,
			@SYSTEM.Client.Session.log_APP_ID = NULL,
			@SYSTEM.Client.Session.log_DEV_ID = NULL,
			@SYSTEM.Client.Session.IS.System = NULL,
			@SYSTEM.Client.Session.Status = NULL,
			@SYSTEM.Client.Session.Exists = 0
		;
	END IF;
	
	IF _MODE IN ('SET.VAR', 'SET.VAR.?') THEN
	/************************************************************************************************
		Ustaw zmienne najpierw czyszcząc
		CALL _sessions_APP('SET.VAR', 'EVENT:2737:20220120:localhost:47130', '', '', '', '', ''['']['<select>']);
		UWAGA
		CALL _sessions_APP('SET.VAR.?', '', '', '', '', '', '');
		'SET.VAR.?'	- oznacza że nie pobieramy danych gdy @SYSTEM.Client.Session.Exists nie jest NULL
					ta zmienna jest nowa i w starszych inicjacjach małp nie wystepuje zatem gdy jest null 
					wstawiamy wszystkie zmienne
		dodaj duplikat małpy @SYSTEM.Client.Session.log_USER_GUID
	************************************************************************************************/
		IF _MODE = 'SET.VAR.?' AND @SYSTEM.Client.Session.Exists IS NOT NULL THEN
			LEAVE S_sessions_APP;
		END IF;
				IF FALSE AND NOT (@session.globals.Owner IN ('CDG', 'MPGK', 'KONKOL', 'SIMEX')) THEN
					DO _counters_tools('INC', CONCAT('_sessions_APP: ', _MODE), '', '');		-- to tylko Licznik!!!!
				END IF;
		
		SET
			_GUID = IFNULL(NULLIF(_GUID, ''), @SYSTEM.Current.Session.GUID) -- poniewaz moge wołac sobie 'SET.VAR' bez parametrów
		;
	--	czyść zmienne	
		CALL _sessions_APP('CLEAR.VAR', '', '', '', '', '', '');
	--	.. jeśli tak to uzupełnij dane
								-- set @Deb.1 = concat_WS(' / ', @Deb.1, 'Variables.1');
		-- IF NULLIF(@SYSTEM.Client.Session.GUID, '') IS NULL THEN
		SELECT 
			IFNULL(l.Kind, 'WWW'),
			l.log_USER_GUID,
			l.log_USER,
		/*	!!!!!!!!!! dodać do _sys_db_logons pola user_type, admin, ugrpguid i inicjowac przy kreowaniu/logowaniu	*/
			u.user_type, 
			u.admin,
			IFNULL(o.ugrpguid, 'ALL') AS ugrpguid,
			l.log_Host,
			IFNULL(l.log_HOST_NAME, 'PC') AS log_HOST_NAME,
			l.log_MACAddress,
			l.log_AppName,
			l.log_APP_ID,
			l.log_DEV_ID,
			l.Status,
			TRUE AS Session_Exists
		INTO
			@SYSTEM.Client.Session.Kind,
			@SYSTEM.Client.Session.log_USER_GUID,
			@SYSTEM.Client.Session.log_USER,
			@SYSTEM.Client.Session.log_USER.user_type, 
			@SYSTEM.Client.Session.log_USER.admin,
			@SYSTEM.Client.Session.log_USER.ugrpguid,
			@SYSTEM.Client.Session.log_Host,
			@SYSTEM.Client.Session.log_HOST_NAME,
			@SYSTEM.Client.Session.log_MACAddress,
			@SYSTEM.Client.Session.log_AppName,
			@SYSTEM.Client.Session.log_APP_ID,
			@SYSTEM.Client.Session.log_DEV_ID,
			@SYSTEM.Client.Session.Status,
			@SYSTEM.Client.Session.Exists
		FROM `_sys_db_logons` l
		/*	!!!!!!!!!! 2 x LEFT kiedyś wywalić - dodać do _sys_db_logons pola user_type, admin, ugrpguid i inicjowac przy kreowaniu/logowaniu	*/
		LEFT JOIN `_user_accounts` u ON u.OsobaGUID = l.log_USER_GUID
		LEFT JOIN `osoby` o ON o.GUID = l.log_USER_GUID
		WHERE
			l.GUID = _GUID
		;
	--	Ta zmienna ponizej jest tu inicjowana i nie zmieniana nigdzie - sluzy do badania czy czasem jest null (rozlaczenie) czy nie (nie czyszczona)
		SET @SYSTEM.Client.Session.log_USER_GUID.TEST = @SYSTEM.Client.Session.log_USER_GUID;
		/*
			IS.System to zmiena określająca czy sesja jest uzytkownika (exe/www/etc) czy systemowa (event/todo/etc)
		*/
		SET @SYSTEM.Client.Session.IS.System = 
			(IFNULL(@SYSTEM.Client.Session.Kind, '') = 'EVENT')
			OR
			(IFNULL(@SYSTEM.Client.Session.GUID, '') LIKE 'EVENT%')
			OR
			(IFNULL(@SYSTEM.Client.Session.log_USER_GUID, '') = 'System')
		;	
		IF @SYSTEM.Client.Session.IS.System THEN
			SET
				@session.Registration.UserGUID = 'System',
				@session.user.CurrugrpGUID = 'ALL',
				@session.user.Admin = 0,
				@session.Registration.Admin = 0
			;
		ELSE
			SET
				@session.Registration.UserGUID = IFNULL(@SYSTEM.Client.Session.log_USER_GUID, @session.Registration.UserGUID),
				@session.user.CurrugrpGUID = IFNULL(@SYSTEM.Client.Session.log_USER.ugrpguid, @session.user.CurrugrpGUID),
				@session.user.Admin = IFNULL(@SYSTEM.Client.Session.log_USER.admin, @session.user.Admin),
				@session.Registration.Admin = IFNULL(@SYSTEM.Client.Session.log_USER.admin, @session.Registration.Admin)
			;
		END IF;
								-- set @Deb.1 = concat_WS(' / ', @Deb.1, 'Variables.2');
		IF @SYSTEM.Client.Session.Kind LIKE '%WWW%' OR @SYSTEM.Client.Session.Kind LIKE '%MOB%' THEN
			SET
				@session.Registration.UserGUID = @SYSTEM.Client.Session.log_USER_GUID,
				@session.user.CurrugrpGUID = @SYSTEM.Client.Session.log_USER.ugrpguid,
				@session.user.Admin = @SYSTEM.Client.Session.log_USER.admin,
				@session.Registration.Admin = @SYSTEM.Client.Session.log_USER.admin
			;
			/*
			rafal prosil !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			SET
				@session.Registration.UserLogin = @SYSTEM.Client.Session.log_USER,
				@session.user.UserLogin = @SYSTEM.Client.Session.log_USER,
				@session.user.UserGUID = @SYSTEM.Client.Session.log_USER_GUID,
			;
			*/
		END IF;
		IF @SYSTEM.Client.Session.Kind = 'EXE' THEN
			SET
				@session.Registration.UserGUID = IFNULL(@session.Registration.UserGUID, @SYSTEM.Client.Session.log_USER_GUID),
				@session.user.CurrugrpGUID = IFNULL(@session.user.CurrugrpGUID, @SYSTEM.Client.Session.log_USER.ugrpguid),
				@session.user.Admin = IFNULL(@session.user.Admin, @SYSTEM.Client.Session.log_USER.admin),
				@session.Registration.Admin = IFNULL(@session.Registration.Admin, @SYSTEM.Client.Session.log_USER.admin)
			;
		END IF;			
	/*
		1. Czy 
			b.stare logowanie via C_User60
			nowsze _sys_connection
			najnowsze sys_db_logons
			...
		2. ..i zwiazane z tym zmiene
		
	*/
		SET @session.INFO.Log.Ver = '4.0._sys_db_logons_Tools';
		
		IF @session.INFO.Log.Ver = '4.0._sys_db_logons_Tools' THEN
		--	Wszystkie nowe zmienne do starych 
			SET
				@session.INFO.User_GUID = @SYSTEM.Client.Session.log_USER_GUID,
				@session.INFO.User_Login = @SYSTEM.Client.Session.log_USER,
				@session.INFO.User_user_type = @SYSTEM.Client.Session.log_USER.user_type,
				@session.INFO.User_UgrpGUID = @SYSTEM.Client.Session.log_USER.ugrpguid,
				@session.INFO.User_Admin = @SYSTEM.Client.Session.log_USER.admin,
				@session.INFO.Host_IP = @SYSTEM.Client.Session.log_Host,
				@session.INFO.Host_Name = @SYSTEM.Client.Session.log_HOST_NAME,
				@session.INFO.AppName = @SYSTEM.Client.Session.log_AppName,
				@session.INFO.MACAddress = @SYSTEM.Client.Session.log_MACAddress
			;
			
			IF @session.INFO.Host_IP = '' AND @session.INFO.User_GUID = 'System' THEN
				SET @session.INFO.Host_IP = 'Server';
			END IF;
		END IF;
								-- set @Deb.1 = concat_WS(' / ', @Deb.1, 'Variables.8');
		
		SET @session.INFO.INSERT.LOG.ip = 
			CONCAT_WS('',
				@session.INFO.Host_Name, 
				' - IP: ', @session.INFO.Host_IP, 
				', MCA: ', @session.INFO.MACAddress, 
				', ID: ', IFNULL(@SYSTEM.Client.Session.GUID, CONNECTION_ID())
			)
		;
	/*
		STARE małpy których czasem brak!!!
		np. zmienne do zapisów nagłówków etc.
		UWAGA były one ustawiane w 
		proc. CALL _sys_db_logons_Tools('SELECT.Moduly'...
	*/
		SET @session.CheckLogonUser = @SYSTEM.Client.Session.log_USER_GUID;
		SET @session.CurrMyCompNameStr = IFNULL(@session.CurrMyCompNameStr, 'local'); 
		SET @session.CurrMyIPOnly = IFNULL(@session.CurrMyIPOnly, ''); 
		SET @session.CurrMACAddresses = IFNULL(@session.CurrMACAddresses, @SYSTEM.Client.Session.log_MACAddress); 
		
		SET @session.Registration.UserLogin = IFNULL(@session.Registration.UserLogin, @SYSTEM.Client.Session.log_USER); 
		SET @session.Registration.IdnUser = IFNULL(@session.Registration.UserLogin, @SYSTEM.Client.Session.log_USER); 
		
		SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, @session.Registration.UserLogin); 
		SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, @SYSTEM.Client.Session.log_USER); 
		SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, '<by procedure call>'); 
			

	/*
		poniewaz nie mam 100% pewnosci to czasem zawlam full refresh (_Session_Refresh_Variables) and tylko settings (_Setting_Variables)
		zalezy to czy wolamy chcek z np. z EXE 
		dlatego gdy w _Params = 'GO' lub '' to settings ale gdy w _Param_E = 'GO.FULL' to refresh
	*/
								-- set @Deb.1 = concat_WS(' / ', @Deb.1, 'Variables.9');
		IF _Params LIKE '%<FULL>%' THEN
			CALL _Session_Refresh_Variables('', '', '');
		ELSE
		--	spr. zmienną którą i tak sprawdzamy wewn. ale już tutaj sprawdzmy i jak jest <> null to nie wołaj - bezp. i szybciej!!!
			IF @_Setting_Variables.alocaltime IS NULL THEN
				CALL _Setting_Variables('CHECK', '', '');
			END IF;
		END IF;
	END IF;

END$$
DELIMITER ;

DELIMITER $$
DROP PROCEDURE IF EXISTS `_sessions_SEL`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_sessions_SEL`(
	IN _MODE VARCHAR(250), 
	IN _GUID VARCHAR(255),
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200),
	IN _Params MEDIUMTEXT
)
/*
	Procedura TYLKO do selectów - selecty nie zaimplem. w _sessions_APP aby uchronic alg. w trig.
*/
_sessions_SEL: BEGIN
	DECLARE _SQLText, _Params TEXT;
	DECLARE _Need_Select BOOLEAN;
	DECLARE _UserGUID, _Md5_UserGUID VARCHAR(150); 
	-- DECLARE _UserGUID, _Md5_SESSION_GUID, _Md5_UserGUID, _Md5_Login, _Md5_Pswd, _Md5_log_DEV_ID, _Md5_log_APP_ID VARCHAR(150); 
	DO _Birth_System(); -- było DO _TriggerDisabled();	--	aby miec @session.globals.INPUT_SALT_Hash

	SET _Need_Select = (_Params LIKE '%<select%>%');
	SET _Params = REPLACE(_Params, '<select>', '');
	SET
		@._sessions_APP.Result = 'OK',
		@._sessions_APP.Result.Msg = ''
	;
    
		IF _MODE LIKE 'SELECT%' THEN
			IF _MODE LIKE 'SELECT' THEN
				SET @.s.g.2.1 := _GUID;
				SELECT
				-- 	sdl.*,
					sdl.GUID, sdl.log_USER, sdl.log_USER_GUID, 
					sdl.LAST_MSG, 
					IF(sdl.LAST_MSG LIKE 'ERR%' OR sdl.LAST_MSG LIKE '%.RODO.Need.Change.PSWD',
						sdl.LAST_MSG,
						''
					) AS VIEW_MSG,
					sdl.STATUS, 
					u.Administrator, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
					NazwiskoImie AS NazwiskoImiona,
					u.User_account_Type,
					IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
					IFNULL(
						IFNULL(
							(SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
							,
							(SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
						),
						''
					) AS KontrGUID
				FROM `_sys_db_logons` sdl
				LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
				WHERE 
					sdl.GUID = _GUID
					-- sdl.GUID = @.SYSTEM.Last_Insert.Session.GUID
				;
			END IF;
		
			IF _MODE IN ('SELECT.SHORT', 'SELECT.CHECK') THEN
				SET @.s.g.2.1 := _GUID;
				SELECT
					IFNULL(sdl.GUID, _GUID) AS GUID,
					IFNULL(sdl.log_USER, '?') AS log_USER,
					IFNULL(sdl.log_USER_GUID, '?') AS log_USER_GUID,
					IFNULL(sdl.LAST_MSG, ses_err.LAST_MSG) AS LAST_MSG,
					IFNULL(sdl.STATUS, ses_err.STATUS) AS STATUS,
					IFNULL(sdl.INACTIVE, 1) AS INACTIVE
				FROM
					(
					SELECT
						_VarStr(IF(_GUID = '{prohibited}', 'Sesja jest własnością innego użytkownika', 'Sesja nie istnieje')) AS LAST_MSG,
						_VarStr(IF(_GUID = '{prohibited}', 'ERR.PROHIBITED', 'ERR.NOT.EXISTS!!!')) AS STATUS
					) ses_err
				LEFT JOIN
					(
					SELECT
					-- 	sdl.*,
						sdl.GUID, sdl.log_USER, sdl.log_USER_GUID, 
						IFNULL(sdl.LAST_MSG, '') AS LAST_MSG, 
						sdl.STATUS,
						sdl.INACTIVE
					FROM `_sys_db_logons` sdl
					WHERE 
						sdl.GUID = _GUID
					) sdl ON TRUE 
				;
				/*
				SELECT
				-- 	sdl.*,
					sdl.GUID, sdl.log_USER, sdl.log_USER_GUID, 
					sdl.LAST_MSG, 
					sdl.STATUS
				FROM `_sys_db_logons` sdl
				WHERE 
					sdl.GUID = _GUID
					-- sdl.GUID = @.SYSTEM.Last_Insert.Session.GUID
				;
				
				*/
			END IF;
            --  WYWAL wszystkie _MODE LIKE --SELECT !!!!!!!!!!!!!!!!!!!  
			IF _MODE LIKE '--SELECT.AUTH' THEN
				SELECT
					tsel.Session_GUID,
					tsel.Oper_Status AS Verify_Status, --  AS Inf_Status, 
					tsel.Oper_Status LIKE 'OK%' AS Verify_OK, --  AS Inf_Status_OK,  
					tsel.Oper_Status LIKE 'OK%' AS _Verify_OK,	-- kompatybilnośc z poprz. 
					-- tar.USER_GUID, -- tar.OsobaGUID,
					tsel.Oper_Status_Msg AS Msg,
					tsel.Oper_Status_Msg AS _MSG,	-- kompatybilnośc z poprz. 
					CONCAT_WS('\n',
						NULLIF(tsel.Msg_Warn, ''),
						tsel.Msg_Log
					) AS MSG_LONG,
					tsel.Msg_Warn AS Msg_Warning,
					(IFNULL(tsel.Msg_Warn, '') <> '') AS IS_Warning,
					tsel.Status_N_Warn AS Verify_Status_All,
					-- tar.Add_MSG AS Inf_MsgEx,
					-- było ale zabrałem tsel.Verify_Access_available, --  AS Inf_Access_available,
					-- było ale zabrałem tsel.MSG_APP_ID_Err, -- tekst o braku dostepy
					-- było ale zabrałem tsel.MSG_APP_ID_OK,	 -- tekst o dostepach (dodatk.)
					IFNULL(u.err_logon_count, 0) AS err_logon_count,
					(@.auth.Max_User_Err_logon_count - IFNULL(u.err_logon_count, 0)) AS logon_tries, 
					sdl.GUID, 
					sdl.log_USER, 
					sdl.log_USER_GUID, 
					sdl.LAST_MSG, 
					/*
					IF(sdl.LAST_MSG LIKE 'ERR%' OR sdl.LAST_MSG LIKE '%.RODO.Need.Change.PSWD',
						sdl.LAST_MSG,
						''
					) AS VIEW_MSG,
					*/
					sdl.STATUS, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
					u.User_account_Type,
					u.Administrator, 
					-- IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
					u.Ad_mail,
					IFNULL(
						IFNULL(
							(SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
							,
							(SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
						),
						''
					) AS KontrGUID
				FROM `t_ua_inf` tsel
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tsel.Session_GUID
				-- LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
				-- LEFT JOIN `v_user_accounts` u ON u.GUID = sdl.log_USER_GUID
				LEFT JOIN `v_user_accounts_short` u ON u.GUID = sdl.log_USER_GUID
				WHERE 
					tsel.Session_GUID = _GUID
					-- tsel.Session_GUID = @.SYSTEM.Last_Insert.Session.GUID
				;
			END IF;
			
			IF _MODE LIKE '--SELECT.old.AUTH' THEN
				SELECT
					Session_GUID,
					tar.Verify_Status, --  AS Inf_Status, 
					tar.Verify_OK, --  AS Inf_Status_OK,  
					-- tar.USER_GUID, -- tar.OsobaGUID,
					tar.MSG, --  AS Inf_Msg, 
					tar.MSG_LONG, --  AS Inf_Msg_Long,
					-- tar.Add_MSG AS Inf_MsgEx,
					tar.Verify_Access_available, --  AS Inf_Access_available,
					tar.MSG_APP_ID_Err,
					tar.MSG_APP_ID_OK,
					sdl.GUID, 
					sdl.log_USER, 
					sdl.log_USER_GUID, 
					sdl.LAST_MSG, 
					/*
					IF(sdl.LAST_MSG LIKE 'ERR%' OR sdl.LAST_MSG LIKE '%.RODO.Need.Change.PSWD',
						sdl.LAST_MSG,
						''
					) AS VIEW_MSG,
					*/
					sdl.STATUS, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
					-- u.NazwiskoImie AS NazwiskoImiona,
					u.User_account_Type,
					u.Administrator, 
					-- IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
					IFNULL(
						IFNULL(
							(SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
							,
							(SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
						),
						''
					) AS KontrGUID
				FROM `t_auth_rec` tar
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tar.Session_GUID
				LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
				WHERE 
					tar.Session_GUID = _GUID
					-- tar.Session_GUID = @.SYSTEM.Last_Insert.Session.GUID
				;
			END IF;

			IF _MODE LIKE '--SELECT.AUTH._sys_db_logons_Tools' THEN
			--	_sys_db_logons_Tools
				SELECT 
					l.GUID, l.log_USER, l.log_USER_GUID, 
					-- l.LAST_MSG, 
					IFNULL(NULLIF(@.auth.Final.MSG, ''), @.auth.Final.Verify_Status) AS LAST_MSG,
					l.STATUS, u.Administrator, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, u.User_account_Type, u.user_type,
					-- IF(l.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
					IF(@.auth.Final.Verify_Status = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
				FROM `_sys_db_logons` l
				LEFT JOIN `v_intnet_users` u ON u.GUID = l.log_USER_GUID
				WHERE 
					l.GUID = _GUID
				;
			END IF;
			
			IF _MODE LIKE '--SELECT.AUTH._sys_authorization' THEN
			--	_sys_authorization
				SELECT
					-- tsel.*,
					sdl.GUID AS _Session_GUID, 
					tsel.IN_Mode AS L_Mode,
					tsel.UserGUID AS USER_GUID,
						-- sdl.log_USER AS User_login,
					u.login AS User_login,
					tsel.Oper_Status LIKE 'OK%' AS _Verify_OK,
					tsel.Oper_Status AS _Verify_Status,
					tsel.Oper_Status_Msg AS _MSG,	-- kompatybilnośc z poprz. 
					u.User_account_Type AS User_type,
					u.Administrator AS admin, 
					u.Status,
					u.Ad_Mail,
					u.date_from,
					u.date_to,
					IFNULL(u.err_logon_count, 0) AS err_logon_count,
					u.GUID AS OsobaGUID,
					tsel.Owner,
					tsel.APP_ID,
					
					u.User_account_Type AS Typ,
					IF(@session.globals.RODO.Days = 0, '2100-01-01', DATE(DATE_ADD(u.Last_Change_Pswd, INTERVAL @session.globals.RODO.Days DAY))) AS USER_First_Day_to_Change_Pswd,
					u.Last_Change_Pswd AS USER_Last_Change_Pswd,
					tsel.Salt AS _INPUT_SALT_Hash,
							-- u.
				/*
					
					tsel.Msg_Log,
					tsel.Owner,
						-- tsel.Session_GUID,
					tsel.Oper_Status AS Verify_Status, --  AS Inf_Status, 
					tsel.Oper_Status LIKE 'OK%' AS Verify_OK, --  AS Inf_Status_OK,  
					tsel.Oper_Status LIKE 'OK%' AS _Verify_OK,	-- kompatybilnośc z poprz. 
					-- tar.USER_GUID, -- tar.OsobaGUID,
					tsel.Oper_Status_Msg AS Msg,
					tsel.Oper_Status_Msg AS _MSG,	-- kompatybilnośc z poprz. 
					CONCAT_WS('\n',
						NULLIF(tsel.Msg_Warn, ''),
						tsel.Msg_Log
					) AS MSG_LONG,
					tsel.Msg_Warn AS Msg_Warning,
					(IFNULL(tsel.Msg_Warn, '') <> '') AS IS_Warning,
					tsel.Status_N_Warn AS Verify_Status_All,
					-- tar.Add_MSG AS Inf_MsgEx,
					-- było ale zabrałem tsel.Verify_Access_available, --  AS Inf_Access_available,
					-- było ale zabrałem tsel.MSG_APP_ID_Err, -- tekst o braku dostepy
					-- było ale zabrałem tsel.MSG_APP_ID_OK,	 -- tekst o dostepach (dodatk.)
					IFNULL(u.err_logon_count, 0) AS err_logon_count,
					(@.auth.Max_User_Err_logon_count - IFNULL(u.err_logon_count, 0)) AS logon_tries, 
					sdl.GUID, 
					sdl.log_USER, 
					sdl.log_USER_GUID, 
					sdl.LAST_MSG, 
					sdl.STATUS, 
					CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
					u.User_account_Type,
					u.Administrator, 
				*/
					-- IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
				/*	byc moze pozniej
					IFNULL(
						IFNULL(
							(SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
							,
							(SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
						),
						''
					) AS KontrGUID,
				*/
					CONCAT_WS(' ', IFNULL(u.Nazwisko, 'Nie ustalony'), u.Imiona) AS USER_Str
				FROM `t_ua_inf` tsel
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tsel.Session_GUID
				-- LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
				-- LEFT JOIN `v_user_accounts` u ON u.GUID = sdl.log_USER_GUID
				LEFT JOIN `v_user_accounts_short` u ON u.GUID = tsel.UserGUID -- sdl.log_USER_GUID
				WHERE 
					TRUE
					-- and tsel.Session_GUID = 'CON:20221214.084903:3111'
					-- tsel.Session_GUID = @.SYSTEM.Last_Insert.Session.GUID
					-- l.GUID = _GUID
				;
			END IF;
			
			IF _MODE LIKE '--SELECT.AUTH._sys_connection_Tool' THEN
			--	_sys_connection_Tool
				SELECT tsel.Msg INTO @.tsel.Msg FROM `t_ua_inf` tsel;
				SELECT
					IF(sdl.Status LIKE '%ERR%', NULL, sdl.con_ID) AS Session_ID, 
					-- sdl.con_ID AS Session_ID, 
					IF(sdl.Status LIKE '%ERR%', NULL, sdl.GUID) AS Session_GUID, 
					-- sdl.GUID AS Session_GUID,
					IF(sdl.Status LIKE '%ERR%', NULL, sdl.log_USER_GUID) AS USER_GUID, 
					-- sdl.log_USER_GUID AS USER_GUID,
					IF(sdl.Status LIKE '%ERR%', @.tsel.Msg, 'Wersja zweryfikowana') AS Message
				FROM (
					SELECT
						CONNECTION_ID() AS Session_ID, '' AS Session_GUID, '' AS USER_GUID
					) n
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = _GUID
				;
			END IF;
			
			IF _MODE LIKE 'SELECT.ALL.@' THEN
				SELECT
					@SYSTEM.Client.Session.GUID,
				-- 	zmienne	po logowaniu
					@SYSTEM.Client.Session.Kind,
					@SYSTEM.Client.Session.Status,
					@SYSTEM.Client.Session.IS.System,
					@SYSTEM.Client.Session.log_USER_GUID,
					@SYSTEM.Client.Session.log_USER,
					@SYSTEM.Client.Session.log_USER.user_type, 
					@SYSTEM.Client.Session.log_USER.admin,
					@SYSTEM.Client.Session.log_USER.ugrpguid,
					@SYSTEM.Client.Session.log_Host,
					@SYSTEM.Client.Session.log_HOST_NAME,
					@SYSTEM.Client.Session.log_MACAddress,
					@SYSTEM.Client.Session.log_AppName,
					@SYSTEM.Client.Session.log_APP_ID,
					@SYSTEM.Client.Session.log_DEV_ID,							
				-- 	starsze
					@session.INFO.User_GUID,
					@session.INFO.User_Login,
					@session.INFO.User_user_type,
					@session.INFO.User_UgrpGUID,
					@session.INFO.User_Admin,
					@session.INFO.Host_IP,
					@session.INFO.Host_Name,
					@session.INFO.AppName,
					@session.INFO.MACAddress,
					@session.INFO.INSERT.LOG.ip,
				-- 	i jeszcze starsze
					@session.Registration.UserGUID,
					@session.Registration.UserLogin,
					@session.Registration.Admin,
					@session.Registration.IP,
					
					@session.user.CurrugrpGUID,
					@session.user.Admin,
					@session.CheckLogonUser					,
					@session.CheckLogonUserLogin,
					@session.CurrMyCompNameStr, 
					@session.CurrMyIPOnly,
					@session.CurrMACAddresses,
					
					@X
				;
			END IF;
			
			IF _MODE LIKE 'SELECT.ALL.@.Table' THEN
				DROP TEMPORARY TABLE IF EXISTS `t_malpy`;
				CREATE TEMPORARY TABLE `t_malpy` (
					`Var_Name` VARCHAR(150) NOT NULL DEFAULT '',
					`Var_Inf` VARCHAR(150) NOT NULL DEFAULT '',
					`Var_Value` VARCHAR(250) NOT NULL DEFAULT '',
					PRIMARY KEY (`Var_Name`)
				);
				TRUNCATE `t_malpy`;
				INSERT IGNORE INTO `t_malpy` 
				(Var_Name, Var_Inf, Var_Value)
				VALUES
				('@SYSTEM.Client.Session.GUID', 'Sesja', IFNULL(@SYSTEM.Client.Session.GUID, 'NULL')),
				('@SYSTEM.Client.Session.Kind', 'Typ sesji', @SYSTEM.Client.Session.Kind),
				('@SYSTEM.Client.Session.log_USER_GUID', 'USER GUID', @SYSTEM.Client.Session.log_USER_GUID),
				('@SYSTEM.Client.Session.log_USER', 'USER login', @SYSTEM.Client.Session.log_USER),
				('@SYSTEM.Client.Session.log_USER.user_type', 'user_type', @SYSTEM.Client.Session.log_USER.user_type),
				('@SYSTEM.Client.Session.log_USER.admin', 'USER admin', @SYSTEM.Client.Session.log_USER.admin),
				('@SYSTEM.Client.Session.log_USER.ugrpguid', 'UgrpGUID', @SYSTEM.Client.Session.log_USER.ugrpguid),
				('@SYSTEM.Client.Session.log_Host', 'log_Host', @SYSTEM.Client.Session.log_Host),
				('@SYSTEM.Client.Session.log_HOST_NAME', 'HOST_NAME', @SYSTEM.Client.Session.log_HOST_NAME),
				('@SYSTEM.Client.Session.log_MACAddress', 'MACAddress', @SYSTEM.Client.Session.log_MACAddress),
				('@SYSTEM.Client.Session.log_AppName', 'AppName', @SYSTEM.Client.Session.log_AppName),
				('@SYSTEM.Client.Session.log_APP_ID', 'log_APP_ID', @SYSTEM.Client.Session.log_APP_ID),
				('@SYSTEM.Client.Session.log_DEV_ID', 'log_DEV_ID', @SYSTEM.Client.Session.log_DEV_ID),
			/* 	starsze	*/
				('@session.INFO.User_GUID', 'USER GUID', @session.INFO.User_GUID),
				('@session.INFO.User_Login', 'USER login', @session.INFO.User_Login),
				('@session.INFO.User_user_type', 'user_type', @session.INFO.User_user_type),
				('@session.INFO.User_UgrpGUID', 'UgrpGUID', @session.INFO.User_UgrpGUID),
				('@session.INFO.User_Admin', 'USER admin', @session.INFO.User_Admin),
				('@session.INFO.Host_IP', 'Host_IP', @session.INFO.Host_IP),
				('@session.INFO.Host_Name', 'HOST_NAME', @session.INFO.Host_Name),
				('@session.INFO.AppName', 'AppName', @session.INFO.AppName),
				('@session.INFO.MACAddress', 'MACAddress', @session.INFO.MACAddress),
				('@session.INFO.INSERT.LOG.ip', 'Host_IP', @session.INFO.INSERT.LOG.ip),
			/* 	i jeszcze starsze	*/
				('@session.Registration.UserGUID', 'USER GUID', @session.Registration.UserGUID),
				('@session.Registration.UserLogin', 'USER login', @session.Registration.UserLogin),
				('@session.Registration.Admin', 'USER admin', @session.Registration.Admin),
				('@session.Registration.IP', 'Host_IP', @session.Registration.IP),
				('@session.user.CurrugrpGUID', 'UgrpGUID', @session.user.CurrugrpGUID),
				('@session.user.Admin', 'USER admin', @session.user.Admin),

				('@session.CheckLogonUser', 'USER admin', @session.CheckLogonUser),
				('@session.CheckLogonUserLogin', 'USER login', @session.CheckLogonUserLogin),
				('@session.CurrMyCompNameStr', 'Comp.Name', @session.CurrMyCompNameStr),
				('@session.CurrMyIPOnly', 'IP', @session.CurrMyIPOnly),
				('@session.CurrMACAddresses', 'MACAddress', @session.CurrMACAddresses)
				;
				SELECT 
					tm.*
				FROM `t_malpy` tm
				;
				IF NOT IFNULL(@session.Delfinek, FALSE) THEN
					DROP TEMPORARY TABLE IF EXISTS `t_malpy`;
				END IF;
			END IF;
			
			
		END IF;
	
    
    
	IF _MODE LIKE 'init.blabla.SELECT.%' THEN
	/******************************************************************************************************************************************
		LIMIT%					Sesje aktywne do limitow ...
		Last.CON[status]%		Ostatnie utworzone sesje
		Last.LOG[status]%		Ostatnie zalogowane
		Last.PING[status]%		Ostatnie pingowane
		Last.CHECK[status]%		Ostatnie sprawdzane
		Last.ERR[status]%		Ostatnie błędne
		Status = ACTIVE/ERR/CLOSE - oznacza czy mamy konieczność spr. status np, 
			Last.LOG.ACTIVE		ogranicza do aktywnych
	******************************************************************************************************************************************/
		SET
			@.sdl.SQL.STATUS.WHERE = 'AND TRUE',
			@.sdl.SQL.ALG.WHERE = 'AND TRUE',
			@.sdl.SQL.ADD.WHERE = 'AND TRUE'
		;
		SET @.sdl.SQL.ALG = '';
			
		
		SET
			@.sdl.SQL.ALG.COLS.LIMIT = 
			"--	ALG: LIMIT
				sdl.INACTIVE, sdl.Status, sdl.Kind, log_APP_ID,log_APPNAME, sdl.TIME_OUT, sdl.TIME_IDLE, sdl.LAST_CHECK_AT,
				sdl.PING_AT, sdl.PING_COUNT, 
				sdl.logon_ver, sdl.LAST_Do_Info,
				sdl.GUID, 
				sdl.LOGGED_AT, sdl.Info, 
				sdl.LAST_MSG
			"
		;
		SET
			@.sdl.SQL.ALG.WHERE.LIMIT = 
			"--	ALG: LIMIT
				AND 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.STATUS <> 'NEW'
				AND sdl.Kind <> 'EVENT'
				AND sdl.Ext_Flag != @.C_Ext_Flag_PROGRAMISTA	-- != 'SUPERVISOR'
			"
		;
		SET
			@.sdl.SQL.ALG.ORDER.LIMIT = "sdl.Ping_AT DESC"
		;
		
		SET
			@.sdl.SQL.ALG.COLS = @.sdl.SQL.ALG.COLS.LIMIT,
			@.sdl.SQL.ALG.WHERE = @.sdl.SQL.ALG.WHERE.LIMIT,
			@.sdl.SQL.ALG.ORDER = @.sdl.SQL.ALG.ORDER.LIMIT
		;
		SELECT @.sdl.SQL.ALG.COLS, @.sdl.SQL.ALG.WHERE, @.sdl.SQL.ALG.ORDER;
		
		SET
			@.sdl.SQL.Init = 
			"
			SELECT 
				#ALG.COLS#,
				sdl.*
			FROM `_sys_db_logons` sdl 
			WHERE 
			TRUE
			-- 	WHERE Statusu o ile konieczny
				#STATUS.WHERE#
			-- 	WHERE z MODE
				#ALG.WHERE#
			-- 	WHERE dodatkowy
				#ADD.WHERE#
			ORDER BY
			-- 	Sortowanie z MODE
				#ALG.ORDER#
			;
			"
		;
		
		SET
			@.sdl.SQL = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@.sdl.SQL.Init,
				'#ALG.COLS#', @.sdl.SQL.ALG.COLS),
				'#STATUS.WHERE#', @.sdl.SQL.STATUS.WHERE),
				'#ALG.WHERE#', @.sdl.SQL.ALG.WHERE),
				'#ADD.WHERE#', @.sdl.SQL.ADD.WHERE),
				'#ALG.ORDER#', @.sdl.SQL.ALG.ORDER)
		;
		SELECT @.sdl.SQL;
	
	END IF;

	IF _MODE LIKE 'SPEC.%' THEN
	/******************************************************************************************************************************************
		SPEC.EVENT.
	******************************************************************************************************************************************/
		IF _MODE LIKE 'SPEC.TIME.%' THEN
			-- IF _MODE LIKE 'SPEC.TIME.EVENT.15.MIN%' THEN
			IF _MODE LIKE 'SPEC.TIME.CLEAR.EVENT%' THEN
				-- LEAVE _sessions_SEL;
				/* ****	23 X 2023 !!! NA jakis czas	aż aplik. kierowc. nie bedzie wylogowywać **** 
				IF @session.globals.Owner IN ('KONKOL') THEN
					UPDATE `_sys_db_logons` sdl 
					SET
						TIME_OUT = 360
					WHERE
						log_APP_ID = 'M.MOB.Mobile.Seller'
						AND Inactive = 0
						AND TIME_OUT < 100
					ORDER BY idn DESC;
				END IF;
				*/
										
				-- było DO _counters_tools('INC', 'e_sys_db_logons_Refresh', '', '');		-- to tylko Licznik!!!!
				SET
					@.COUNTERS.Sessions.CHECK.Interval = IF(@session.globals.Owner IN ('CDG'), 12*60, 1)
				;
				IF 
					_counters_tools('GET', 'Sessions.CHECK.EVENT', '', '') > 0
					AND
					TIMESTAMPDIFF(MINUTE, @.COUNTERS.Last_Time, NOW()) < @.COUNTERS.Sessions.CHECK.Interval 
				THEN
					LEAVE _sessions_SEL;
				END IF;
				DO _counters_tools('INC', 'Sessions.CHECK.EVENT', '', '');		
				DROP TEMPORARY TABLE IF EXISTS `tupd_sys_db_logons`; 
				CREATE TEMPORARY TABLE `tupd_sys_db_logons` 
					SELECT
						ssdl.IDN, ssdl.Status, ssdl.INACTIVE, ssdl.Kind, 
						ssdl.LAST_CHECK_AT,
						ssdl.LOGGED_AT,
						ssdl.PING_AT,
						(@.ssdl.TIME_SILENT := TIMESTAMPDIFF(MINUTE, ssdl.PING_AT, NOW())) AS TIME_SILENT,
						@.ssdl.TIME_SILENT > ssdl.TIME_IDLE AS T_IDLE_Exceeded,
						@.ssdl.TIME_SILENT > ssdl.TIME_OUT AS T_OUT_Exceeded,
						
						ssdl.TIME_IDLE, ssdl.TIME_OUT,
						ssdl.GUID, ssdl.Do_Info, 
						ssdl.log_USER_GUID, log_APP_ID, log_APP_VER, log_APPNAME,
						ssdl.con_ID,
						ssdl.con_DB,
						p.ID AS process_ID
						-- _VarINT(0) AS process_ID
						-- tsdl.* 
					FROM (
						SELECT
							sdl.*
						FROM `_sys_db_logons` sdl
						WHERE
						TRUE
						-- było ale zmiana na małpe AND IFNULL(sdl.LAST_CHECK_AT + INTERVAL 12 MINUTE < NOW(), TRUE)
						-- AND IFNULL(sdl.LAST_CHECK_AT + INTERVAL @.sdl.interval.LAST_CHECK_AT MINUTE < NOW(), TRUE)
						AND NOT sdl.INACTIVE	--	dla aktywnych sesji
						AND sdl.STATUS <> 'SLEEP'
						-- AND sdl.Kind IN ('WWW', 'EXE', 'EVENT', 'MOB')		--	do testow
						-- AND sdl.PING_AT <> '0000-00-00 00:00:00'

					) ssdl
					LEFT JOIN `information_schema`.`PROCESSLIST` p ON p.ID = ssdl.con_ID AND p.DB = ssdl.con_DB
					ORDER BY idn
				;
			--	Dla Exe pobierz ID procesu
				UPDATE `tupd_sys_db_logons` tsdl
				SET 
					tsdl.Do_Info = 'ACTIVE.EXE_LOST_CONNECTION'
				WHERE
					IFNULL(tsdl.Do_Info, '') = ''
					AND tsdl.Status != 'ACTIVE.EXE_LOST_CONNECTION'
					AND (tsdl.T_IDLE_Exceeded)
					AND NOT (tsdl.T_OUT_Exceeded)
					AND tsdl.Kind = 'EXE'
					AND tsdl.process_ID IS NULL
				; 	
			--	Exe
				UPDATE `tupd_sys_db_logons` tsdl
				SET 
					tsdl.Do_Info = 'ACTIVE.EXE_LOST_CONNECTION'
				WHERE
					IFNULL(tsdl.Do_Info, '') = ''
					AND tsdl.Status != 'ACTIVE.EXE_LOST_CONNECTION'
					AND (tsdl.T_IDLE_Exceeded)
					AND NOT (tsdl.T_OUT_Exceeded)
					AND tsdl.Kind = 'EXE'
					AND tsdl.process_ID IS NULL
				; 	
			--	Eventy 	
				UPDATE `tupd_sys_db_logons` tsdl
				SET 
					tsdl.Do_Info = 'CLOSE.TIMEOUT'
				WHERE
					IFNULL(tsdl.Do_Info, '') = ''
					AND tsdl.Kind = 'EVENT'
					AND (TIMESTAMPDIFF(MINUTE, tsdl.LOGGED_AT, NOW()) > 20)
					AND tsdl.process_ID IS NULL
				; 	
			--	Cała reszta	
				UPDATE `tupd_sys_db_logons` tsdl
				SET 
					tsdl.Do_Info = 
						IF(tsdl.T_OUT_Exceeded,
							'CHECK.STATE',		--	TIME OUT
							IF(tsdl.T_IDLE_Exceeded AND tsdl.STATUS IN ('ACTIVE', 'NEW', 'OPEN'),	-- OPEN to jakis rzadki
								'CHECK.STATE',	--	IDLE
								tsdl.Do_Info
							)
						)
				WHERE
					TRUE
					AND IFNULL(tsdl.Do_Info, '') IN ('')
					AND (tsdl.T_IDLE_Exceeded OR tsdl.T_OUT_Exceeded)
				; 	
				/*
					SELECT 
						tsdl.Do_Info, tsdl.*
					FROM `tupd_sys_db_logons` tsdl 
					WHERE 
						TRUE 
						AND IFNULL(tsdl.Do_Info, '') <> ''
					;
				*/
				UPDATE `_sys_db_logons` sdl, `tupd_sys_db_logons` tsdl
				SET 
					sdl.Do_Info = tsdl.Do_Info
				WHERE
					TRUE
					AND IFNULL(tsdl.Do_Info, '') <> ''
					AND sdl.GUID = tsdl.GUID
				; 	
				IF NOT IFNULL(@session.Delfinek, FALSE) THEN
					DROP TEMPORARY TABLE IF EXISTS `tupd_sys_db_logons`; 
				END IF;
			--	Przy okazji pousuwaj z logu aplikacji stare wpisy	
				CALL _sys_app_logtxt('UPDATE.DELETED', '', '', '', '', '', '', '', '');
				CALL _sys_app_logtxt('DELETE.DELETED', '', '', '', '', '', '', '', '');
				
			END IF;
		END IF;
	END IF;

END$$
DELIMITER ;


/*
--	TODO UWAGA!!!!!!!!! 
WYWAL jeśli możliwe - ZAPYTAJ DARKA i GRZESIA ale chyba nikt tego nie woła - ja na perwno!!!
UWAGA poniższe funkcje, procki
przenies potem gdzies do a'la sys_db_logons bo tutaj w tym pliku jest autoryzacja 
*/
DELIMITER $$

DROP FUNCTION IF EXISTS `_sdl`$$


DROP PROCEDURE IF EXISTS `_TEST_sys_db_logons_Tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_TEST_sys_db_logons_Tools`(
	IN _MODE VARCHAR(250), 
	IN _GUID VARCHAR(38),
	IN _CONNECTION_ID INTEGER,
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200),
	IN _Param_C VARCHAR(200),
	IN _Param_D VARCHAR(200),
	IN _Param_E VARCHAR(200),
	IN _Param_F VARCHAR(200),
	IN _Param_G VARCHAR(200)
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		np.
		CALL _sys_db_logons_Tools('', '', 0, 'select', '', '', '', '', '', '');
		CALL _sys_db_logons_Tools('RENAME.@session.Variables', '', 0, '', '', '', '', '', '', '');
		CALL _sys_db_logons_Tools('CHECK', GUIDSesji, 0, '', '', '', '', '', '', '');
		CALL _sys_db_logons_Tools('PING', GUIDSesji, 0, '', '', '', '', '', '', '');
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S__sys_db_logons_Tools: BEGIN

	DECLARE _SQLText MEDIUMTEXT; 
	SET @.auth.Final.Verify_OK = NULL;
	DO _Birth_System();	--	aby miec m.in. @session.globals.INPUT_SALT_Hash
	IF _MODE IN ('TEST.Set.Params') THEN
	/********************************************************************************************************
		CALL _TEST_sys_db_logons_Tools('TEST.Set.Params', 
			@.LOG.Input.Session, 0, 
			'select', '', 
			'jmam', 
			'@koszalkowo@', -- 'zle haslo', 
			'AC-16-2D-47-52-D7', 
			'M.EXE.HT2003', ''
		);
		IN _GUID 		Sesja wejściowa
		IN _CONNECTION_ID 
		IN _Param_A 	'select',
		IN _Param_B 	'',	pusto - hmm???
		IN _Param_C 	Login,
		IN _Param_D 	Pswd
		IN _Param_E 	MCA
		IN _Param_F 	APPLIKACJA
		IN _Param_G 	'',	pusto - hmm???
	********************************************************************************************************/
	
		SET 
		-- wejsciowa sesja dla CALL _sys_db_logons_Tools w którym obok soli jest jeszcze pieprz w postaci sesji
			@.LOG.Input.Session = @SYSTEM.Client.Session.GUID
		-- dla haszów bez sesji
		--	@.LOG.Input.Session = NULL
		;	
		-- APP ID
		SET
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.MOB.Mobile.Seller'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.WEB.PortaMag.Logistyka'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.WEB.Dostawcy'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.EXE.PL2003'), '', '')
		@.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := _Param_F), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.WEB.Grafiki'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.MOB.mDoc'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.MOB.Mobile.Rampa'), '', '')
		;
		-- DEV ID
		SET
		-- @.LOG.Input.DEV_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.DEV_ID := '863705045551355'), '', '')
		@.LOG.Input.DEV_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.DEV_ID := _Param_E), '', '')
		;

		-- USER GUID do 	CALL _sys_authorization('authorization.LOG.#UserGUID'
		SET
		@.LOG.Input.USER_GUID.Hash := _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5(@.LOG.Input.USER_GUID := '{1D4E0A82-4D55-4843-A556-41F858CC27AC}'), '', '')	-- jmam konkol ht
		-- @.LOG.Input.USER_GUID.Hash := _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5(@.LOG.Input.USER_GUID := '{3A6D52C6-5AE3-4E46-9E89-3DFB89E56226}'), '', '')
		-- @.LOG.Input.USER_GUID.Hash := _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5(@.LOG.Input.USER_GUID := 'e43bed4b-dbf2-11e7-bde9-52540078c2f5*'), '', '') -- piotrek
		-- @.LOG.Input.USER_GUID.Hash := _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5(@.LOG.Input.USER_GUID := '{59BA08BB-433C-4443-BB24-7F345912E369}'), '', '') --  Łukasz Zwara Jarzebinscy {59BA08BB-433C-4443-BB24-7F345912E369}
		;
		--	Login do 	CALL _sys_authorization('authorization.LOG.#Login,#Pswd'
		SET
		-- @.LOG.Input.LOG_User.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_User := 'mateusz.milosz')), '', '')
		-- @.LOG.Input.LOG_User.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_User := 'SM')), '', '')
		@.LOG.Input.LOG_User.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_User := _Param_C)), '', '')
		-- @.LOG.Input.LOG_User.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_User := 'rafald')), '', '')
		; 
		--	Pass do 	CALL _sys_authorization('authorization.LOG.#Login,#Pswd'
		SET
		-- @.LOG.Input.LOG_PASS.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_PASS := 'pr3z3s$')), '', '')
		@.LOG.Input.LOG_PASS.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_PASS := _Param_D)), '', '')
		; 

		SELECT @.LOG.Input.Params, @.LOG.Input.Session, @session.globals.INPUT_SALT_Hash, @.LOG.Input.LOG_User.Hash, @.LOG.Input.LOG_PASS.Hash, @.LOG.Input.DEV_ID.Hash, @SYSTEM.Client.Session.GUID;


		SET @.LOG.Input.Session = @SYSTEM.Client.Session.GUID;		SELECT @.LOG.Input.Session, @SYSTEM.Client.Session.GUID; -- CON:4957:20220126.165638
		
	END IF;
	
	IF _MODE IN ('LOG ON') THEN
	/*
		Zalogowanie prawidlowe/bledne
		CALL _sys_db_logons_Tools('LOG ON', @_SESSION_GUID, 0, 'select', '', @_INPUT_LOGIN_Hash, @_INPUT_Datas_Hash, @_INPUT_MACADDRESS_Hash, 'M.WEB.ScanPack', '');

		Zalogowanie prawidlowe/bledne
		CALL _sys_db_logons_Tools('LOG ON', @_SESSION_GUID, 0, 'select', '', @_INPUT_LOGIN_Hash, @_INPUT_Datas_Hash, @_INPUT_MACADDRESS_Hash, 'M.WEB.ScanPack', '');
		CALL _sys_db_logons_Tools('LOG ON.TEST', '39033242-5cc4-11eb-9347-00215e4eee26', 0, 'select', '', 
			MD5(CONCAT('28825d161c6ba55a849ad21b0dfbfee6',@SYSTEM.Client.Session.GUID,
			MD5('jmam'))), MD5(CONCAT('28825d161c6ba55a849ad21b0dfbfee6',@SYSTEM.Client.Session.GUID,
			MD5('pr3z3s$'))), MD5(CONCAT('28825d161c6ba55a849ad21b0dfbfee6',@SYSTEM.Client.Session.GUID,
			MD5('AC-16-2D-47-52-D7'))), 'M.EXE.HT2003', ''
		);
		IN _GUID 		Sesja wejściowa
		IN _CONNECTION_ID 
		IN _Param_A 	'select',
		IN _Param_B 	'',	pusto - hmm???
		IN _Param_C 	#LoginVARCHAR(200),
		IN _Param_D 	#Pswd
		IN _Param_E 	#MCA
		IN _Param_F 	APPLIKACJA
		IN _Param_G 	'',	pusto - hmm???
		
	*/
	--	Parametry do zmiennych
		SET
			@.LOG.Input.Session = _GUID,
			@.LOG.Input.LOG_User.Hash = _Param_C,
			@.LOG.Input.LOG_PASS.Hash = _Param_D,
			@.LOG.Input.USER_GUID.Hash = NULL,
			@.LOG.Input.DEV_ID.Hash = _Param_E,
			@.LOG.Input.APP_ID.Hash = NULL,
			@.LOG.Input.DEV_ID = NULL,
			@.LOG.Input.APP_ID = _Param_F
		;
	--	Paremtry do sznurka	
		SET
			@._IN_Auth_Params = 
			CONCAT_WS('&',
				CONCAT('S.ID=', @.LOG.Input.Session),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
				CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),
				CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),
				CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),
				CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),
				CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
				CONCAT('D.ID=', @.LOG.Input.DEV_ID),
				CONCAT('A.ID=', @.LOG.Input.APP_ID)
			)
		;
		
	--	Logowanie
		SET @.sdb.log_Mode.Pre = '_sys_db_logons_Tools(''LOG ON''..)';
		CALL _authorization('LOG:#Login,#Pswd', _GUID, @._IN_Auth_Params, '', '', '', '', '');

		SELECT 
			l.GUID, l.log_USER, l.log_USER_GUID, l.LAST_MSG, l.STATUS, u.Administrator, 
			CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, u.User_account_Type, u.user_type,
			IF(l.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
		FROM `_sys_db_logons` l
		LEFT JOIN `v_intnet_users` u ON u.GUID = l.log_USER_GUID
		WHERE 
			l.GUID = _GUID
		;
		LEAVE S__sys_db_logons_Tools;
		
		
		CALL _sys_db_logons_LOG('CHECK.NEW', _GUID, _Param_C, _Param_D, _Param_E, '', _Param_F, _Param_G, '');
		SELECT 
			l.GUID, l.log_USER, l.log_USER_GUID, l.LAST_MSG, l.STATUS, u.Administrator, 
			CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, u.User_account_Type, u.user_type,
			IF(l.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
		FROM `_sys_db_logons` l
		LEFT JOIN `v_intnet_users` u ON u.GUID = l.log_USER_GUID
		WHERE 
			l.GUID = _GUID
		;
		-- SELECT GUID,log_USER,log_USER_GUID,LAST_MSG,STATUS FROM `_sys_db_logons` WHERE GUID = _GUID;
		-- END IF;
	END IF;	-- koniec @session.LOGON.Ver < 2.15	
END$$

DROP PROCEDURE IF EXISTS `_TEST_sys_authorization`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_TEST_sys_authorization`(
	IN _MODE VARCHAR(250), 
	IN _ID VARCHAR(255),
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200),
	IN _Param_C VARCHAR(200),
	IN _Param_D VARCHAR(200),
	IN _Param_E VARCHAR(200)
)
S_sys_authorization: BEGIN
	IF _MODE IN ('TEST.Set.Params') THEN
	/********************************************************************************************************
		CALL _TEST_sys_db_logons_Tools('TEST.Set.Params', 
			@.LOG.Input.Session, 0, 
			'select', '', 
			'jmam', 
			'@koszalkowo@', -- 'zle haslo', 
			'AC-16-2D-47-52-D7', 
			'M.EXE.HT2003', ''
		);
	dla najczestszych 
	authorization.LOG.#Login,#Pswd
		_ID			Sesja (moze byc ''/null 
		_Param_A	#Login
		_Param_B	#Pswd
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
	********************************************************************************************************/
	
		SET 
		-- wejsciowa sesja dla CALL _sys_db_logons_Tools w którym obok soli jest jeszcze pieprz w postaci sesji
			@.LOG.Input.Session = _ID -- @SYSTEM.Client.Session.GUID
		-- dla haszów bez sesji
		--	@.LOG.Input.Session = NULL
		;	
		-- APP ID
		SET
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.MOB.Mobile.Seller'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.WEB.PortaMag.Logistyka'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.WEB.Dostawcy'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.EXE.PL2003'), '', '')
		@.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := _Param_F), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.WEB.Grafiki'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.MOB.mDoc'), '', '')
		-- @.LOG.Input.APP_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.APP_ID := 'M.MOB.Mobile.Rampa'), '', '')
		;
		-- DEV ID
		SET
		-- @.LOG.Input.DEV_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.DEV_ID := '863705045551355'), '', '')
		@.LOG.Input.DEV_ID.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, (@.LOG.Input.DEV_ID := _Param_E), '', '')
		;

		-- USER GUID do 	CALL _sys_authorization('authorization.LOG.#UserGUID'
		SET
		@.LOG.Input.USER_GUID.Hash := _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5(@.LOG.Input.USER_GUID := '{1D4E0A82-4D55-4843-A556-41F858CC27AC}'), '', '')	-- jmam konkol ht
		-- @.LOG.Input.USER_GUID.Hash := _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5(@.LOG.Input.USER_GUID := '{3A6D52C6-5AE3-4E46-9E89-3DFB89E56226}'), '', '')
		-- @.LOG.Input.USER_GUID.Hash := _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5(@.LOG.Input.USER_GUID := 'e43bed4b-dbf2-11e7-bde9-52540078c2f5*'), '', '') -- piotrek
		-- @.LOG.Input.USER_GUID.Hash := _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5(@.LOG.Input.USER_GUID := '{59BA08BB-433C-4443-BB24-7F345912E369}'), '', '') --  Łukasz Zwara Jarzebinscy {59BA08BB-433C-4443-BB24-7F345912E369}
		;
		--	Login do 	CALL _sys_authorization('authorization.LOG.#Login,#Pswd'
		SET
		-- @.LOG.Input.LOG_User.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_User := 'mateusz.milosz')), '', '')
		-- @.LOG.Input.LOG_User.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_User := 'SM')), '', '')
		@.LOG.Input.LOG_User.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_User := _Param_C)), '', '')
		-- @.LOG.Input.LOG_User.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_User := 'rafald')), '', '')
		; 
		--	Pass do 	CALL _sys_authorization('authorization.LOG.#Login,#Pswd'
		SET
		-- @.LOG.Input.LOG_PASS.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_PASS := 'pr3z3s$')), '', '')
		@.LOG.Input.LOG_PASS.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, MD5((@.LOG.Input.LOG_PASS := _Param_D)), '', '')
		; 

		SELECT @.LOG.Input.Params, @.LOG.Input.Session, @session.globals.INPUT_SALT_Hash, @.LOG.Input.LOG_User.Hash, @.LOG.Input.LOG_PASS.Hash, @.LOG.Input.DEV_ID.Hash, @SYSTEM.Client.Session.GUID;


		SET @.LOG.Input.Session = @SYSTEM.Client.Session.GUID;		SELECT @.LOG.Input.Session, @SYSTEM.Client.Session.GUID; -- CON:4957:20220126.165638
		
	END IF;
	
	IF _MODE LIKE 'authorization.%' THEN
	/******************************************************************************************************************************************
		Tryby
			LOG.#Login,#Pswd
			LOG.#UserGUID
			BIO.#Login,#DEV_ID
			BIO.#UserGUID,#DEV_ID
		UWAGA gdy mamy doklejone wyrazenie ".Search.active.session" to szukamy niezamknietej sesji tego user dla urzadzebnia i aplikacji
		możemy mieć więc tryby ###.Search.active.session 
			LOG.#Login,#Pswd.Search.active.session 
			LOG.#UserGUID.Search.active.session 
			BIO.#Login,#DEV_ID.Search.active.session 
			BIO.#UserGUID,#DEV_ID.Search.active.session 
		
		CALL _sys_authorization('authorization.LOG.#Login,#Pswd', '', #Login, #Pswd, #DEV_ID, #APP_ID, '');
		_ID			Sesja (moze byc ''/null 
		_Param_A	#Login
		_Param_B	#Pswd
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
		CALL _sys_authorization('authorization.LOG.#UserGUID', '', '#USER_GUID', '', #DEV_ID, #APP_ID, '');
		_ID			Sesja (moze byc ''/null 
		_Param_A	#USER_GUID
		_Param_B	...
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
		CALL _sys_authorization('authorization.BIO.#Login,#DEV_ID', '', #Login, '', #DEV_ID, #APP_ID, '');
		_ID			Sesja (moze byc ''/null 
		_Param_A	#Login
		_Param_B	...
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
		CALL _sys_authorization('authorization.BIO.#UserGUID,#DEV_ID', '', '#USER_GUID', '', #DEV_ID, #APP_ID, '');
		_ID			Sesja (moze byc ''/null 
		_Param_A	#USER_GUID
		_Param_B	...
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
		CALL _sys_authorization('authorization.LOG.#SesjaZlecajaca', '', #Login, #Pswd, #DEV_ID, #APP_ID, '');
		_Param_A	_Md5_SESSION_GUID
		
		!!!!!!!UWAGA !!!!!!!!!! poniższe dwa mody jeszcze czakaj*a na wdrożenie (stan na 2021-01-25)
		CALL _sys_authorization('authorization.CHECK.#Login,#Pswd', '', #Login, #Pswd, #DEV_ID, #APP_ID, '');
			Sprawdzenie	istnienia konta (poprawności login/hasło)
		_ID			Sesja (moze byc ''/null 
		_Param_A	#Login
		_Param_B	#Pswd
		CALL _sys_authorization('authorization.CHECK.THIS.Session.#Login,#Pswd', '', #Login, #Pswd, #DEV_ID, #APP_ID, '');
			Służy do odblokowania sesji
		_ID			Sesja KONIECZNA!!! -> @_Input_Session
		_Param_A	#Login
		_Param_B	#Pswd
		
		zwraca rekord
	******************************************************************************************************************************************/
	--	Parametry do zmiennych
		IF _MODE = 'authorization.LOG.#Login,#Pswd' THEN
		/*******************************************************************************************************
			dla	'authorization.LOG.#Login,#Pswd'
			_ID			Sesja (moze byc ''/null 
			_Param_A	#Login
			_Param_B	#Pswd
			_Param_C	#DEV_ID
			_Param_D	#APP_ID
		*******************************************************************************************************/	
			SET
				@.LOG.Input.Session = _ID,
				@.LOG.Input.LOG_User.Hash = _Param_A,
				@.LOG.Input.LOG_PASS.Hash = _Param_B,
				@.LOG.Input.USER_GUID.Hash = NULL,
				@.LOG.Input.DEV_ID.Hash = _Param_C,
				@.LOG.Input.APP_ID.Hash = _Param_D,
				@.LOG.Input.DEV_ID = NULL,	-- nie uistotne
				@.LOG.Input.APP_ID = NULL	-- nie uistotne
			;
		END IF;
	--	Paremtry do sznurka	
		SET
			@._IN_Auth_Params = 
			CONCAT_WS('&',
				CONCAT('S.ID=', @.LOG.Input.Session),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
				CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),
				CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),
				CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),
				CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),
				CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
				CONCAT('D.ID=', @.LOG.Input.DEV_ID),
				CONCAT('A.ID=', @.LOG.Input.APP_ID)
			)
		;
		
	--	Logowanie
		SET @.sdb.log_Mode.Pre = CONCAT('_sys_authorization(', _MODE, '...');
		IF _MODE = 'authorization.LOG.#Login,#Pswd' THEN
			CALL _authorization('LOG:#Login,#Pswd', _ID, @._IN_Auth_Params, '', '', '', '', '');
		END IF;

		SELECT 
			l.GUID, l.log_USER, l.log_USER_GUID, l.LAST_MSG, l.STATUS, u.Administrator, 
			CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, u.User_account_Type, u.user_type,
			IF(l.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
		FROM `_sys_db_logons` l
		LEFT JOIN `v_intnet_users` u ON u.GUID = l.log_USER_GUID
		WHERE 
			l.GUID = _ID
		;
		LEAVE S_sys_authorization;
	END IF;
	
END$$


DROP PROCEDURE IF EXISTS `_TEST_sys_db_logons_LOG`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_TEST_sys_db_logons_LOG`(
	IN _MODE VARCHAR(250), 
	IN _SESSION_GUID VARCHAR(38),
	IN _INPUT_LOGIN_Hash VARCHAR(200),
	IN _INPUT_Datas_Hash VARCHAR(200),
	IN _INPUT_MACADDRESS_Hash VARCHAR(200),
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200),
	IN _Param_C VARCHAR(200),
	IN _Param_D VARCHAR(200)
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		np.
		SET
			@_SESSION_GUID = 'CON:20221128.143519:13363',
			@_INPUT_LOGIN_Hash = MD5(CONCAT('e9d2de780919146a7cd5bca435fe67a8','CON:20221128.143519:13363',MD5('jmam'))),
			@_INPUT_Datas_Hash = MD5(CONCAT('e9d2de780919146a7cd5bca435fe67a8','CON:20221128.143519:13363',MD5('pr3z3s$'))),
			@_Param_B = 'M.EXE.HT2003'
		;
		CALL _TEST_sys_db_logons_LOG('CHECK.NEW', 
			@_SESSION_GUID, 
			@_INPUT_LOGIN_Hash, 
			@_INPUT_Datas_Hash, 
			@_INPUT_MACADDRESS_Hash, 
			'', 
			@_Param_B, 	-- APP_ID = _Param_B	--	czy aby na pewno to jest zwykłe App czy #app ???
			'', '');

------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_TEST_sys_db_logons_LOG: BEGIN
	IF _MODE IN ('CHECK.NEW', 'CHECK.NEW.BIO') THEN
	/*
		CALL _sys_db_logons_LOG(IF(_MODE = 'LOG ON NEW', 'CHECK.NEW', 'CHECK.NEW.BIO'), _GUID, _Param_C, _Param_D, _Param_E, '', _Param_F, _Param_G, '');
		wołane z 
			DROP PROCEDURE IF EXISTS `_sys_db_logons_Tools`$$
			CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_db_logons_Tools`(
				IN _MODE VARCHAR(250), 		-- CHECK.NEW lub CHECK.NEW.BIO	-> _MODE
				IN _GUID VARCHAR(38),		-- $session_guid				-> _SESSION_GUID
				IN _CONNECTION_ID INTEGER,	-- 0							
				IN _Param_A VARCHAR(200),	-- "select"
				IN _Param_B VARCHAR(200),	-- ""
				IN _Param_C VARCHAR(200),	-- $username					-> _INPUT_LOGIN_Hash		-- w BIO podawany
				IN _Param_D VARCHAR(200),	-- $pass						-> _INPUT_Datas_Hash		-- w BIO pusty
				IN _Param_E VARCHAR(200),	-- $mac_hash					-> _INPUT_MACADDRESS_Hash	-- w BIO nie podawany
				IN _Param_F VARCHAR(200),	-- $app_upr						-> _Param_B
				IN _Param_G VARCHAR(200)	-- ""							-> _Param_C
			)
		
	*/
	--	Parametry do zmiennych
		SET
			@.LOG.Input.Session = _SESSION_GUID,
			@.LOG.Input.LOG_User.Hash = _INPUT_LOGIN_Hash,
			@.LOG.Input.LOG_PASS.Hash = _INPUT_Datas_Hash,
			@.LOG.Input.USER_GUID.Hash = NULL,
			@.LOG.Input.DEV_ID.Hash = _INPUT_MACADDRESS_Hash,
			@.LOG.Input.APP_ID.Hash = NULL,
			@.LOG.Input.DEV_ID = NULL,
			@.LOG.Input.APP_ID = _Param_B	--	czy aby na pewno to jest zwykłe App czy #app ???
		;
		SET
			@.LOG.Input.APP_ID.Hash = 
				IF(IFNULL(@.LOG.Input.APP_ID, '') <> '',
					_MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.Session, @.LOG.Input.APP_ID, '', ''),
					NULL
				)
		;
	--	Paremtry do sznurka	
		SET
			@._IN_Auth_Params = 
			CONCAT_WS('&',
				CONCAT('S.ID=', @.LOG.Input.Session),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
				CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),
				CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),
				CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),
				CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),
				CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
				CONCAT('D.ID=', @.LOG.Input.DEV_ID),
				CONCAT('A.ID=', @.LOG.Input.APP_ID)
			)
		;
		
	--	Logowanie
		SET @.sdb.log_Mode.Pre = '_sys_db_logons_Tools(''LOG ON''..)';
		CALL _authorization('LOG:#Login,#Pswd', _SESSION_GUID, @._IN_Auth_Params, '', '', '', '', '');

		SELECT 
			l.GUID, l.log_USER, l.log_USER_GUID, 
			-- l.LAST_MSG, 
			@.auth.Final.Verify_Status AS LAST_MSG,
			l.STATUS, u.Administrator, 
			CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, u.User_account_Type, u.user_type,
			-- IF(l.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
			IF(@.auth.Final.Verify_Status = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
		FROM `_sys_db_logons` l
		LEFT JOIN `v_intnet_users` u ON u.GUID = l.log_USER_GUID
		WHERE 
			l.GUID = _SESSION_GUID
		;
	END IF;
END$$

DROP PROCEDURE IF EXISTS `_AUTH_CONV_Params_to_Sznurek`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_AUTH_CONV_Params_to_Sznurek`(
	IN _PROC VARCHAR(255),	--	jaka porocedura
	IN _MODE VARCHAR(250), 
	IN _ID VARCHAR(255),
	--	IN _CONNECTION_ID INTEGER,	tylko dla `_sys_db_logons_Tools` ale nie jest tam uzywana
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200),
	IN _Param_C VARCHAR(200),
	IN _Param_D VARCHAR(200),
	IN _Param_E VARCHAR(200),
	IN _Param_F TEXT,
	IN _Param_G VARCHAR(200)	-- tylko w  `_sys_db_logons_Tools` ale nie wiem czy jest kiedykolwiek wykorzystany
)
_AUTH_CONV_Params_to_Sznurek: BEGIN
	SET @._AUTH_CONV_Params = NULL;
set @.cos = _ID;	
	IF _PROC = '_sys_db_logons_Tools' THEN
	/******************************************************************************************************************************************
		Zalogowanie prawidlowe/bledne
		CALL _sys_db_logons_Tools('LOG ON', @_SESSION_GUID, 0, 'select', '', @_INPUT_LOGIN_Hash, @_INPUT_Datas_Hash, @_INPUT_MACADDRESS_Hash, 'M.WEB.ScanPack', '');

		IN _GUID 		Sesja wejściowa
		IN _CONNECTION_ID 
		IN _Param_A 	'select',
		IN _Param_B 	'',	pusto - hmm???
		IN _Param_C 	#Login,
		IN _Param_D 	#Pswd
		IN _Param_E 	#MCA
		IN _Param_F 	APPLIKACJA
		IN _Param_G 	'',	pusto - hmm???
		
	******************************************************************************************************************************************/
		IF _MODE = 'LOG ON' THEN
		/*******************************************************************************************************
			Zalogowanie prawidlowe/bledne
			CALL _sys_db_logons_Tools('LOG ON', @_SESSION_GUID, 0, 'select', '', @_INPUT_LOGIN_Hash, @_INPUT_Datas_Hash, @_INPUT_MACADDRESS_Hash, 'M.WEB.ScanPack', '');
			CALL _sys_db_logons_Tools('LOG ON.TEST', '39033242-5cc4-11eb-9347-00215e4eee26', 0, 'select', '', 
				MD5(CONCAT('28825d161c6ba55a849ad21b0dfbfee6',@SYSTEM.Client.Session.GUID,
				MD5('jmam'))), MD5(CONCAT('28825d161c6ba55a849ad21b0dfbfee6',@SYSTEM.Client.Session.GUID,
				MD5('pr3z3s$'))), MD5(CONCAT('28825d161c6ba55a849ad21b0dfbfee6',@SYSTEM.Client.Session.GUID,
				MD5('AC-16-2D-47-52-D7'))), 'M.EXE.HT2003', ''
			);
		*******************************************************************************************************/	
	--	Parametry do zmiennych
			SET
				@.LOG.Input.Session = _ID,
				@.LOG.Input.LOG_User.Hash = _Param_C,
				@.LOG.Input.LOG_PASS.Hash = _Param_D,
				@.LOG.Input.USER_GUID.Hash = NULL,
				@.LOG.Input.DEV_ID.Hash = _Param_E,
				@.LOG.Input.APP_ID.Hash = NULL,
				@.LOG.Input.DEV_ID = NULL,
				@.LOG.Input.APP_ID = _Param_F
			;
		END IF;
	--	Paremtry do sznurka	
		SET
			@._AUTH_CONV_Params = 
			CONCAT_WS('&',
				CONCAT('S.ID=', @.LOG.Input.Session),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
				CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),
				CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),
				CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),
				CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),
				CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
				CONCAT('D.ID=', @.LOG.Input.DEV_ID),
				CONCAT('A.ID=', @.LOG.Input.APP_ID)
			)
		;
	END IF;
	
	IF _PROC = '_sys_authorization' THEN
	/******************************************************************************************************************************************
		Tryby
			LOG.#Login,#Pswd
			LOG.#UserGUID
			BIO.#Login,#DEV_ID
			BIO.#UserGUID,#DEV_ID
		UWAGA gdy mamy doklejone wyrazenie ".Search.active.session" to szukamy niezamknietej sesji tego user dla urzadzebnia i aplikacji
		możemy mieć więc tryby ###.Search.active.session 
			LOG.#Login,#Pswd.Search.active.session 
			LOG.#UserGUID.Search.active.session 
			BIO.#Login,#DEV_ID.Search.active.session 
			BIO.#UserGUID,#DEV_ID.Search.active.session 
		
		CALL _sys_authorization('authorization.LOG.#Login,#Pswd', '', #Login, #Pswd, #DEV_ID, #APP_ID, '');
		_ID			Sesja (moze byc ''/null 
		_Param_A	#Login
		_Param_B	#Pswd
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
		CALL _sys_authorization('authorization.LOG.#UserGUID', '', '#USER_GUID', '', #DEV_ID, #APP_ID, '');
		_ID			Sesja (moze byc ''/null 
		_Param_A	#USER_GUID
		_Param_B	...
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
		CALL _sys_authorization('authorization.BIO.#Login,#DEV_ID', '', #Login, '', #DEV_ID, #APP_ID, '');
		_ID			Sesja (moze byc ''/null 
		_Param_A	#Login
		_Param_B	...
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
		CALL _sys_authorization('authorization.BIO.#UserGUID,#DEV_ID', '', '#USER_GUID', '', #DEV_ID, #APP_ID, '');
		_ID			Sesja (moze byc ''/null 
		_Param_A	#USER_GUID
		_Param_B	...
		_Param_C	#DEV_ID
		_Param_D	#APP_ID
		CALL _sys_authorization('authorization.LOG.#SesjaZlecajaca', '', #Login, #Pswd, #DEV_ID, #APP_ID, '');
		_Param_A	_Md5_SESSION_GUID
		
		!!!!!!!UWAGA !!!!!!!!!! poniższe dwa mody jeszcze czakaj*a na wdrożenie (stan na 2021-01-25)
		CALL _sys_authorization('authorization.CHECK.#Login,#Pswd', '', #Login, #Pswd, #DEV_ID, #APP_ID, '');
			Sprawdzenie	istnienia konta (poprawności login/hasło)
		_ID			Sesja (moze byc ''/null 
		_Param_A	#Login
		_Param_B	#Pswd
		CALL _sys_authorization('authorization.CHECK.THIS.Session.#Login,#Pswd', '', #Login, #Pswd, #DEV_ID, #APP_ID, '');
			Służy do odblokowania sesji
		_ID			Sesja KONIECZNA!!! -> @_Input_Session
		_Param_A	#Login
		_Param_B	#Pswd
		
		zwraca rekord
	******************************************************************************************************************************************/
	--	Parametry do zmiennych
		IF _MODE = 'authorization.LOG.#Login,#Pswd' THEN
		/*******************************************************************************************************
			dla	'authorization.LOG.#Login,#Pswd'
			_ID			Sesja (moze byc ''/null 
			_Param_A	#Login
			_Param_B	#Pswd
			_Param_C	#DEV_ID
			_Param_D	#APP_ID
		*******************************************************************************************************/	
			SET
				@.LOG.Input.Session = _ID,
				@.LOG.Input.LOG_User.Hash = _Param_A,
				@.LOG.Input.LOG_PASS.Hash = _Param_B,
				@.LOG.Input.USER_GUID.Hash = NULL,
				@.LOG.Input.DEV_ID.Hash = _Param_C,
				@.LOG.Input.APP_ID.Hash = _Param_D,
				@.LOG.Input.DEV_ID = NULL,	-- nie uistotne
				@.LOG.Input.APP_ID = NULL	-- nie uistotne
			;
		END IF;
	--	Paremtry do sznurka	
		SET
			@._AUTH_CONV_Params = 
			CONCAT_WS('&',
				CONCAT('S.ID=', @.LOG.Input.Session),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
				CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),
				CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),
				CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),
				CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),
				CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
				CONCAT('D.ID=', @.LOG.Input.DEV_ID),
				CONCAT('A.ID=', @.LOG.Input.APP_ID)
			)
		;
			
	END IF;

	IF _PROC = '_sys_db_logons_LOG' THEN
	/******************************************************************************************************************************************
		np.
		CALL _sys_db_logons_LOG('CHECK', @_SESSION_GUID, @_INPUT_LOGIN_Hash, @_INPUT_Datas_Hash, @_INPUT_MACADDRESS_Hash, '', '', '', '');
		IN _MODE VARCHAR(250), 
		IN _SESSION_GUID VARCHAR(38),			->	_ID
		IN _INPUT_LOGIN_Hash VARCHAR(200),		->	_Param_A
		IN _INPUT_Datas_Hash VARCHAR(200),		->	_Param_B
		IN _INPUT_MACADDRESS_Hash VARCHAR(200),	->	_Param_C
		IN _Param_A VARCHAR(200),				->	_Param_D
		IN _Param_B VARCHAR(200),				->	_Param_E
		IN _Param_C VARCHAR(200),				->	_Param_F
		IN _Param_D VARCHAR(200)				->	_Param_G
	******************************************************************************************************************************************/
		IF _MODE IN ('CHECK.NEW', 'CHECK.NEW.BIO') THEN
		/*******************************************************************************************************
		CALL _sys_db_logons_LOG(IF(_MODE = 'LOG ON NEW', 'CHECK.NEW', 'CHECK.NEW.BIO'), _GUID, _Param_C, _Param_D, _Param_E, '', _Param_F, _Param_G, '');
		wołane z 
			DROP PROCEDURE IF EXISTS `_sys_db_logons_Tools`$$
			CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_db_logons_Tools`(
				IN _MODE VARCHAR(250), 		-- CHECK.NEW lub CHECK.NEW.BIO	-> _MODE
				IN _GUID VARCHAR(38),		-- $session_guid				-> _SESSION_GUID
				IN _CONNECTION_ID INTEGER,	-- 0							
				IN _Param_A VARCHAR(200),	-- "select"
				IN _Param_B VARCHAR(200),	-- ""
				IN _Param_C VARCHAR(200),	-- $username					-> _INPUT_LOGIN_Hash		-- w BIO podawany
				IN _Param_D VARCHAR(200),	-- $pass						-> _INPUT_Datas_Hash		-- w BIO pusty
				IN _Param_E VARCHAR(200),	-- $mac_hash					-> _INPUT_MACADDRESS_Hash	-- w BIO nie podawany
				IN _Param_F VARCHAR(200),	-- $app_upr						-> _Param_B
				IN _Param_G VARCHAR(200)	-- ""							-> _Param_C
			)
		*******************************************************************************************************/	
			SET
				@.LOG.Input.Session = _ID,
				@.LOG.Input.LOG_User.Hash = _Param_A,
				@.LOG.Input.LOG_PASS.Hash = _Param_B,
				@.LOG.Input.USER_GUID.Hash = NULL,
				@.LOG.Input.DEV_ID.Hash = _Param_C,
				@.LOG.Input.DEV_ID = NULL,	-- nie uistotne
				@.LOG.Input.APP_ID = _Param_D	-- @.LOG.Input.APP_ID.Hash = _Param_D,
			;
		END IF;
	--	Paremtry do sznurka	
		SET
			@._AUTH_CONV_Params = 
			CONCAT_WS('&',
				CONCAT('S.ID=', @.LOG.Input.Session),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
				CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),
				CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),
				CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),
				CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),
				CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
				CONCAT('D.ID=', @.LOG.Input.DEV_ID),
				CONCAT('A.ID=', @.LOG.Input.APP_ID)
				--	w _Param_D 	'Selcet'
				--	w _Param_E 	Access_Module
			)
		;
	END IF;
END$$

		DROP PROCEDURE IF EXISTS `_auth_bypass`$$
		CREATE DEFINER=`root`@`localhost` PROCEDURE `_auth_bypass`(
			IN _PROC VARCHAR(255),	--	jaka porocedura
			IN _MODE VARCHAR(250), 
			IN _GUID VARCHAR(255),
			--	IN _CONNECTION_ID INTEGER,	tylko dla `_sys_db_logons_Tools` ale nie jest tam uzywana
			IN _Param_A VARCHAR(200),
			IN _Param_B VARCHAR(200),
			IN _Param_C VARCHAR(200),
			IN _Param_D VARCHAR(200),
			IN _Param_E VARCHAR(200),
			IN _Param_F TEXT,
			IN _Param_G VARCHAR(200)	-- tylko w  `_sys_db_logons_Tools` ale nie wiem czy jest kiedykolwiek wykorzystany
		)
		S_auth_bypass: BEGIN
			DO _Birth_System();		-- aby miec m.in. select @session.globals.INPUT_SALT_Hash;
			/*** Sesja wej. ***/
			SET @.bypass.we.Session = _GUID;
			/*** Sól i pieprz ***/
			--	Sól
			SET	@.auth.Salt = @session.globals.INPUT_SALT_Hash;		-- select @.auth.Salt;
			--	Pieprz tylko w razie potrzeby - patrz niżej
			SET	@.auth.Pepper = NULL;	


			
			IF _PROC = '_sys_db_logons_Tools' THEN
				IF _MODE = 'LOG ON' THEN
				/*****************************************************************************************
					CALL _auth_bypass('_sys_db_logons_Tools', 'LOG ON',
						@.we.Session, 
						'select', '', 
						@.we.U.L.5, 
						@.we.U.P.5, 
						@.we.D.ID.5, 
						@.we.A.ID,
						''
					);
						
					zamiast ....
					
					CALL _sys_db_logons_LOG(IF(_MODE = 'LOG ON NEW', 'CHECK.NEW', 'CHECK.NEW.BIO'), _GUID, _Param_C, _Param_D, _Param_E, '', _Param_F, _Param_G, '');
					wołane z 
						DROP PROCEDURE IF EXISTS `_sys_db_logons_Tools`$$
						CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_db_logons_Tools`(
							IN _MODE VARCHAR(250), 		-- CHECK.NEW lub CHECK.NEW.BIO	-> _MODE
							IN _GUID VARCHAR(38),		-- $session_guid				-> _SESSION_GUID
							IN _CONNECTION_ID INTEGER,	-- 0							
							IN _Param_A VARCHAR(200),	-- "select"
							IN _Param_B VARCHAR(200),	-- ""
							IN _Param_C VARCHAR(200),	-- $username					-> _INPUT_LOGIN_Hash		-- w BIO podawany
							IN _Param_D VARCHAR(200),	-- $pass						-> _INPUT_Datas_Hash		-- w BIO pusty
							IN _Param_E VARCHAR(200),	-- $mac_hash					-> _INPUT_MACADDRESS_Hash	-- w BIO nie podawany
							IN _Param_F VARCHAR(200),	-- $app_upr						-> _Param_B
							IN _Param_G VARCHAR(200)	-- ""							-> _Param_C
						)
					
				******************************************************************************************/
				/*	UWAGA akcja stare płace PL2003!!!	WYJĄTEK NA LATA!!!!	*/
				CALL _sys_app_logtxt('LOG.User.Add', '', 'watch', _Param_F, '', '', '', '', 
					CONCAT_WS('/', 
						CONCAT('MODE: ', _PROC, '.', _MODE), 
						CONCAT('APP.ID: ', _Param_F), 
						NULL
					)
				);
					IF 
						_Param_F IS NOT NULL 
					AND 
						IFNULL((SELECT a.Disabled FROM `_sys_app_reg` a WHERE a.ID = _Param_F), 0) = 1
					/*
					IF 
						_Param_F = 'M.EXE.PL2003'
					AND 
						IFNULL((SELECT  `Value` FROM `_db_globals` WHERE `key` = 'blokada.PL2023'), 0) = 1
					*/
					THEN
						CALL _sys_app_logtxt('LOG.User.Add', '', 'watch', 'jmam', '', '', '', '', CONCAT_WS('/', 'Udaw. blokada', CONCAT('APP.ID: ', _Param_F), NULL));
						UPDATE `_sys_db_logons` l
						SET
							-- l.LAST_MSG = (@.auth.Final.Verify_Status := 'Nieaktualna wersja aplikacji, proszę użyć nowej wersji!')	-- ważna małpa!!!
							l.LAST_MSG = (@.auth.Final.Verify_Status := 'Aplikacja ta została wycofana z użytkowania, wznowienie działania wymaga zmian administracyjnych! (BP)'),	-- ważna małpa!!!
							l.Status = 'INACTIVE.LOG.ERR',
							l.log_APP_ID = _Param_F
							-- , l.Inactive = 1 
						WHERE 
							l.GUID = @.bypass.we.Session
						;
						CALL _sessions_APP('SELECT.AUTH._sys_db_logons_Tools', @.bypass.we.Session, '', '', '', '', '');
						LEAVE S_auth_bypass;
					END IF;
				
					SET @.bypass.Input_Params = _Param_A;	-- np. "select"
				--	Parametry do zmiennych
					SET
						@.auth.we.S.ID = @.bypass.we.Session,
						@.auth.we.U.L.5 = _Param_C,	-- Hash LOGIN
						@.auth.we.U.P.5 = _Param_D,	-- Hash Pswd,
						@.auth.we.U.G.5 = NULL,
						@.auth.we.D.ID.5 = _Param_E,	-- Hash _DevID/MACADDRESS,
						@.auth.we.A.ID.5 = NULL,
						@.auth.we.D.ID = NULL,
						@.auth.we.A.ID = _Param_F,	--	czy aby na pewno to jest zwykłe App czy #app ???
						@.auth.we.A.NAME = NULL,
						@.bypass.auth.MODE.SELECT = 
							IF(@.bypass.Input_Params LIKE '%select%', '<select._sys_db_logons_Tools>', '')
					;
					/*** pieprz ***/
					--	Pieprz
					SET	@.auth.Pepper = @.bypass.we.Session;	-- do szukania ponizej, z sesją gdy <> NULL
					SET
						@.auth.we.A.ID.5 = 
							IF(IFNULL(@.auth.we.A.ID, '') <> '',
								_MD5_CHARSET('', @.auth.Salt, @.auth.Pepper, @.auth.we.A.ID, '', ''),
								NULL
							)
					;
				--	Parametry do sznurka + Logowanie!!!
					CALL _authorization('LOG:#Login,#Pswd', @.bypass.we.Session, '<prepare.by.@>', '', '', '', '', @.bypass.auth.MODE.SELECT);
				END IF;
				IF _MODE = 'LOG ON BIO' THEN
				/*****************************************************************************************
					CALL _auth_bypass('_sys_db_logons_Tools', 'LOG ON BIO', 
						@.we.Session, 
						0,
						'select', 
						'', 
						@.we.U.L.5, 	-- _Param_C
						@.we.U.P.5, 
						@.we.D.ID.5, 
						@.we.A.ID,
						''
					);
						
					zamiast ....
					
					CALL _sys_db_logons_Tools('LOG ON', @_SESSION_GUID, 0, 'select', '', @_INPUT_LOGIN_Hash, @_INPUT_Datas_Hash, @_INPUT_MACADDRESS_Hash, 'M.WEB.ScanPack', '');
					
					CALL _sys_db_logons_LOG(IF(_MODE = 'LOG ON NEW', 'CHECK.NEW', 'CHECK.NEW.BIO'), _GUID, _Param_C, _Param_D, _Param_E, '', _Param_F, _Param_G, '');
					wołane z 
						DROP PROCEDURE IF EXISTS `_sys_db_logons_Tools`$$
						CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_db_logons_Tools`(
							IN _MODE VARCHAR(250), 		-- CHECK.NEW lub CHECK.NEW.BIO	-> _MODE
							IN _GUID VARCHAR(38),		-- $session_guid				-> _SESSION_GUID
							IN _CONNECTION_ID INTEGER,	-- 0							
							IN _Param_A VARCHAR(200),	-- "select"
							IN _Param_B VARCHAR(200),	-- ""
							IN _Param_C VARCHAR(200),	-- $username					-> _INPUT_LOGIN_Hash		-- w BIO podawany
							IN _Param_D VARCHAR(200),	-- $pass						-> _INPUT_Datas_Hash		-- w BIO pusty
							IN _Param_E VARCHAR(200),	-- $mac_hash					-> _INPUT_MACADDRESS_Hash	-- w BIO nie podawany
							IN _Param_F VARCHAR(200),	-- $app_upr						-> _Param_B
							IN _Param_G VARCHAR(200)	-- ""							-> _Param_C
						)
					
				******************************************************************************************/
					SET @.bypass.Input_Params = _Param_A;	-- np. "select"
				--	Parametry do zmiennych
					SET
						@.auth.we.S.ID = @.bypass.we.Session,
						@.auth.we.U.L.5 = _Param_C,	-- Hash LOGIN
						@.auth.we.U.P.5 = _Param_D,	-- Hash Pswd,
						@.auth.we.U.G.5 = NULL,
						@.auth.we.D.ID.5 = _Param_E,	-- Hash _DevID/MACADDRESS,
						@.auth.we.A.ID.5 = NULL,
						@.auth.we.D.ID = NULL,
						@.auth.we.A.ID = _Param_F,	--	czy aby na pewno to jest zwykłe App czy #app ???
						@.auth.we.A.NAME = NULL,
						@.bypass.auth.MODE.SELECT = 
							IF(@.bypass.Input_Params LIKE '%select%', '<select._sys_db_logons_Tools>', '')
					;
					/*** pieprz ***/
					--	Pieprz
					SET	@.auth.Pepper = @.bypass.we.Session;	-- do szukania ponizej, z sesją gdy <> NULL
					SET
						@.auth.we.A.ID.5 = 
							IF(IFNULL(@.auth.we.A.ID, '') <> '',
								_MD5_CHARSET('', @.auth.Salt, @.auth.Pepper, @.auth.we.A.ID, '', ''),
								NULL
							)
					;
				--	Parametry do sznurka + Logowanie!!!
					CALL _authorization('LOG.BIO:#Login.Only', @.bypass.we.Session, '<prepare.by.@>', '', '', '', '', @.bypass.auth.MODE.SELECT);
				END IF;
			END IF;
			
			
			IF _PROC = '_sys_authorization' THEN
				IF _MODE = 'authorization.LOG.#Login,#Pswd' THEN
				/******************************************************************************************
					_GUID		Sesja (moze byc ''/null 
					_Param_A	#Login
					_Param_B	#Pswd
					_Param_C	#DEV_ID
					_Param_D	#APP_ID
					_Param_E	Params
					CALL _auth_bypass('_sys_authorization', 'authorization.LOG.#Login,#Pswd', 
							@.we.Session, 
							@.we.U.L.5, 
							@.we.U.P.5, 
							@.we.D.ID.5, 
							@.we.A.ID.5,
							'<Session.In.Hash>', 	-- paramsy
							'', '');
					
				******************************************************************************************/
				--	Sesja!!! Czasem do mieszania HASH używamy też sesji - np. prog. EXE wtedy w _Param_E dajemy słowo "<Session.In.Hash>"
				--	Gdy jest pusto to w MD5 pierwszy parametr pusty ale gdy jest <> '' (np xxx.EXE) - to trzeba uwzgl. w MD5 
					SET @.bypass.Input_Params = _Param_E;
					SET 
						@.bypass.we.Session = 
							IF(@.bypass.Input_Params LIKE '%<Session.In.Hash>%',
								NULLIF(_GUID, ''),
								NULL
							)
					;
				--	Parametry do zmiennych
					SET
						@.auth.we.S.ID = @.bypass.we.Session,
						@.auth.we.U.L.5 = _Param_A,	-- Hash LOGIN
						@.auth.we.U.P.5 = _Param_B,	-- Hash Pswd,
						@.auth.we.U.G.5 = NULL,
						@.auth.we.D.ID.5 = _Param_C,	-- Hash _DevID/MACADDRESS,
						@.auth.we.A.ID.5 = _Param_D,	-- Hash  AppID,
						@.auth.we.D.ID = NULL,
						@.auth.we.A.ID = NULL,
						@.auth.we.A.NAME = NULL,
						@.bypass.auth.MODE.SELECT = 
							IF(@.bypass.Input_Params LIKE '%No.select%', '', '<select._sys_authorization>')
					;
				--	Parametry do sznurka + Logowanie!!!
					CALL _authorization('LOG:#Login,#Pswd', _GUID /* @.bypass.we.Session */, '<prepare.by.@>', '', '', '', '', @.bypass.auth.MODE.SELECT);
				END IF;
			END IF;
			
			IF _PROC = '_sys_connection_Tool' THEN
				IF _MODE LIKE 'LOGON.SERVICE%' THEN
				/*	UWAGA to logowanie do baaardzo starej tabeli `_db_logons` i w oryginale 
					odbywa się autoryzacja na gdy OK tworzona jest sesja
					Zatem
						tutaj tworzę sesję w _sys_db_logons i dalej juz utarty szlakiem...
					CALL _auth_bypass('_sys_connection_Tool', 'LOGON.SERVICE', 
						@_SESSION_GUID, 
						@_INPUT_LOGIN_Hash, 
						@_INPUT_Datas_Hash, 
						@_INPUT_MACADDRESS_Hash, 
						'', 
						@_Param_B, 	-- APP_ID = _Param_B	--	czy aby na pewno to jest zwykłe App czy #app ???
						'', '');
						
					zamiast ....
					CALL _sys_connection_Tool('LOGON.SERVICE','LOGIN', MD5('jmam'),MD5('pr3z3s$'),'192.168.1.12','192.168.1.12','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.56','BakerDroid','');
					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', '');		
					'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"
						
				*/
				--	Tworzę sesję do zalogowania ... ale za nim to mały sznurek do tworzenia sesji ...
					SET
						@.auth.we.A.NAME = _Param_E,
						@.auth.we.A.ID = NULL,
						@.auth.we.log_HOST = _Param_B, 
						@.auth.we.log_MACADDRESS = _Param_C,
						@.auth.we.log_HOST_NAME = CONCAT_WS(':', _Param_B, _Param_C, _Param_D),
						@.auth.we.U.L = _GUID,
						@.auth.we.U.P = _Param_A
					;
								--	SET	@.bypass.debug = _MODE;
					IF TRUE THEN
						SET
							@.auth.we.A.ID = 
								IF(@.auth.we.A.NAME = 'DostawcaGazu',
									'M.MOB.GASDROID',
									IF(@.auth.we.A.NAME = 'MHDroid',
										'M.MOB.MHDroid',
										IF(@.auth.we.A.NAME = 'BakerDroid',
											'M.MOB.BakerDroid',
											NULL
										)
									)
								)
						;
								--	SET	@.bypass.debug = concat_WS('/', @.bypass.debug, concat_WS('=', 'A.ID', quote(@.auth.we.A.ID)));
					END IF;
					SET
						@.insert.we.Params = 
						CONCAT_WS('&',
							-- CONCAT('A.ID=', @.auth.we.A.ID),
							CONCAT('A.NAME=', @.auth.we.A.NAME),
							CONCAT('A.ID=', @.auth.we.A.ID),
							CONCAT('log_HOST=', @.auth.we.log_HOST), 
							CONCAT('log_HOST_NAME=', @.auth.we.log_HOST_NAME), 
							CONCAT('log_MACADDRESS=', @.auth.we.log_MACADDRESS)
						)
					;
				--	teraz tworzę sesję
					CALL _sessions_APP('INSERT', 'NEW', '', '', '', '', @.insert.we.Params);
				--	Ustaw sesję, pieprz ...
					SET @.bypass.we.Session = @SYSTEM.Current.Session.GUID;
					SET	@.auth.Pepper = @.bypass.we.Session;	-- do szukania ponizej, z sesją gdy <> NULL
				--	Parametry do zmiennych
					SET
						@.auth.we.S.ID = @.bypass.we.Session,
					--	posól Login i hasło bo same są tylko MD5
						@.auth.we.U.L.5 = 
							_MD5_CHARSET('', @.auth.Salt, @.auth.Pepper, _GUID, '', ''),	-- Hash LOGIN
							-- _MD5_CHARSET('', @.auth.Salt, _GUID, '', '', ''),	-- Hash LOGIN
						@.auth.we.U.P.5 = 
							_MD5_CHARSET('', @.auth.Salt, @.auth.Pepper, _Param_A, '', ''),	-- Hash Pswd
							-- _MD5_CHARSET('', @.auth.Salt, _Param_A, '', '', ''),	-- Hash Pswd
						@.auth.we.U.G.5 = NULL,
						@.auth.we.D.ID.5 = NULL,	-- Hash _DevID/MACADDRESS,
						@.auth.we.A.ID.5 = NULL,	-- Hash  AppID,
						@.auth.we.D.ID = CONCAT_WS(':', _Param_B, _Param_C, _Param_D),
						-- @.auth.we.A.ID = NULL,
						-- juz mam @.auth.we.A.NAME = _Param_E,
						-- juz mam @.auth.we.log_HOST = _Param_B, 
						-- juz mam @.auth.we.log_MACADDRESS = _Param_C,
						-- juz mam @.auth.we.log_HOST_NAME = CONCAT_WS(':', _Param_B, _Param_C, _Param_D), 
						@.bypass.auth.MODE.SELECT = '<select._sys_connection_Tool>'
					;
					IF IFNULL(@session.Delfinek, FALSE) THEN
						SET
							@.auth.we.U.L.5 = 
								_MD5_CHARSET('', @.auth.Salt, @.auth.Pepper, @.auth.we.U.L, '', ''),	-- Hash LOGIN
								-- _MD5_CHARSET('', @.auth.Salt, _GUID, '', '', ''),	-- Hash LOGIN
							@.auth.we.U.P.5 = 
								_MD5_CHARSET('', @.auth.Salt, @.auth.Pepper, @.auth.we.U.P, '', '')	-- Hash Pswd
						;
					END IF;
					/*
					SET
						@.LOG.Input.Session = NULL,
						@.LOG.Input.LOG_User.Hash = _GUID,
						@.LOG.Input.LOG_PASS.Hash = _Param_A,
						@.LOG.Input.USER_GUID.Hash = NULL,
						@.LOG.Input.DEV_ID.Hash = NULL,
						@.LOG.Input.APP_ID.Hash = NULL,
						@.LOG.Input.DEV_ID = CONCAT_WS(':', _Param_B, _Param_C, _Param_D),
						@.LOG.Input.APP_ID = _Param_E	--	czy aby na pewno to jest zwykłe App czy #app ???
					;
				--	Dodatkowo posól @.LOG.Input.LOG_User.Hash i @.LOG.Input.LOG_PASS.Hash
					SET
						@.LOG.Input.LOG_User.Hash = 
							_MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.LOG_User.Hash, '', '', ''),
						@.LOG.Input.LOG_PASS.Hash = 
							_MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, @.LOG.Input.LOG_PASS.Hash, '', '', '')
					;
				--	Paremtry do sznurka	
					SET
						@.bypass.auth.Params = 
						CONCAT_WS('&',
						--	NIE!!!	CONCAT('S.ID=', @.LOG.Input.Session),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
							CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),
							CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),
							-- CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),
							-- CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),
							-- CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
							CONCAT('D.ID=', @.LOG.Input.DEV_ID),
							CONCAT('A.ID=', @.LOG.Input.APP_ID)
						)
					;
					*/
				--	Logowanie
					CALL _authorization('LOG:#Login,#Pswd', @.bypass.we.Session, '<prepare.by.@>', '', '', '', '', @.bypass.auth.MODE.SELECT);
					
				END IF;
			END IF;
		
		END$$

/*
	Przeniesiona do eventów: e_sys_db_logons_Refresh.sql
DROP EVENT IF EXISTS `e_sys_db_logons_Refresh`$$
CREATE EVENT `e_sys_db_logons_Refresh`
	ON SCHEDULE EVERY 15 MINUTE 
DO
BEGIN
/* ************************************************************************************************************************************************************************
	UWAGA!!!!!!!!!!!
		od 9 II 2023 przeniesiona z _sys_db_logons.sql 
	Event - Sprawdza co 15 minut stan sesji w  `_sys_db_logons` żądając Do_Info = 'CHECK.STATE' 
	UWAGA
	SHOW VARIABLES LIKE '%event%';
	SHOW VARIABLES LIKE '%event_scheduler%';
	SET GLOBAL event_scheduler = ON;
************************************************************************************************************************************************************************ /	
	-- dawne wołanie w innym miejscu CALL _sys_db_logons_Time_Update('', '', '', '', '', '');
	CALL _sessions_SEL('SPEC.TIME.CLEAR.EVENT', '', '', '','');
END;
$$
*/

DELIMITER ;

/*
$Log: _sessions_APP.sql,v $
Revision 1.7  2025/03/31 12:52:11  jmam
$send$ dawne poprawki

*/

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================

Logowanie biometryczne
1. Aplikacja (tak było mniemam dotychczas pposiada:
- 	GUID USER oraz
-	ID urządzenia - ogólnie pojmowany ID np jakies IMEI/Mcaddress/etc.
Aby się zalogowac te dwa parametry musza byc przekazane analogicznie ja Login/hasło
w zwykłym logowaniu
Oczywiście teke parametyry musza byc posolone i popieprzone!!!
2. Parametry
W delfinku sznurek przygotowuje nastepujaco:
SET
	@._IN_Auth_Params = 
	CONCAT_WS('&',
		CONCAT('S.ID=', @.LOG.Input.Session),
		CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
		CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),	-- ID urzadzenia -> Sól/pieprz
		CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),	-- UserGUID -> Sól/pieprz
		CONCAT('A.VER=', @.LOG.Input.APP_VER)		-- wersja app. (nieobow.!!!!!)
	)
;
czyli analogicznie jak logowanie tyler że 
3. Call - wołanie czyli procedura
CALL _authorization('LOG.BIO:#UserGUID,#DEV_ID', @.LOG.Input.Session, @._IN_Auth_Params, '', '', '', '', '<Select>');

Rejestracja BIO 
1. Rejestracja polega na autoryzacji i zarejestrowaniu ID urządzenia (chodzi o to samo ID co 
w p. 1.2.3 logowania BIO
Poniewaz jest tu także autoryzacja to sznurek musi posiadać za zatem user musi podać Login/hasło!!! a dodatkowo
oczywiście przekazywane jest ID
2. Parametry rej. BIO
SET
	@._IN_Auth_Params = 
	CONCAT_WS('&',
		CONCAT('S.ID=', @.LOG.Input.Session),
		CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),	-- login -> Sól/pieprz
		CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),	-- pswd -> Sól/pieprz
		CONCAT('D.ID=', @.LOG.Input.DEV_ID)			-- ID urzadzenia 
	)
;
3. Call rej. BIO
CALL _authorization('AUTH:#Login,#Pswd+ADD.BIO:DEV_ID', @.LOG.Input.Session, @._IN_Auth_Params, '', '', '', '', '<Select>');		

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
