Просмотр исходного кода

Merge branch 'master' of ssh://biuro.biall-net.pl:2222/plabudda/se

Mariusz Muszyński 8 лет назад
Родитель
Сommit
6d3472cefd

+ 28 - 30
SE/procesy/testy.php

@@ -550,38 +550,36 @@ function task_CRM_TEST() {
 		return;
 	}
 
-	$test_obj = DB::get_by_id('CRM_TESTY', $test_id);
+	$test_obj = (object)DB::getPDO()->fetchFirst(" select * from CRM_TESTY where ID = :ID ", [ 'ID' => $test_id ]);
 	if (!$test_obj) {
 		echo'<p class="red">'."Wrond ID.".'</p>';
 		return;
 	}
 
-	$stanowisko = DB::get_by_id('CRM_LISTA_ZASOBOW', $test_obj->ID_STANOWISKO);
-	$proces = DB::get_by_id('CRM_PROCES', $test_obj->ID_PROCES_INIT);
+	$stanowisko = (object)DB::getPDO()->fetchFirst(" select * from CRM_LISTA_ZASOBOW where ID = :ID ", [ 'ID' => $test_obj->ID_STANOWISKO ]);
+	$proces = (object)DB::getPDO()->fetchFirst(" select * from CRM_PROCES where ID = :ID ", [ 'ID' => $test_obj->ID_PROCES_INIT ]);
 
 	if (!$proces || !$stanowisko) {
-		?>
-<div class="alert alert-danger">
-	Błędny proces lub stanowisko!
-</div>
-<?php
+		UI::alert('danger', "Błędny proces lub stanowisko!");
 		return;
 	}
