Piotr Labudda 5 år sedan
förälder
incheckning
15bb577f17

+ 1 - 2
SE/procesy5.php

@@ -1818,10 +1818,9 @@ function tree_callback__show_item_from_CRM_PROCES( &$r, &$tree ) {
 	if ($tree->get_param('editable') && $tree->get_param('HasAclPytaniaTbl')) {
 		$userAcl = User::getAcl();
 		$tblAcl = $userAcl->getTableAcl($tblPytaniaId);
-		$dataSource = $tblAcl->getDataSource();
 		$params = array();
 		$params['f_ID_PROCES'] = $r->ID;
-		$pytania = $dataSource->getItems($params);
+		$pytania = $tblAcl->getDataSource()->getItems($params);
 		$tree->log('show item -> fetch-pytania', array('fetch-pytania'));
 	}
 

+ 154 - 134
SE/se-lib/Billing.php

@@ -3,14 +3,18 @@
 Lib::loadClass('TableAcl');
 Lib::loadClass('UserAcl');
 
+// TODO: @used_by:
+//   $result_KORV = Billing::lista_korekt($row['ID_BILLING_NUMBERS']);
+//   $fp = Billing::BILLING_USERS_ADD($fv_naglowek['ID_BILLING_USERS']);
+//   Billing::get_BILLING_NUMBERS_TYPE();
+//   $lista_dok_finansowych = Billing::lista_dok_finansowych();
+
 class Billing {
 
 	function __construct($DATABASE) {
-		$this->db = DB::getDB($DATABASE);
-		DEBUG_S(3,'DB',array($this->db,$DATABASE),__FILE__,__FUNCTION__,__LINE__);
-		if(empty($DATABASE)) die('You must set in config database for billing zasob_id variable');
+		if (empty($DATABASE)) die('You must set in config database for billing zasob_id variable');
+		$this->_pdo = DB::getPDO($DATABASE);
 		$this->TableAcl->GetTablesByDbId = TableAcl::GetTablesByDbId($DATABASE);
-		DEBUG_S(3,'TableAcl->GetTablesByDbId',$this->TableAcl,__FILE__,__FUNCTION__,__LINE__);
 	}
 
 	function set_client_filter($ID_BILLING_USERS) {
@@ -18,11 +22,11 @@ class Billing {
 	}
 
 	function show_doc_BILLING_NUMBER_TYPE_header($ID_BILLING_NUMBERS) {
-		$sql = "select ID,ID_BILLING_PREFIXES,NUMBER,ID_BILLING_USERS,U_ID,BILLING_OWNER from BILLING_NUMBERS where ID=".$ID_BILLING_NUMBERS;
-		$res = $this->db->query($sql);
-		while ($h = $this->db->fetch($res)) {
-			return $h;
-		}
+		return $this->_pdo->fetchFirstAsObject("
+			select ID, ID_BILLING_PREFIXES, NUMBER, ID_BILLING_USERS, U_ID, BILLING_OWNER
+			from BILLING_NUMBERS
+			where ID = {$ID_BILLING_NUMBERS}
+		");
 	}
 
 	function _show_doc_BILLING_NUMBERS_TYPE_CLASS_FINANCE($ID_BILLING_NUMBERS) {
@@ -30,9 +34,11 @@ class Billing {
 		$this->check_perms();
 		$result_BILLING_NUMBERS_TYPE = $this->get_document_type($ID_BILLING_NUMBERS);
 		$header = $this->show_doc_BILLING_NUMBER_TYPE_header($ID_BILLING_NUMBERS);
-		$sql = "select * from ".$result_BILLING_NUMBERS_TYPE['TABLE']." where ID_BILLING_NUMBERS=".$header->ID;
-		$res = $this->db->query($sql);
-		$docum = $this->db->fetch($res);
+		$docum = $this->_pdo->fetchFirstAsObject("
+			select *
+			from {$result_BILLING_NUMBERS_TYPE['TABLE']}
+			where ID_BILLING_NUMBERS = {$header->ID}
+		");
 		$client = $this->BILLING_USERS_ADD($header->ID_BILLING_USERS);
 		$author = $this->BILLING_USERS_ADD($header->U_ID);
 		$owner = $this->BILLING_OWNER($client->BILLING_OWNER);
@@ -54,14 +60,14 @@ class Billing {
 		$result_BILLING_NUMBERS_TYPE = $this->get_document_type($ID_BILLING_NUMBERS);
 		$billingTblName = $result_BILLING_NUMBERS_TYPE['TABLE'];
 		$billingNumbersTblName = $result_BILLING_NUMBERS_TYPE['BILLING_NUMBERS_TABLE'];
-		DEBUG_S(3,'result_BILLING_NUMBERS_TYPE',$result_BILLING_NUMBERS_TYPE,__FILE__,__FUNCTION__,__LINE__);
 
 		$header = $this->show_doc_BILLING_NUMBER_TYPE_header($ID_BILLING_NUMBERS);
-		DEBUG_S(3,'header',$header,__FILE__,__FUNCTION__,__LINE__);
 
-		$sql = "select * from {$billingTblName} where ID_BILLING_NUMBERS={$header->ID}";
-		$res = $this->db->query($sql);
-		$docum = $this->db->fetch($res);
+		$docum = $this->_pdo->fetchFirstAsObject("
+			select *
+			from {$billingTblName}
+			where ID_BILLING_NUMBERS = {$header->ID}
+		");
 
 		$sqlbl = "
 			select {$billingNumbersTblName}.NUMBER
@@ -91,13 +97,17 @@ class Billing {
 				left join list_sww on {$billingTblName}_POS.id_list_sww=list_sww.id
 			 where {$billingTblName}.ID_BILLING_NUMBERS = '{$ID_BILLING_NUMBERS}'
 		";
-		$res = $this->db->query($sqlbl);
+
+		$sth = $this->_pdo->prepare($sqlbl);
+
 		$i = 1;
 
 		$docum->razem_netto = 0;
 		$docum->razem_brutto = 0;
 
-		while ($h = $this->db->fetch($res)) {
+		$sth->execute();
+		while ($item = $sth->fetch()) {
+			$h = (object)$item;
 			$pos[$i] = $h;
 
 			if ($h->description) {
@@ -137,14 +147,10 @@ class Billing {
 
 			$i++;
 		}
-		DEBUG_S(3,'pos',$pos,__FILE__,__FUNCTION__,__LINE__);
-		DEBUG_S(3,'docum',$docum,__FILE__,__FUNCTION__,__LINE__);
 
 		$client = $this->BILLING_USERS_ADD($header->ID_BILLING_USERS);
 		$author = $this->BILLING_USERS_ADD($header->U_ID);
-		DEBUG_S(3,'client',$client,__FILE__,__FUNCTION__,__LINE__);
 		$owner = $this->BILLING_OWNER($client->BILLING_OWNER);
-		DEBUG_S(3,'owner',$owner,__FILE__,__FUNCTION__,__LINE__);
 
 		$pay_option = $this->LIST_FORM_PAY($docum->PAYMENT_TYPE, $owner->id_list_form_pay);
 
@@ -156,6 +162,7 @@ class Billing {
 		$doc->docum = $docum;
 		$doc->pos = $pos;
 		$doc->pay_option = $pay_option;
+
 		return $doc;
 	}
 
@@ -172,9 +179,7 @@ class Billing {
 				     
 				     WHERE ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.ID=".$POS_ID;
 				//    echo "$sql4<br><br>";
-				    $result4 = $this->db->query($sql4);
-				    $all4 = $this->db->fetch($result4);
-					return $all4;
+					return $this->_pdo->fetchFirstAsObject($sql4);
 		
 	}
 */
@@ -199,32 +204,36 @@ class Billing {
 	}
 
 	function BILLING_OWNER($ID_BILLING_OWNER) {
-		$sql = "select * from BILLING_OWNER where id={$ID_BILLING_OWNER}";
-		$res = $this->db->query($sql);
-		while ($h = $this->db->fetch($res)) {
-			return $h;
-		}
+		return $this->_pdo->fetchFirstAsObject("
+			select *
+			from BILLING_OWNER
+			where id = {$ID_BILLING_OWNER}
+		");
 	}
 
-	function LIST_FORM_PAY($id_used_pay_type=null,$user_accessible_pay_type=null) {
-		if(!empty($id_used_pay_type)) {
-		    $sqlpay = "SELECT * FROM list_form_pay WHERE id=".$id_used_pay_type;
-		    $resultpay = $this->db->query($sqlpay);
-		    $allpay = $this->db->fetch($resultpay);
-		  } else {
-		    $sqlpay = "SELECT * FROM list_form_pay WHERE id=".$user_accessible_pay_type;
-		    $resultpay = $this->db->query($sqlpay);
-		    $allpay = $this->db->fetch($resultpay);
-		  }
-		return $allpay ;
+	function LIST_FORM_PAY($id_used_pay_type = null, $user_accessible_pay_type = null) {
+		if (!empty($id_used_pay_type)) {
+		    return $this->_pdo->fetchFirstAsObject("
+				SELECT *
+				FROM list_form_pay
+				WHERE id = {$id_used_pay_type}
+			");
+		}
+		if (!empty($user_accessible_pay_type)) {
+			return $this->_pdo->fetchFirstAsObject("
+				SELECT *
+				FROM list_form_pay
+				WHERE id = {$user_accessible_pay_type}
+			");
+		}
 	}
 
 	function BILLING_USERS_ADD($ID_BILLING_USERS) {
-		$sqlp = "select * from COMPANIES where ID='".$ID_BILLING_USERS."'";
-		$db = DB::getDB();
-		$resultp = $db->query($sqlp);
-		$fp = $db->fetch($resultp);
-		return($fp);
+		return $this->_pdo->fetchFirstAsObject("
+			select *
+			from COMPANIES
+			where ID = '{$ID_BILLING_USERS}'
+		");
 	}
 
 //VERSION 2004-07-07 0.96
@@ -377,7 +386,8 @@ for($i2=0; $i2<=$liczba_linii_crc;$i2++) {
 		$this->check_perms();
 
 		//TODO check if has perms for that...
-		$sql7= "select BILLS_FVAT.ID
+		$sql7= "
+			select BILLS_FVAT.ID
 				, count(BILLS_FVAT_POS.ID) as count_BILLS_FVAT_POS_ID
 				, BILLS_FVAT_POS.ID_BILLS_FVAT
 				, BILLS_FVAT.ID_CURRENCY
@@ -398,13 +408,9 @@ for($i2=0; $i2<=$liczba_linii_crc;$i2++) {
 				left join BILLING_NUMBERS on BILLING_NUMBERS.ID=BILLS_FVAT.ID_BILLING_NUMBERS
 			where BILLS_FVAT.ID_BILLING_USERS='".$this->set_client_filter."' group by BILLS_FVAT.ID order by BILLS_FVAT.ID
 		";
-		DEBUG_S(3,'zap_sql_do_fv',$sql7,__FILE__,__FUNCTION__,__LINE__);
-		$result7 = $this->db->query($sql7);
-		while ($h = $this->db->fetch_assoc($result7)) {
-			$result7_arr[] = $h;
-		}
-		DEBUG_S(3,'lista_faktur',array($sql7,$result7_arr),__FILE__,__FUNCTION__,__LINE__);
-		return $result7_arr;
+		return array_map(function ($item) {
+			return (object)$item;
+		}, $this->_pdo->fetchAll($sql7));
 	}
 
 	function lista_korekt($ID_BILLING_NUMBERS) {
@@ -423,83 +429,95 @@ for($i2=0; $i2<=$liczba_linii_crc;$i2++) {
 						 ".$KORV_TABLE.".ID_BILLING_NUMBERS , ".$KORV_TABLE.".OPEN , ".$KORV_TABLE.".FK_ZAKSIEG ,".$KORV_TABLE.".IF_KORV
 						 from ".$KORV_TABLE." left join ".$KORV_TABLE."_POS on ".$KORV_TABLE.".ID=".$KORV_TABLE."_POS.ID_BILLS_FVAT  
 						where   ".$KORV_TABLE.".REMOTE_ID_BILLING_NUMBERS_TYPE='1' and ".$KORV_TABLE.".REMOTE_ID_BILLING_NUMBERS='".$ID_BILLING_NUMBERS."' group by ".$KORV_TABLE.".ID order by ".$KORV_TABLE.".ID ";
-						DEBUG_S(3,'SQL lista_korekt',$sql,__FILE__,__FUNCTION__,__LINE__);
-				 $result_KORV=$this->db->query($sql);
-				 while($h=$this->db->fetch_assoc($result_KORV)) {
-					 $result_KORV_arr[]=$h;	
-				}
-				return $result_KORV_arr;
+
+		return $this->_pdo->fetchAll($sql);
 	}
 
 	function lista_BILLING_NUMBERS_TYPE_CLASS_SELL_MA($result_BILLING_NUMBERS_TYPE) {
-				                        $sql= "select ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID, count(".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.ID), ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.ID_BILLS_FVAT, ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_CURRENCY,
-				                        round(sum(
-				                         ((".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.AMMOUNT * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.PRICE) * ( 1 + ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.VAT / 100))
-				                        - (".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_AMMOUNT * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_PRICE * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_VAT / 100)
-				                        + (".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_AMMOUNT * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_PRICE * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.VAT / 100)
-				                        ),2) as MA ,
-				                        round(sum((".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_AMMOUNT * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_PRICE) * ( 1 + ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_VAT / 100)),2) as WINIEN ,
-				                         ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_NUMBERS , ".$result_BILLING_NUMBERS_TYPE[TABLE].".OPEN , ".$result_BILLING_NUMBERS_TYPE[TABLE].".FK_ZAKSIEG ,
-							".$result_BILLING_NUMBERS_TYPE[TABLE].".IF_KORV , ".$result_BILLING_NUMBERS_TYPE[TABLE].".BILL_DATE , ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".NUMBER ,
-							".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_FK_DEKRET
-				                         from ".$result_BILLING_NUMBERS_TYPE[TABLE]." 
-							left join ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE]." on ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".ID=".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_NUMBERS
-							left join ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS on ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID=".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.ID_BILLS_FVAT
-				                        where ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_USERS='".$this->set_client_filter."'
-				                        group by ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID order by ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID ";
-					$result_KP=$this->db->query($sql); 
-				    $i=0;
-				    while($h=$this->db->fetch_assoc($result_KP)) {
-					    $result_KP_arr[$i]=$h;
-					    $result_KP_arr[$i]['ID_BILLING_NUMBERS_TYPE']=$result_BILLING_NUMBERS_TYPE['ID'];
-					    $result_KP_arr[$i]['CLASS']=$result_BILLING_NUMBERS_TYPE['CLASS'];
-						$result_KP_arr[$i]['TYPE']=$result_BILLING_NUMBERS_TYPE['TYPE'];
-						$i++;
-				    }
-				    	DEBUG_S(-3,'lista_BILLING_NUMBERS_TYPE_CLASS_SELL_MA',$result_KP_arr,__FILE__,__FUNCTION__,__LINE__);
-				    return $result_KP_arr;
+		$sql = "
+			select ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID
+				, count(".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.ID)
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.ID_BILLS_FVAT
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_CURRENCY
+				, round(sum(
+					((".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.AMMOUNT * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.PRICE) * ( 1 + ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.VAT / 100))
+					- (".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_AMMOUNT * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_PRICE * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_VAT / 100)
+					+ (".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_AMMOUNT * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_PRICE * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.VAT / 100)
+					),2) as MA
+				, round(sum((".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_AMMOUNT * ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_PRICE) * ( 1 + ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.N_VAT / 100)),2) as WINIEN
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_NUMBERS , ".$result_BILLING_NUMBERS_TYPE[TABLE].".OPEN , ".$result_BILLING_NUMBERS_TYPE[TABLE].".FK_ZAKSIEG
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".IF_KORV , ".$result_BILLING_NUMBERS_TYPE[TABLE].".BILL_DATE , ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".NUMBER
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_FK_DEKRET
+			from ".$result_BILLING_NUMBERS_TYPE[TABLE]."
+				left join ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE]." on ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".ID=".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_NUMBERS
+				left join ".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS on ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID=".$result_BILLING_NUMBERS_TYPE[TABLE]."_POS.ID_BILLS_FVAT
+			where ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_USERS='".$this->set_client_filter."'
+			group by ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID
+			order by ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID
+		";
+
+		$result_KP_arr = [];
+		$i = 0;
+		$listItems = $this->_pdo->fetchAll($sql);
+		foreach ($listItems as $h) {
+			$result_KP_arr[$i] = $h;
+			$result_KP_arr[$i]['ID_BILLING_NUMBERS_TYPE'] = $result_BILLING_NUMBERS_TYPE['ID'];
+			$result_KP_arr[$i]['CLASS'] = $result_BILLING_NUMBERS_TYPE['CLASS'];
+			$result_KP_arr[$i]['TYPE'] = $result_BILLING_NUMBERS_TYPE['TYPE'];
+			$i++;
+		}
+
+		return $result_KP_arr;
 	}
 
 	function lista_BILLING_NUMBERS_TYPE_CLASS_FINANCE($result_BILLING_NUMBERS_TYPE) {
-		$sql="select ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID,".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_NUMBERS , ".$result_BILLING_NUMBERS_TYPE[TABLE].".BILL_DATE , ".$result_BILLING_NUMBERS_TYPE[TABLE].".WINIEN , ".$result_BILLING_NUMBERS_TYPE[TABLE].".MA , 
-				     ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_FK_DEKRET, ".$result_BILLING_NUMBERS_TYPE[TABLE].".OPEN , ".$result_BILLING_NUMBERS_TYPE[TABLE].".FK_ZAKSIEG , ".$result_BILLING_NUMBERS_TYPE[TABLE].".do_dokumentu , ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".NUMBER , 
-				     ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".ID_BILLING_PREFIXES , ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".ID_BILLING_NUMBERS_TYPE 
-				     from ".$result_BILLING_NUMBERS_TYPE[TABLE]." 
-				     left join ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE]." on ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".ID=".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_NUMBERS
-				where ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_USERS='".$this->set_client_filter."' "; 
-				//	echo "<br> ".$sql ;
-				    $result_KP=$this->db->query($sql); 
-				    $i=0;
-				    while($h=$this->db->fetch_assoc($result_KP)) {
-					    $result_KP_arr[$i]=$h;
-					    $result_KP_arr[$i]['ID_BILLING_NUMBERS_TYPE']=$result_BILLING_NUMBERS_TYPE['ID'];
-					    $result_KP_arr[$i]['CLASS']=$result_BILLING_NUMBERS_TYPE['CLASS'];
-					    $result_KP_arr[$i]['TYPE']=$result_BILLING_NUMBERS_TYPE['TYPE'];
-						$i++;
-				    }
-				    return $result_KP_arr;
+		$sql = "
+			select ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_NUMBERS
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".BILL_DATE
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".WINIEN
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".MA
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_FK_DEKRET
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".OPEN
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".FK_ZAKSIEG
+				, ".$result_BILLING_NUMBERS_TYPE[TABLE].".do_dokumentu
+				, ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".NUMBER
+				, ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".ID_BILLING_PREFIXES
+				, ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".ID_BILLING_NUMBERS_TYPE 
+			from ".$result_BILLING_NUMBERS_TYPE[TABLE]."
+				left join ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE]." on ".$result_BILLING_NUMBERS_TYPE[BILLING_NUMBERS_TABLE].".ID=".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_NUMBERS
+			where ".$result_BILLING_NUMBERS_TYPE[TABLE].".ID_BILLING_USERS='".$this->set_client_filter."'
+		";
+		$i = 0;
+		$listItems = $this->_pdo->fetchAll($sql);
+		foreach ($listItems as $h) {
+			$result_KP_arr[$i] = $h;
+			$result_KP_arr[$i]['ID_BILLING_NUMBERS_TYPE'] = $result_BILLING_NUMBERS_TYPE['ID'];
+			$result_KP_arr[$i]['CLASS'] = $result_BILLING_NUMBERS_TYPE['CLASS'];
+			$result_KP_arr[$i]['TYPE'] = $result_BILLING_NUMBERS_TYPE['TYPE'];
+			$i++;
+		}
+		return $result_KP_arr;
 	}
 
 	function get_BILLING_NUMBERS_TYPE() {
-		 //zwraca typy dowiazan do tabel fakturujacych
-		 $ID_BILLING_NUMBERS_ARR=array(4,5,7,3,8);      
-		 $sql="select * from BILLING_NUMBERS_TYPE where ID in (".implode(',',$ID_BILLING_NUMBERS_ARR).")";
-		 $result_BILLING_NUMBERS_TYPE_res=$this->db->query($sql) ; 
-		 while ($result_BILLING_NUMBERS_TYPE=$this->db->fetch_assoc($result_BILLING_NUMBERS_TYPE_res)) {
-		 	$this->BILLING_NUMBERS_TYPE[$result_BILLING_NUMBERS_TYPE['ID']]=$result_BILLING_NUMBERS_TYPE;
-		 }
-		 DEBUG_S(-3,'get_BILLING_NUMBERS_TYPE',$this->BILLING_NUMBERS_TYPE,__FILE__,__FUNCTION__,__LINE__);
+		//zwraca typy dowiazan do tabel fakturujacych
+		$ID_BILLING_NUMBERS_ARR = array(4,5,7,3,8);
+		$this->BILLING_NUMBERS_TYPE = $this->_pdo->fetchAllByKey("
+			select *
+			from BILLING_NUMBERS_TYPE
+			where ID in (" . implode(',', $ID_BILLING_NUMBERS_ARR) . ")
+		", 'ID');
 	}
 
 	function get_BILLING_NUMBERS_TYPE_all() {
-		 //zwraca typy dowiazan do tabel fakturujacych
-		 $ID_BILLING_NUMBERS_ARR=array(1,3,4,5,7,3,8);      
-		 $sql="select * from BILLING_NUMBERS_TYPE where ID in (".implode(',',$ID_BILLING_NUMBERS_ARR).")";
-		 $result_BILLING_NUMBERS_TYPE_res=$this->db->query($sql) ; 
-		 while ($result_BILLING_NUMBERS_TYPE=$this->db->fetch_assoc($result_BILLING_NUMBERS_TYPE_res)) {
-		 	$this->BILLING_NUMBERS_TYPE_ALL[$result_BILLING_NUMBERS_TYPE['ID']]=$result_BILLING_NUMBERS_TYPE;
-		 }
-		 DEBUG_S(3,'get_BILLING_NUMBERS_TYPE',$this->BILLING_NUMBERS_TYPE_ALL,__FILE__,__FUNCTION__,__LINE__);
+		//zwraca typy dowiazan do tabel fakturujacych
+		$ID_BILLING_NUMBERS_ARR = array(1,3,4,5,7,3,8);
+		$this->BILLING_NUMBERS_TYPE = $this->_pdo->fetchAllByKey("
+			select *
+			from BILLING_NUMBERS_TYPE
+			where ID in (" . implode(',', $ID_BILLING_NUMBERS_ARR) . ")
+		", 'ID');
 	}
 
 	function lista_dok_finansowych() {
@@ -518,12 +536,15 @@ for($i2=0; $i2<=$liczba_linii_crc;$i2++) {
 	}
 	
 	function get_document_type($ID_BILLING_NUMBERS) {
-		if(empty($this->BILLING_NUMBERS_TYPE_ALL)) $this->get_BILLING_NUMBERS_TYPE_all();
-		$sql="select ID_BILLING_NUMBERS_TYPE from BILLING_NUMBERS where ID=".$ID_BILLING_NUMBERS;
-		$res=$this->db->query($sql);
-		while($h=$this->db->fetch($res)) {
-			return $this->BILLING_NUMBERS_TYPE_ALL[$h->ID_BILLING_NUMBERS_TYPE];
-		}
+		if (empty($this->BILLING_NUMBERS_TYPE_ALL)) $this->get_BILLING_NUMBERS_TYPE_all();
+
+		$idType = $this->_pdo->fetchValue("
+			select ID_BILLING_NUMBERS_TYPE
+			from BILLING_NUMBERS
+			where ID = {$ID_BILLING_NUMBERS}
+		");
+
+		if ($idType) return $this->BILLING_NUMBERS_TYPE_ALL[$idType];
 	}
 
 	//TODO funkcja do zastapienia przez ZNAJDZ_ID_FAKTUR_DO_ZAMKNIECIA
@@ -1076,7 +1097,8 @@ $result_S_N_R = $this->SZUKAJ_NIEROZLICZONEJ_TRANSAKCJI($FINANCE_KSIEGOWANIE,$re
 		 $WARIANT=$LEWO_PRAWO."0" ;
 		if(strlen($do_dokumentu)<>0) $KROK=0; else  $KROK=2 ;
 		 for(;$KROK<=2;$KROK++) {
-		 $sql="  select t1.ID_BILLING_NUMBERS AS NR_DOK ,t1.ID_BILLING_USERS as PLATNIK ,t1.WINIEN,t1.MA , t1.ID_FIN_WINIEN as ID_F_W, t1.ID_FIN_WINIEN_VAL as F_WINIEN_V,
+		 $sql="
+		 	select t1.ID_BILLING_NUMBERS AS NR_DOK ,t1.ID_BILLING_USERS as PLATNIK ,t1.WINIEN,t1.MA , t1.ID_FIN_WINIEN as ID_F_W, t1.ID_FIN_WINIEN_VAL as F_WINIEN_V,
 		 t1.ID_FIN_MA as ID_F_M, t1.ID_FIN_MA_VAL as F_MA_V, max(t2.ID), sum(t2.ID_FIN_WINIEN_VAL) as ROZ_WINIEN , max(t2.ID), sum(t2.ID_FIN_MA_VAL) as ROZ_MA,
 		 t1.WINIEN - sum(t2.ID_FIN_WINIEN_VAL) - sum(t2.ID_FIN_MA_VAL)   as POZ_WINIEN, t1.MA -  sum(t2.ID_FIN_MA_VAL)  - sum(t2.ID_FIN_WINIEN_VAL) as POZ_MA
 		
@@ -1085,12 +1107,10 @@ $result_S_N_R = $this->SZUKAJ_NIEROZLICZONEJ_TRANSAKCJI($FINANCE_KSIEGOWANIE,$re
 		where
 		 t1.ID_FIN_WINIEN is NULL and t1.ID_FIN_MA is NULL and t1.".$WHERE_PRIM." = 0 and  t1.".$WHERE." > 0 and 
 		 $WHERE_ID_BILLING_NUMBERS
-		 t1.ID_BILLING_USERS=".$ID_BILLING_USERS." ".$this->DO_DOKUMENTU_MAKESQL($do_dokumentu,$KROK)."  group by t1.ID_BILLING_NUMBERS   limit 0,1   ";
-			 if($_SESSION[DEBUG]>3) echo "<br> krok: $KROK SQL(SZUKAJ_NIEROZLICZONEJ_TRANSAKCJI) to $sql ***";
-		 $result_S_N_R=$this->db->query($sql); 
-		 $result_S_N_R=$this->db->fetch_assoc($result_S_N_R);
-		 DEBUG_S(3,'result_S_N_R',array($result_S_N_R,$sql),__FILE__,__FUNCTION__,__LINE__);
-		  if($result_S_N_R) break ; 
+		 t1.ID_BILLING_USERS=".$ID_BILLING_USERS." ".$this->DO_DOKUMENTU_MAKESQL($do_dokumentu,$KROK)."  group by t1.ID_BILLING_NUMBERS   limit 0,1
+		 ";
+		 $result_S_N_R = $this->_pdo->fetchFirst($sql);
+		  if($result_S_N_R) break;
 		 }
 
 		if($result_S_N_R) {
@@ -1115,7 +1135,7 @@ $result_S_N_R = $this->SZUKAJ_NIEROZLICZONEJ_TRANSAKCJI($FINANCE_KSIEGOWANIE,$re
 		 t1.ID_FIN_WINIEN is NULL and t1.ID_FIN_MA is NULL and t1.".$WHERE." = 0 and  t1.".$WHERE_PRIM." > 0 and 
 		 t1.ID_BILLING_NUMBERS='$SRC_ID_BILLING_NUMBERS' and
 		 t1.ID_BILLING_USERS=".$ID_BILLING_USERS."  group by t1.ID_BILLING_NUMBERS   limit 0,1   ";
-		 $result_S_N_R_K=$this->db->query($sql); $result_S_N_R_K=$this->db->fetch_assoc($result_S_N_R_K);
+		 $result_S_N_R_K = $this->_pdo->fetchFirst($sql);
 		 $KWOTA = $result_S_N_R_K[$WHERE_PRIM]-$result_S_N_R_K["ROZ_".$WHERE_PRIM]-$result_S_N_R_K["ROZ_".$WHERE] ;
 		 DEBUG_S(3,'result_S_N_R_K',array($result_S_N_R_K,$sql),__FILE__,__FUNCTION__,__LINE__);
 		if($_SESSION[DEBUG]>3) echo "..... <font color=red> <b>WYKRYLEM POZOSTALA KWOTE KWOTE $KWOTA (a nasza to $POZ_S_N_R_KWOTA) </b></font>" ;

+ 54 - 110
SE/se-lib/Data_Source.php

@@ -32,19 +32,10 @@ class Data_Source {
 
 	function __construct($db = null) {
 		$this->_idDatabase = ($db) ? $db : null;
-		// if ($db) { // TODO: RM use DB::getPDO($this->_idDatabase)
-		// 	$this->_db = DB::getDB($db); // TODO: RM
-		// } else {
-		// 	$this->_db = DB::getDB(); // TODO: RM
-		// }
 		$this->_default_sql_limit = 10;
 		$this->_showMsgsSpecialFilter = true;// TODO: allow by acl, procesy?
 	}
 
-	function getDB() {
-		return ($this->_idDatabase) ? DB::getDB($this->_idDatabase) : DB::getDB();
-	}
-
 	function set_table($tbl) {// TODO: RMME
 		$this->setTable($tbl);
 	}
@@ -99,22 +90,16 @@ class Data_Source {
 	}
 
 	public function getUniqueKeys() {
-		$sqlKeys = array();
-		//$dbID = $this->getDB();
-		$db = $this->getDB();
-		$tblName = $this->_tbl;//(TableAcl) $this->getName();
-		if (!$db) {
-			throw new Exception('DataSource is not defined');
-		}
-		$sql = "SHOW KEYS FROM  `{$tblName}`";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			if ($r->Non_unique == '0') {
-				$sqlKeys[$r->Column_name] = true;
+		$allKeys = DB::getPDO($this->_idDatabase)->fetchAll("
+			SHOW KEYS FROM  `{$tblName}`
+		");
+		$uniqueKeys = [];
+		foreach ($allKeys as $item) {
+			if ($item['Non_unique'] == '0') {
+				$uniqueKeys[$item['Column_name']] = true;
 			}
 		}
-		$sqlKeys = array_keys($sqlKeys);
-		return $sqlKeys;
+		return array_keys($uniqueKeys);
 	}
 
 	function set_cols($cols) {// TODO: RMME
@@ -538,38 +523,39 @@ class Data_Source {
 				}
 
 				if (substr($v, 0, 1) == '=') {
-					$v = $this->getDB()->_(substr($v, 1));
-					if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`='{$v}'";
+					$val = substr($v, 1);
+					if (strlen($val)) {
+						$sql_where_and[] = "t.`{$fldName}` = " . DB::getPDO($this->_idDatabase)->quote($val);
+					}
 				}
 				else if ($v == '!NULL' || $v == 'IS NOT NULL') {
 					$sql_where_and[] = "t.`{$fldName}` is not null";
 				}
 				else if (substr($v, 0, 1) == '!') {
-					$v = $this->getDB()->_(substr($v, 1));
-					if (strlen($v)) $sql_where_and[] = "t.`{$fldName}` not like '{$v}'";
+					$val = substr($v, 1);
+					if (strlen($val)) $sql_where_and[] = "t.`{$fldName}` not like " . DB::getPDO($this->_idDatabase)->quote($val);
 				}
 				else if (substr($v, 0, 2) == '<=') {
-					$v = $this->getDB()->_(substr($v, 2));
-					if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`<='{$v}'";
+					$val = substr($v, 2);
+					if (strlen($val)) $sql_where_and[] = "t.`{$fldName}` <= " . DB::getPDO($this->_idDatabase)->quote($val);
 				}
 				else if (substr($v, 0, 2) == '>=') {
-					$v = $this->getDB()->_(substr($v, 2));
-					if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`>='{$v}'";
+					$val = substr($v, 2);
+					if (strlen($val)) $sql_where_and[] = "t.`{$fldName}` >= " . DB::getPDO($this->_idDatabase)->quote($val);
 				}
 				else if (substr($v, 0, 1) == '<') {
-					$v = $this->getDB()->_(substr($v, 1));
-					if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`<'{$v}'";
+					$val = substr($v, 1);
+					if (strlen($val)) $sql_where_and[] = "t.`{$fldName}` < " . DB::getPDO($this->_idDatabase)->quote($val);
 				}
 				else if (substr($v, 0, 1) == '>') {
-					$v = $this->getDB()->_(substr($v, 1));
-					if (strlen($v)) $sql_where_and[] = "t.`{$fldName}`>'{$v}'";
+					$val = substr($v, 1);
+					if (strlen($val)) $sql_where_and[] = "t.`{$fldName}` > " . DB::getPDO($this->_idDatabase)->quote($val);
 				}
 				else if (false !== strpos($v, '%')) {
-					$sql_where_and[] = "t.`{$fldName}` like '{$v}'";
+					$sql_where_and[] = "t.`{$fldName}` like " . DB::getPDO($this->_idDatabase)->quote($v);
 				}
 				else if ($this->isColTypeNumber($fldName)) {
-					$v = $this->getDB()->_($v);
-					$sql_where_and[] = "t.`{$fldName}`='{$v}'";
+					$sql_where_and[] = "t.`{$fldName}` = " . DB::getPDO($this->_idDatabase)->quote($v);
 				}
 				else {
 					$queryWhereBuilder = new SqlQueryWhereBuilder();
@@ -577,8 +563,7 @@ class Data_Source {
 					$sqlWhereWords = array();
 					if (!empty($searchWords)) {
 						foreach ($searchWords as $word) {
-							$sqlWord = $this->getDB()->_($word);
-							$sqlWhereWords[] = "t.`{$fldName}` like '%{$sqlWord}%'";
+							$sqlWhereWords[] = "t.`{$fldName}` like " . DB::getPDO($this->_idDatabase)->quote("%{$word}%");
 						}
 					}
 					if (!empty($searchWords)) {
@@ -601,7 +586,7 @@ class Data_Source {
 			else if ('primaryKey' == $k) {
 				if (!empty($v)) {
 					$primaryKeyField = $this->getPrimaryKeyField();
-					$sql_where_and[] = "t.`{$primaryKeyField}` = '" . $this->getDB()->_($v) . "'";
+					$sql_where_and[] = "t.`{$primaryKeyField}` = " . DB::getPDO($this->_idDatabase)->quote($v);
 				}
 			}
 		}
@@ -748,17 +733,21 @@ class Data_Source {
 		}
 		$sql->where = $this->_parseSqlWhere($params);
 		$sql->cols = $this->_getSqlCols($sql->_cols);
-		$sql->query = "select {$sql->cols}
+		$sql->query = "
+			select {$sql->cols}
 			from `{$this->_tbl}` t
 			where {$sql->where}
 			{$sql->orderBy}
 			limit {$sql->limit} offset {$sql->offset}
 		";
 		DBG::log([ 'msg'=>"Data_Source::getItems - \$sql", '$sql'=>$sql ]);
-		$res = $this->getDB()->query($sql->query);
-		while ($r = $this->getDB()->fetch($res)) {
+
+		$items = [];
+		foreach (DB::getPDO($this->_idDatabase)->fetchAll($sql->query) as $row) {
+			$r = (object)$r;
 			$items[$r->{$primaryKeyField}] = $r;
 		}
+
 		return $items;
 	}
 
@@ -813,17 +802,13 @@ class Data_Source {
 	}
 
 	public function getTotal($params = array()) {
-		$ret = 0;
 		$sql_where = $this->_parseSqlWhere($params);
-		$sql = "select count(1) as cnt
+		$total = DB::getPDO($this->_idDatabase)->fetchValue("
+			select count(1) as cnt
 			from {$this->_tbl} as t
 			where {$sql_where}
-		";
-		$res = $this->getDB()->query($sql);
-		if ($r = $this->getDB()->fetch($res)) {
-			$ret = $r->cnt;
-		}
-		return $ret;
+		");
+		return ($total) ? (int)$total : 0;
 	}
 
 	function set_sql_where($sql_where) {
@@ -875,17 +860,13 @@ class Data_Source {
 	}
 
 	function count() {
-		$ret = 0;
-		$sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
-		$sql = "select count(1) as cnt
+		$sql_where = ($this->_sql_where) ? $this->_sql_where : "1=1";
+		$total = DB::getPDO($this->_idDatabase)->fetchValue("
+			select count(1) as cnt
 			from `{$this->_tbl}`
 			where {$sql_where}
-		";
-		$res = $this->getDB()->query($sql);
-		if ($r = $this->getDB()->fetch($res)) {
-			$ret = $r->cnt;
-		}
-		return $ret;
+		");
+		return ($total) ? (int)$total : 0;
 	}
 
 	function fetch_list($limit = 10, $offset = 0) {
@@ -901,11 +882,12 @@ class Data_Source {
 			where {$sql_where}
 			limit {$this->_sql_limit} offset {$this->_sql_offset}
 		";
-		$res = $this->getDB()->query($sql);
-		while ($r = $this->getDB()->fetch($res)) {
-			$ret[$r->{$primaryKeyField}] = $r;
+		$items = [];
+		foreach (DB::getPDO($this->_idDatabase)->fetchAll($sql) as $row) {
+			$r = (object)$r;
+			$items[$r->{$primaryKeyField}] = $r;
 		}
-		return $ret;
+		return $items;
 	}
 
 	function field_check_value($field_name, $val) {
@@ -918,44 +900,6 @@ class Data_Source {
 		return true;
 	}
 
-	function save_item(&$item, $values, $prefix) {
-		if (!$item->ID) {
-			return null;
-		}
-		$sql_obj = new stdClass();
-		$sql_obj->ID = $item->ID;
-		foreach ($values as $k_field_with_prefix => $v_field) {
-			if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
-				continue;
-			}
-			$k_field = substr($k_field_with_prefix, strlen($prefix));
-			if ($this->field_allow_write($k_field)) {
-				if ($this->field_check_value($k_field, $v_field)) {
-					$sql_obj->$k_field = $v_field;
-				}
-			}
-		}
-		$affected = $this->getDB()->PDATE_OBJ($this->_tbl, $sql_obj);
-		return $affected;
-	}
-
-	function add_item($values, $prefix) {
-		$sql_obj = new stdClass();
-		foreach ($values as $k_field_with_prefix => $v_field) {
-			if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
-				continue;
-			}
-			$k_field = substr($k_field_with_prefix, strlen($prefix));
-			if ($this->field_allow_create($k_field)) {
-				if ($this->field_check_value($k_field, $v_field)) {
-					$sql_obj->$k_field = $v_field;
-				}
-			}
-		}
-		$insert_id = $this->getDB()->ADD_NEW_OBJ($this->_tbl, $sql_obj);
-		return $insert_id;
-	}
-
 	public function isGeomField($fldName) {
 		return ('the_geom' == $fldName);
 	}
@@ -994,9 +938,9 @@ class Data_Source {
 		}
 
 		$itemPatch = (object)$itemPatch;
-		$affected = $this->getDB()->UPDATE_OBJ($this->_tbl, $itemPatch);
+		$affected = DB::getDB($this->_idDatabase)->UPDATE_OBJ($this->_tbl, $itemPatch);
 		if ($affected < 0) {
-			$dsErrors = $this->getDbErrors();
+			$dsErrors = $this->getLegacyDBErrors();
 			//$dsErrors = "Wystąpiły błędy!\n" . implode("\n", $dsErrors);
 			if (!empty($dsErrors)) {
 				throw new StorageException($dsErrors);
@@ -1026,19 +970,19 @@ class Data_Source {
 			}
 		}
 
-		$primaryKey = $this->getDB()->ADD_NEW_OBJ($this->_tbl, (object)$item);
+		$primaryKey = DB::getDB($this->_idDatabase)->ADD_NEW_OBJ($this->_tbl, (object)$item);
 		if ($primaryKey <= 0) {
-			$dsErrors = $this->getDbErrors();
+			$dsErrors = $this->getLegacyDBErrors();
 			$dsErrors = "Wystąpiły błędy!\n" . implode("\n", $dsErrors);
 			throw new Exception($dsErrors);
 		}
 		return $primaryKey;
 	}
 
-	public function getDbErrors() {
+	public function getLegacyDBErrors() {
 		$errors = array();
-		if ($this->getDB()->has_errors()) {
-			$errorsSql = $this->getDB()->get_errors();
+		if (DB::getDB($this->_idDatabase)->has_errors()) {
+			$errorsSql = DB::getDB($this->_idDatabase)->get_errors();
 			foreach ($errorsSql as $vErr) {
 				if ('SQL QUERY FAILED: ' == substr($vErr, 0, 18)) {
 					$vErr = substr($vErr, 18);

+ 60 - 100
SE/se-lib/ProcesTestyHelper.php

@@ -22,20 +22,15 @@ class ProcesTestyHelper {
 		if ($params['order by']) {
 			$sql_order_by = "order by " . $params['order by'] . " " . $allowed_order_by[$params['order by']];
 		}
-		$db = DB::getDB();
-		$sql = "select `ID`,`ADM_NAME`,`ADM_PHONE`,`ADM_OTHER_INFO`
+		return array_map(function ($item) { return (object)$item; }, DB::getPDO()->fetchAll("
+			select `ID`,`ADM_NAME`,`ADM_PHONE`,`ADM_OTHER_INFO`
 			from `ADMIN_USERS`
-		where `ADM_ADMIN_LEVEL`>=3
-			and `A_STATUS`!='OFF_HARD' and  `A_STATUS`!='DELETED'
-			 and `EMPLOYEE_TYPE` like '%Kandydat%'
-			{$sql_order_by}
-			limit 1000
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[] = $r;
-		}
-		return $ret;
+			where `ADM_ADMIN_LEVEL`>=3
+				and `A_STATUS`!='OFF_HARD' and  `A_STATUS`!='DELETED'
+				and `EMPLOYEE_TYPE` like '%Kandydat%'
+				{$sql_order_by}
+				limit 1000
+		"));
 	}
 
 	public static function get_testy_by_kandydat($kandydat_id) {
@@ -58,20 +53,14 @@ class ProcesTestyHelper {
 	}
 
 	public static function get_testy_total($params = array()) {
-		$ret = 0;
 		$sql_where = self::_get_testy_sql_where($params);
-		$db = DB::getDB();
-		$sql = "select
+		return DB::getPDO()->fetchValue("
+			select
 				count(1) as cnt
 			from `CRM_TESTY` as t
 			where
 				{$sql_where}
-		";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$ret = $r->cnt;
-		}
-		return $ret;
+		");
 	}
 
 	public static function get_testy($params = array()) {
@@ -126,9 +115,8 @@ class ProcesTestyHelper {
 
 		$sql_join = implode("\n\t", $sql_join);
 		$sql_select = implode(", ", $sql_select);
-		$db = DB::getDB();
-		$sql = "select
-				{$sql_select}
+		$listItems = DB::getPDO()->fetchAll("
+			select {$sql_select}
 			from `CRM_TESTY` as t
 				left join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=t.`ID_STANOWISKO`)
 				left join `ADMIN_USERS` as u on(u.`ID`=t.`ID_TESTER`)
@@ -137,9 +125,10 @@ class ProcesTestyHelper {
 				{$sql_where}
 			{$sql_order_by}
 			limit {$sql_limit}
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
+		");
+
+		return array_map(function ($item) {
+			$r = (object)$item;
 			//$sql_select[] = "IF( z.`ID` is null, t.`ID_STANOWISKO`, z.`DESC` ) as Stanowisko";
 			//$sql_select[] = "IF( u.`ID` is null, t.`ID_TESTER`, concat(u.`ADM_NAME`, ' (', u.`ADM_PHONE`, ', ', u.`ADM_OTHER_INFO`, ')') ) as Kandydat";
 			//$sql_select[] = "IF( u.`ID` is null, t.`ID_TESTER`, u.`ADM_NAME`) as Kandydat_Name";
@@ -152,24 +141,22 @@ class ProcesTestyHelper {
 			if (!$r->Kandydat_Name) {
 				$r->Kandydat_Name = $r->ID_TESTER;
 			}
-
-			$ret[] = $r;
-		}
-		return $ret;
+			return $r;
+		}, $listItems);
 	}
 
 	/**
 	 * @return array( ID_PROCES => array( ID_PYTANIE => {ID,ODPOWIEDZ,ODP_0,ODP_1,ODP_2,ODP_3,ODP_4,OCENA} ) )
 	 */
 	public static function get_odpowiedzi($test_id, $type = 'TEORETYCZNY') {
-		$ret = array();
+		$ret = [];
 		$sql_type = "";
 		$types_allowed = self::get_allowed_types();
 		if (array_key_exists($type, $types_allowed)) {
 			$sql_type = "and pyt.`TEST_TYPE`='{$type}'";
 		}
-		$db = DB::getDB();
-		$sql = "select
+		$listItems = DB::getPDO()->fetchAll("
+			select
 				odp.`ID`
 				, odp.`ID_PYTANIE`
 				, pyt.`ID_PROCES` as ID_PROCES
@@ -186,9 +173,9 @@ class ProcesTestyHelper {
 				pyt.`ID` is not NULL
 				and odp.`ID_TEST`='{$test_id}'
 				{$sql_type}
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
+		");
+		foreach ($listItems as $item) {
+			$r = (object)$item;
 			$ret[$r->ID_PROCES][$r->ID_PYTANIE] = $r;
 		}
 		return $ret;
@@ -201,19 +188,14 @@ class ProcesTestyHelper {
 		if (array_key_exists($type, $types_allowed)) {
 			$sql_type = "and pyt.`TEST_TYPE`='{$type}'";
 		}
-		$db = DB::getDB();
-		$sql = "select pyt.*
+		return array_map(function ($item) { return (object)$item; }, DB::getPDO()->fetchAllByKey("
+			select pyt.*
 			from `CRM_TESTY_PYTANIA` as pyt
 			where
 				pyt.`ID_PROCES`='{$proces_id}'
 				{$sql_type}
 			order by pyt.`ID` ASC
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[$r->ID] = $r;
-		}
-		return $ret;
+		", 'ID'));
 	}
 
 	/**
@@ -224,18 +206,13 @@ class ProcesTestyHelper {
 		if (empty($pytania_id)) return $ret;
 		// TODO: if int or array
 		if (!is_array($pytania_id)) $pytania_id = array($pytania_id);
-		$db = DB::getDB();
-		$sql = "select
+		return array_map(function ($item) { return (object)$item; }, DB::getPDO()->fetchAllByKey("
+			select
 				pyt.*
 			from `CRM_TESTY_PYTANIA` as pyt
 			where
 				pyt.`ID` in(".implode(",", $pytania_id).")
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[$r->ID] = $r;
-		}
-		return $ret;
+		", 'ID'));
 	}
 
 	/**
@@ -243,43 +220,43 @@ class ProcesTestyHelper {
 	 * moved to trigger after insert/delete `CRM_TESTY_PYTANIA`
 	 */
 	public static function update_proces_stat($remote_id) {
-		$db = DB::getDB();
-		$sql = "update `CRM_PROCES`
-				set `TEST_PYTANIE`=(
+		$sql = "
+			update `CRM_PROCES`
+				set `TEST_PYTANIE` = (
 					select count(1)
 					from `CRM_TESTY_PYTANIA`
 					where
-						`ID_PROCES`='{$remote_id}'
+						`ID_PROCES` = '{$remote_id}'
 				)
-			where `ID`='{$remote_id}'
+			where `ID` = '{$remote_id}'
 			limit 1;
 		";
 		// update all records
-		$sql = "update `CRM_PROCES` as p
-			set p.`TEST_PYTANIE`=(
+		DB::getPDO()->execSql("
+			update `CRM_PROCES` as p
+			set p.`TEST_PYTANIE` = (
 				select count(1)
 				from `CRM_TESTY_PYTANIA` as pyt
 				where
-					pyt.`ID_PROCES`=p.ID
+					pyt.`ID_PROCES` = p.ID
 			)
-		";
-		$res = $db->query($sql);
-		$affected = $db->affected_rows();
-		return $affected;
+		");
+		// $affected = $db->affected_rows();
+		// return $affected;
 	}
 
 	public static function delete_pytanie($id, $remote_id) {
-		$db = DB::getDB();
-		$sql = "delete from `CRM_TESTY_PYTANIA`
+		DB::getPDO()->execSql("
+			delete from `CRM_TESTY_PYTANIA`
 			where
-				`ID`='{$id}'
-				and `ID_PROCES`='{$remote_id}'
+				`ID` = '{$id}'
+				and `ID_PROCES` = '{$remote_id}'
 			limit 1
-		";
-		$db->query($sql);
-		$affected = $db->affected_rows();
+		");
+		// $affected = $db->affected_rows();
 
-		return $affected;
+		// return $affected;
+		return 1;
 	}
 
 	/**
@@ -336,7 +313,6 @@ class ProcesTestyHelper {
 	public static function get_tetsy_stats($idUser, $max_age = 0, $proces_ids = array()) {
 		$testy_stats = array();
 		Lib::loadClass('DB');
-		$db = DB::getDB();
 		$sqlWhereAnd = array();
 		if (!empty($proces_ids)) {
 			$sqlWhereAnd[] = "t.`ID_PROCES_INIT` in (" . implode(",", $proces_ids) . ")";
@@ -345,7 +321,7 @@ class ProcesTestyHelper {
 			$sqlWhereAnd[] = "COALESCE(UNIX_TIMESTAMP(t.`TEST_END`), 0) > (UNIX_TIMESTAMP(NOW()) - {$max_age})";
 		}
 		$sqlWhereAnd = (!empty($sqlWhereAnd)) ? "and " . implode("\n and ", $sqlWhereAnd) : '';
-		$sql = "
+		return array_map(function ($item) { return (object)$item; }, DB::getPDO()->fetchAll("
 			select test.ID
 				,  test.ID_PROCES_INIT
 				,  test.OCENA
@@ -360,12 +336,7 @@ class ProcesTestyHelper {
 					{$sqlWhereAnd}
 				group by t.TEST_TYPE, t.ID_PROCES_INIT
 			)
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$testy_stats[] = $r;
-		}
-		return $testy_stats;
+		"));
 	}
 
 	/**
@@ -373,23 +344,17 @@ class ProcesTestyHelper {
 	 * @param $steps_ids
 	 */
 	public static function get_max_update_date($steps_ids) {// TODO: RMME, mved to UserAcl->getProcesMaxUpdateDate
-		$max_update_date = null;
-		$db = DB::getDB();
-		$sql = "select max(p.`A_RECORD_UPDATE_DATE`) as max_update_date
+		$max_update_date = DB::getPDO()->fetchValue("
+			select max(p.`A_RECORD_UPDATE_DATE`) as max_update_date
 			from `CRM_PROCES` as p
 			where p.`ID` in(" . implode(", ", $steps_ids) . ")
-		";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$max_update_date = $r->max_update_date;
-		}
-		return $max_update_date;
+		");
+		return ($max_update_date) ? $max_update_date : null;
 	}
 
 	public static function getLastTestEndDate($id_test, $id_tester, $id_proces_init, $id_stanowisko) {
-		$lastTestEnd = null;
-		$db = DB::getDB();
-		$sql = "select t.`TEST_END`
+		$lastTestEnd = DB::getPDO()->fetchValue("
+			select t.`TEST_END`
 			from `CRM_TESTY` as t
 			where
 				t.`ID_TESTER` = {$id_tester}
@@ -397,12 +362,7 @@ class ProcesTestyHelper {
 				and t.`ID_STANOWISKO` = {$id_stanowisko}
 				and t.`ID` < {$id_test}
 			limit 1
-		";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$lastTestEnd = $r->TEST_END;
-		}
-		return $lastTestEnd;
+		");
 	}
 
 	public static function getOcenaLabel($ocena) {

+ 0 - 1
SE/se-lib/TableAcl.php

@@ -1809,7 +1809,6 @@ class TableAcl extends Core_AclBase {
 		$dsConfig['field_types'] = $this->getTypes();
 		$dsConfig['fields_virtual'] = $this->getVirtualFieldListByIdZasob();
 		$dsConfig['acl_fltr_allowed'] = !$this->hasSuperAccessPerms(); // filtr Access is visible only if user dont have supe access perms. If has then see all rows
-		// DBG::log($dsConfig, 'array', "DBG:DataSourceFactory::buildFromZasobInfo(\$dsConfig)");
 		return DataSourceFactory::buildFromZasobInfo($dsConfig);
 	}
 

+ 21 - 34
SE/se-lib/TableAjax.php

@@ -1322,9 +1322,7 @@ jQuery(document).ready(function(){
 	public function ajax__FILES_UPLOAD__Task($args) {
 		$id = V::get('ID', 0, $args, 'int');
 		if ($id <= 0) throw new HttpException("404", 404);
-		$dbID = $this->_acl->getDB();
-		$db = DB::getDB($dbID);
-		if (!$db) throw new HttpException("No DB ({$dbID})", 406);
+
 		$record = $this->_acl->buildQuery([])->getItem($id);
 		if (!$record) throw new HttpException("No item ID({$id})", 404);
 		if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
@@ -1359,10 +1357,15 @@ jQuery(document).ready(function(){
 		$retJson->msg = "Plik został poprawnie wgrany do odpowiedniego katalogu {$uploadedFileName}";
 
 		if (!empty($uploadedFileName)) {
-			$sqlObj = new stdClass();
-			$sqlObj->ID = $record['ID'];
-			$sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
-			$db->UPDATE_OBJ($this->_tbl, $sqlObj);
+			$toUpdate = [
+				'M_DIST_FILES' => "Wgrano plik {$uploadedFileName}",
+				'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+				'A_RECORD_UPDATE_DATE' => "NOW()",
+			];
+			DB::getPDO($this->_acl->getDB())->update($this->_tbl, 'ID', $record['ID'], $toUpdate);
+			DB::getPDO($this->_acl->getDB())->insert("{$this->_tbl}_HIST", array_merge($toUpdate, [
+				'ID_USERS2' => $record['ID'],
+			]));
 		}
 		return $retJson;
 	}
@@ -1370,9 +1373,7 @@ jQuery(document).ready(function(){
 	public function ajax__FILES_LIST__Task($args) {
 		$id = V::get('ID', 0, $args, 'int');
 		if ($id <= 0) throw new HttpException("404", 404);
-		$dbID = $this->_acl->getDB();
-		$db = DB::getDB($dbID);
-		if (!$db) throw new HttpException("No DB ({$dbID})", 406);
+
 		$record = $this->_acl->buildQuery([])->getItem($id);
 		if (!$record) throw new HttpException("No item ID({$id})", 404);
 		if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
@@ -1397,10 +1398,6 @@ jQuery(document).ready(function(){
 		$id = V::get('ID', 0, $args, 'int');
 		if ($id <= 0) throw new HttpException("Wrong param ID", 404);
 
-		$dbID = $this->_acl->getDB();
-		$db = DB::getDB($dbID);
-		if (!$db) throw new HttpException("No DB", 406);
-
 		$record = $this->_acl->buildQuery([])->getItem($id);
 		if (!$record) throw new Exception("No item ID({$id})", 404);
 
@@ -1410,10 +1407,10 @@ jQuery(document).ready(function(){
 		$sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
 		$sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
 		$sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
-		$mainDB = DB::getDB();
 
 		if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
-			$sql = "insert into `_SYNC_FILE_PERMS` (
+			$sql = "
+				insert into `_SYNC_FILE_PERMS` (
 					`ID_PROJECT`,
 					`A_SYNCHRONIZED`
 				)
@@ -1426,7 +1423,8 @@ jQuery(document).ready(function(){
 			";
 		}
 		else if ('IN7_DZIENNIK_KORESP' == $tblName) {
-			$sql = "insert into `_SYNC_FILE_PERMS` (
+			$sql = "
+				insert into `_SYNC_FILE_PERMS` (
 					`ID_PROJECT`,
 					`A_SYNCHRONIZED`
 				)
@@ -1439,7 +1437,8 @@ jQuery(document).ready(function(){
 			";
 		}
 		else {
-			$sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
+			$sql = "
+				insert into `_SYNC_TABLE_FILE_PERMS` (
 					`TBL_NAME`,
 					`TBL_ID`,
 					`L_APPOITMENT_USER`,
@@ -1460,10 +1459,10 @@ jQuery(document).ready(function(){
 			";
 		}
 
-		$res = $mainDB->query($sql);
-		if ($mainDB->has_errors()) {
-			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
-			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainDB->get_errors());echo'</pre>';
+		try {
+			DB::getPDO()->execSql($sql);
+		} catch (Exception $e) {
+			DBG::log($e);
 			throw new Exception("Nie udało się dodać zadania");
 		}
 
@@ -1504,14 +1503,6 @@ jQuery(document).ready(function(){
 		header("Content-type: application/json");
 		$DBG = ('1' == V::get('DBG', '', $_REQUEST));
 
-		$dbID = $this->_acl->getDB();
-		$db = DB::getDB($dbID);
-		if (!$db) {
-			header('HTTP/1.0 406 Not Acceptable');
-			echo 'No DB (' . $dbID . ')';
-			exit;
-		}
-
 		$record = $this->_acl->buildQuery([])->getItem($id);
 		if (!$record) {
 			header('HTTP/1.0 404 Not Found');
@@ -1640,10 +1631,6 @@ jQuery(document).ready(function(){
 		$DBG = ('1' == V::get('DBG', '', $_REQUEST));
 		$acl = $this->_acl;
 
-		$dbID = $acl->getDB();
-		$db = DB::getDB($dbID);
-		if (!$db) throw new HttpException("", 406);
-
 		$record = $acl->buildQuery([])->getItem($id);
 		if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
 

+ 151 - 182
SE/se-lib/UserStorageDB.php

@@ -6,10 +6,7 @@ Lib::loadClass('ObjectGroupDB');
 
 class UserStorageDB extends UserStorageBase {
 
-	private $_db;
-
-	public function __construct($db) {
-		$this->_db = $db;
+	public function __construct() {
 	}
 
 	/**
@@ -26,11 +23,10 @@ class UserStorageDB extends UserStorageBase {
 	 *   $usr->isDisabled				true, false or null if not set
 	 */
 	public function getUser($usrLogin) {
-		if (!$this->_db) return false;
 		if (empty($usrLogin)) return false;
 
-		$user = null;
-		$sql = "SELECT a.`ID` as primaryKey
+		$user = DB::getPDO()->fetchFirstAsObject("
+			SELECT a.`ID` as primaryKey
 				, a.`ADM_ACCOUNT` as login
 				, a.`ADM_PASSWD` as password
 				, a.`ADM_NAME` as name
@@ -46,13 +42,12 @@ class UserStorageDB extends UserStorageBase {
 		--		, a.`ADM_NIP`  -- NIP
 		--		, a.`ADM_PESEL`  -- nr. PESEL
 			from `ADMIN_USERS` as a
-			where a.`ADM_ACCOUNT`='{$usrLogin}'
-		";
-		$res = $this->_db->query($sql);
-		if ($r = $this->_db->fetch($res)) {
-			$user = $this->_buildUserFromRow($r);
-		}
-		return $user;
+			where a.`ADM_ACCOUNT` = :login
+		", [
+			':login' => $usrLogin,
+		]);
+
+		return ($user) ? $this->_buildUserFromRow($user) : null;
 	}
 
 	private function _buildUserFromRow($r) {
@@ -112,71 +107,59 @@ class UserStorageDB extends UserStorageBase {
 	 *   (optional) $group->zasobDESC
 	 */
 	public function getGroup($idGroup) {
-		if (!$this->_db) return false;
 		if ($idGroup <= 0) return false;
 
-		$group = null;
-		$sql = "SELECT z.`ID`
+		$group = DB::getPDO()->fetchFirstAsObject("
+			SELECT z.`ID`
 				, z.`DESC`
 				, z.`TYPE`
 		--		, IF(a.`A_STATUS`='NORMAL', 0, 1) as isDisabled
 			from `CRM_LISTA_ZASOBOW` as z
-			where z.`ID`='{$idGroup}'
-				and z.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-		";
-		$res = $this->_db->query($sql);
-		if ($r = $this->_db->fetch($res)) {
-			$group = $this->_buildGroupFromRow($r, $fetchNested = true);
-		}
-		return $group;
+			where z.`ID` = '{$idGroup}'
+				and z.`TYPE` in ( 'STANOWISKO', 'PODMIOT', 'DZIAL' )
+		");
+
+		return ($group) ? $this->_buildGroupFromRow($group, $fetchNested = true) : null;
 	}
 
 	public function getGroupWithoutNested($idGroup) {
-		if (!$this->_db) return false;
 		if ($idGroup <= 0) return false;
 
-		$group = null;
-		$sql = "SELECT z.`ID`
+		$group = DB::getPDO()->fetchFirstAsObject("
+			SELECT z.`ID`
 				, z.`DESC`
 				, z.`TYPE`
-		--		, IF(a.`A_STATUS`='NORMAL', 0, 1) as isDisabled
+		--		, IF(a.`A_STATUS` = 'NORMAL', 0, 1) as isDisabled
 			from `CRM_LISTA_ZASOBOW` as z
-			where z.`ID`='{$idGroup}'
-				and z.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-		";
-		$res = $this->_db->query($sql);
-		if ($r = $this->_db->fetch($res)) {
-			$group = $this->_buildGroupFromRow($r, $fetchNested = false);
-		}
-		return $group;
+			where z.`ID` = '{$idGroup}'
+				and z.`TYPE` in ( 'STANOWISKO', 'PODMIOT', 'DZIAL' )
+		");
+
+		return ($group) ? $this->_buildGroupFromRow($group, $fetchNested = false) : null;
 	}
 
 	public function fetchNestedGroups($idGroup) {
-		if (!$this->_db) return null;
 		if ($idGroup <= 0) return null;
-		$groups = array();
-		$sql = "SELECT l.`TABLE_2_ID` as groupID
+
+		return array_map(function ($item) {
+			return $this->_buildGroupFromRow((object)$item, $fetchNested = false);
+		}, DB::getPDO()->fetchAllByKey("
+			SELECT l.`TABLE_2_ID` as groupID
 				, z2.`ID`
 				, z2.`DESC`
 				, z2.`TYPE`
 			from `ITEM_LINKS` as l
-				join `CRM_LISTA_ZASOBOW` as z1 on(z1.`ID`=l.`TABLE_1_ID`)
-				join `CRM_LISTA_ZASOBOW` as z2 on(z2.`ID`=l.`TABLE_2_ID`)
-			where l.`TABLE_1_ID`='{$idGroup}'
-				and l.`TABLE_2_ID`>0
-				and l.`LINKS_TYPE_ID`=5
-				and l.`TABLE_1_NAME`='CRM_LISTA_ZASOBOW'
-				and l.`A_STATUS` in('NORMAL')
-				and l.`TABLE_2_NAME`='CRM_LISTA_ZASOBOW'
-				and z1.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-				and z2.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-		";
-		$res = $this->_db->query($sql);
-		while ($r = $this->_db->fetch($res)) {
-			$groups[$r->groupID] = $this->_buildGroupFromRow($r, $fetchNested = false);
-		}
-
-		return $groups;
+				join `CRM_LISTA_ZASOBOW` as z1 on ( z1.`ID` = l.`TABLE_1_ID` )
+				join `CRM_LISTA_ZASOBOW` as z2 on ( z2.`ID` = l.`TABLE_2_ID` )
+			where l.`TABLE_1_ID` = '{$idGroup}'
+				and l.`TABLE_2_ID` > 0
+				and l.`LINKS_TYPE_ID` = 5
+				and l.`TABLE_1_NAME` = 'CRM_LISTA_ZASOBOW'
+				and l.`A_STATUS` in ( 'NORMAL' )
+				and l.`TABLE_2_NAME` = 'CRM_LISTA_ZASOBOW'
+				and z1.`TYPE` in ( 'STANOWISKO', 'PODMIOT', 'DZIAL' )
+				and z2.`TYPE` in ( 'STANOWISKO', 'PODMIOT', 'DZIAL' )
+		", 'groupID'));
 	}
 
 	public function getParentGroups(ObjectGroup $group) {
@@ -184,58 +167,53 @@ class UserStorageDB extends UserStorageBase {
 	}
 
 	public function fetchParentGroups($idGroup) {
-		if (!$this->_db) return null;
 		if ($idGroup <= 0) return null;
-		$groups = array();
-		$sql = "SELECT l.`TABLE_1_ID` as groupID
+
+		return array_map(function ($item) {
+			return $this->_buildGroupFromRow((object)$item, $fetchNested = false);
+		}, DB::getPDO()->fetchAllByKey("
+			SELECT l.`TABLE_1_ID` as groupID
 				, z1.`ID`
 				, z1.`DESC`
 				, z1.`TYPE`
 			from `ITEM_LINKS` as l
-				join `CRM_LISTA_ZASOBOW` as z1 on(z1.`ID`=l.`TABLE_1_ID`)
-				join `CRM_LISTA_ZASOBOW` as z2 on(z2.`ID`=l.`TABLE_2_ID`)
-			where l.`TABLE_1_ID`>0
-				and l.`TABLE_2_ID`='{$idGroup}'
-				and l.`LINKS_TYPE_ID`=5
-				and l.`TABLE_1_NAME`='CRM_LISTA_ZASOBOW'
-				and l.`A_STATUS` in('NORMAL')
-				and l.`TABLE_2_NAME`='CRM_LISTA_ZASOBOW'
-				and z1.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-				and z2.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-		";
-		$res = $this->_db->query($sql);
-		while ($r = $this->_db->fetch($res)) {
-			$groups[$r->groupID] = $this->_buildGroupFromRow($r, $fetchNested = false);
-		}
-
-		return $groups;
+				join `CRM_LISTA_ZASOBOW` as z1 on ( z1.`ID` = l.`TABLE_1_ID` )
+				join `CRM_LISTA_ZASOBOW` as z2 on ( z2.`ID` = l.`TABLE_2_ID` )
+			where l.`TABLE_1_ID` > 0
+				and l.`TABLE_2_ID` = '{$idGroup}'
+				and l.`LINKS_TYPE_ID` = 5
+				and l.`TABLE_1_NAME` = 'CRM_LISTA_ZASOBOW'
+				and l.`A_STATUS` in ( 'NORMAL' )
+				and l.`TABLE_2_NAME` = 'CRM_LISTA_ZASOBOW'
+				and z1.`TYPE` in ( 'STANOWISKO', 'PODMIOT', 'DZIAL' )
+				and z2.`TYPE` in ( 'STANOWISKO', 'PODMIOT', 'DZIAL' )
+		", 'groupID'));
 	}
 
 	private function _getGroupConnection($idParentGroup, $idGroup) {
-		if (!$this->_db) return null;
 		if ($idParentGroup <= 0) return null;
 		if ($idGroup <= 0) return null;
-		$sql = "SELECT l.*
+
+		$listItems = array_map(function ($item) {
+			return (object)$item;
+		}, DB::getPDO()->fetchAll("
+			SELECT l.*
 			from `ITEM_LINKS` as l
-				join `CRM_LISTA_ZASOBOW` as z1 on(z1.`ID`=l.`TABLE_1_ID`)
-				join `CRM_LISTA_ZASOBOW` as z2 on(z2.`ID`=l.`TABLE_2_ID`)
-			where l.`TABLE_1_ID`='{$idParentGroup}'
-				and l.`TABLE_2_ID`='{$idGroup}'
-				and l.`LINKS_TYPE_ID`=5
-				and l.`TABLE_1_NAME`='CRM_LISTA_ZASOBOW'
-				and l.`TABLE_2_NAME`='CRM_LISTA_ZASOBOW'
-				and z1.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-				and z2.`TYPE` in('STANOWISKO','PODMIOT','DZIAL')
-		";
-		$res = $this->_db->query($sql);
-		if ($r = $this->_db->fetch($res)) {
-			return $r;
-		}
-		return null;
+				join `CRM_LISTA_ZASOBOW` as z1 on ( z1.`ID` = l.`TABLE_1_ID` )
+				join `CRM_LISTA_ZASOBOW` as z2 on ( z2.`ID` = l.`TABLE_2_ID` )
+			where l.`TABLE_1_ID` = '{$idParentGroup}'
+				and l.`TABLE_2_ID` = '{$idGroup}'
+				and l.`LINKS_TYPE_ID` = 5
+				and l.`TABLE_1_NAME` = 'CRM_LISTA_ZASOBOW'
+				and l.`TABLE_2_NAME` = 'CRM_LISTA_ZASOBOW'
+				and z1.`TYPE` in ( 'STANOWISKO', 'PODMIOT', 'DZIAL' )
+				and z2.`TYPE` in ( 'STANOWISKO', 'PODMIOT', 'DZIAL' )
+		"));
+
+		return (!empty($listItems)) ? $listItems : null;
 	}
 
 	private function _setGroupConnection($idParentGroup, $idGroup, $errorMsg = null) {
-		if (!$this->_db) throw new Exception("Error: no DB!");
 		if ($idGroup <= 0) throw new Exception("Wrong param id group!");
 		if ($idParentGroup <= 0) throw new Exception("Wrong param id parent group!");
 		if (!$errorMsg) $errorMsg = "Nie udało się utworzyć połączenia grup [{$idGroup}] i [{$idParentGroup}]";
@@ -248,7 +226,7 @@ class UserStorageDB extends UserStorageBase {
 		$connObj = $this->_getGroupConnection($idParentGroup, $idGroup);
 		if ($connObj) {
 			$connObj->A_STATUS = 'NORMAL';
-			$affected = $this->_db->UPDATE_OBJ('ITEM_LINKS', $connObj);
+			$affected = DB::getDB()->UPDATE_OBJ('ITEM_LINKS', $connObj);
 			if ($affected <= 0) throw new Exception($errorMsg);
 		}
 		else {
@@ -262,13 +240,12 @@ class UserStorageDB extends UserStorageBase {
 			$sqlObj->LINKS_TYPE_ID = 5;// NestedGroups
 			$sqlObj->A_STATUS = 'NORMAL';
 
-			$idCreatedRow = $this->_db->ADD_NEW_OBJ('ITEM_LINKS', $sqlObj);
+			$idCreatedRow = DB::getDB()->ADD_NEW_OBJ('ITEM_LINKS', $sqlObj);
 			if ($idCreatedRow <= 0) throw new Exception($errorMsg);
 		}
 	}
 
 	public function addNestedGroup($idGroup, $idNestedGroup) {
-		if (!$this->_db) throw new Exception("Error: no DB!");
 		if ($idGroup <= 0) throw new Exception("Wrong param id group!");
 		if ($idNestedGroup <= 0) throw new Exception("Wrong param id nested group!");
 		$errorMsg = "Nie udało się dodać grupy zagnieżdżonej [{$idNestedGroup}] do grupy [{$idGroup}]";
@@ -276,7 +253,6 @@ class UserStorageDB extends UserStorageBase {
 	}
 
 	public function addParentGroup($idGroup, $idParentGroup) {
-		if (!$this->_db) throw new Exception("Error: no DB!");
 		if ($idGroup <= 0) throw new Exception("Wrong param id group!");
 		if ($idParentGroup <= 0) throw new Exception("Wrong param id parent group!");
 		$errorMsg = "Nie udało się dodać grupy nadrzędnej [{$idParentGroup}] do grupy [{$idGroup}]";
@@ -284,14 +260,13 @@ class UserStorageDB extends UserStorageBase {
 	}
 
 	public function removeNestedGroup($idGroup, $idNestedGroup) {
-		if (!$this->_db) throw new Exception("Error: no DB!");
 		if ($idGroup <= 0) throw new Exception("Wrong param id group!");
 		if ($idNestedGroup <= 0) throw new Exception("Wrong param id nested group!");
 
 		$connObj = $this->_getGroupConnection($idGroup, $idNestedGroup);
 		if ($connObj) {
 			$connObj->A_STATUS = 'DELETED';
-			$affected = $this->_db->UPDATE_OBJ('ITEM_LINKS', $connObj);
+			$affected = DB::getDB()->UPDATE_OBJ('ITEM_LINKS', $connObj);
 			if ($affected <= 0) {
 				throw new Exception("Nie udało się usunąć grupy zagnieżdżonej '{$kGroupID}' do grupy '{$groupID}' w bazie danych");
 			}
@@ -299,14 +274,13 @@ class UserStorageDB extends UserStorageBase {
 	}
 
 	public function removeParentGroup($idGroup, $idParentGroup) {
-		if (!$this->_db) throw new Exception("Error: no DB!");
 		if ($idGroup <= 0) throw new Exception("Wrong param id group!");
 		if ($idParentGroup <= 0) throw new Exception("Wrong param id parent group!");
 
 		$connObj = $this->_getGroupConnection($idParentGroup, $idGroup);
 		if ($connObj) {
 			$connObj->A_STATUS = 'DELETED';
-			$affected = $this->_db->UPDATE_OBJ('ITEM_LINKS', $connObj);
+			$affected = DB::getDB()->UPDATE_OBJ('ITEM_LINKS', $connObj);
 			if ($affected <= 0) {
 				throw new Exception("Nie udało się usunąć grupy nadrzędnej [{$idParentGroupToRemove}] do grupy [{$idGroup}]");
 			}
@@ -336,7 +310,8 @@ class UserStorageDB extends UserStorageBase {
 		} else {
 			$sqlStatus = 'NORMAL';
 		}
-		$sql = "update `ADMIN_USERS`
+		$sql = "
+			update `ADMIN_USERS`
 			set `A_STATUS`='{$sqlStatus}'
 			where
 				`ADM_ACCOUNT`='{$usrLogin}'
@@ -355,31 +330,26 @@ class UserStorageDB extends UserStorageBase {
 	}
 
 	public function _getUserGroupsAll($usrLogin) {
-		$groups = array();
-
 		$sql_select = array();
 		$sql_select[] = "z.`ID`";
 		$sql_select[] = "z.`DESC`";
 		$sql_select[] = "z.`TYPE`";
 		//$sql_select[] = "z.`OPIS`";
 		$sql_select[] = "z.`A_LDAP_GID`";
-
 		$sql_select = implode(', ', $sql_select);
-		$sql = "select {$sql_select}
+
+		return array_map(function ($item) {
+			return $this->_buildGroupFromRow((object)$item);
+		}, DB::getPDO()->fetchAllByKey("
+			select {$sql_select}
 			from `CRM_AUTH_PROFILE` as up
-				join `ADMIN_USERS` as a on(a.`ID`=up.`REMOTE_ID` and up.`REMOTE_TABLE`='ADMIN_USERS')
-				join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=up.`ID_ZASOB`)
+				join `ADMIN_USERS` as a on ( a.`ID` = up.`REMOTE_ID` and up.`REMOTE_TABLE` = 'ADMIN_USERS' )
+				join `CRM_LISTA_ZASOBOW` as z on ( z.`ID` = up.`ID_ZASOB` )
 			where
-				a.`ADM_ACCOUNT`='{$usrLogin}'
-				and up.`A_STATUS` in('WAITING', 'NORMAL')
-				and z.`TYPE` in('STANOWISKO','DZIAL','PODMIOT')
-		";
-		$res = $this->_db->query($sql);
-		while ($r = $this->_db->fetch($res)) {
-			$groups[$r->ID] = $this->_buildGroupFromRow($r);
-		}
-
-		return $groups;
+				a.`ADM_ACCOUNT` = '{$usrLogin}'
+				and up.`A_STATUS` in ( 'WAITING', 'NORMAL' )
+				and z.`TYPE` in ( 'STANOWISKO', 'DZIAL', 'PODMIOT' )
+		", 'ID'));
 	}
 
 	private function _getUserGroupsBelow($groups) {// TODO: fetch groups below
@@ -555,7 +525,6 @@ class UserStorageDB extends UserStorageBase {
 	 */
 	public function getProfileById($profileID) {
 		if (!$profileID) return false;
-		$profile = null;
 
 		$sql_select = array();
 		$sql_select[] = "z.`ID`";
@@ -569,24 +538,26 @@ class UserStorageDB extends UserStorageBase {
 		$sql_select[] = "a.`ID` as usrId";
 
 		$sql_select = implode(', ', $sql_select);
-		$sql = "select {$sql_select}
+
+		$r = DB::getPDO()->fetchFirstAsObject("
+			select {$sql_select}
 			from `CRM_AUTH_PROFILE` as up
-				join `ADMIN_USERS` as a on(a.`ID`=up.`REMOTE_ID` and up.`REMOTE_TABLE`='ADMIN_USERS')
-				join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=up.`ID_ZASOB`)
+				join `ADMIN_USERS` as a on ( a.`ID` = up.`REMOTE_ID` and up.`REMOTE_TABLE` = 'ADMIN_USERS' )
+				join `CRM_LISTA_ZASOBOW` as z on ( z.`ID` = up.`ID_ZASOB` )
 			where
-				up.`ID`='{$profileID}'
-				and up.`A_STATUS` in('WAITING', 'NORMAL')
-				and z.`TYPE` in('STANOWISKO','DZIAL','PODMIOT')
-		";
-		$res = $this->_db->query($sql);
-		if ($r = $this->_db->fetch($res)) {
-			$profile = new stdClass();
-			$profile->profileId = $r->profileId;
-			$profile->localisationId = $r->localisationId;
-			$profile->usrId = $r->usrId;
-			$profile->usrLogin = $r->usrLogin;
-			$profile->group = $this->_buildGroupFromRow($r);
-		}
+				up.`ID` = '{$profileID}'
+				and up.`A_STATUS` in ( 'WAITING', 'NORMAL' )
+				and z.`TYPE` in ( 'STANOWISKO', 'DZIAL', 'PODMIOT' )
+		");
+
+		if (!$r) return null;
+
+		$profile = new stdClass();
+		$profile->profileId = $r->profileId;
+		$profile->localisationId = $r->localisationId;
+		$profile->usrId = $r->usrId;
+		$profile->usrLogin = $r->usrLogin;
+		$profile->group = $this->_buildGroupFromRow($r);
 
 		return $profile;
 	}
@@ -617,27 +588,26 @@ class UserStorageDB extends UserStorageBase {
 		$sql_select[] = "a.`ID` as usrId";
 
 		$sql_select = implode(', ', $sql_select);
-		$sql = "select {$sql_select}
-			from `CRM_AUTH_PROFILE` as up
-				join `ADMIN_USERS` as a on(a.`ID`=up.`REMOTE_ID` and up.`REMOTE_TABLE`='ADMIN_USERS')
-				join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=up.`ID_ZASOB`)
-			where
-				a.`ADM_ACCOUNT`='{$usrLogin}'
-				and up.`A_STATUS` in('WAITING', 'NORMAL')
-				and z.`TYPE` in('STANOWISKO','DZIAL','PODMIOT')
-		";
-		$res = $this->_db->query($sql);
-		while ($r = $this->_db->fetch($res)) {
+		return array_map(function ($item) {
+			$r = (object)$item;
 			$profile = new stdClass();
 			$profile->profileId = $r->profileId;
 			$profile->localisationId = $r->localisationId;
 			$profile->usrId = $r->usrId;
 			$profile->usrLogin = $r->usrLogin;
 			$profile->group = $this->_buildGroupFromRow($r);
-			$profiles[] = $profile;
-		}
 
-		return $profiles;
+			return $profile;
+		}, DB::getPDO()->fetchAll("
+			select {$sql_select}
+			from `CRM_AUTH_PROFILE` as up
+				join `ADMIN_USERS` as a on ( a.`ID` = up.`REMOTE_ID` and up.`REMOTE_TABLE` = 'ADMIN_USERS' )
+				join `CRM_LISTA_ZASOBOW` as z on ( z.`ID` = up.`ID_ZASOB` )
+			where
+				a.`ADM_ACCOUNT` = '{$usrLogin}'
+				and up.`A_STATUS` in ( 'WAITING', 'NORMAL' )
+				and z.`TYPE` in ( 'STANOWISKO', 'DZIAL', 'PODMIOT' )
+		"));
 	}
 
 	/**
@@ -645,53 +615,52 @@ class UserStorageDB extends UserStorageBase {
 	 * Only in UserStorageDB
 	 */
 	public function removeUserGroupByProfileId($usrLogin, $group, $profileID) {
-		if (!$this->_db) return false;
 		if (!$usrLogin || !$profileID || !$group || !$group->zasobID) return false;
 		$usrDB = $this->getUser($usrLogin);
 		if (!$usrDB) return false;
 
-		$sql = "delete from `CRM_AUTH_PROFILE`
+		DB::getPDO()->execSql("
+			delete from `CRM_AUTH_PROFILE`
 			where
-				`ID_ZASOB`='{$group->zasobID}'
-				and `REMOTE_ID`='{$usrDB->primaryKey}'
-				and `REMOTE_TABLE`='ADMIN_USERS'
-				and `ID`='{$profileID}'
-		";
-		$res = $this->_db->query($sql);
+				`ID_ZASOB` = '{$group->zasobID}'
+				and `REMOTE_ID` = '{$usrDB->primaryKey}'
+				and `REMOTE_TABLE` = 'ADMIN_USERS'
+				and `ID` = '{$profileID}'
+		");
 		return true;
 	}
 
 	public function setSyncUserDate($usrLogin) {
-		if (!$this->_db) return false;
-		$sql = "update `ADMIN_USERS` set `A_SYNC_LDAP_DATE`=NOW() where `ADM_ACCOUNT`='{$usrLogin}' ";
-		$res = $this->_db->query($sql);
+		DB::getPDO()->execSql("
+			update `ADMIN_USERS`
+			set `A_SYNC_LDAP_DATE` = NOW()
+			where `ADM_ACCOUNT` = '{$usrLogin}'
+		");
 	}
 
 	public function setSyncGroupDate($idGroup) {
-		if (!$this->_db) return false;
 		if ($idGroup <= 0) return false;
-		$sql = "update `CRM_LISTA_ZASOBOW` set `A_SYNC_LDAP_DATE`=NOW() where `ID`='{$idGroup}' ";
-		$res = $this->_db->query($sql);
+
+		DB::getPDO()->execSql("
+			update `CRM_LISTA_ZASOBOW`
+			set `A_SYNC_LDAP_DATE` = NOW()
+			where `ID` = '{$idGroup}'
+		");
 	}
 
 	public function isPasswordChanged($usrLogin) {
-		$cnt = 0;
-		$sql = "
-		  SELECT
-		--         h.`ADM_PASSWD`,
-		         count(1) as cnt
-		    FROM `ADMIN_USERS` as u
-		    JOIN `ADMIN_USERS_HIST` as h on(h.`ID_USERS2`=u.`ID`)
-		   WHERE u.`ADM_ACCOUNT`='{$usrLogin}'
-		     AND h.`A_RECORD_CREATE_DATE`>u.`A_SYNC_LDAP_DATE`
-		     AND h.`ADM_PASSWD`!='N/S;'
-		     AND h.`ADM_PASSWD`!=''
-		-- GROUP BY h.`ADM_PASSWD`
-		";
-		$res = $this->_db->query($sql);
-		if ($r = $this->_db->fetch($res)) {
-			$cnt = $r->cnt;
-		}
+		$cnt = DB::getPDO()->fetchValue("
+			SELECT count(1) as cnt
+				, h.`ADM_PASSWD`
+			FROM `ADMIN_USERS` as u
+				JOIN `ADMIN_USERS_HIST` as h on ( h.`ID_USERS2` = u.`ID` )
+			WHERE u.`ADM_ACCOUNT` = '{$usrLogin}'
+				AND h.`A_RECORD_CREATE_DATE` > u.`A_SYNC_LDAP_DATE`
+				AND h.`ADM_PASSWD` != 'N/S;'
+				AND h.`ADM_PASSWD` != ''
+			-- GROUP BY h.`ADM_PASSWD`
+		");
+
 		return ($cnt > 0);
 	}
 

+ 1 - 2
SE/se-lib/UserStorageFactory.php

@@ -8,8 +8,7 @@ class UserStorageFactory {
 	public static function getStorage($clientType) {
 		$usrStorage = null;
 		if ($clientType == 'DB') {
-			$db = DB::getDB();
-			$usrStorage = new UserStorageDB($db);
+			$usrStorage = new UserStorageDB();
 		}
 		else if ($clientType == 'MacOSX') {
 			$ldapConfName = 'default_ldap';

+ 140 - 175
SE/se-lib/UsersHelper.php

@@ -33,18 +33,12 @@ class UsersHelper {
 	}
 
 	public static function get_users_total($params = array()) {
-		$total = 0;
-		$db = DB::getDB();
 		$sql_where = UsersHelper::_parse_query($params);
-		$sql = "select count(1) as cnt
+		return DB::getPDO()->fetchValue("
+			select count(1) as cnt
 			from `ADMIN_USERS` as a
 			where {$sql_where}
-		";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$total = $r->cnt;
-		}
-		return $total;
+		");
 	}
 
 	public static function &get_users_list($params = array(), $limit = 10, $limit_start = 0, $order_by = '', $order_dir = '') {
@@ -68,8 +62,10 @@ class UsersHelper {
 		}
 
 		// 'WAITING','NORMAL','MONITOR','WARNING','OFF_SOFT','OFF_HARD','DELETED'
-		$db = DB::getDB();
-		$sql = "SELECT a.`ID`
+		return array_map(function ($item) {
+			return (object)$item;
+		}, DB::getPDO()->fetchAllByKey("
+			SELECT a.`ID`
 				, a.`A_STATUS`
 				, a.`ADM_ACCOUNT`
 				, a.`ADM_ADMIN_LEVEL`
@@ -89,21 +85,14 @@ class UsersHelper {
 			group by a.ID
 			{$sql_order_by}
 			{$sql_limit}
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[$r->ID] = $r;
-		}
-		return $ret;
+		", 'ID'));
 	}
 
 	public static function get_user_by_id( $id ) {
-		$ret = null;
-		if ($id <= 0) return $ret;
+		if ($id <= 0) return null;
 
-		$sql_where = "a.`ID`='{$id}'";
-		$db = DB::getDB();
-		$sql = "SELECT a.`ID`
+		return DB::getPDO()->fetchFirstAsObject("
+			SELECT a.`ID`
 				, a.`A_STATUS`
 				, a.`ADM_ACCOUNT`
 				, a.`ADM_ADMIN_LEVEL`
@@ -117,21 +106,17 @@ class UsersHelper {
 			from `ADMIN_USERS` as a
 				left join CRM_AUTH_PROFILE as cp on (cp.REMOTE_TABLE='ADMIN_USERS' and cp.REMOTE_ID=a.ID)
 				left join TELBOXES as tx on (tx.ID=cp.T_TELBOX_NEIGHBOUR_IN_ID)
-			where {$sql_where}
-		";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$ret = $r;
-		}
-		return $ret;
+			where a.`ID` = :id
+		", [
+			':id' => $id,
+		]);
 	}
 
 	public static function getUserByEmail($email) {
 		if (empty($email)) return null;
-		$usr = null;
 
-		$db = DB::getDB();
-		$sql = "SELECT a.`ID`
+		return DB::getPDO()->fetchFirstAsObject("
+			SELECT a.`ID`
 				, a.`A_STATUS`
 				, a.`ADM_ACCOUNT`
 				, a.`ADM_ADMIN_LEVEL`
@@ -144,21 +129,17 @@ class UsersHelper {
 				, a.`EMPLOYEE_TYPE`  -- EMPLOYEE_TYPE (ldap:employeeType)
 				, a.`A_SYNC_LDAP_DATE`
 			from `ADMIN_USERS` as a
-			where a.`EMAIL`='{$email}'
-		";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$usr = $r;
-		}
-		return $usr;
+			where a.`EMAIL` = :email
+		", [
+			':email' => $email,
+		]);
 	}
 
 	public static function getUserByName($userName) {
 		if (empty($userName)) return null;
-		$user = null;
 
-		$db = DB::getDB();
-		$sql = "SELECT a.`ID`
+		return DB::getPDO()->fetchFirstAsObject("
+			SELECT a.`ID`
 				, a.`A_STATUS`
 				, a.`ADM_ACCOUNT`
 				, a.`ADM_ADMIN_LEVEL`
@@ -171,21 +152,19 @@ class UsersHelper {
 				, a.`EMPLOYEE_TYPE`  -- EMPLOYEE_TYPE (ldap:employeeType)
 				, a.`A_SYNC_LDAP_DATE`
 			from `ADMIN_USERS` as a
-			where a.`ADM_ACCOUNT`='{$userName}'
-		";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$user = $r;
-		}
-		return $user;
+			where a.`ADM_ACCOUNT` = :name
+		", [
+			':name' => $userName,
+		]);
 	}
 
 	public static function getUsersByGroupId($zasobId) {
 		if (empty($zasobId)) return null;
-		$users = array();
 
-		$db = DB::getDB();
-		$sql = "select u.`ID`
+		return array_map(function ($item) {
+			return (object)$item;
+		}, DB::getPDO()->fetchAllByKey("
+			select u.`ID`
 				, u.`A_STATUS`
 				, u.`ADM_ACCOUNT`
 				, u.`ADM_ADMIN_LEVEL`
@@ -200,30 +179,30 @@ class UsersHelper {
 			from `CRM_AUTH_PROFILE` as up
 				left join `ADMIN_USERS` as u on (u.`ID`=up.`REMOTE_ID`)
 			where
-				up.`ID_ZASOB`='{$zasobId}'
+				up.`ID_ZASOB` = :id
 				and up.`REMOTE_TABLE`='ADMIN_USERS'
 				and up.`A_STATUS` in('WAITING', 'NORMAL')
 				and u.`A_STATUS` in('WAITING', 'NORMAL')
 			group by u.`ID`
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$users[$r->ID] = $r;
-		}
-		return $users;
+		", 'ID', [
+			':id' => $zasobId,
+		]));
 	}
 
 	public static function getUsersByGroupsIds($zasobyIds, $ignoreUsrIds = array()) {
 		if (empty($zasobyIds)) return null;
 		$users = array();
 
-		$db = DB::getDB();
 		$sqlIds = " and up.`ID_ZASOB` in(" . implode(",", $zasobyIds) . ")";
 		$sqlIgnore = "";
 		if (!empty($ignoreUsrIds)) {
 			$sqlIgnore = " and u.`ID` not in(" . implode(",", $ignoreUsrIds) . ")";
 		}
-		$sql = "select u.`ID`
+
+		return array_map(function ($item) {
+			return (object)$item;
+		}, DB::getPDO()->fetchAllByKey("
+			select u.`ID`
 				, u.`A_STATUS`
 				, u.`ADM_ACCOUNT`
 				, u.`ADM_ADMIN_LEVEL`
@@ -243,29 +222,21 @@ class UsersHelper {
 				{$sqlIds}
 				{$sqlIgnore}
 			group by u.`ID`
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$users[$r->ID] = $r;
-		}
-		return $users;
+		", 'ID'));
 	}
 
 	public static function get_group_list() {
 		static $_groups;
 		if (!$_groups) {
-			$_groups = array();
-			$db = DB::getDB();
-			$sql = "select z.`ID`, z.`DESC`, z.`OPIS`
+			$_groups = array_map(function ($item) {
+				return (object)$item;
+			}, DB::getPDO()->fetchAllByKey("
+				select z.`ID`, z.`DESC`, z.`OPIS`
 				from `CRM_LISTA_ZASOBOW` as z
 				where
-					z.`TYPE` in('STANOWISKO','PODMIOT')
-					order by z.`DESC`
-			";
-			$res = $db->query($sql);
-			while ($r = $db->fetch($res)) {
-				$_groups[$r->ID] = $r;
-			}
+					z.`TYPE` in ( 'STANOWISKO', 'PODMIOT' )
+				order by z.`DESC`
+			", 'ID'));
 		}
 		return $_groups;
 	}
@@ -273,18 +244,15 @@ class UsersHelper {
 	public static function get_localisation_list() {
 		static $_groups;
 		if (!$_groups) {
-			$_groups = array();
-			$db = DB::getDB();
-			$sql = "select tx.`ID`, tx.`T_TELBOX_NAME`, tx.`T_TELBOX_TYPE`
+			$_groups = array_map(function ($item) {
+				return (object)$item;
+			}, DB::getPDO()->fetchAllByKey("
+				select tx.`ID`, tx.`T_TELBOX_NAME`, tx.`T_TELBOX_TYPE`
 				from `TELBOXES` as tx
 				where
-					tx.`A_STATUS`!='DELETED'
+					tx.`A_STATUS` != 'DELETED'
 				order by tx.`T_TELBOX_NAME`
-			";
-			$res = $db->query($sql);
-			while ($r = $db->fetch($res)) {
-				$_groups[$r->ID] = $r;
-			}
+			", 'ID'));
 		}
 		return $_groups;
 	}
@@ -293,25 +261,25 @@ class UsersHelper {
 		if (empty($items)) return;
 		$user_list_id = array();
 		foreach ($items as $k_ind => $v_item) {
-			$items[$k_ind]->groups = array();
+			$items[$k_ind]->groups = [];
 			$user_list_id[] = "'{$v_item->ID}'";
 		}
 		if (empty($user_list_id)) return;
-		$db = DB::getDB();
-		$sql = "select z.`ID`, z.`DESC`, z.`OPIS`
+
+		$listGroups = DB::getPDO()->fetchAll("
+			select z.`ID`, z.`DESC`, z.`OPIS`
 				, up.`REMOTE_ID`
 			from `CRM_AUTH_PROFILE` as up
-				left join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=up.`ID_ZASOB`)
+				left join `CRM_LISTA_ZASOBOW` as z on ( z.`ID` = up.`ID_ZASOB` )
 			where
 				up.`REMOTE_ID` in (" . implode(",", $user_list_id) . ")
-				and up.`A_STATUS` in('WAITING', 'NORMAL')
-				and up.`REMOTE_TABLE`='ADMIN_USERS'
+				and up.`A_STATUS` in ( 'WAITING', 'NORMAL' )
+				and up.`REMOTE_TABLE` = 'ADMIN_USERS'
 				and z.`ID` is not null
-				and z.`TYPE` in('STANOWISKO','PODMIOT')
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$items[$r->REMOTE_ID]->groups[$r->ID] = $r->DESC;//array('DESC'=>$r->DESC , 'OPIS'=>$r->OPIS);
+				and z.`TYPE` in ( 'STANOWISKO', 'PODMIOT' )
+		");
+		foreach ($listGroups as $group) {
+			$items[$group['REMOTE_ID']]->groups[$group['ID']] = $group['DESC'];//array('DESC'=>$r->DESC , 'OPIS'=>$r->OPIS);
 		}
 	}
 
@@ -320,16 +288,11 @@ class UsersHelper {
 	}
 
 	public static function getGroupByUserName($userName, $params = array()) {
-		$db = DB::getDB();
-		$userID = 0;
-		$sql = "select u.`ID`
+		$userID = DB::getPDO()->fetchValue("
+			select u.`ID`
 			from `ADMIN_USERS` as u
-			where u.`ADM_ACCOUNT`='{$userName}'
-		";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$userID = $r->ID;
-		}
+			where u.`ADM_ACCOUNT` = '{$userName}'
+		");
 		if ($userID > 0) {
 			return self::getGroupByUser($userID, $params);
 		}
@@ -371,8 +334,8 @@ class UsersHelper {
 				and z.`TYPE` in('STANOWISKO','PODMIOT')
 				{$sql_select_where_and}
 		";
-		return array_map(function ($row) {
-			return (object)$row;
+		return array_map(function ($item) {
+			return (object)$item;
 		}, DB::getPDO()->fetchAllByKey($sql, 'ID'));
 	}
 
@@ -385,66 +348,52 @@ class UsersHelper {
 	}
 
 	public static function getGroupsAll() {
-		$allGroups = array();
-
-		$db = DB::getDB();
-		$sql = "select z.`ID`, z.`TYPE`, z.`DESC`, z.`A_LDAP_GID`
+		$sql = "
+			select z.`ID`, z.`TYPE`, z.`DESC`, z.`A_LDAP_GID`
 			from `CRM_LISTA_ZASOBOW` as z
 			where
 				z.`A_STATUS` in('WAITING', 'NORMAL')
 				and z.`TYPE` in('STANOWISKO','DZIAL','PODMIOT')
 		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$allGroups[$r->ID] = $r;
-		}
-		return $allGroups;
+		return array_map(function ($item) {
+			return (object)$item;
+		}, DB::getPDO()->fetchAllByKey($sql, 'ID'));
 	}
 
 	public static function getGroupByID($id) {
-		$db = DB::getDB();
 		$sql = "
 			select z.`ID`, z.`TYPE`, z.`DESC`, z.`A_LDAP_GID`
 			from `CRM_LISTA_ZASOBOW` as z
 			where
 				z.`A_STATUS` in('WAITING', 'NORMAL')
 				and z.`TYPE` in('STANOWISKO','DZIAL','PODMIOT')
-				and z.ID = {$id}
+				and z.ID = :id
 		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			return $r;
-		}
-		return null;
+		return DB::getPDO()->fetchFirstAsObject($sql, [ ':id' => $id ]);
 	}
 
 	/**
 	 * @params $ids array of integer
 	 */
 	public static function getGroupsByLdapGids($ldapGids) {
-		$groups = array();
 		if (empty($ldapGids)) {
 			return false;
 		}
 
-		$db = DB::getDB();
-		$sql = "select z.`ID`, z.`TYPE`, z.`DESC`, z.`A_LDAP_GID`
+		$sql = "
+			select z.`ID`, z.`TYPE`, z.`DESC`, z.`A_LDAP_GID`
 			from `CRM_LISTA_ZASOBOW` as z
 			where
 				z.`A_STATUS` in('WAITING', 'NORMAL')
 				and z.`TYPE` in('STANOWISKO','DZIAL','PODMIOT')
 				and z.`A_LDAP_GID` in(" . implode(",", $ldapGids) . ")
 		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$groups[$r->ID] = $r;
-		}
-		return $groups;
+		return array_map(function ($item) {
+			return (object)$item;
+		}, DB::getPDO()->fetchAllByKey($sql, 'ID'));
 	}
 
 	public static function getUsersAll() {
-		$allGroups = array();
-
 		$sql_order_by = '';
 		$sql_limit = '';
 
@@ -462,8 +411,8 @@ class UsersHelper {
 		}
 		$sql_where = implode(" and ", $sql_where_and_arr);
 
-		$db = DB::getDB();
-		$sql = "SELECT a.`ID`
+		$sql = "
+			SELECT a.`ID`
 				, a.`A_STATUS`
 				, a.`ADM_ACCOUNT`
 				, a.`ADM_ADMIN_LEVEL`
@@ -483,11 +432,9 @@ class UsersHelper {
 			-- {$sql_order_by}
 			-- {$sql_limit}
 		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$allGroups[$r->ID] = $r;
-		}
-		return $allGroups;
+		return array_map(function ($item) {
+			return (object)$item;
+		}, DB::getPDO()->fetchAllByKey($sql, 'ID'));
 	}
 
 	public static function getLDAPUsersAll() {
@@ -516,41 +463,58 @@ class UsersHelper {
 	public static function add_group($user_id, $group_id, $add_localisation) {
 		if ($group_id <= 0) return -1;
 		if ($user_id <= 0) return -1;
-		$db = DB::getDB();
 		$sqlToday = date('Y-m-d-H:i');
 		$sqlUser = User::getName();
-		$sql = "insert into `CRM_AUTH_PROFILE` (`ID_ZASOB`, `REMOTE_ID`, `REMOTE_TABLE`, `A_RECORD_CREATE_DATE`, `A_RECORD_CREATE_AUTHOR`,`T_TELBOX_NEIGHBOUR_IN_ID`)
-			select `ID`, '{$user_id}' as user_id, 'ADMIN_USERS' as REMOTE_TABLE
-				, '{$sqlToday}' as A_RECORD_CREATE_DATE
-				, '{$sqlUser}' as A_RECORD_CREATE_AUTHOR , '{$add_localisation}' as T_TELBOX_NEIGHBOUR_IN_ID
+		DB::getPDO()->execSql("
+			insert into `CRM_AUTH_PROFILE` (`ID_ZASOB`, `REMOTE_ID`, `REMOTE_TABLE`, `A_RECORD_CREATE_DATE`, `A_RECORD_CREATE_AUTHOR`,`T_TELBOX_NEIGHBOUR_IN_ID`)
+			select `ID`, :id_user as user_id, 'ADMIN_USERS' as REMOTE_TABLE
+				, :today as A_RECORD_CREATE_DATE
+				, :name as A_RECORD_CREATE_AUTHOR , :add_localisation as T_TELBOX_NEIGHBOUR_IN_ID
 			from `CRM_LISTA_ZASOBOW`
-			where `ID`='{$group_id}' and `TYPE` in('STANOWISKO','PODMIOT')
-		";
-		$db->query($sql);
-		$ret_id = $db->insert_id();
-		return $ret_id;
+			where `ID` = :id_group and `TYPE` in('STANOWISKO','PODMIOT')
+		", [
+			':id_user' => $user_id,
+			':id_group' => $group_id,
+			':today' => $sqlToday,
+			':name' => $sqlUser,
+			':add_localisation' => $add_localisation,
+		]);
+
+		return DB::getPDO()->lastInsertId();
 	}
 
 	public static function remove_group($user_id, $group_id) {
 		if ($group_id <= 0) return -1;
 		if ($user_id <= 0) return -1;
-		$db = DB::getDB();
-		$sql = "select `ID` from `CRM_AUTH_PROFILE` where `ID_ZASOB`='{$group_id}' and `REMOTE_ID`='{$user_id}' and `REMOTE_TABLE`='ADMIN_USERS' ";
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$table = 'CRM_AUTH_PROFILE';
-			$sql_obj = new stdClass();
-			$sql_obj->ID = $r->ID;
-			$sql_obj->A_STATUS = 'DELETED';
-			$ret = $db->UPDATE_OBJ($table, $sql_obj);
-			if ($ret > 0) {
-				$sql = "delete from `CRM_AUTH_PROFILE` where `ID`='{$r->ID}' limit 1;";
-				$db->query($sql);
-			}
-			return $ret;
-		} else {
-			return -1;
-		}
+
+		$record = DB::getPDO()->fetchFirst("
+			select `ID`
+			from `CRM_AUTH_PROFILE`
+			where `ID_ZASOB` = :id_group
+				and `REMOTE_ID` = :id_user
+				and `REMOTE_TABLE` = 'ADMIN_USERS'
+		", [
+			':id_group' => $group_id,
+			':id_user' => $user_id,
+		]);
+		if (!$record) return -1;
+
+		$tableName = 'CRM_AUTH_PROFILE';
+
+		$toUpdate = [
+			'A_STATUS' => 'DELETED',
+			'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+			'A_RECORD_UPDATE_DATE' => 'NOW()',
+		];
+		$affectedRows = DB::getPDO($dbID)->update($tableName, 'ID', $record['ID'], $toUpdate);
+		DB::getPDO($dbID)->insert("{$tableName}_HIST", array_merge($toUpdate, [
+			'ID_USERS2' => $record['ID'],
+		]));
+
+		if ($affectedRows > 0) {
+			DB::getPDO()->execSql(" delete from `CRM_AUTH_PROFILE` where `ID` = :id limit 1; ", [ ':id' => $record['ID'] ]);
+		}
+		return $affectedRows;
 	}
 
 	public static function getGroupsTree() {
@@ -567,7 +531,7 @@ class UsersHelper {
 		return $dataAll['items'];
 	}
 
-	public static function _fetchGroupsTreeAll() {
+	public static function _fetchGroupsTreeAll() { // TODO: fix performance
 		static $dataAll;
 		if (is_array($dataAll)) {
 			return $dataAll;
@@ -576,16 +540,17 @@ class UsersHelper {
 		$dataAll = array();
 		$filterTreeTypes = array('STANOWISKO','DZIAL','PODMIOT');
 		// tree flat
-		$db = DB::getDB();
-		$sql = "select z.`ID`, z.`PARENT_ID`, z.`TYPE`, z.`DESC`, z.`A_LDAP_GID`
+		$dataAll['items'] = array();
+		$treeZasoby = array();
+		$sql = "
+			select z.`ID`, z.`PARENT_ID`, z.`TYPE`, z.`DESC`, z.`A_LDAP_GID`
 			from `CRM_LISTA_ZASOBOW` as z
 			where
 				z.`A_STATUS` in('WAITING', 'NORMAL')
 		";
-		$res = $db->query($sql);
-		$dataAll['items'] = array();
-		$treeZasoby = array();
-		while ($r = $db->fetch($res)) {
+		$listItems = DB::getPDO()->fetchAll($sql);
+		foreach ($listItems as $item) {
+			$r = (object)$item;
 			$treeZasoby[$r->ID] = $r->PARENT_ID;
 			if (in_array($r->TYPE, $filterTreeTypes)) {
 				$r->sub = array();