-	?>
-<div class="panel panel-default">
-  <div class="panel-heading">Test:</div>
-  <div class="panel-body">
-		<ul>
-			<li>
-				Proces: <b class="text-danger">{<?php echo $proces->ID; ?>} <?php echo $proces->DESC; ?></b>
-			</li>
-			<li>
-				Stanowisko: <b class="text-success">[<?php echo $stanowisko->ID; ?>] <?php echo $stanowisko->DESC; ?></b>
-			</li>
-		</ul>
-  </div>
-</div>
-<?php
+	echo UI::h('div', [ 'class' => "container" ], [
+		UI::h('div', [ 'class' => "panel panel-default" ], [
+			UI::h('div', [ 'class' => "panel-heading" ], "Test:"),
+			UI::h('div', [ 'class' => "panel-body" ], [
+				UI::h('ul', [], [
+					UI::h('li', [], [
+						"Proces: ",
+						UI::h('b', [ 'class' => "text-danger" ], "{{$proces->ID}} {$proces->DESC}"),
+					]),
+					UI::h('li', [], [
+						"Stanowisko: ",
+						UI::h('b', [ 'class' => "text-success" ], "[{$stanowisko->ID}] {$stanowisko->DESC}"),
+					]),
+				]),
+			]),
+		]),
+	]);
 
 	$lastTestDate = null;
 	if ($test_obj->ID_TEST_TO_FIX > 0) {
@@ -604,7 +602,7 @@ function task_CRM_TEST() {
 	else if ($test_obj->A_STATUS == 'MONITOR' && $test_obj->TEST_START == '0000-00-00 00:00:00') {// czytanie - test rozpoczety z data TEST_INIT
 		$id_proces = $test_obj->ID_PROCES_INIT;
 
-		$p = DB::get_by_id('CRM_PROCES', $id_proces);
+		$p = (object)DB::getPDO()->fetchFirst(" select * from CRM_PROCES where ID = :ID ", [ 'ID' => $id_proces ]);
 		if (!$p) {
 			echo '<div class="alert alert-danger">' . "Proces {$id_proces} nie istnieje" . '</div>';
 			return;
@@ -629,18 +627,18 @@ function task_CRM_TEST() {
 			}
 		}
 		if (!empty($gotoIds)) {
-			$db = DB::getDB();
 			$sqlIds = implode(",", $gotoIds);
-			$sql = "select p.`ID`, p.`DESC`, p.`OPIS`
+			$sql = "
+				select p.`ID`, p.`DESC`
+					-- , p.`OPIS`
 				from `CRM_PROCES` as p
 				where
 					p.`A_STATUS` in('WAITING', 'NORMAL')
 					and p.`ID` in({$sqlIds})
 			";
-			$res = $db->query($sql);
-			while ($r = $db->fetch($res)) {
-				$gotoLinks[$r->ID] = $r->DESC;
-			}
+			$gotoLinks = array_map(function ($row) {
+				return $row['DESC'];
+			}, DB::getPDO()->fetchAllByKey($sql, 'ID'));
 		}
 
 		foreach ($listFlat as $vItem) {

+ 74 - 48
SE/se-lib/ACL.php

@@ -20,12 +20,12 @@ class ACL {
 	 */
 	public static function getTableProcesInitList($idTable) {
 		$tableProcesInitList = array();
-		$sqlIdProcesListSql = <<<SQL
+		$sqlIdProcesListSql = "
 			select tpv.`ID_PROCES`
 				from `CRM_PROCES_idx_TABLE_TO_PROCES_VIEW` tpv
 				where tpv.`ID_TABLE`='{$idTable}'
-SQL;
-		$fetchTableProcesInitListSql = <<<SQL
+		";
+		$fetchTableProcesInitListSql = "
 			-- time ~0.07 -- no goto and return
 			select p.`ID`, p.`DESC`
 			from `CRM_PROCES` p
@@ -36,7 +36,7 @@ SQL;
 				)
 				and p.`TYPE`='PROCES_INIT'
 			order by p.`SORT_PRIO`
-SQL;
+		";
 		/*
 			SELECT p.`ID` , p.`DESC`
 			FROM `CRM_PROCES` p
@@ -54,7 +54,7 @@ SQL;
 			AND p.`TYPE` = 'PROCES_INIT'
 			order by p.`SORT_PRIO`
 		*/
-		$fetchTableProcesInitListSql = <<<SQL
+		$fetchTableProcesInitListSql = "
 			-- time ~0.15s
 			select p.`ID`, p.`DESC`
 			from `CRM_PROCES` p
@@ -70,8 +70,8 @@ SQL;
 				)
 				and p.`TYPE`='PROCES_INIT'
 			order by p.`SORT_PRIO`
-SQL;
-		$fetchTableProcesInitListSql = <<<SQL
+		";
+		$fetchTableProcesInitListSql = "
 			-- time ~0.14
 			select p.`ID`, p.`DESC`
 			from `CRM_PROCES` p
@@ -87,33 +87,28 @@ SQL;
 				)
 				and p.`TYPE`='PROCES_INIT'
 			order by p.`SORT_PRIO`
-SQL;
-		//echo'<pre>$fetchTableProcesInitListSql('.$idTable.') ';print_r($fetchTableProcesInitListSql);echo'</pre>';
-		$tableProcesInitList = array();
-		$db = DB::getDB();
-		$res = $db->query($fetchTableProcesInitListSql);
-		while ($r = $db->fetch($res)) {
-			$tableProcesInitList[$r->ID] = $r->DESC;
-		}
-		return $tableProcesInitList;
+		";
+		return array_map(function ($row) {
+			return $row['DESC'];
+		}, DB::getPDO()->fetchAllByKey($fetchTableProcesInitListSql, 'ID'));
 	}
 
 	public static function getProcesInitMapTreeOnlyIds($ids) {
 		$mapTree = array();
 		$map = self::getProcesInitMapOnlyIds($ids);
-		foreach ($map as $r) {
-			if ('PROCES_INIT' == $r->TYPE) {
-				$mapTree[$r->ID_PROCES] = array();
+		foreach ($map as $row) {
+			if ('PROCES_INIT' == $row['TYPE']) {
+				$mapTree[ $row['ID_PROCES'] ] = array();
 			}
 		}
-		foreach ($map as $r) {
-			if ('GOTO_AND_RETURN' == $r->TYPE) {
-				$mapTree[$r->idx_MAIN_PROCES_INIT_ID][$r->ID_PROCES] = array();
+		foreach ($map as $row) {
+			if ('GOTO_AND_RETURN' == $row['TYPE']) {
+				$mapTree[ $row['idx_MAIN_PROCES_INIT_ID'] ][ $row['ID_PROCES'] ] = array();
 			}
 		}
-		foreach ($map as $r) {
-			if ('GOTO_AND_RETURN_LVL2' == $r->TYPE) {
-				$mapTree[$r->idx_MAIN_PROCES_INIT_ID][$r->idx_GOTO_LVL2_INIT_ID][$r->ID_PROCES] = true;
+		foreach ($map as $row) {
+			if ('GOTO_AND_RETURN_LVL2' == $row['TYPE']) {
+				$mapTree[ $row['idx_MAIN_PROCES_INIT_ID'] ][ $row['idx_GOTO_LVL2_INIT_ID'] ][ $row['ID_PROCES'] ] = true;
 			}
 		}
 		return $mapTree;
@@ -124,7 +119,7 @@ SQL;
 		$sqlIds = V::filter($ids, array('V', 'filterPositiveInteger'));
 		$sqlIds = implode(',', $sqlIds);
 		if (empty($sqlIds)) return $map;
-		$sql = <<<SQL
+		$sql = "
 			select i.`ID_PROCES`
 				, i.`PARENT_ID`
 				, i.`TYPE`
@@ -141,35 +136,21 @@ SQL;
 			from `CRM_PROCES_idx` i
 			where i.`ID_PROCES` in({$sqlIds})
 				and i.`idx_MAIN_PROCES_INIT_ID` in({$sqlIds})
-SQL;
-		DBG::_('DBG_MAP', '1', "MAP SQL", $sql, __CLASS__, __FUNCTION__, __LINE__);
-		$db = DB::getDB();
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$map[] = $r;
-		}
-		//DBG::table("MAP", $map, __CLASS__, __FUNCTION__, __LINE__);
-		return $map;
+		";
+		return DB::getPDO()->fetchAll($sql);
 	}
 
 	public static function canGroupViewProces($idGroup, $idProcesInit) {
 		$isAllowed = false;
 		$idProcesInit = (int)$idProcesInit;
 		if (!$idProcesInit) return false;
-		$checkProcesAccessSql = <<<SQL
+		$checkProcesAccessSql = "
 			select count(*) as cnt
-				from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` giv
-				where giv.`ID_GROUP` = '{$idGroup}'
-					and giv.`ID_PROCES_INIT` = '{$idProcesInit}'
-SQL;
-		$db = DB::getDB();
-		$res = $db->query($checkProcesAccessSql);
-		if ($r = $db->fetch($res)) {
-			if ($r->cnt > 0) {
-				$isAllowed = true;
-			}
-		}
-		return $isAllowed;
+			from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` giv
+			where giv.`ID_GROUP` = '{$idGroup}'
+				and giv.`ID_PROCES_INIT` = '{$idProcesInit}'
+		";
+		return ( DB::getPDO()->fetchValue($checkProcesAccessSql) > 0 );
 	}
 
 	public static function getStorageByNamespace($namespace, $forceTblAclInit = false) {
@@ -481,6 +462,51 @@ SQL;
 		return $refInfo;
 	}
 
+	public static function generateIsInstanceFunctionBody($namespace, $item = null) {
+		if (!$item) $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
+		if (!in_array( $item['_type'], [ 'AntAcl' ] )) return null;
+		$sqlFunBody = " RETURN 1; ";
+		$localFieldsWithRestrictions = array_filter($item['field'], function ($field) {
+			if (!$field['isLocal']) return false;
+			if (empty($field['xsdRestrictions'])) return false;
+			if ('[]' == $field['xsdRestrictions']) return false;
+			return true;
+		});
+		// TODO: get fields with minOccurs > 1 (may require select by ref)
+		$sqlTablePrefix = 'root';
+		$sqlWhereFromRestrictions = (!empty($localFieldsWithRestrictions))
+		?	array_reduce(
+				array_map(function ($field) use ($sqlTablePrefix) {
+					$sqlRestrictions = [];
+					// 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
+					$restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
+					if (!empty($restrictions)) {
+						if (!empty($restrictions['enumeration'])) {
+							$sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
+						}
+					}
+					return $sqlRestrictions;
+				}, $localFieldsWithRestrictions),
+				function ($ret, $cur) {
+					return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
+				},
+				[]
+			)
+		:	'';
+		DBG::nicePrint($localFieldsWithRestrictions, "\$localFieldsWithRestrictions");
+		DBG::nicePrint($sqlWhereFromRestrictions, "\$sqlWhereFromRestrictions");
+		$sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
+		$pkField = 'ID'; // TODO: primaryKeyField into SystemObject structure
+		$rootTableName = $item['_rootTableName'];
+		$sqlFunBody = (!empty($sqlWhereFromRestrictions))
+		?	" RETURN IF(
+				(select count(1) as cnt from `{$rootTableName}` root where root.`{$pkField}` = pk and {$sqlWhereFromRestrictions}) > 0
+				, 1, 0)
+			"
+		:	" RETURN 1; ";
+		return $sqlFunBody;
+	}
+
 	public static function getInstanceId($namespace) {
 		$conf = self::getInstanceConfig($namespace);
 		return $conf['id'];

+ 17 - 1
SE/se-lib/Api/Wfs/GetFeature.php

@@ -23,7 +23,7 @@ class Api_Wfs_GetFeature {
 		if (empty($ogcPropertyList)) {
 			$ogcPropertyList = array_values($acl->getFieldListByIdZasob());
 			$ogcPropertyList = array_filter($ogcPropertyList, function ($fieldName) use ($acl) {
-				return $acl->canReadField($fieldName); // TODO: || $acl->canReadObjectField();
+				return $acl->canReadField($fieldName);
 			});
 		}
 
@@ -38,6 +38,22 @@ class Api_Wfs_GetFeature {
 			},
 			[]
 		);
+		if (!empty($nestedFields)) {
+			if (array_key_exists('*', $nestedFields)) {
+				$nestedParts = $nestedFields['*'];
+				unset($nestedFields['*']);
+				DBG::log($nestedParts, 'array', "convertOgcPropsRecurse: TODO: '*' in \$nestedFields - \$nestedParts");
+				$canReadRefs = array_values($acl->getFieldListByIdZasob());
+				$canReadRefs = array_filter($canReadRefs, function ($fieldName) use ($acl) {
+					return (false !== strpos($fieldName, ":") && $acl->canReadField($fieldName));
+				});
+				foreach ($canReadRefs as $refField) {
+					foreach ($nestedParts as $nestedPart) {
+						$nestedFields[ $refField ][] = $nestedPart;
+					}
+				}
+			}
+		}
 		if (!empty($nestedFields)) {
 			$aclFields = array_unique(array_merge($aclFields, array_keys($nestedFields)));
 		}

+ 13 - 1
SE/se-lib/Api/WfsServerBase.php

@@ -1338,6 +1338,9 @@ if($DBG){echo 'L.' . __LINE__ . ' $validateConvertedTransactionXsdString:';print
 		if (empty($requestOgcFilter)) return '';
 		$requestXml = new DOMDocument();
 		$requestXml->loadXml($requestOgcFilter);
+		$rootNode = $requestXml->documentElement;
+		// if ($rootNode->getAttribute('resolve'))
+		DBG::log([$rootNode->getAttribute('resolve'), $rootNode->getAttribute('resolveDepth')], 'array', "TODO: use wfs:GetFeature @resolve, @resolveDepth");
 		$nodesQuery = [];
 		foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/wfs', 'Query') as $element) {
 			DBG::log($element->nodeName, 'array', "main loop - wfs:Query");
@@ -1368,7 +1371,16 @@ if($DBG){echo 'L.' . __LINE__ . ' $validateConvertedTransactionXsdString:';print
 			$tagsWfsPropertyName = [];
 			foreach ($requestXml->getElementsByTagNameNS('http://www.opengis.net/wfs', 'PropertyName') as $element) {
 				// DBG::log($element->nodeValue, 'array', "loop wfs:PropertyName (1 * wfs:Query)");
-				$tagsWfsPropertyName[] = $element->nodeValue;
+				if ($element->getAttribute('resolve')) DBG::log([$element->getAttribute('resolve'), $element->getAttribute('resolveDepth'), $element->getAttribute('resolvePath')], 'array', "TODO: use wfs:PropertyName @resolve, @resolveDepth, @resolvePath");
+				$value = $element->nodeValue;
+				if (in_array($element->getAttribute('resolve'), ['all', 'local', 'remote'])) {
+					$depth = $element->getAttribute('resolveDepth');
+					if ('*' !== substr($value, -1)) { // TODO: propertyName is not regex
+						if ('*' === $depth) $value .= "/**"; // TODO: resolveDepth="*" - resolve all
+						else if ((int)$depth > 0) $value .= str_repeat("/*", $depth);
+					}
+				}
+				$tagsWfsPropertyName[] = $value;
 			}
 			DBG::log($tagsWfsPropertyName, 'array', "\$tagsWfsPropertyName (1 * wfs:Query)");
 			return array_filter([

+ 42 - 169
SE/se-lib/ProcesHelper.php

@@ -27,12 +27,9 @@ class ProcesHelper {
 	}
 
 	public static function getWskaznikiByIds($ids, $params = array()) {
-		$wskazniki = array();
-		if (empty($ids)) {
-			return $wskazniki;
-		}
-		$db = DB::getDB();
-		$sql = "select
+		if (empty($ids)) return [];
+		$sql = "
+			select
 				clz.*
 				, w.`ID_PROCES`
 				, w.`ID` as CW_ID, w.`TYP` as CW_TYP, w.`OPIS_ZASOB` as OPIS_ZASOB, w.`SORT_PRIO` as CW_SORT_PRIO, w.`ID_PRZYPADEK` as CW_ID_PRZYPADEK
@@ -46,9 +43,9 @@ class ProcesHelper {
 				and w.`A_STATUS` in('WAITING','NORMAL','MONITOR')
 			order by w.`SORT_PRIO` asc, w.`ID` asc
 		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$wskazniki[$r->ID_PROCES][$r->CW_ID] = $r;
+		$wskazniki = array();
+		foreach (DB::getPDO()->fetchAll($sql) as $row) {
+			$wskazniki[ $row['ID_PROCES'] ][ $row['CW_ID'] ] = (object)$row;
 		}
 
 		if (1 == V::get('group_stanowiska', '', $params)) {
@@ -72,110 +69,6 @@ class ProcesHelper {
 		return $wskazniki;
 	}
 
-	public static function get_list_for_user_count($user_groups, $params = array()) {
-		$ret = array();
-		$db = DB::getDB();
-		$sql = self::_get_list_for_user_sql($user_groups, $params, true);
-		$res = $db->query($sql);
-		if ($r = $db->fetch($res)) {
-			$ret = $r->cnt;
-		}
-		return $ret;
-	}
-
-	public static function get_list_for_user($user_groups, $params = array()) {
-		$ret = array();
-		$db = DB::getDB();
-		$sql = self::_get_list_for_user_sql($user_groups, $params);
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[] = $r;
-		}
-		return $ret;
-	}
-
-	/**
-	 * TODO: find user proces
-	 */
-	public static function _get_list_for_user_sql($user_groups, $params = array(), $count = false) {
-		$sql_select = array();
-		$sql_limit = "";
-		$sql_where = "";
-
-		if ($count) {
-			$sql_select[] = "count(1) as cnt";
-		} else {
-			$sql_select[] = "t.*";
-			$sql_limit = V::get('limit', '10', $params);
-			$sql_offset = V::get('offset', '0', $params);
-			$sql_limit = "limit {$sql_limit} offset {$sql_offset}";
-		}
-
-		$sql_select = implode(", ", $sql_select);
-		$sql = "select
-				{$sql_select}
-			from `CRM_PROCES_LOG` as t
-	--			left join `` as p on(p.``=t.``)
-			where
-				{$sql_where}
-			{$sql_limit}
-		";
-		return $sql;
-	}
-
-	/**
-	 * Get allowed Stanowiska ID for given proces.
-	 * @param $proces_id - proces ID
-	 * @returns array of Stanowiska ID
-	 * Search recursively up by p.PARENT_ID, stop when find p.PROCES_INIT or find z.STANOWISKO
-	 */
-	public static function get_allowed_stanowiska_by_proces_id($proces_id) {
-		$ret = array();
-		$proces_id = intval($proces_id);
-		if ($proces_id <= 0) return $ret;
-		// TODO: DB::get_by_id('CRM_PROCES', $proces_id);
-		// TODO: check TYPE=PROCES_INIT -> get STANOWISKO and stop
-		// TODO: find wskazniki STANOWISKO
-		// TODO: if !empty return else recursive - TODO: add recursive limit!
-		$db = DB::getDB();
-		$sql = "select
-				p.`TYPE` as p__TYPE
-				, z.`ID` as z__ID
-				, z.`TYPE` as z__TYPE
-			from `CRM_PROCES` as p
-				left join `CRM_WSKAZNIK` as w on(w.`ID_PROCES`=p.`ID`)
-				left join `CRM_LISTA_ZASOBOW` as z on (z.`ID`=w.`ID_ZASOB`)
-			where
-				p.`ID`='{$proces_id}'
-				and w.`A_STATUS` in('WAITING','NORMAL','MONITOR')
-				and z.`TYPE`='STANOWISKO'
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[] = $r->z__ID;
-		}
-	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">ret: ';print_r($ret);echo'</pre>';
-		return $ret;
-	}
-
-	public static function getProcesByUser($user_name, $groups) {
-		$ret = array();
-		$db = DB::getDB();
-		$sql = "select plog.*
-			from `CRM_PROCES_LOG` as plog
-			where
-				( plog.`A_RECORD_CREATE_AUTHOR`='{$user_name}'
-					or plog.`A_RECORD_UPDATE_AUTHOR`='{$user_name}'
-				)
-			order by plog.ID DESC
-		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[$r->ID] = $r;
-		}
-		return $ret;
-	}
-
 	public static function split_wskazniki_by_table(&$wsk) {
 		$wsk_split = array();
 		echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">wsk: ';print_r($wsk);echo'</pre>';
@@ -198,22 +91,16 @@ class ProcesHelper {
 	 * @param $stanowiska_id - array of integer
 	 */
 	public static function get_procesy_by_stanowiska($stanowiska_id = array()) {
-		$db = DB::getDB();
-		$ret = array();
-		if (empty($stanowiska_id)) {
-			return $ret;
-		}
+		if (empty($stanowiska_id)) return [];
 		$sql_stanowiska_id = array();
 		foreach ($stanowiska_id as $v_id) {
 			$v_id = intval($v_id);
-			if ($v_id > 0) {
-				$sql_stanowiska_id[] = "'{$v_id}'";
-			}
-		}
-		if (empty($sql_stanowiska_id)) {
-			return $ret;
+			if ($v_id > 0) $sql_stanowiska_id[] = "'{$v_id}'";
 		}
-		$sql = "select
+		if (empty($sql_stanowiska_id)) return [];
+		$ret = array();
+		$sql = "
+			select
 				p.`ID`
 				, p.`PARENT_ID`
 				, p.`TYPE`
@@ -235,11 +122,9 @@ class ProcesHelper {
 				and z.`ID` in (" . implode(",", $sql_stanowiska_id) . ")
 			order by p.`TEST_SORT_PRIO` DESC, p.`ID` ASC
 		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[] = $r;
-		}
-		return $ret;
+		return array_map(function ($row) {
+			return (object)$row;
+		}, DB::getPDO()->fetchAll($sql));
 	}
 
 	/**
@@ -247,9 +132,8 @@ class ProcesHelper {
 	 * @return array ID => TEST_SORT_PRIO
 	 */
 	public static function get_procesy_init_list_order() {
-		$ret = array();
-		$db = DB::getDB();
-		$sql = "select
+		$sql = "
+			select
 				p.`ID`
 				, p.`TEST_SORT_PRIO`
 			from `CRM_PROCES` as p
@@ -258,11 +142,9 @@ class ProcesHelper {
 				and p.`A_STATUS` in('WAITING','NORMAL','MONITOR')
 			order by p.`TEST_SORT_PRIO` DESC, p.`ID` ASC
 		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[$r->ID]= $r->TEST_SORT_PRIO;
-		}
-		return $ret;
+		return array_map(function ($row) {
+			return $row['TEST_SORT_PRIO'];
+		}, DB::getPDO()->fetchAllByKey($sql, 'ID'));
 	}
 
 	/**
@@ -270,46 +152,42 @@ class ProcesHelper {
 	 */
 	public static function get_procesy_init_list() {
 		$ret = array();
-		$db = DB::getDB();
-		$sql = "select
+		$sql = "
+			select
 				p.`ID`
 				, p.`PARENT_ID`
 				, p.`TYPE`
 				, p.`DESC`
 				, p.`TEST_SORT_PRIO`
---				, w.`ID` as w__ID
---				, w.`OPIS_ZASOB` as w__OPIS_ZASOB
---				, z.`ID` as z__ID
+		--		, w.`ID` as w__ID
+		--		, w.`OPIS_ZASOB` as w__OPIS_ZASOB
+		--		, z.`ID` as z__ID
 				, cps.`path`
 				, p.`TEST_SORT_PRIO`
 				, p.`SORT_PRIO`
 			from `CRM_PROCES` as p
---				left join `CRM_WSKAZNIK` as w on(w.`ID_PROCES`=p.`ID`)
---				left join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=w.`ID_ZASOB`)
+		--		left join `CRM_WSKAZNIK` as w on(w.`ID_PROCES`=p.`ID`)
+		--		left join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=w.`ID_ZASOB`)
 				left join `_CRM_PROCES_STATS_proc_wiev` as cps on(p.`ID`=cps.`ID`)
 			where
 				p.`TYPE`='PROCES_INIT'
 				and p.`A_STATUS` in('WAITING','NORMAL','MONITOR')
---				and w.`A_STATUS` in('WAITING','NORMAL','MONITOR')
---				and w.`ID_PRZYPADEK`=1
---				and z.`A_STATUS` in('WAITING','NORMAL','MONITOR')
---				and z.`TYPE`='STANOWISKO'
---				and z.`ID` is not null
+		--		and w.`A_STATUS` in('WAITING','NORMAL','MONITOR')
+		--		and w.`ID_PRZYPADEK`=1
+		--		and z.`A_STATUS` in('WAITING','NORMAL','MONITOR')
+		--		and z.`TYPE`='STANOWISKO'
+		--		and z.`ID` is not null
 			order by p.`TEST_SORT_PRIO` DESC, p.`ID` ASC
 		";
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$ret[] = $r;
-		}
-		return $ret;
+		return array_map(function ($row) {
+			return (object)$row;
+		}, DB::getPDO()->fetchAll($sql));
 	}
 
 	/**
 	 * Przeniesienie procesu w kolejności w testach.
 	 */
 	public static function proces_init_move($proces_id, $sort_prio_dir) {
-		$db = DB::getDB();
-
 		$proces_list = self::get_procesy_init_list();
 		$proces_list = array_reverse($proces_list);
 
@@ -339,6 +217,7 @@ class ProcesHelper {
 			$wsk_order[$wsk[$proces_id] + 1] = $tmp;
 		}
 		if (empty($wsk_order)) return;
+		$db = DB::getDB();
 		foreach ($wsk_order as $k_sort_prio => $v_proces_id) {
 			$sql = "update `CRM_PROCES` set `TEST_SORT_PRIO`='{$k_sort_prio}' where `ID`='{$v_proces_id}'; ";
 			$db->query($sql);
@@ -347,19 +226,12 @@ class ProcesHelper {
 	}
 
 	public static function proces_flag($proces_id, $goto_id, $flag) {
-		$ret = '';
 		switch ($flag) {
-			case 'GOTO':
-				$ret = '<span style="color:#FF0000">' . "&rarr;" . '</span>' . $goto_id;
-				break;
-			case 'GOTO_AND_RETURN':
-				$ret = '<span style="color:#FF0000">' . "&rarr;" . '</span>' . $goto_id . '<span style="color:#FF0000">' . "&crarr;" . '</span>';
-				break;
-			case 'FORK':
-				$ret = '<span style="color:#FF0000">' . "&oplus;&rarr;" . '</span>' . $goto_id;
-				break;
+			case 'GOTO': return '<span style="color:#FF0000">' . "&rarr;" . '</span>' . $goto_id;
+			case 'GOTO_AND_RETURN': return '<span style="color:#FF0000">' . "&rarr;" . '</span>' . $goto_id . '<span style="color:#FF0000">' . "&crarr;" . '</span>';
+			case 'FORK': return '<span style="color:#FF0000">' . "&oplus;&rarr;" . '</span>' . $goto_id;
 		}
-		return $ret;
+		return '';
 	}
 
 	/**
@@ -374,7 +246,8 @@ class ProcesHelper {
 		$ret = array();
 		$return_by = V::get('return_by', '', $params);
 		$db = DB::getDB();
-		$sql = "select
+		$sql = "
+			select
 				p.`ID`
 				, p.`IF_TRUE_GOTO`
 				, p.`IF_TRUE_GOTO_FLAG`

+ 25 - 8
SE/se-lib/Route/Storage.php

@@ -1596,16 +1596,33 @@ jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', fun
 			$objFieldAcl = new Schema_SystemObjectFieldStorageAcl();
 			$objFieldAcl->updateCache($namespace);
 
+			DBG::nicePrint([
+				'idInstance' => ACL::getInstanceId($namespace),
+				'rootInstance' => ACL::getRootNamespace($namespace),
+				'conf' => ACL::fetchInstanceConfig($namespace),
+				'table' => ACL::getInstanceTable($namespace),
+			], "dbg");
+
 			{
-				DBG::nicePrint([
-					'idInstance' => ACL::getInstanceId($namespace),
-					'rootInstance' => ACL::getRootNamespace($namespace),
-					'conf' => ACL::fetchInstanceConfig($namespace),
-					'table' => ACL::getInstanceTable($namespace),
-				], "dbg");
-				throw new Exception("TODO...");
+				$item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
+				if ('AntAcl' === $item['_type']) {
+					$dbName = DB::getPDO()->getDatabaseName();
+					$sqlFunBody = ACL::generateIsInstanceFunctionBody($namespace, $item);
+					DBG::nicePrint($sqlFunBody, "\$sqlFunBody");
+					DB::getPDO()->execSql(" DROP FUNCTION IF EXISTS `{$dbName}`.`isInstance_{$namespace}` ");
+					// CREATE
+					//     [DEFINER = { user | CURRENT_USER }]
+					//     FUNCTION sp_name ([func_parameter[,...]])
+					//     RETURNS type
+					//     [characteristic ...] routine_body
+					DB::getPDO()->execSql("
+						CREATE DEFINER=`root`@`localhost`
+						FUNCTION `{$dbName}`.`isInstance_{$namespace}` ( pk INT(11) )
+						RETURNS TINYINT(1)
+						{$sqlFunBody}
+					");
+				}
 			}
-
 		} catch (Exception $e) {
 			UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
 			DBG::log($e);

+ 97 - 2
SE/se-lib/Route/Storage/AclStruct.php

@@ -658,7 +658,7 @@ class Route_Storage_AclStruct extends RouteBase {
 		$thisGetLink = [ $this, 'getLink' ];
 		{ // not installed ref
 			$refFields = array_filter($item['field'], function ($field) {
-				return 'ref:' === substr($field['xsdType'], 0, 4);
+				return ('ref:' === substr($field['xsdType'], 0, 4) && $field['isActive']);
 			});
 			UI::table([
 				'caption' => UI::h('span', [], "Obiekty powiązane (TODO backRef)"),
@@ -782,8 +782,65 @@ class Route_Storage_AclStruct extends RouteBase {
 				unset($tblItem['objectNamespace']);
 				unset($tblItem['fieldNamespace']);
 				return $tblItem;
-			}, $item['field'])
+			}, array_filter($item['field'], function ($field) { return $field['isActive']; }))
 		]);
+		$removedFields = array_filter($item['field'], function ($field) { return !$field['isActive']; });
+		if (!empty($removedFields)) {
+			// echo UI::h('details', [ 'style' => "padding:6px; background-color:#333; color:#fff", 'open' => "open" ], [
+			// 	UI::h('summary', [ 'style' => "padding:0 3px; outline:none; cursor:pointer" ], "WFS Response converted to JSON"),
+			// 	UI::h('pre', [ 'id' => 'wfsResponse', 'style' => "margin:0; font-size:x-small; border-radius:0" ], 'loading...'),
+			echo UI::h('details', [ 'style' => "margin-bottom:12px; padding:6px; background-color:#dedede; color:#000" ], [
+				UI::h('summary', [ 'style' => "padding:0 3px; outline:none; cursor:pointer" ], "Pola w koszu (".count($removedFields).")"),
+				UI::h('table', [ 'style' => "margin:6px 0 0 0; background-color:#fff; font-size:x-small", 'class' => "table table-bordered table-hover table-condensed" ], [
+					UI::h('thead', [], [
+						UI::h('tr', [], [
+							UI::h('th', [], "#"),
+							UI::h('th', [], "namespace"),
+							UI::h('th', [], "xsdType"),
+							UI::h('th', [], "xsdRestrictions"),
+							UI::h('th', [], "appInfo"),
+							UI::h('th', [], "minOccurs"),
+							UI::h('th', [], "maxOccurs"),
+							UI::h('th', [], "isActive"),
+						]),
+					]),
+					UI::h('tbody', [], array_map(function ($field) use ($item, $thisGetLink) {
+						return UI::h('tr', [], [
+							UI::h('td', [], [
+								UI::hButtonAjax("usuń", 'removeFieldFromTrashAjax', [
+									'class' => "btn btn-xs btn-danger",
+									'href' => $thisGetLink('removeFieldFromTrashAjax'),
+									'data' => [
+										'namespace' => $item['namespace'],
+										'fieldNamespace' => $field['namespace'],
+									]
+								])
+							]),
+							UI::h('td', [], $field['fieldNamespace']),
+							UI::h('td', [], $field['xsdType']),
+							UI::h('td', [], $field['xsdRestrictions']),
+							UI::h('td', [], $field['appInfo']),
+							UI::h('td', [], $field['minOccurs']),
+							UI::h('td', [], $field['maxOccurs']),
+							UI::h('td', [], $field['isActive']),
+						]);
+					}, $removedFields)),
+				]),
+			]);
+		}
+		UI::hButtonAjaxOnResponse('removeFieldFromTrashAjax', /* payload, n */ "
+			if (!payload.type) return false
+			jQuery.notify(payload.msg, payload.type)
+			if ('success' == payload.type) {
+				var trJqNode = jQuery(n).closest('tr')
+				var tbodyJqNode = trJqNode.parent()
+				var detailsJqNode = trJqNode.closest('details')
+				trJqNode.remove()
+				if (!tbodyJqNode.children().length) {
+					detailsJqNode.remove()
+				}
+			}
+		");
 		UI::hButtonAjaxOnResponse('addFieldToZasobyAjax', /* payload, n */ "
 			if (!payload.type) return false
 			if (payload.body && payload.body.id && payload.body.id > 0) { // if ('success' == payload.type) {
@@ -952,6 +1009,44 @@ class Route_Storage_AclStruct extends RouteBase {
 		];
 	}
 
+	public function removeFieldFromTrashAjaxAction() {
+		DBG::log($_REQUEST, 'array', '$_REQUEST');
+		Response::sendTryCatchJson(array($this, 'removeFieldFromTrashAjax'), $_REQUEST);
+	}
+	public function removeFieldFromTrashAjax($args) {
+		$namespace = V::get('namespace', '', $args);
+		if (empty($namespace)) throw new HttpException("Missing namespace");
+		$fieldNamespace = V::get('fieldNamespace', '', $args);
+		if (empty($fieldNamespace)) throw new HttpException("Missing fieldNamespace");
+		$fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($fieldNamespace);
+		if (!$fieldItem) throw new HttpException("Field not found '{$fieldNamespace}'", 404);
+		DBG::log($fieldItem, 'array', "\$fieldItem");
+		switch ($fieldItem['xsdType']) {
+			case 'p5:enum': throw new Exception("TODO: remove enum values first"); break; // CRM_#CACHE_ACL_OBJECT_FIELD_enum
+			default: {
+				if ('ref:' === substr($fieldItem['xsdType'], 0, 4)) { // OK, remove
+				} else throw new Exception("TODO: remove xsdType: {$fieldItem['xsdType']}");
+			}
+		}
+
+		DB::getPDO()->execSql("
+			DELETE from `CRM_#CACHE_ACL_OBJECT_FIELD`
+			where namespace = :namespace
+				and objectNamespace = :objectNamespace
+				and _rootTableName = :rootTableName
+				and isActive = 0
+			limit 1
+		", [
+			'namespace' => $fieldItem['namespace'],
+			'objectNamespace' => $fieldItem['objectNamespace'],
+			'rootTableName' => $fieldItem['_rootTableName'],
+		]);
+		return [
+			'type' => "success",
+			'msg' => "Usunięto pole {$fieldItem['fieldNamespace']}",
+		];
+	}
+
 	public function addFieldToZasobyAjaxAction() {
 		DBG::log($_REQUEST, 'array', '$_REQUEST');
 		Response::sendTryCatchJson(array($this, 'addFieldToZasobyAjax'), $_REQUEST);

+ 13 - 0
SE/se-lib/Route/UrlAction/BiAuditGenerate.php

@@ -1,5 +1,15 @@
 <?php
 
+//TODO optimal - akcja aby doruzcic do pracownikow do analizy jakas spolke z kontekstu przegladania KRS - zapytanie przyklad:
+// insert ignore into BI_audit_ENERGA_PRACOWNICY (imiona, nazwisko, pesel, source )
+// select p.imiona, p.nazwisko, p.pesel, 'ENSO_STORA/zadanie' from `BI_audit_KRS_person` as p
+// right join `CRM__#REF_TABLE__12` as r on r.`REMOTE_PRIMARY_KEY`=p.ID
+//  right join BI_audit_KRS as k on k.ID=r.`PRIMARY_KEY`
+//  where k.`nazwa` like '%Stora%enso%';
+
+
+//TODO mozliwosc przerwania przetwarzania
+
 Lib::loadClass('RouteBase');
 Lib::loadClass('FoldersConfig');
 Lib::loadClass('FileUploader');
@@ -58,6 +68,7 @@ class Route_UrlAction_BiAuditGenerate extends RouteBase {
               <td>Pesel</td>
               <td>NIP</td>
               <td>Regon</td>
+              <td>source</td>
             </tr>
           </thead>
           <tbody>
@@ -76,6 +87,8 @@ class Route_UrlAction_BiAuditGenerate extends RouteBase {
               <td><?=$pracownik['pesel']?></td>
               <td><?=$pracownik['nip']?></td>
               <td><?=$pracownik['regon']?></td>
+              <td><?=$pracownik['source']?></td>
+
             </tr>
 <?php
 		}

+ 31 - 3
SE/se-lib/Route/WfsJsRequestPanel.php

@@ -35,6 +35,34 @@ class Route_WfsJsRequestPanel extends RouteBase {
 				"	<wfs:PropertyName>DESC</wfs:PropertyName>",
 				"	<wfs:PropertyName>default_db__x3A__CRM_PROCES:PROCES</wfs:PropertyName>",
 			];
+			$listExampleProp['lvl2-by-@-1'] = [
+				"	<wfs:PropertyName>ID</wfs:PropertyName>",
+				"	<wfs:PropertyName>PARENT_ID</wfs:PropertyName>",
+				"	<wfs:PropertyName>TYPE</wfs:PropertyName>",
+				"	<wfs:PropertyName>DESC</wfs:PropertyName>",
+				"	<wfs:PropertyName resolve=\"all\" resolveDepth=\"1\">default_db__x3A__CRM_PROCES:PROCES</wfs:PropertyName>",
+			];
+			$listExampleProp['lvl2-by-@-2'] = [
+				"	<wfs:PropertyName>ID</wfs:PropertyName>",
+				"	<wfs:PropertyName>PARENT_ID</wfs:PropertyName>",
+				"	<wfs:PropertyName>TYPE</wfs:PropertyName>",
+				"	<wfs:PropertyName>DESC</wfs:PropertyName>",
+				"	<wfs:PropertyName resolve=\"all\" resolveDepth=\"2\">default_db__x3A__CRM_PROCES:PROCES</wfs:PropertyName>",
+			];
+			$listExampleProp['lvl2-by-@-3'] = [
+				"	<wfs:PropertyName>ID</wfs:PropertyName>",
+				"	<wfs:PropertyName>PARENT_ID</wfs:PropertyName>",
+				"	<wfs:PropertyName>TYPE</wfs:PropertyName>",
+				"	<wfs:PropertyName>DESC</wfs:PropertyName>",
+				"	<wfs:PropertyName resolve=\"all\" resolveDepth=\"3\">default_db__x3A__CRM_PROCES:PROCES</wfs:PropertyName>",
+			];
+			$listExampleProp['lvl2-by-@-*'] = [
+				"	<wfs:PropertyName>ID</wfs:PropertyName>",
+				"	<wfs:PropertyName>PARENT_ID</wfs:PropertyName>",
+				"	<wfs:PropertyName>TYPE</wfs:PropertyName>",
+				"	<wfs:PropertyName>DESC</wfs:PropertyName>",
+				"	<wfs:PropertyName resolve=\"all\" resolveDepth=\"*\">default_db__x3A__CRM_PROCES:PROCES</wfs:PropertyName>",
+			];
 			$listExampleProp['lvl2'] = [
 				"	<wfs:PropertyName>ID</wfs:PropertyName>",
 				"	<wfs:PropertyName>PARENT_ID</wfs:PropertyName>",
@@ -84,7 +112,7 @@ class Route_WfsJsRequestPanel extends RouteBase {
 				"	<!-- <wfs:PropertyName>default_db__x3A__CRM_PROCES:PROCES_INIT/**</wfs:PropertyName> -->",
 				"	<wfs:PropertyName>default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK/*</wfs:PropertyName>",
 			];
-			$exampleWfsRequestBody = "<wfs:Query>" . implode("\n", array_merge($listExampleProp['lvl1'], $exampleFltr)) . "</wfs:Query>";
+			$exampleWfsRequestBody = "<wfs:Query>" . "\n" . implode("\n", array_merge($listExampleProp['lvl1'], $exampleFltr)) . "\n" ."</wfs:Query>";
 
 			UI::startContainer();
 
@@ -108,7 +136,7 @@ class Route_WfsJsRequestPanel extends RouteBase {
 			echo UI::h('button', [ 'class' => "btn btn-primary", 'onClick' => "return sendWfsRequest(this)" ], "Wyslij");
 			echo UI::h('div', [ 'style' => "display:inline", 'id' => "wfs-example-btns" ]);
 			echo UI::h('details', [ 'style' => "padding:6px; background-color:#333; color:#fff", 'open' => "open" ], [
-				UI::h('summary', [ 'style' => "padding:0 3px; outline:none; cursor:pointer" ], "WFS Response"),
+				UI::h('summary', [ 'style' => "padding:0 3px; outline:none; cursor:pointer" ], "WFS Response converted to JSON"),
 				UI::h('pre', [ 'id' => 'wfsResponse', 'style' => "margin:0; font-size:x-small; border-radius:0" ], 'loading...'),
 			]);
 			echo UI::h('details', [ 'style' => "padding:6px; background-color:#68cbfd; color:#fff" ], [
@@ -139,7 +167,7 @@ class Route_WfsJsRequestPanel extends RouteBase {
 			]);
 			UI::endContainer();
 			$examples = array_map(function ($props) use ($exampleFltr) {
-				return "<wfs:Query>" . implode("\n", array_merge($props, $exampleFltr)) . "</wfs:Query>";
+				return "<wfs:Query>" . "\n" . implode("\n", array_merge($props, $exampleFltr)) . "\n" . "</wfs:Query>";
 			}, $listExampleProp);
 			echo UI::h('script', [], "
 				var examples = " . json_encode($examples) . ";

+ 430 - 429
SE/se-lib/Schema/SystemObjectFieldStorageAcl.php

@@ -6,120 +6,120 @@ Lib::loadClass('Router');
 
 class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
 
-  public $_simpleSchema = [
-    'root' => [
-      '@namespace' => 'default_objects/SystemObjectField',
-      '@primaryKey' => 'namespace',
-      'idZasob' => [ '@type' => 'xsd:integer' ],
-      'idDatabase' => [ '@type' => 'xsd:integer' ],
-      '_rootTableName' => [ '@type' => 'xsd:string' ],
-      'namespace' => [ '@type' => 'xsd:string' ],
-      'objectNamespace' => [ '@type' => 'xsd:string' ],
-      'fieldNamespace' => [ '@type' => 'xsd:string' ],
-      'xsdType' => [ '@type' => 'xsd:string' ],
-      'xsdRestrictions' => [ '@type' => 'xsd:string' ],
-      'appInfo' => [ '@type' => 'xsd:string' ],
-      'minOccurs' => [ '@type' => 'xsd:string' ],
-      'maxOccurs' => [ '@type' => 'xsd:string' ], //  '0..unbounded',
-      'isActive' => [ '@type' => 'xsd:integer' ], // installed
-      'description' => [ '@type' => 'xsd:string' ],
-      'isLocal' => [ '@type' => 'xsd:integer', '@comment' => "is in _rootTableName" ],
-      // 'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
-      // 'A_RECORD_CREATE_DATE' => [ '@type' => 'xsd:date' , '@label' => 'utworzono' ],
-      // 'A_RECORD_UPDATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'zaktualizował' ],
-      // 'A_RECORD_UPDATE_DATE' => [ '@type' => 'xsd:date', '@label' => 'zaktualizowano' ],
-    ]
-  ];
-  // public $_rootTableName = 'CRM_LISTA_ZASOBOW';
-  public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT_FIELD';
-  public $_version = '1';
+	public $_simpleSchema = [
+		'root' => [
+			'@namespace' => 'default_objects/SystemObjectField',
+			'@primaryKey' => 'namespace',
+			'idZasob' => [ '@type' => 'xsd:integer' ],
+			'idDatabase' => [ '@type' => 'xsd:integer' ],
+			'_rootTableName' => [ '@type' => 'xsd:string' ],
+			'namespace' => [ '@type' => 'xsd:string' ],
+			'objectNamespace' => [ '@type' => 'xsd:string' ],
+			'fieldNamespace' => [ '@type' => 'xsd:string' ],
+			'xsdType' => [ '@type' => 'xsd:string' ],
+			'xsdRestrictions' => [ '@type' => 'xsd:string' ],
+			'appInfo' => [ '@type' => 'xsd:string' ],
+			'minOccurs' => [ '@type' => 'xsd:string' ],
+			'maxOccurs' => [ '@type' => 'xsd:string' ], //	'0..unbounded',
+			'isActive' => [ '@type' => 'xsd:integer' ], // installed
+			'description' => [ '@type' => 'xsd:string' ],
+			'isLocal' => [ '@type' => 'xsd:integer', '@comment' => "is in _rootTableName" ],
+			// 'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
+			// 'A_RECORD_CREATE_DATE' => [ '@type' => 'xsd:date' , '@label' => 'utworzono' ],
+			// 'A_RECORD_UPDATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'zaktualizował' ],
+			// 'A_RECORD_UPDATE_DATE' => [ '@type' => 'xsd:date', '@label' => 'zaktualizowano' ],
+		]
+	];
+	// public $_rootTableName = 'CRM_LISTA_ZASOBOW';
+	public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT_FIELD';
+	public $_version = '1';
 
-  public function updateCache($namespace = null) {
-    DBG::simpleLog('schema', "SystemObjectField::updateCache({$namespace})...");
-    // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
-    DB::getPDO()->execSql("
-      create table if not exists `{$this->_rootTableName}` (
-        `namespace` varchar(255) DEFAULT '',
-        `fieldNamespace` varchar(255) DEFAULT '',
-        `idZasob` int(11) DEFAULT NULL,
-        `idDatabase` int(11) NOT NULL,
-        `_rootTableName` varchar(255) DEFAULT '',
-        `objectNamespace` varchar(255) DEFAULT '',
-        `xsdType` varchar(255) DEFAULT '',
-        `xsdRestrictions` varchar(1000) DEFAULT '',
-        `appInfo` varchar(1000) DEFAULT '',
-        `minOccurs` int(11) DEFAULT '0',
-        `maxOccurs` varchar(11) DEFAULT '1' COMMENT '0..unbounded',
-        `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
-        `description` varchar(255) DEFAULT '',
-        `isLocal` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'is in _rootTableName',
-        UNIQUE KEY `idZasob` (idZasob),
-        PRIMARY KEY (`namespace`),
-        KEY `isActive` (isActive)
-      ) ENGINE=MyISAM  DEFAULT CHARSET=latin2
-    ");
-    try {
-      DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `appInfo` VARCHAR(1000) NOT NULL DEFAULT '' AFTER `xsdRestrictions` ");
-    } catch (Exception $e) {
-      DBG::log($e);
-    }
-    try {
-      DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `isLocal` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'is in _rootTableName' AFTER `description` ");
-    } catch (Exception $e) {
-      DBG::log($e);
-    }
-    // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}_enum` ");// TODO: DBG
-    DB::getPDO()->execSql("
-      create table if not exists `{$this->_rootTableName}_enum` (
-        `namespace` varchar(255) DEFAULT '' COMMENT 'concat obj ns / field ns / value',
-        `fieldNamespace` varchar(255) DEFAULT '',
-        `objectNamespace` varchar(255) DEFAULT '',
-        `value` varchar(255) DEFAULT '',
-        `label` varchar(255) DEFAULT '',
-        `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
-        KEY `objectNamespace` (`objectNamespace`),
-        KEY `fieldNamespace` (`fieldNamespace`),
-        KEY `isActive` (isActive)
-      ) ENGINE=MyISAM  DEFAULT CHARSET=latin2
-    ");
+	public function updateCache($namespace = null) {
+		DBG::simpleLog('schema', "SystemObjectField::updateCache({$namespace})...");
+		// DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
+		DB::getPDO()->execSql("
+			create table if not exists `{$this->_rootTableName}` (
+				`namespace` varchar(255) DEFAULT '',
+				`fieldNamespace` varchar(255) DEFAULT '',
+				`idZasob` int(11) DEFAULT NULL,
+				`idDatabase` int(11) NOT NULL,
+				`_rootTableName` varchar(255) DEFAULT '',
+				`objectNamespace` varchar(255) DEFAULT '',
+				`xsdType` varchar(255) DEFAULT '',
+				`xsdRestrictions` varchar(1000) DEFAULT '',
+				`appInfo` varchar(1000) DEFAULT '',
+				`minOccurs` int(11) DEFAULT '0',
+				`maxOccurs` varchar(11) DEFAULT '1' COMMENT '0..unbounded',
+				`isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
+				`description` varchar(255) DEFAULT '',
+				`isLocal` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'is in _rootTableName',
+				UNIQUE KEY `idZasob` (idZasob),
+				PRIMARY KEY (`namespace`),
+				KEY `isActive` (isActive)
+			) ENGINE=MyISAM DEFAULT CHARSET=latin2
+		");
+		try {
+			DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `appInfo` VARCHAR(1000) NOT NULL DEFAULT '' AFTER `xsdRestrictions` ");
+		} catch (Exception $e) {
+			DBG::log($e);
+		}
+		try {
+			DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `isLocal` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'is in _rootTableName' AFTER `description` ");
+		} catch (Exception $e) {
+			DBG::log($e);
+		}
+		// DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}_enum` ");// TODO: DBG
+		DB::getPDO()->execSql("
+			create table if not exists `{$this->_rootTableName}_enum` (
+				`namespace` varchar(255) DEFAULT '' COMMENT 'concat obj ns / field ns / value',
+				`fieldNamespace` varchar(255) DEFAULT '',
+				`objectNamespace` varchar(255) DEFAULT '',
+				`value` varchar(255) DEFAULT '',
+				`label` varchar(255) DEFAULT '',
+				`isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
+				KEY `objectNamespace` (`objectNamespace`),
+				KEY `fieldNamespace` (`fieldNamespace`),
+				KEY `isActive` (isActive)
+			) ENGINE=MyISAM DEFAULT CHARSET=latin2
+		");
 
-	if (!$namespace) return;
+		if (!$namespace) return;
 
-    DB::getPDO()->update($this->_rootTableName, 'objectNamespace', $namespace, ['isActive' => 0]);
-    DB::getPDO()->update("{$this->_rootTableName}_enum", 'objectNamespace', $namespace, ['isActive' => 0]);
-    $sysObjectStorage = SchemaFactory::loadDefaultObject('SystemObject');
-    if (!$namespace) throw new Exception("Missing namespace '{$namespace}'");
-    $objectItem = $sysObjectStorage->getItem($namespace);
-    DBG::nicePrint($objectItem, '$objectItem');
-    DBG::log($objectItem, 'array', '$objectItem');
+		DB::getPDO()->update($this->_rootTableName, 'objectNamespace', $namespace, ['isActive' => 0]);
+		DB::getPDO()->update("{$this->_rootTableName}_enum", 'objectNamespace', $namespace, ['isActive' => 0]);
+		$sysObjectStorage = SchemaFactory::loadDefaultObject('SystemObject');
+		if (!$namespace) throw new Exception("Missing namespace '{$namespace}'");
+		$objectItem = $sysObjectStorage->getItem($namespace);
+		DBG::nicePrint($objectItem, '$objectItem');
+		DBG::log($objectItem, 'array', '$objectItem');
 
-    switch ($objectItem['_type']) {
-      case 'AntAcl': $this->updateCacheAntAcl($objectItem); break;
-      case 'TableAcl': $this->updateCacheTableAcl($objectItem); break;
-      default: throw new Exception("TODO: Not Implemented type '{$objectItem['_type']}'");
-    }
-    // TODO: mv from methods: SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
-    //   'namespace' => $item['namespace'],
-    //   'isStructInstalled' => 1
-    // ]);
-    $dbName = DB::getPDO()->getDatabaseName();
-    DB::getPDO()->execSql("
-      update `{$this->_rootTableName}` t
-      set t.isLocal = IF(
-        ( select c.COLUMN_NAME
-          from information_schema.COLUMNS c
-          where c.COLUMN_NAME = t.fieldNamespace
-            and c.TABLE_SCHEMA = '{$dbName}'
-            and c.TABLE_NAME = '{$objectItem['_rootTableName']}'
-          limit 1
-        ) is null
-        , 0, 1)
-      where t.objectNamespace = '{$objectItem['namespace']}'
-        and t._rootTableName = '{$objectItem['_rootTableName']}'
-    ");
-  }
+		switch ($objectItem['_type']) {
+			case 'AntAcl': $this->updateCacheAntAcl($objectItem); break;
+			case 'TableAcl': $this->updateCacheTableAcl($objectItem); break;
+			default: throw new Exception("TODO: Not Implemented type '{$objectItem['_type']}'");
+		}
+		// TODO: mv from methods: SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
+		// 'namespace' => $item['namespace'],
+		// 'isStructInstalled' => 1
+		// ]);
+		$dbName = DB::getPDO()->getDatabaseName();
+		DB::getPDO()->execSql("
+			update `{$this->_rootTableName}` t
+			set t.isLocal = IF(
+				(	select c.COLUMN_NAME
+					from information_schema.COLUMNS c
+					where c.COLUMN_NAME = t.fieldNamespace
+						and c.TABLE_SCHEMA = '{$dbName}'
+						and c.TABLE_NAME = '{$objectItem['_rootTableName']}'
+					limit 1
+				) is null
+			, 0, 1)
+			where t.objectNamespace = '{$objectItem['namespace']}'
+			and t._rootTableName = '{$objectItem['_rootTableName']}'
+		");
+	}
 
-  public function updateCacheAntAcl($item) {
+	public function updateCacheAntAcl($item) {
 		Lib::loadClass('AntAclBase');
 		$antAclPath = APP_PATH_SCHEMA . DS . 'ant-object' . DS . str_replace(['__x3A__', ':'], ['.', '/'], $item['typeName']);
 		if (!file_exists("{$antAclPath}/build.xml")) throw new Exception("Ant build file not exists");
@@ -151,74 +151,74 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
 			DBG::nicePrint($n, 'TODO: parse complexType');
 			// complexType/sequence/element
 			// complexType/complexContent/extension[base=...]/sequence/element
-      switch ($n[2][0][0]) {
-        case 'xs:sequence':
-        case 'xsd:sequence': $xsdType['struct'] = XML::findFieldsFromSequence($schema, $n[2][0]); break;
-        case 'xs:complexContent':
-        case 'xsd:complexContent': $xsdType['struct'] = XML::findFieldsFromComplexContent($schema, $n[2][0]); break;
-        case 'xs:annotation':
-        case 'xsd:annotation': {
-          switch ($n[2][1][0]) {
-            case 'xs:sequence':
-            case 'xsd:sequence': $xsdType['struct'] = XML::findFieldsFromSequence($schema, $n[2][1]); break;
-            case 'xs:complexContent':
-            case 'xsd:complexContent': $xsdType['struct'] = XML::findFieldsFromComplexContent($schema, $n[2][1]); break;
-          }
-        } break;
-      }
+			switch ($n[2][0][0]) {
+				case 'xs:sequence':
+				case 'xsd:sequence': $xsdType['struct'] = XML::findFieldsFromSequence($schema, $n[2][0]); break;
+				case 'xs:complexContent':
+				case 'xsd:complexContent': $xsdType['struct'] = XML::findFieldsFromComplexContent($schema, $n[2][0]); break;
+				case 'xs:annotation':
+				case 'xsd:annotation': {
+					switch ($n[2][1][0]) {
+						case 'xs:sequence':
+						case 'xsd:sequence': $xsdType['struct'] = XML::findFieldsFromSequence($schema, $n[2][1]); break;
+						case 'xs:complexContent':
+						case 'xsd:complexContent': $xsdType['struct'] = XML::findFieldsFromComplexContent($schema, $n[2][1]); break;
+					}
+				} break;
+			}
 			// if ($n[2][0][0] != 'xsd:complexContent') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent'");
 		}
 
 		DBG::nicePrint($xsdType, '$xsdType');
-    if (empty($xsdType['struct'])) throw new Exception("Field list not found for '{$item['namespace']}'");
-    foreach ($xsdType['struct'] as $fieldName => $x) {
-      $listEnum = [];
-      if (!empty($x['restrictions']['enumeration'])) {
-        $listEnum = $x['restrictions']['enumeration'];
-        unset($x['restrictions']['enumeration']);
-      }
-      DB::getPDO()->insertOrUpdate($this->_rootTableName, [
-        'namespace' => "{$item['namespace']}/{$fieldName}",
-        'objectNamespace' => $item['namespace'],
-        'idDatabase' => $item['idDatabase'],
-        '_rootTableName' => $item['_rootTableName'],
-        'fieldNamespace' => $fieldName,
-        'xsdType' => $x['type'],
-        'xsdRestrictions' => json_encode($x['restrictions']),
-        'appInfo' => json_encode($x['appInfo']),
-        'minOccurs' => $x['minOccurs'],
-        'maxOccurs' => $x['maxOccurs'],
-        'isActive' => 1
-      ]);
-      if (!empty($listEnum)) {
-        DBG::nicePrint($listEnum, '$listEnum');
-        foreach ($listEnum as $value => $label) {
-          DB::getPDO()->insertOrUpdate("{$this->_rootTableName}_enum", [
-            'namespace' => "{$item['namespace']}/{$fieldName}/@{$value}",
-            'fieldNamespace' => $fieldName,
-            'objectNamespace' => $item['namespace'],
-            'value' => $value,
-            'label' => $label,
-            'isActive' => 1
-          ]);
-        }
-      }
-    }
-    SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
-      'namespace' => $item['namespace'],
-      'isStructInstalled' => 1
-    ]);
-    $zasobTableName = substr($item['objectNamespace'], strlen('default_db/'));
+		if (empty($xsdType['struct'])) throw new Exception("Field list not found for '{$item['namespace']}'");
+		foreach ($xsdType['struct'] as $fieldName => $x) {
+			$listEnum = [];
+			if (!empty($x['restrictions']['enumeration'])) {
+				$listEnum = $x['restrictions']['enumeration'];
+				unset($x['restrictions']['enumeration']);
+			}
+			DB::getPDO()->insertOrUpdate($this->_rootTableName, [
+				'namespace' => "{$item['namespace']}/{$fieldName}",
+				'objectNamespace' => $item['namespace'],
+				'idDatabase' => $item['idDatabase'],
+				'_rootTableName' => $item['_rootTableName'],
+				'fieldNamespace' => $fieldName,
+				'xsdType' => $x['type'],
+				'xsdRestrictions' => json_encode($x['restrictions']),
+				'appInfo' => json_encode($x['appInfo']),
+				'minOccurs' => $x['minOccurs'],
+				'maxOccurs' => $x['maxOccurs'],
+				'isActive' => 1
+			]);
+			if (!empty($listEnum)) {
+				DBG::nicePrint($listEnum, '$listEnum');
+				foreach ($listEnum as $value => $label) {
+					DB::getPDO()->insertOrUpdate("{$this->_rootTableName}_enum", [
+						'namespace' => "{$item['namespace']}/{$fieldName}/@{$value}",
+						'fieldNamespace' => $fieldName,
+						'objectNamespace' => $item['namespace'],
+						'value' => $value,
+						'label' => $label,
+						'isActive' => 1
+					]);
+				}
+			}
+		}
+		SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
+			'namespace' => $item['namespace'],
+			'isStructInstalled' => 1
+		]);
+		$zasobTableName = substr($item['objectNamespace'], strlen('default_db/'));
 		$zasobTableName = (false !== strpos($zasobTableName, '/'))
-			? $item['objectNamespace']
-			: $zasobTableName;
-    DB::getPDO()->execSql("
-      update `{$this->_rootTableName}` t
-        join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}')
-        join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
-      set t.idZasob = z.ID
-      where t.objectNamespace = '{$item['namespace']}'
-    ");
+		?	$item['objectNamespace']
+		:	$zasobTableName;
+		DB::getPDO()->execSql("
+			update `{$this->_rootTableName}` t
+			join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}')
+			join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
+			set t.idZasob = z.ID
+			where t.objectNamespace = '{$item['namespace']}'
+		");
 
 		{// TODO: DBG
 			DBG::nicePrint($schema, '$schema');
@@ -233,136 +233,136 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
 			echo UI::h('pre', ['style' => 'max-height:400px; overflow:scroll'], htmlspecialchars(ob_get_clean()));
 		}
 	}
-  public function updateCacheTableAcl($item) {
-    // TODO: xsdType - convert mysql type to xsdType, xsdRestrictions
-    $xsdInfo = [];
-    Lib::loadClass('SchemaHelper');
-    $dbName = DB::getPDO()->getDatabaseName();
-    $mysqlTypes = DB::getPDO()->fetchAll("
-      select c.COLUMN_NAME, c.COLUMN_TYPE, c.DATA_TYPE, c.IS_NULLABLE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.NUMERIC_SCALE
-      from `information_schema`.`COLUMNS` c
-      where c.TABLE_SCHEMA = '{$dbName}'
-        and c.TABLE_NAME = '{$item['_rootTableName']}'
-    ");
-    foreach ($mysqlTypes as $mysqlType) {
-      $xsdInfo[ $mysqlType['COLUMN_NAME'] ] = SchemaHelper::convertMysqlTypeToSchemaXsd($mysqlType);
-    }
-    DBG::nicePrint($xsdInfo, '$xsdInfo');
+	public function updateCacheTableAcl($item) {
+		// TODO: xsdType - convert mysql type to xsdType, xsdRestrictions
+		$xsdInfo = [];
+		Lib::loadClass('SchemaHelper');
+		$dbName = DB::getPDO()->getDatabaseName();
+		$mysqlTypes = DB::getPDO()->fetchAll("
+			select c.COLUMN_NAME, c.COLUMN_TYPE, c.DATA_TYPE, c.IS_NULLABLE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.NUMERIC_SCALE
+			from `information_schema`.`COLUMNS` c
+			where c.TABLE_SCHEMA = '{$dbName}'
+				and c.TABLE_NAME = '{$item['_rootTableName']}'
+		");
+		foreach ($mysqlTypes as $mysqlType) {
+			$xsdInfo[ $mysqlType['COLUMN_NAME'] ] = SchemaHelper::convertMysqlTypeToSchemaXsd($mysqlType);
+		}
+		DBG::nicePrint($xsdInfo, '$xsdInfo');
 
-    foreach ($xsdInfo as $fieldName => $x) {
-      $listEnum = [];
-      if (!empty($x['restrictions']['enumeration'])) {
-        $listEnum = $x['restrictions']['enumeration'];
-        unset($x['restrictions']['enumeration']);
-      }
-      DB::getPDO()->insertOrUpdate($this->_rootTableName, [
-        'namespace' => "{$item['namespace']}/{$fieldName}",
-        'fieldNamespace' => $fieldName,
-        'isActive' => 1,
-        'idDatabase' => $item['idDatabase'],
-        '_rootTableName' => $item['_rootTableName'],
-        'objectNamespace' => $item['namespace'],
-        'xsdType' => $x['type'],
-        'xsdRestrictions' => json_encode($x['restrictions']),
-        'appInfo' => json_encode([]),
-      ]);
-      if (!empty($listEnum)) {
-        DBG::nicePrint($listEnum, '$listEnum');
-        foreach ($listEnum as $value => $label) {
-          DB::getPDO()->insertOrUpdate("{$this->_rootTableName}_enum", [
-            'namespace' => "{$item['namespace']}/{$fieldName}/@{$value}",
-            'fieldNamespace' => $fieldName,
-            'objectNamespace' => $item['namespace'],
-            'value' => $value,
-            'label' => $label,
-            'isActive' => 1
-          ]);
-        }
-      }
-    }
-    SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
-      'namespace' => $item['namespace'],
-      'isStructInstalled' => 1
-    ]);
-    $zasobTableName = substr($item['namespace'], strlen('default_db/'));
+		foreach ($xsdInfo as $fieldName => $x) {
+			$listEnum = [];
+			if (!empty($x['restrictions']['enumeration'])) {
+				$listEnum = $x['restrictions']['enumeration'];
+				unset($x['restrictions']['enumeration']);
+			}
+			DB::getPDO()->insertOrUpdate($this->_rootTableName, [
+				'namespace' => "{$item['namespace']}/{$fieldName}",
+				'fieldNamespace' => $fieldName,
+				'isActive' => 1,
+				'idDatabase' => $item['idDatabase'],
+				'_rootTableName' => $item['_rootTableName'],
+				'objectNamespace' => $item['namespace'],
+				'xsdType' => $x['type'],
+				'xsdRestrictions' => json_encode($x['restrictions']),
+				'appInfo' => json_encode([]),
+			]);
+			if (!empty($listEnum)) {
+				DBG::nicePrint($listEnum, '$listEnum');
+				foreach ($listEnum as $value => $label) {
+					DB::getPDO()->insertOrUpdate("{$this->_rootTableName}_enum", [
+						'namespace' => "{$item['namespace']}/{$fieldName}/@{$value}",
+						'fieldNamespace' => $fieldName,
+						'objectNamespace' => $item['namespace'],
+						'value' => $value,
+						'label' => $label,
+						'isActive' => 1
+					]);
+				}
+			}
+		}
+		SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
+			'namespace' => $item['namespace'],
+			'isStructInstalled' => 1
+		]);
+		$zasobTableName = substr($item['namespace'], strlen('default_db/'));
 		$zasobTableName = (false !== strpos($zasobTableName, '/'))
-			? $item['namespace']
-			: $zasobTableName;
-    DB::getPDO()->execSql("
-      update `{$this->_rootTableName}` t
-        join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}' and zp.PARENT_ID = {$item['idDatabase']})
-        join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
-      set t.idZasob = z.ID
-      where t.objectNamespace = '{$item['namespace']}'
-    ");
+		?	$item['namespace']
+		:	$zasobTableName;
+		DB::getPDO()->execSql("
+			update `{$this->_rootTableName}` t
+			join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}' and zp.PARENT_ID = {$item['idDatabase']})
+			join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
+			set t.idZasob = z.ID
+			where t.objectNamespace = '{$item['namespace']}'
+		");
 
-    $struct = $this->getItems([
-      '__backRef' => [
-        'namespace' => 'default_objects/SystemObject',
-        'primaryKey' => $item['namespace']
-      ]
-    ]);
-    DBG::nicePrint($struct, '$struct');
+		$struct = $this->getItems([
+			'__backRef' => [
+				'namespace' => 'default_objects/SystemObject',
+				'primaryKey' => $item['namespace']
+			]
+		]);
+		DBG::nicePrint($struct, '$struct');
 
-    {// TODO: DBG
-      $schema = ['xsd:schema', [
-        'xmlns:xsd' => "http://www.w3.org/2001/XMLSchema",
-        'xmlns:gml' => "http://www.opengis.net/gml",
-        'xmlns:p5' => "https://biuro.biall-net.pl/wfs",
-        'xmlns:default_db' => "https://biuro.biall-net.pl/wfs/default_db",
-        'xmlns:default_objects' => "https://biuro.biall-net.pl/wfs/default_objects",
-        'elementFormDefault' => "qualified",
-        'version' => "1.0.0",
-      ], []];
-      Lib::loadClass('Api_WfsNs');
-      $tnsUri = Api_WfsNs::getNsUri($item['nsPrefix']);
-      $schema[1]['xmlns:' . Api_WfsNs::getNsPrefix($tnsUri)] = $tnsUri;
-      $schema[1]['targetNamespace'] = $tnsUri;
-      $schema[2][] = ['xsd:import', ['namespace'=>"http://www.opengis.net/gml", 'schemaLocation'=>"https://biuro.biall-net.pl/dev-pl/se-master/schema/gml/2.1.2/feature.xsd"], null];
-      $schema[2][] = ['xsd:complexType', [ 'name'=> $item['name'] . "Type" ], [
-        [ 'xsd:complexContent', [], [
-          [ 'xsd:extension', ['base'=>"gml:AbstractFeatureType"], [
-            [ 'xsd:sequence', [], array_map(function ($field) {
-              $attrs = [
-                'name' => $field['fieldNamespace'],
-                // <xsd:element minOccurs="1" maxOccurs="1" name="ID" type="xsd:integer" nillable="true"/>
-                'minOccurs' => $field['minOccurs'],
-                'maxOccurs' => $field['maxOccurs'],
-              ];
-              $childrens = null;
-              $restrictions = [];
-              foreach ($this->getXsdRestrictionsValue($field) as $k => $v) {
-                if ('enumeration' == $k) {
-                  foreach ($v as $enumValue) {
-                    $restrictions[] = [ 'xsd:enumeration', [ 'value' => $enumValue ], null ];
-                  }
-                } else if ('maxLength' == $k) {
-                  $restrictions[] = [ 'xsd:maxLength', [ 'value' => $v ], null ];
-                } else if ('totalDigits' == $k) {
-                  $restrictions[] = [ 'xsd:totalDigits', [ 'value' => $v ], null ];
-                } else if ('fractionDigits' == $k) {
-                  $restrictions[] = [ 'xsd:fractionDigits', [ 'value' => $v ], null ];
-                } else if ('nillable' == $k) {
-                  if ($v) $attrs['nillable'] = "true";
-                } else {
-                  DBG::log(['TODO' => $k, $v]);
-                }
-              }
-              if (!empty($restrictions)) {
-                $childrens = [
-                  [ 'xsd:simpleType', [], [
-                    [ 'xsd:restriction', [ 'base' => $field['xsdType'] ], $restrictions ]
-                  ]]
-                ];
-              } else {
-                $attrs['type'] = $field['xsdType'];
-              }
-              return [ 'xsd:element', $attrs, $childrens ];
-            }, $struct)]
-          ]]
-        ]]
-      ]];
-      $schema[2][] = ['xsd:element', [ 'name' => $item['name'], 'type' => "{$item['nsPrefix']}:{$item['name']}Type", 'substitutionGroup' => "gml:_Feature" ], null];
+		{// TODO: DBG
+			$schema = ['xsd:schema', [
+				'xmlns:xsd' => "http://www.w3.org/2001/XMLSchema",
+				'xmlns:gml' => "http://www.opengis.net/gml",
+				'xmlns:p5' => "https://biuro.biall-net.pl/wfs",
+				'xmlns:default_db' => "https://biuro.biall-net.pl/wfs/default_db",
+				'xmlns:default_objects' => "https://biuro.biall-net.pl/wfs/default_objects",
+				'elementFormDefault' => "qualified",
+				'version' => "1.0.0",
+			], []];
+			Lib::loadClass('Api_WfsNs');
+			$tnsUri = Api_WfsNs::getNsUri($item['nsPrefix']);
+			$schema[1]['xmlns:' . Api_WfsNs::getNsPrefix($tnsUri)] = $tnsUri;
+			$schema[1]['targetNamespace'] = $tnsUri;
+			$schema[2][] = ['xsd:import', ['namespace'=>"http://www.opengis.net/gml", 'schemaLocation'=>"https://biuro.biall-net.pl/dev-pl/se-master/schema/gml/2.1.2/feature.xsd"], null];
+			$schema[2][] = ['xsd:complexType', [ 'name'=> $item['name'] . "Type" ], [
+				[ 'xsd:complexContent', [], [
+					[ 'xsd:extension', ['base'=>"gml:AbstractFeatureType"], [
+						[ 'xsd:sequence', [], array_map(function ($field) {
+							$attrs = [
+								'name' => $field['fieldNamespace'],
+								// <xsd:element minOccurs="1" maxOccurs="1" name="ID" type="xsd:integer" nillable="true"/>
+								'minOccurs' => $field['minOccurs'],
+								'maxOccurs' => $field['maxOccurs'],
+							];
+							$childrens = null;
+							$restrictions = [];
+							foreach ($this->getXsdRestrictionsValue($field) as $k => $v) {
+								if ('enumeration' == $k) {
+									foreach ($v as $enumValue) {
+										$restrictions[] = [ 'xsd:enumeration', [ 'value' => $enumValue ], null ];
+									}
+								} else if ('maxLength' == $k) {
+									$restrictions[] = [ 'xsd:maxLength', [ 'value' => $v ], null ];
+								} else if ('totalDigits' == $k) {
+									$restrictions[] = [ 'xsd:totalDigits', [ 'value' => $v ], null ];
+								} else if ('fractionDigits' == $k) {
+									$restrictions[] = [ 'xsd:fractionDigits', [ 'value' => $v ], null ];
+								} else if ('nillable' == $k) {
+									if ($v) $attrs['nillable'] = "true";
+								} else {
+									DBG::log(['TODO' => $k, $v]);
+								}
+							}
+							if (!empty($restrictions)) {
+								$childrens = [
+									[ 'xsd:simpleType', [], [
+										[ 'xsd:restriction', [ 'base' => $field['xsdType'] ], $restrictions ]
+									] ]
+								];
+							} else {
+								$attrs['type'] = $field['xsdType'];
+							}
+							return [ 'xsd:element', $attrs, $childrens ];
+						}, $struct) ]
+					] ]
+				] ]
+			] ];
+			$schema[2][] = ['xsd:element', [ 'name' => $item['name'], 'type' => "{$item['nsPrefix']}:{$item['name']}Type", 'substitutionGroup' => "gml:_Feature" ], null];
 
 			DBG::nicePrint($schema, '$schema');
 			Lib::loadClass('Core_XmlWriter');
@@ -375,147 +375,148 @@ class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
 			$xmlWriter->endDocument();
 			echo UI::h('pre', ['style' => 'max-height:400px; overflow:scroll'], htmlspecialchars(ob_get_clean()));
 		}
-  }
+	}
 
-  public function _parseWhere($params = []) {
-    $sqlWhere = [];
-    DBG::log($params, 'array', "SystemObject::_parseWhere");
-    if (!empty($params['__backRef'])) {
-      // '__backRef' => [
-      //     'namespace' => 'default_objects/SystemObject',
-      //     'primaryKey' => 'default_db/TEST_PERMS',
-      //  ),
-      if (empty($params['__backRef']['namespace'])) throw new Exception("Missing refFrom/namespace");
-      if (empty($params['__backRef']['primaryKey'])) throw new Exception("Missing refFrom/primaryKey");
+	public function _parseWhere($params = []) {
+		$sqlWhere = [];
+		DBG::log($params, 'array', "SystemObject::_parseWhere");
+		if (!empty($params['__backRef'])) {
+			// '__backRef' => [
+			//	 'namespace' => 'default_objects/SystemObject',
+			//	 'primaryKey' => 'default_db/TEST_PERMS',
+			//	),
+			if (empty($params['__backRef']['namespace'])) throw new Exception("Missing refFrom/namespace");
+			if (empty($params['__backRef']['primaryKey'])) throw new Exception("Missing refFrom/primaryKey");
 
-      if ('default_objects/SystemObject' != $params['__backRef']['namespace']) throw new Exception("Unsupported refFrom/namespace '{$params['__backRef']['namespace']}'");
-      $sqlWhere[] = "t.objectNamespace = " . DB::getPDO()->quote($params['__backRef']['primaryKey'], PDO::PARAM_INT);
-    }
-    {
-      $filterParams = [];
-      $xsdFields = $this->getXsdTypes();
-      DBG::log($xsdFields);
-      foreach ($params as $k => $v) {
-        if ('f_' != substr($k, 0, 2)) continue;
-        $fieldName = substr($k, 2);
-        if (!array_key_exists($fieldName, $xsdFields)) {
-          // TODO: check query by xpath or use different param prefix
-          throw new Exception("Field '{$fieldName}' not found in '{$this->_namespace}'");
-        }
-        if ('p5:' == substr($xsdFields[$fieldName]['xsdType'], 0, 3)) {
-          continue;
-        }
-        $filterParams[$fieldName] = $v;
-      }
-    }
-    if (!empty($filterParams)) {
-      DBG::log($filterParams, 'array', "SystemObject::_parseWhere TODO \$filterParams");
-      foreach ($filterParams as $fieldName => $value) {
-        if (is_array($value)) {
-          DBG::log($value, 'array', "TODO SystemObject::_parseWhere array value for \$filterParams[{$fieldName}]");
-        } else if (is_scalar($value)) {
-          if ('=' == substr($value, 0, 1)) {
-            $sqlWhere[] = "t.{$fieldName} = " . DB::getPDO()->quote(substr($value, 1), PDO::PARAM_STR);
-          } else {
-            $sqlWhere[] = "t.{$fieldName} like " . DB::getPDO()->quote("%{$value}%", PDO::PARAM_STR);
-          }
-        } else {
-          DBG::log($value, 'array', "BUG SystemObject::_parseWhere unknown type for \$filterParams[{$fieldName}]");
-        }
-      }
-    }
-    return (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : '';
-  }
+			if ('default_objects/SystemObject' != $params['__backRef']['namespace']) throw new Exception("Unsupported refFrom/namespace '{$params['__backRef']['namespace']}'");
+			$sqlWhere[] = "t.objectNamespace = " . DB::getPDO()->quote($params['__backRef']['primaryKey'], PDO::PARAM_INT);
+		}
+		{
+			$filterParams = [];
+			$xsdFields = $this->getXsdTypes();
+			DBG::log($xsdFields);
+			foreach ($params as $k => $v) {
+				if ('f_' != substr($k, 0, 2)) continue;
+				$fieldName = substr($k, 2);
+				if (!array_key_exists($fieldName, $xsdFields)) {
+					// TODO: check query by xpath or use different param prefix
+					throw new Exception("Field '{$fieldName}' not found in '{$this->_namespace}'");
+				}
+				if ('p5:' == substr($xsdFields[$fieldName]['xsdType'], 0, 3)) {
+					continue;
+				}
+				$filterParams[$fieldName] = $v;
+			}
+		}
+		if (!empty($filterParams)) {
+			DBG::log($filterParams, 'array', "SystemObject::_parseWhere TODO \$filterParams");
+			foreach ($filterParams as $fieldName => $value) {
+				if (is_array($value)) {
+					DBG::log($value, 'array', "TODO SystemObject::_parseWhere array value for \$filterParams[{$fieldName}]");
+				} else if (is_scalar($value)) {
+					if ('=' == substr($value, 0, 1)) {
+						$sqlWhere[] = "t.{$fieldName} = " . DB::getPDO()->quote(substr($value, 1), PDO::PARAM_STR);
+					} else {
+						$sqlWhere[] = "t.{$fieldName} like " . DB::getPDO()->quote("%{$value}%", PDO::PARAM_STR);
+					}
+				} else {
+					DBG::log($value, 'array', "BUG SystemObject::_parseWhere unknown type for \$filterParams[{$fieldName}]");
+				}
+			}
+		}
+		return (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : '';
+	}
 
-  public function getTotal($params = []) {
-    $sqlWhere = $this->_parseWhere($params);
-    return DB::getPDO()->fetchValue("
-      select count(1) as cnt
-      from `{$this->_rootTableName}` t
-      {$sqlWhere}
-    ");
-  }
+	public function getTotal($params = []) {
+		$sqlWhere = $this->_parseWhere($params);
+		return DB::getPDO()->fetchValue("
+			select count(1) as cnt
+			from `{$this->_rootTableName}` t
+			{$sqlWhere}
+		");
+	}
 
-  public function getItem($pk, $params = []) {
-    if (!$pk) throw new Exception("Missing primary key '{$this->_namespace}'");
-    $pkField = $this->getSqlPrimaryKeyField();
-    if (!$pkField) throw new Exception("Missing primary key field defined in '{$this->_namespace}'");
-    $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
-    $item = DB::getPDO()->fetchFirst("
-      select t.*
-      from `{$this->_rootTableName}` t
-      where t.`{$pkField}` = {$sqlPk}
-    ");
-    if (!$item) throw new Exception("Item '{$pk}' not exists - type '{$this->_namespace}'");
-    return $this->buildFeatureFromSqlRow($item, $params);
-  }
+	public function getItem($pk, $params = []) {
+		if (!$pk) throw new Exception("Missing primary key '{$this->_namespace}'");
+		$pkField = $this->getSqlPrimaryKeyField();
+		if (!$pkField) throw new Exception("Missing primary key field defined in '{$this->_namespace}'");
+		$sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
+		$item = DB::getPDO()->fetchFirst("
+			select t.*
+			from `{$this->_rootTableName}` t
+			where t.`{$pkField}` = {$sqlPk}
+		");
+		if (!$item) throw new Exception("Item '{$pk}' not exists - type '{$this->_namespace}'");
+		return $this->buildFeatureFromSqlRow($item, $params);
+	}
 
-  public function getItems($params = []) {
-    $sqlWhere = $this->_parseWhere($params);
+	public function getItems($params = []) {
+		$sqlWhere = $this->_parseWhere($params);
 
-    $currSortCol = V::get('order_by', 'idZasob', $params);
-    $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
-    // TODO: validate $currSortCol is in field list
-    // TODO: validate $currSortFlip ('asc' or 'desc')
-    $xsdFields = $this->getXsdTypes();
-    if (!array_key_exists($currSortCol, $xsdFields)) throw new Exception("Field '{$currSortCol}' not found in '{$this->_namespace}'");
-    if (!in_array($currSortFlip, ['asc', 'desc'])) throw new Exception("Sort dir not allowed");
-    $sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
+		$currSortCol = V::get('order_by', 'idZasob', $params);
+		$currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
+		// TODO: validate $currSortCol is in field list
+		// TODO: validate $currSortFlip ('asc' or 'desc')
+		$xsdFields = $this->getXsdTypes();
+		if (!array_key_exists($currSortCol, $xsdFields)) throw new Exception("Field '{$currSortCol}' not found in '{$this->_namespace}'");
+		if (!in_array($currSortFlip, ['asc', 'desc'])) throw new Exception("Sort dir not allowed");
+		$sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
 
-    $limit = V::get('limit', 0, $params, 'int');
-    $limit = ($limit < 0) ? 0 : $limit;
-    $offset = V::get('limitstart', 0, $params, 'int');
-    $offset = ($offset < 0) ? 0 : $offset;
-    $sqlLimit = ($limit > 0)
-      ? "limit {$limit} offset {$offset}"
-      : '';
+		$limit = V::get('limit', 0, $params, 'int');
+		$limit = ($limit < 0) ? 0 : $limit;
+		$offset = V::get('limitstart', 0, $params, 'int');
+		$offset = ($offset < 0) ? 0 : $offset;
+		$sqlLimit = ($limit > 0)
+		?	"limit {$limit} offset {$offset}"
+		:	'';
 
-    return array_map(array($this, 'buildFeatureFromSqlRow'), DB::getPDO()->fetchAll("
-      select t.*
-      from `{$this->_rootTableName}` t
-      {$sqlWhere}
-      {$sqlOrderBy}
-      {$sqlLimit}
-    "));
-  }
+		return array_map(array($this, 'buildFeatureFromSqlRow'), DB::getPDO()->fetchAll("
+			select t.*
+			from `{$this->_rootTableName}` t
+			{$sqlWhere}
+			{$sqlOrderBy}
+			{$sqlLimit}
+		"));
+	}
 
-  public function getXsdRestrictionsValue($item) {
-    $xsdRestrictions = @json_decode($item['xsdRestrictions'], $assoc = true);
-    if (empty($xsdRestrictions)) $xsdRestrictions = [];
-    if (array_key_exists('__DBG__', $xsdRestrictions)) unset($xsdRestrictions['__DBG__']);
-    return $xsdRestrictions;
-  }
+	public function getXsdRestrictionsValue($item) {
+		$xsdRestrictions = @json_decode($item['xsdRestrictions'], $assoc = true);
+		if (empty($xsdRestrictions)) $xsdRestrictions = [];
+		if (array_key_exists('__DBG__', $xsdRestrictions)) unset($xsdRestrictions['__DBG__']);
+		return $xsdRestrictions;
+	}
 
-  public function buildFeatureFromSqlRow($item) {
-    if ('p5:enum' == V::get('xsdType', '', $item)) {
-      $xsdRestrictions = @json_decode($item['xsdRestrictions'], $assoc = true);
-      $xsdRestrictions['enumeration'] = [];
-      foreach (DB::getPDO()->fetchAll("
-        select t.value, t.label
-        from `{$this->_rootTableName}_enum` t
-        where t.objectNamespace = '{$item['objectNamespace']}'
-          and t.fieldNamespace = '{$item['fieldNamespace']}'
-          and t.isActive = 1
-      ") as $enum) {
-        $xsdRestrictions['enumeration'][ $enum['value'] ] = $enum['label'];
-      }
-      $item['xsdRestrictions'] = json_encode($xsdRestrictions);
-    }
-    return $item;
-  }
+	public function buildFeatureFromSqlRow($item) {
+		if ('p5:enum' == V::get('xsdType', '', $item)) {
+			$xsdRestrictions = @json_decode($item['xsdRestrictions'], $assoc = true);
+			$xsdRestrictions['enumeration'] = [];
+			foreach (DB::getPDO()->fetchAll("
+				select t.value, t.label
+				from `{$this->_rootTableName}_enum` t
+				where t.objectNamespace = '{$item['objectNamespace']}'
+					and t.fieldNamespace = '{$item['fieldNamespace']}'
+					and t.isActive = 1
+			") as $enum) {
+				$xsdRestrictions['enumeration'][ $enum['value'] ] = $enum['label'];
+			}
+			$item['xsdRestrictions'] = json_encode($xsdRestrictions);
+		}
+		return $item;
+	}
 
-  public function updateItem($itemPatch) {
-    $pkField = $this->getPrimaryKeyField();
-    $pk = V::get($pkField, null, $itemPatch);
-    if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
-    DBG::log(['updateItem $itemPatch', $itemPatch]);
-    unset($itemPatch[$pkField]);
-    if (empty($itemPatch)) return 0;
-    foreach ($itemPatch as $fieldName => $value) {
-      if ('idZasob' == $fieldName) continue;
-      throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
-    }
-    return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
-  }
+	public function updateItem($itemPatch) {
+		SchemaFactory::loadDefaultObject('SystemObject')->clearGetItemCache();
+		$pkField = $this->getPrimaryKeyField();
+		$pk = V::get($pkField, null, $itemPatch);
+		if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
+		DBG::log(['updateItem $itemPatch', $itemPatch]);
+		unset($itemPatch[$pkField]);
+		if (empty($itemPatch)) return 0;
+		foreach ($itemPatch as $fieldName => $value) {
+			if ('idZasob' == $fieldName) continue;
+			throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
+		}
+		return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
+	}
 
 }

+ 18 - 1
SE/se-lib/Schema/SystemObjectStorageAcl.php

@@ -293,7 +293,23 @@ class Schema_SystemObjectStorageAcl extends Core_AclSimpleSchemaBase {
 		");
 	}
 
+	public function clearGetItemCache($pk = null) {
+		if (!$pk) $this->_cache = [];
+		else if (array_key_exists($pk, $this->_cache)) unset($this->_cache[$pk]);
+	}
 	public function getItem($pk, $params = []) {
+		// TODO: ceche query for: $pk = 'default_db/CRM_PROCES/PROCES', $params = [ 'propertyName' => "*,field" ]
+		if (!$this->_cache) $this->_cache = [];
+		if (!empty($this->_cache) && 1 === count($params) && "*,field" === V::get('propertyName', '', $params)) {
+			if (array_key_exists($pk, $this->_cache)) return $this->_cache[$pk];
+			$this->_cache[$pk] = $this->_getItem($pk, $params);
+		} else {
+			return $this->_getItem($pk, $params);
+		}
+		return $this->_cache[$pk];
+	}
+
+	public function _getItem($pk, $params = []) {
 		if (!$pk) throw new Exception("Missing primary key '{$this->_namespace}'");
 		$pkField = $this->getSqlPrimaryKeyField();
 		if (!$pkField) throw new Exception("Missing primary key field defined in '{$this->_namespace}'");
@@ -366,10 +382,11 @@ class Schema_SystemObjectStorageAcl extends Core_AclSimpleSchemaBase {
 		return $item;
 	}
 
-	public function updateItem($itemPatch) {
+	public function updateItem($itemPatch) { // @required [ 'namespace' => ... ] (primaryKey)
 		$pkField = $this->getPrimaryKeyField();
 		$pk = V::get($pkField, null, $itemPatch);
 		if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
+		$this->clearGetItemCache($pk);
 		DBG::log(['updateItem $itemPatch', $itemPatch]);
 		unset($itemPatch[$pkField]);
 		if (empty($itemPatch)) return 0;

+ 22 - 34
SE/se-lib/TreeListView.php

@@ -1,7 +1,7 @@
 <?php
 
 /**
- * 
+ *
  * DBG: url arg: '&DBG_TF=1'
  */
 class TreeListView {
@@ -26,18 +26,16 @@ class TreeListView {
 		}
 
 		$this->_treeFlat = array();
-		$db = DB::getDB();
-		$sql = "select t.`ID`, t.`{$this->_tblParentField}` as PARENT_ID
+		$sql = "
+			select t.`ID`, t.`{$this->_tblParentField}` as PARENT_ID
 			from `{$this->_tbl}` as t
 			where t.`A_STATUS` in('WAITING','NORMAL')
 			order by t.`{$this->_tblParentField}`, t.`SORT_PRIO`, t.`ID`
 		";
-		if(V::get('DBG_TF', '', $_GET) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			$this->_treeFlat[$r->PARENT_ID][] = $r->ID;
+		foreach (DB::getPDO()->fetchAll($sql) as $row) {
+			$this->_treeFlat[ $row['PARENT_ID'] ][] = $row['ID'];
 		}
-		if(V::get('DBG_TF', '', $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">treeFlatAll (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_treeFlat);echo'</pre>';}
+		DBG::log($this->_treeFlat, 'array', "treeFlat");
 	}
 
 	public function generateListFlat() {
@@ -51,13 +49,13 @@ class TreeListView {
 			2.1						2771 Dodanie nowego klienta Proces mówiący o tym jak dodać nowego k
 			2.1.1						2772 Wprowadź dane klienta Wprowadź wszystkie dane klienta: imię, nazwi
 			2.2						2774 Dodanie numeru telefonu dla istniejącego klienta Proces dodawania nume
-			2.2.1						2773 Wprowadź dane dotyczące nowego numeru telefonu Wypełnij dane z tabeli: 
-			2.2.2						2828 Edytowanie konta klienta Dodawanie dostępu do panelu klienckiego (miejsca  
-		 * 
+			2.2.1						2773 Wprowadź dane dotyczące nowego numeru telefonu Wypełnij dane z tabeli:
+			2.2.2						2828 Edytowanie konta klienta Dodawanie dostępu do panelu klienckiego (miejsca
+		 *
 		 * 1	[2768]	deep:1
 		 * 2	[2770]	deep:1
 		 * 3	[2771]	deep:2
-		 * 
+		 *
 		 */
 
 		$this->_listFlat = array();//  array('ID'=>$id_proces, 'LIST_NRS' => array(1));
@@ -121,42 +119,32 @@ class TreeListView {
 
 	public function fetchData() {
 		$sqlIds = $this->_listIds;
-
-		if (empty($sqlIds)) {
-			return $this->_data;
-		}
-
+		if (empty($sqlIds)) return $this->_data;
 		$sqlGotoIds = array();
-
-		$db = DB::getDB();
-		$sql = "select t.*
+		$sql = "
+			select t.*
 			from `{$this->_tbl}` as t
 			where t.`A_STATUS` in('WAITING','NORMAL')
 				and t.`ID` in(" . implode(",", $sqlIds) . ")
 		";
-		if(V::get('DBG_TF', '', $_GET) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
-		$res = $db->query($sql);
-		while ($r = $db->fetch($res)) {
-			if ($r->IF_TRUE_GOTO > 0) {
-				$sqlGotoIds[] = $r->IF_TRUE_GOTO;
+		foreach (DB::getPDO()->fetchAll($sql) as $row) {
+			if ($row['IF_TRUE_GOTO'] > 0) {
+				$sqlGotoIds[] = $row['IF_TRUE_GOTO'];
 			}
-			$this->_data[$r->ID] = $r;
+			$this->_data[ $row['ID'] ] = (object)$row;
 		}
-
 		if (!empty($sqlGotoIds)) {
-			$sql = "select t.*
+			$sql = "
+				select t.*
 				from `{$this->_tbl}` as t
 				where t.`A_STATUS` in('WAITING','NORMAL')
 					and t.`ID` in(" . implode(",", $sqlGotoIds) . ")
 			";
-			if(V::get('DBG_TF', '', $_GET) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sqlGoto (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
-			$res = $db->query($sql);
-			while ($r = $db->fetch($res)) {
-				$this->_data[$r->ID] = $r;
+			foreach (DB::getPDO()->fetchAll($sql) as $row) {
+				$this->_data[ $row['ID'] ] = (object)$row;
 			}
 		}
-
-		if(V::get('DBG_TF', '', $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">data (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_data);echo'</pre>';}
+		DBG::log($this->_data, 'array', "TreeListView \$data");
 
 		return $this->_data;
 	}

+ 15 - 18
SE/se-lib/UserAcl.php

@@ -468,28 +468,25 @@ class UserAcl {
 	 * List of Proces Init for user (skip filters)
 	 */
 	public function getUserProcesInitList() {// TODO: read from CRM_PROCES_idx_GROUP_to_INIT_VIEW?
-		$userProcesInitList = array();
 		$idUserGroupList = $this->fetchGroups();
+		if (empty($idUserGroupList)) return [];
 		$sqlIdUserGroupList = implode(",", array_keys($idUserGroupList));
-		$sqlIdProcesListSql = <<<SQL
+		$sqlIdProcesListSql = "
 			select gi.`ID_PROCES`
-				from `CRM_PROCES_idx_GROUP_to_PROCES` gi
-				where gi.`ID_GROUP` in({$sqlIdUserGroupList})
-SQL;
-		$fetchUserProcesInitListSql = <<<SQL
+			from `CRM_PROCES_idx_GROUP_to_PROCES` gi
+			where gi.`ID_GROUP` in({$sqlIdUserGroupList})
+		";
+		$sqlFetchUserProcesInitList = "
 			select p.`ID`, p.`DESC`
-				from `CRM_PROCES_idx` i
-					join `CRM_PROCES` p on(p.`ID`=i.`idx_PROCES_INIT_ID`)
-				where i.`ID_PROCES` in({$sqlIdProcesListSql})
-				group by p.`ID`
-				order by p.`SORT_PRIO`
-SQL;
-		$db = DB::getDB();
-		$res = $db->query($fetchUserProcesInitListSql);
-		while ($r = $db->fetch($res)) {
-			$userProcesInitList[$r->ID] = $r->DESC;
-		}
-		return $userProcesInitList;
+			from `CRM_PROCES_idx` i
+				join `CRM_PROCES` p on(p.`ID`=i.`idx_PROCES_INIT_ID`)
+			where i.`ID_PROCES` in({$sqlIdProcesListSql})
+			group by p.`ID`
+			order by p.`SORT_PRIO`
+		";
+		return array_map(function ($row) {
+			return $row['DESC'];
+		}, DB::getPDO()->fetchAllByKey($sqlFetchUserProcesInitList, 'ID'));
 	}
 
 	/**

+ 38 - 48
SE/se-lib/UsersHelper.php

@@ -18,14 +18,14 @@ class UsersHelper {
 			$sql_where_and_arr[] = "a.`ADM_ADMIN_LEVEL`='{$adm_lvl}'";
 		}
 		if (!empty($params['group'])) {
-			$sql_where_and_arr[] = "(select up.`ID` 
-					from `CRM_AUTH_PROFILE` as up 
+			$sql_where_and_arr[] = "(select up.`ID`
+					from `CRM_AUTH_PROFILE` as up
 					where
 						up.`REMOTE_TABLE`='ADMIN_USERS'
 						and up.`A_STATUS` in('WAITING', 'NORMAL')
 						and up.`REMOTE_ID`=a.`ID`
 						and up.`ID_ZASOB`='{$params['group']}'
-					limit 1 
+					limit 1
 				)>0";
 		}
 		$sql_where = implode(" and ", $sql_where_and_arr);
@@ -269,13 +269,13 @@ class UsersHelper {
 		}
 		return $_groups;
 	}
-	
+
 	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` 
+			$sql = "select tx.`ID`, tx.`T_TELBOX_NAME`, tx.`T_TELBOX_TYPE`
 				from `TELBOXES` as tx
 				where
 					tx.`A_STATUS`!='DELETED'
@@ -337,53 +337,43 @@ class UsersHelper {
 	}
 
 	public static function getGroupByUser($userID, $params = array()) {
-		//static $_groups;// TODO: whould be $_groups[$user_id] - array of stanowiska
-		//if (!$_groups) {
-			$_groups = array();
-
-			$db = DB::getDB();
-			$sql_select = array();
-			$sql_left_join = "";
-
-			$sql_select[] = "z.`ID`";
-			$sql_select[] = "z.`DESC`";
-			$sql_select[] = "z.`OPIS`";
-			$sql_select[] = "z.`A_LDAP_GID`";
-
-			$telbox = V::get('T_TELBOX_NAME', 0, $params, 'int');
-			$SHOW_IN_PERIOD_MARK = V::get('SHOW_IN_PERIOD_MARK', 0, $params, 'string');
-
+		$sql_select = array();
+		$sql_left_join = "";
 
+		$sql_select[] = "z.`ID`";
+		$sql_select[] = "z.`DESC`";
+		$sql_select[] = "z.`OPIS`";
+		$sql_select[] = "z.`A_LDAP_GID`";
 
-			if ($telbox > 0) {
-				$sql_left_join = "left join `TELBOXES` as tx on(tx.`ID`=up.`T_TELBOX_NEIGHBOUR_IN_ID`)";
-				$sql_select[] = "tx.`T_TELBOX_NAME`";
-			}
-			$sql_select_where_and="";
-			if (!empty($SHOW_IN_PERIOD_MARK)) {
-				$sql_select_where_and.= " and up.`SHOW_IN_PERIOD_MARK`='{$SHOW_IN_PERIOD_MARK}' ";
-			}
+		$telbox = V::get('T_TELBOX_NAME', 0, $params, 'int');
+		$SHOW_IN_PERIOD_MARK = V::get('SHOW_IN_PERIOD_MARK', 0, $params, 'string');
 
-			$sql_select = implode(', ', $sql_select);
-			$sql = "select {$sql_select}
-				from `CRM_AUTH_PROFILE` as up
-					left join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=up.`ID_ZASOB`)
-					{$sql_left_join}
-				where
-					up.`REMOTE_ID`='{$userID}'
-					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')
-					{$sql_select_where_and}
-			";
+		if ($telbox > 0) {
+			$sql_left_join = "left join `TELBOXES` as tx on(tx.`ID`=up.`T_TELBOX_NEIGHBOUR_IN_ID`)";
+			$sql_select[] = "tx.`T_TELBOX_NAME`";
+		}
+		$sql_select_where_and = "";
+		if (!empty($SHOW_IN_PERIOD_MARK)) {
+			$sql_select_where_and .= " and up.`SHOW_IN_PERIOD_MARK`='{$SHOW_IN_PERIOD_MARK}' ";
+		}
 
-			$res = $db->query($sql);
-			while ($r = $db->fetch($res)) {
-				$_groups[$r->ID] = $r;
-			}
-		//}
-		return $_groups;
+		$sql_select = implode(', ', $sql_select);
+		$sql = "
+			select {$sql_select}
+			from `CRM_AUTH_PROFILE` as up
+				left join `CRM_LISTA_ZASOBOW` as z on(z.`ID`=up.`ID_ZASOB`)
+				{$sql_left_join}
+			where
+				up.`REMOTE_ID`='{$userID}'
+				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')
+				{$sql_select_where_and}
+		";
+		return array_map(function ($row) {
+			return (object)$row;
+		}, DB::getPDO()->fetchAllByKey($sql, 'ID'));
 	}
 
 	public static function getLDAPGroupByUserName($userName) {

+ 2 - 2
SE/superedit-BUDGET_ANALYTICS.php

@@ -1,5 +1,5 @@
 <?php
-
+//bindera@2017-09-14 - uzyte w superedit-STATYSTYKA_TABELE.php widok test_budget_project_analytics_view - uwzglednic przy zmianie nazwy tabeli z test_*
 function BUDGET_ANALYTICS() {
 
 	$TURN_OFF = true;// OFF 2015-06-24
@@ -506,7 +506,7 @@ jQuery(document).ready(function () {
 		";
 		$sqls['RemoveView_korespMain'] = " drop view if exists `in7_dziennik_koresp_budget_view` ";
 		$sqls['CreateView_korespMain'] = "
-			CREATE VIEW `in7_dziennik_koresp_budget_view` AS
+			CREATE or replace  VIEW `in7_dziennik_koresp_budget_view` AS
 				select k.`ID` AS `ID`
 					, k.`path` AS `path`
 					, k.`ID_PROJECT` AS `ID_PROJECT`

Разница между файлами не показана из-за своего большого размера
+ 1 - 1
SE/superedit-DB_PROCEDURES_CREATE.php


+ 4 - 2
SE/superedit-INSTALL_SES_PROCESY_A.php

@@ -1656,6 +1656,8 @@ function INSTALL_GETCOMMANDS_SE_LAST_UPDATE($ADMIN_USERNAME,$SERVER_ADDRESS_IP,$
 
  }
 $cmd[]['rsh']='php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php '.$SERVER_ADDRESS;
+$cmd[]['rsh']='php /Library/Server/Web/Data/Sites/Default/SE/bash_install_check.php '.$SERVER_ADDRESS; //dla pewnosci - TODO 
+
 //@2016-06 bindera: po aktualizacji sql czesto nie dziala event sheduler np zoompak
 $cmd[]['rsh']=' echo " SET GLOBAL event_scheduler =  \"ON\" " |mysql -uroot -p\''.$ADMIN_USERNAME_PASSWD.'\' -D'.$REMOTE_FOLDER_ROOT.' '; //zalozenie 1 usera TODO synchronizacja z ldap
  $cmd[]['rsh']=' { '.tell_user_gui_error("System zostal zainstalowany - wejdz przegladarka na adres www https://".$SERVER_ADDRESS." (alternatywnie https://".$SERVER_ADDRESS.".procesy5.pl - jezeli domena ".$SERVER_ADDRESS." nie zostala jeszcze skonfigurowana), zaloguj sie na uzytkownika:".$ADMIN_USERNAME." (administrator uzytkownikow) lub ".$ADMIN_USERNAME_DIRECTORY." (administrator domeny LDAP/systemu) . Powinienes teraz zalozyc uzytkownikow systemu i nadac hasla - jezeli jest to pierwsza instalacja ").'; exit 0; } '; //komunikat dla uzytkownika
@@ -2100,12 +2102,12 @@ database=\"SES_USERS2\"
                           left join ADMIN_USERS au on au.ADM_ACCOUNT=\''.$ADMIN_USERNAME_L1.'\'
                           where cz.\\`DESC\\` like \'KONTAKTY_view\' and cz.\\`TYPE\\`=\'TABELA\' limit 1 " |mysql -uroot -p\''.$ADMIN_USERNAME_PASSWD.'\' -D'.$REMOTE_FOLDER_ROOT.' '; //zalozenie 1 usera TODO synchronizacja z ldap
 
-$cmd[]['rsh']=' echo " insert into CRM_AUTH_PROFILE (ID_ZASOB, REMOTE_TABLE,REMOTE_ID) select czp1.ID , \'ADMIN_USERS\', au.ID
+$cmd[]['rsh']=' echo " insert into CRM_AUTH_PROFILE (ID_ZASOB, REMOTE_TABLE,REMOTE_ID) select cz.ID , \'ADMIN_USERS\', au.ID
                           from CRM_LISTA_ZASOBOW cz
                           left join ADMIN_USERS au on au.ADM_ACCOUNT=\''.$ADMIN_USERNAME_L1.'\'
                           where cz.\\`TYPE\\`=\'PODMIOT\' and cz.\\`DESC\\`=\''.$REMOTE_FOLDER_ROOT.'\' limit 1 " |mysql -uroot -p\''.$ADMIN_USERNAME_PASSWD.'\' -D'.$REMOTE_FOLDER_ROOT.' '; //zalozenie 1 usera TODO synchronizacja z ldap domyslna grupa
 
-$cmd[]['rsh']=' echo " insert into CRM_AUTH_PROFILE (ID_ZASOB, REMOTE_TABLE,REMOTE_ID) select czp1.ID , \'ADMIN_USERS\', au.ID
+$cmd[]['rsh']=' echo " insert into CRM_AUTH_PROFILE (ID_ZASOB, REMOTE_TABLE,REMOTE_ID) select cz.ID , \'ADMIN_USERS\', au.ID
                           from CRM_LISTA_ZASOBOW cz
                           left join ADMIN_USERS au on au.ADM_ACCOUNT=\''.$ADMIN_USERNAME_DIRECTORY.'\'
                           where cz.\\`TYPE\\`=\'PODMIOT\' and cz.\\`DESC\\`=\''.$REMOTE_FOLDER_ROOT.'\' limit 1 " |mysql -uroot -p\''.$ADMIN_USERNAME_PASSWD.'\' -D'.$REMOTE_FOLDER_ROOT.' '; //zalozenie 1 usera TODO synchronizacja z ldap domyslna grupa

Некоторые файлы не были показаны из-за большого количества измененных файлов