Prechádzať zdrojové kódy

updated Storage for default_objects StorageAcl

Piotr Labudda 9 rokov pred
rodič
commit
c928a40e79

+ 2 - 2
SE/se-lib/Core/AclBase.php

@@ -26,7 +26,8 @@ class Core_AclBase {
   // TODO: get more xsd restrictions like minOccurs, maxOccurs, nillable and restrictions
   // TODO: get more xsd restrictions like minOccurs, maxOccurs, nillable and restrictions
 
 
   public function getID() {
   public function getID() {
-    if ('default_objects' == $this->getSourceName()) {
+    throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501);
+    if ('default_objects' == $this->getSourceName()) {// TODO: RMM - moved to Storage -> SystemObject->updateCache()
       $idZasobDatabase = DB::getPDO()->getZasobId();
       $idZasobDatabase = DB::getPDO()->getZasobId();
       $namespace = $this->getNamespace();
       $namespace = $this->getNamespace();
       $sqlNamespace = DB::getPDO()->quote($namespace, PDO::PARAM_STR);
       $sqlNamespace = DB::getPDO()->quote($namespace, PDO::PARAM_STR);
@@ -56,7 +57,6 @@ class Core_AclBase {
       ]);
       ]);
       return $idZasob;
       return $idZasob;
     }
     }
-    throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501);
   }
   }
   public function init($force = false) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
   public function init($force = false) { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
   public function isInitialized() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }
   public function isInitialized() { throw new HttpException("Acl function " . __FUNCTION__ . " Not implemented", 501); }

+ 1 - 1
SE/se-lib/Core/Pdo.php

@@ -29,7 +29,7 @@ class Core_Pdo extends PDO {
 	}
 	}
 
 
 	public function getType() {
 	public function getType() {
-		return $this->_type;
+		return strtolower($this->_type);
 	}
 	}
 
 
 	public function getTableStruct($tblName) {// TODO: mved to Core_Storage_*
 	public function getTableStruct($tblName) {// TODO: mved to Core_Storage_*

+ 10 - 0
SE/se-lib/Route/Install.php

@@ -545,6 +545,16 @@ rsync --archive --times --delete --compress --one-file-system --omit-dir-times -
 	--verbose {$rsyncSshPort} \
 	--verbose {$rsyncSshPort} \
 	--exclude='stuff/qgis__kyngchaos.com' \
 	--exclude='stuff/qgis__kyngchaos.com' \
 	--exclude='stuff/qgis__kyngchaos.com/QGIS-2.14.3-1.dmg' \
 	--exclude='stuff/qgis__kyngchaos.com/QGIS-2.14.3-1.dmg' \
+	--exclude='stuff/postgis' \
+	--exclude='stuff/postgis2' \
+	--exclude='stuff/KindleGen_Mac_i386_v2_9' \
+	--exclude='stuff/jdk-8u121-macosx-x64.dmg' \
+	--exclude='stuff/jre-8u112-macosx-x64.tar.gz' \
+	--exclude='stuff/jre-8u121-macosx-x64.dmg' \
+	--exclude='schema/default_db.instance.xml' \
+	--exclude='schema/default_db_xml_cache.public' \
+	--exclude='schema/default_db.instance.xml/**' \
+	--exclude='schema/default_db_xml_cache.public/**' \
 	'{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
 	'{$appLicenceInfo->installPath}/SE/' {$sshHostUsr}:~/se.encrypted.upgrade/SE/;
 ssh {$sshArgs} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
 ssh {$sshArgs} {$sshHostUsr} 'cp -r /Library/Server/Web/Data/Sites/Default/SE/config ~/se.encrypted.upgrade/SE/';
 ssh {$sshArgs} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'
 ssh {$sshArgs} {$sshHostUsr} 'rm /Library/Server/Web/Data/Sites/Default/se.encrypted.upgrade'

+ 73 - 3
SE/se-lib/Route/Storage.php

@@ -530,12 +530,81 @@ jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', fun
 		UI::gora();
 		UI::gora();
 		UI::menu();
 		UI::menu();
 		$this->navView();
 		$this->navView();
+		UI::startContainer();
 		try {
 		try {
 			$idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
 			$idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
 			if (empty($idStorage)) throw new Exception("Missing id storage");
 			if (empty($idStorage)) throw new Exception("Missing id storage");
-			$storageList = $this->getStorageList();
-			if (empty($storageList)) throw new Exception("No storage defined");
-			if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage id='{$idStorage}' not exists");
+
+			$sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
+			$sourceItem = $sourceStorage->getItem($idStorage);
+			if (!$sourceItem) throw new Exception("Storage id='{$idStorage}' not exists");
+			DBG::nicePrint($sourceItem, '$sourceItem');
+
+			// TODO: fetch SystemObject childrens from $sourceItem:
+			// 1. 'SystemSource' -> getItems([ 'cols' => 'SystemObject/*', 'featureId' => $sourceItem['idZasob'] ])
+			// 2. 'SystemObject' -> getItems([ 'refFrom' => $sourceItem['idZasob'] ])
+			// 'default_objects' => _task=systemObjects
+
+			$objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
+			try {
+				$objectStorage->getTotal();
+			} catch (Exception $e) {
+				UI::alert('warning', $e->getMessage());
+				$objectStorage->updateCache();
+				UI::alert('info', "Lista obiketów zaktualizowana");
+			}
+			if ('1' == V::get('refreshObjectList', '', $_POST)) {
+				$objectStorage->updateCache();
+				UI::alert('info', "Lista obiketów zaktualizowana");
+			}
+
+			UI::table([
+				'caption' => "Obiekty w bazie '{$sourceItem['name']}' " .
+					UI::hButtonPost('<i class="glyphicon glyphicon-refresh"></i>' . " odśwież", [
+						'class' => "btn btn-xs btn-link",
+						'data' => [
+							'refreshObjectList' => '1'
+						]
+					]),
+				'rows' => array_map(function ($item) use ($idStorage) {
+					$addToZasobyLink = $this->getLink('addTableToZasoby', ['idStorage' => $idStorage, 'tblName' => $item['name']]);
+					return [
+						'nazwa' => $item['name'],
+						'_type' => $item['_type'], // TODO: editable?
+						'Nr zasobu' => ($item['idZasob'] > 0)
+							? $item['idZasob']
+							: UI::h('button', [
+								'class' => "btn btn-xs btn-primary",
+								'onClick' => "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addTableToZasoby', { href: '{$addToZasobyLink}' })"
+							], "Dodaj do Zasobów"),
+						// 'opis' => $item['description'],
+						'active?' => ($item['isActive']) ? '<span class="label label-success">TAK</span>' : '<span class="text text-muted">nie</span>',
+						'struktura' => UI::h('a', [ 'href' => $this->getLink('tableStruct', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "struktura"),
+						'raw info' => UI::h('a', [ 'href' => $this->getLink('rawInfo', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "raw info"),
+						// 'xsd' => UI::h('a', [ 'href' => $this->getLink('xsd', [ 'idStorage' => $idStorage ]) ], "xsd"),
+					];
+				}, $objectStorage->getItems([
+					'#refFrom' => [
+						'namespace' => 'default_objects/SystemSource',
+						'primaryKey' => $sourceItem['idZasob']
+					]
+				]))
+			]);
+			echo UI::h('script', [], "
+				jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:click', function(e, n, payload) {
+					console.log('event p5UIBtnAjax:Storage:addTableToZasoby:click', n, payload);
+				});
+				jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(e, n, payload) {
+					console.log('event p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', n, payload);
+					if ('success' == payload.type && payload.body && payload.body.id > 0) {
+						jQuery(n).parents('td').text(payload.body.id);
+					}
+					jQuery.notify(payload.msg, payload.type);
+				});
+			");
+
+return;
+			echo '<hr>';
 
 
 			$storagePdo = DB::getStorage($idStorage);
 			$storagePdo = DB::getStorage($idStorage);
 			$viewRealList = $storagePdo->getViewList();
 			$viewRealList = $storagePdo->getViewList();
@@ -636,6 +705,7 @@ jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(
 		} catch (Exception $e) {
 		} catch (Exception $e) {
 			UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
 			UI::alert('danger', "Error #" . $e->getCode() .  "|" . $e->getLine() .  ": " . $e->getMessage());
 		}
 		}
+		UI::endContainer();
 		UI::dol();
 		UI::dol();
 	}
 	}
 
 

+ 215 - 94
SE/se-lib/Schema/SystemObjectStorageAcl.php

@@ -8,19 +8,35 @@ class Schema_SystemObjectStorageAcl extends Core_AclSimpleSchemaBase {
   public $_simpleSchema = [
   public $_simpleSchema = [
     'root' => [
     'root' => [
       '@namespace' => 'default_objects/SystemObject',
       '@namespace' => 'default_objects/SystemObject',
-      '@primaryKey' => 'ID',
-      'ID' => [ '@type' => 'xsd:integer' ],
-      'namespace' => [ '@type' => 'xsd:string' ],
-      'typeName' => [ '@type' => 'xsd:string' ],
-      'tabela' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
-      'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
-      'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
-      'id_zasob' => [ '@type' => 'xsd:integer' ],
-      'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
-      'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
-      'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
-      'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
+      '@primaryKey' => 'idZasob',
+      'idZasob' => [ '@type' => 'xsd:integer' ],
+      'idDatabase' => [ '@type' => 'xsd:integer' ],
+      'nsPrefix' => [ '@type' => 'xsd:string' ],
+      'name' => [ '@type' => 'xsd:string' ],
+      '_rootTableName' => [ '@type' => 'xsd:string' ],
+      '_type' => [ '@type' => 'xsd:string' ],
+      'isActive' => [ '@type' => 'xsd:integer' ], // installed
+      'description' => [ '@type' => 'xsd:string' ],
+      // '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' ],
     ]
     ]
+    // 'root' => [
+    //   '@namespace' => 'default_objects/SystemObject',
+    //   '@primaryKey' => 'ID',
+    //   'ID' => [ '@type' => 'xsd:integer' ],
+    //   'namespace' => [ '@type' => 'xsd:string' ],
+    //   'typeName' => [ '@type' => 'xsd:string' ],
+    //   'tabela' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
+    //   'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
+    //   'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
+    //   'id_zasob' => [ '@type' => 'xsd:integer' ],
+    //   'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
+    //   'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
+    //   'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
+    //   'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
+    // ]
   ];
   ];
   // public $_rootTableName = 'CRM_LISTA_ZASOBOW';
   // public $_rootTableName = 'CRM_LISTA_ZASOBOW';
   public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT';
   public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT';
@@ -31,101 +47,206 @@ class Schema_SystemObjectStorageAcl extends Core_AclSimpleSchemaBase {
   //   self::updateCacheIfNeeded(array($this, 'updateCache'));
   //   self::updateCacheIfNeeded(array($this, 'updateCache'));
   // }
   // }
 
 
-  public static function updateCacheIfNeeded($updateCallback) {
-    static $_cacheUpdated = null;
-    if (null !== $_cacheUpdated) return;
-    $conf = DB::getPDO()->fetchFirst("
-      select (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__last_cache_update_date') as lastCacheUpdate
-          ,  (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__force_cache_update') as forceCacheUpdate
-          ,  (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__schema_version') as schemaVersion
-          ,  (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end') as lastProcesIndexer
-          ,  (
-                select IF('N/S;' = A_RECORD_UPDATE_DATE or A_RECORD_UPDATE_DATE is null or '' = A_RECORD_UPDATE_DATE, A_RECORD_CREATE_DATE, A_RECORD_UPDATE_DATE) as lastUpdateDate
-                from CRM_LISTA_ZASOBOW_HIST
-                order by ID DESC
-                limit 1
-              ) as lastZasobyUpdate
-    ");
-    if ($conf['lastZasobyUpdate']) {// fix date format - convert to Mysql date time format '2002-05-30 09:00:00'
-      if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\-\d\d:\d\d$/', $conf['lastZasobyUpdate'])) { // 'Y-m-d-H:i'
-        $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11) . ":00";
-      } else if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\-\d\d:\d\d:\d\d$/', $conf['lastZasobyUpdate'])) { // 'Y-m-d-H:i:s'
-        $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11);
-      } else if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\ \d\d:\d\d:\d\d$/', $conf['lastZasobyUpdate'])) {
-        $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11);
-      }
-    }
-    // $lastProcesIndexer = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end' ");
-    $updateReason = null;
-    if ('1' == $conf['forceCacheUpdate']) $updateReason = 'forceCacheUpdate = 1';
-    if (!$conf['lastCacheUpdate']) $updateReason = '!lastCacheUpdate';
-    if (!$conf['schemaVersion']) $updateReason = '!schemaVersion';
-    else if ($conf['schemaVersion'] < $this->_version) $updateReason = 'schemaVersion < ' . $this->_version;
-    if ($conf['lastCacheUpdate'] && $conf['lastZasobyUpdate'] && $conf['lastCacheUpdate'] < $conf['lastZasobyUpdate']) $updateReason = 'lastZasobyUpdate';
-    if ($updateReason) {
-      DBG::simpleLog('schema', "SystemObject: update cache reason '{$updateReason}' '" . json_encode($conf) . "'");
-      call_user_func($updateCallback);
-    }
-    DB::getPDO()->execSql("
-      insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
-        values('SystemObject__last_cache_update_date', NOW())
-        on duplicate key update CONF_VAL = NOW()
-    ");
-    DB::getPDO()->execSql("
-      insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
-        values('SystemObject__schema_version', {$this->_version})
-        on duplicate key update CONF_VAL = {$this->_version}
-    ");
-    if ('1' == $conf['forceCacheUpdate']) DB::getPDO()->execSql(" update CRM_CONFIG set CONF_VAL = '0' where CONF_KEY = 'SystemObject__force_cache_update' ");
-    $_cacheUpdated = true;
-  }
-  public function updateCache() {
+  // public static function updateCacheIfNeeded($updateCallback) {
+  //   static $_cacheUpdated = null;
+  //   if (null !== $_cacheUpdated) return;
+  //   $conf = DB::getPDO()->fetchFirst("
+  //     select (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__last_cache_update_date') as lastCacheUpdate
+  //         ,  (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__force_cache_update') as forceCacheUpdate
+  //         ,  (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__schema_version') as schemaVersion
+  //         ,  (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end') as lastProcesIndexer
+  //         ,  (
+  //               select IF('N/S;' = A_RECORD_UPDATE_DATE or A_RECORD_UPDATE_DATE is null or '' = A_RECORD_UPDATE_DATE, A_RECORD_CREATE_DATE, A_RECORD_UPDATE_DATE) as lastUpdateDate
+  //               from CRM_LISTA_ZASOBOW_HIST
+  //               order by ID DESC
+  //               limit 1
+  //             ) as lastZasobyUpdate
+  //   ");
+  //   if ($conf['lastZasobyUpdate']) {// fix date format - convert to Mysql date time format '2002-05-30 09:00:00'
+  //     if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\-\d\d:\d\d$/', $conf['lastZasobyUpdate'])) { // 'Y-m-d-H:i'
+  //       $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11) . ":00";
+  //     } else if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\-\d\d:\d\d:\d\d$/', $conf['lastZasobyUpdate'])) { // 'Y-m-d-H:i:s'
+  //       $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11);
+  //     } else if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\ \d\d:\d\d:\d\d$/', $conf['lastZasobyUpdate'])) {
+  //       $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11);
+  //     }
+  //   }
+  //   // $lastProcesIndexer = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end' ");
+  //   $updateReason = null;
+  //   if ('1' == $conf['forceCacheUpdate']) $updateReason = 'forceCacheUpdate = 1';
+  //   if (!$conf['lastCacheUpdate']) $updateReason = '!lastCacheUpdate';
+  //   if (!$conf['schemaVersion']) $updateReason = '!schemaVersion';
+  //   else if ($conf['schemaVersion'] < $this->_version) $updateReason = 'schemaVersion < ' . $this->_version;
+  //   if ($conf['lastCacheUpdate'] && $conf['lastZasobyUpdate'] && $conf['lastCacheUpdate'] < $conf['lastZasobyUpdate']) $updateReason = 'lastZasobyUpdate';
+  //   if ($updateReason) {
+  //     DBG::simpleLog('schema', "SystemObject: update cache reason '{$updateReason}' '" . json_encode($conf) . "'");
+  //     call_user_func($updateCallback);
+  //   }
+  //   DB::getPDO()->execSql("
+  //     insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
+  //       values('SystemObject__last_cache_update_date', NOW())
+  //       on duplicate key update CONF_VAL = NOW()
+  //   ");
+  //   DB::getPDO()->execSql("
+  //     insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
+  //       values('SystemObject__schema_version', {$this->_version})
+  //       on duplicate key update CONF_VAL = {$this->_version}
+  //   ");
+  //   if ('1' == $conf['forceCacheUpdate']) DB::getPDO()->execSql(" update CRM_CONFIG set CONF_VAL = '0' where CONF_KEY = 'SystemObject__force_cache_update' ");
+  //   $_cacheUpdated = true;
+  // }
+
+  public function updateCache($idDatabase = null) {
     DBG::simpleLog('schema', "SystemObject::updateCache...");
     DBG::simpleLog('schema', "SystemObject::updateCache...");
+    DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
     DB::getPDO()->execSql("
     DB::getPDO()->execSql("
       create table if not exists `{$this->_rootTableName}` (
       create table if not exists `{$this->_rootTableName}` (
-				`idZasob` int(11) NOT NULL,
-				`idDatabase` int(11) NOT NULL,
-				`name` varchar(255) DEFAULT '',
-				`namespace` varchar(255) DEFAULT '',
-				`typeName` varchar(255) DEFAULT '',
-				`_rootTableName` varchar(255) DEFAULT '',
-				UNIQUE KEY `idZasob` (idZasob)
-			) ENGINE=MyISAM  DEFAULT CHARSET=latin2
+        `idZasob` int(11) DEFAULT NULL,
+        `idDatabase` int(11) NOT NULL,
+        `nsPrefix` varchar(255) DEFAULT '',
+        `name` varchar(255) DEFAULT '',
+        `_rootTableName` varchar(255) DEFAULT '',
+        `_type` varchar(255) DEFAULT '',
+        `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
+        `description` varchar(255) DEFAULT '',
+        UNIQUE KEY `idZasob` (idZasob),
+        UNIQUE KEY `typeName` (nsPrefix, name),
+        KEY `isActive` (isActive)
+      ) ENGINE=MyISAM  DEFAULT CHARSET=latin2
     ");
     ");
     $idDefDB = DB::getPDO()->getZasobId();
     $idDefDB = DB::getPDO()->getZasobId();
-    DB::getPDO()->execSql("
-      insert ignore into `{$this->_rootTableName}` (idZasob, idDatabase, name, namespace, typeName)
-      select t.ID as idZasob
-          ,  d.ID as idDatabase
-          ,  d.`DESC` as name
-          ,  concat(IF({$idDefDB} = d.ID, 'default_db', 'zasob_'), '/', t.`DESC`) as namespace
-          ,  concat(IF({$idDefDB} = d.ID, 'default_db', concat('zasob_', d.ID)), ':', t.`DESC`) as typeName
-      from CRM_LISTA_ZASOBOW t
-        join CRM_LISTA_ZASOBOW d on(d.ID = t.PARENT_ID and d.A_STATUS in('NORMAL', 'WAITING'))
-      where t.`TYPE` = 'TABELA'
-        and t.A_STATUS in('NORMAL', 'WAITING')
-        and t.`DESC` not like '%/%'
-    ");
-    // _rootTableName
-    // select idDatabase, name from `{$this->_rootTableName}` where _rootTableName = '' and idDatabase != $idDefDB
-    // group by idDtabase
-    // foreach ... DB::getPDO($idDatabase)->fetchAll(select real _rootTableName)
-    foreach (Core_AclHelper::getAclList() as $typeName) {
-      $ns = Core_AclHelper::parseTypeName($typeName);
-      $namespace = str_replace('__x3A__', '/', $ns['prefix']) . "/{$ns['name']}";
-      $sqlNs = DB::getPDO()->quote($namespace, PDO::PARAM_STR);
-      $idZasob = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where `DESC` = {$sqlNs} and `TYPE` = 'TABELA' and A_STATUS in('WAITING', 'NORMAL') ");
-      if (!$idZasob) {
-        DBG::nicePrint($ns, "TODO: insert zasob PARENT_ID = ?");
+
+    $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
+    foreach ($sourceStorage->getItems([ 'f_hasConfig' => 1 ]) as $source) {
+      if ('default_objects' == $source['nsPrefix']) {
+        foreach (glob(APP_PATH_LIB . "/Schema/*StorageAcl.php", GLOB_NOSORT) as $file) {
+					$clsName = substr(basename($file), 0, -1 * strlen('StorageAcl.php'));
+					try {
+						$acl = SchemaFactory::loadDefaultObject($clsName);
+						$namespace = $acl->getNamespace();
+						$name = $acl->getName();
+		        DB::getPDO()->execSql("
+		          insert ignore into `{$this->_rootTableName}` (nsPrefix, idDatabase, _type, name, description, isActive)
+		            values (
+		              '{$source['nsPrefix']}'
+									, '{$source['idZasob']}'
+                  , 'StorageAcl'
+									, '{$name}'
+									, ''
+									, '1'
+		            )
+		        ");
+					} catch (Exception $e) {
+						UI::alert('danger', $e->getMessage());
+					}
+				}
+        DB::getPDO()->execSql("
+          insert into `{$this->_rootTableName}` (idZasob, nsPrefix, idDatabase, name, description, isActive)
+            select t.ID as idZasob
+                , '{$source['nsPrefix']}' as nsPrefix
+                ,  '{$source['idZasob']}' as idDatabase
+                ,  t.`DESC` as name
+                ,  t.`OPIS` as description
+                ,  1 as isActive
+            from CRM_LISTA_ZASOBOW t
+            where t.`TYPE` = 'TABELA'
+              and t.A_STATUS in('NORMAL', 'WAITING')
+              and t.PARENT_ID = {$source['idZasob']}
+              and t.`DESC` not like '%/%'
+          on duplicate key update idZasob = t.ID
+                                , isActive = 1
+        ");
+      }
+      else {
+        try {
+          $dbName = DB::getPDO($source['idZasob'])->getDatabaseName();
+          $dbType = DB::getPDO($source['idZasob'])->getType();
+          if ('mysql' == $dbType) {
+            UI::alert('warning', "TODO: { id: {$source['idZasob']}, nsPrefix: '{$source['nsPrefix']}', dbName: '{$dbName}', dbType: '{$dbType}'} ...");
+            // TODO: if another DB split select and insert
+            DB::getPDO()->execSql("
+              insert into `{$this->_rootTableName}` (idDatabase, nsPrefix, name, _rootTableName, _type, description)
+                select '{$source['idZasob']}' as idDatabase
+                    , '{$source['nsPrefix']}' as nsPrefix
+                    , t.TABLE_NAME as name
+                    , t.TABLE_NAME as _rootTableName
+                    , 'TableAcl' as _type
+                    , t.TABLE_COMMENT as description
+                from INFORMATION_SCHEMA.TABLES t
+          			where t.TABLE_SCHEMA = '{$dbName}'
+              on duplicate key update _rootTableName = t.TABLE_NAME
+            ");
+            DB::getPDO()->execSql("
+              insert into `{$this->_rootTableName}` (idZasob, nsPrefix, idDatabase, name, description, isActive)
+                select t.ID as idZasob
+                    , '{$source['nsPrefix']}' as nsPrefix
+                    ,  '{$source['idZasob']}' as idDatabase
+                    ,  t.`DESC` as name
+                    ,  t.`OPIS` as description
+                    ,  1 as isActive
+                from CRM_LISTA_ZASOBOW t
+                where t.`TYPE` = 'TABELA'
+                  and t.A_STATUS in('NORMAL', 'WAITING')
+                  and t.PARENT_ID = {$source['idZasob']}
+              on duplicate key update idZasob = t.ID
+                                    , isActive = 1
+            ");
+          // } else if ('pgsql' == $dbType) {// TODO: use pgsql @see Storage Pgsql getTables from information_schema
+          } else {
+            UI::alert('warning', "TODO: { id: {$source['idZasob']}, nsPrefix: '{$source['nsPrefix']}', dbName: '{$dbName}', dbType: <b>'{$dbType}'</b>} ...");
+          }
+        } catch (Exception $e) {
+          UI::alert('danger', "Error source '{$source['idZasob']}' " . $e->getMessage());
+          continue;
+        }
       }
       }
     }
     }
+
+    // // foreach ... DB::getPDO($idDatabase)->fetchAll(select real _rootTableName)
+    // foreach (Core_AclHelper::getAclList() as $typeName) {
+    //   $ns = Core_AclHelper::parseTypeName($typeName);
+    //   $namespace = str_replace('__x3A__', '/', $ns['prefix']) . "/{$ns['name']}";
+    //   $sqlNs = DB::getPDO()->quote($namespace, PDO::PARAM_STR);
+    //   $idZasob = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where `DESC` = {$sqlNs} and `TYPE` = 'TABELA' and A_STATUS in('WAITING', 'NORMAL') ");
+    //   if (!$idZasob) {
+    //     DBG::nicePrint($ns, "TODO: insert zasob PARENT_ID = ?");
+    //   }
+    // }
+  }
+
+  public function _parseWhere($params = []) {
+    $sqlWhere = [];
+    if (!empty($params['#refFrom'])) {
+      // '#refFrom' => [
+      //   'namespace' => 'default_objects/SystemSource',
+      //   'primaryKey' => $sourceItem['idZasob']
+      // ]
+      if (empty($params['#refFrom']['namespace'])) throw new Exception("Missing refFrom/namespace");
+      if (empty($params['#refFrom']['primaryKey'])) throw new Exception("Missing refFrom/primaryKey");
+
+      if ('default_objects/SystemSource' != $params['#refFrom']['namespace']) throw new Exception("Unsupported refFrom/namespace '{$params['#refFrom']['namespace']}'");
+      $sqlWhere[] = "idDatabase = " . DB::getPDO()->quote($params['#refFrom']['primaryKey'], PDO::PARAM_INT);
+    }
+    return (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : '';
   }
   }
 
 
   public function getTotal($params = []) {
   public function getTotal($params = []) {
-    return count($this->_getAllItems());
+    $sqlWhere = $this->_parseWhere($params);
+    return DB::getPDO()->fetchValue("
+      select count(1) as cnt
+      from `{$this->_rootTableName}` t
+      {$sqlWhere}
+    ");
   }
   }
 
 
   public function getItems($params = []) {
   public function getItems($params = []) {
+    $sqlWhere = $this->_parseWhere($params);
+    return DB::getPDO()->fetchAll("
+      select t.*
+      from `{$this->_rootTableName}` t
+      {$sqlWhere}
+    ");
+
     $items = $this->_getAllItems();
     $items = $this->_getAllItems();
     $currSortCol = V::get('order_by', 'ID', $params);
     $currSortCol = V::get('order_by', 'ID', $params);
     $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
     $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));

+ 71 - 0
SE/se-lib/Schema/SystemSourceStorageAcl.php

@@ -10,6 +10,7 @@ class Schema_SystemSourceStorageAcl extends Core_AclSimpleSchemaBase {
       '@namespace' => 'default_objects/SystemSource',
       '@namespace' => 'default_objects/SystemSource',
       '@primaryKey' => 'idZasob',
       '@primaryKey' => 'idZasob',
       'idZasob' => [ '@type' => 'xsd:integer' ],
       'idZasob' => [ '@type' => 'xsd:integer' ],
+      'nsPrefix' => [ '@type' => 'xsd:string' ],
       'name' => [ '@type' => 'xsd:string' ],
       'name' => [ '@type' => 'xsd:string' ],
       'description' => [ '@type' => 'xsd:string' ],
       'description' => [ '@type' => 'xsd:string' ],
       'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
       'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
@@ -24,9 +25,11 @@ class Schema_SystemSourceStorageAcl extends Core_AclSimpleSchemaBase {
 
 
   public function updateCache() {
   public function updateCache() {
     DBG::simpleLog('schema', "SystemSource::updateCache...");
     DBG::simpleLog('schema', "SystemSource::updateCache...");
+    // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
     DB::getPDO()->execSql("
     DB::getPDO()->execSql("
       create table if not exists `{$this->_rootTableName}` (
       create table if not exists `{$this->_rootTableName}` (
 				`idZasob` int(11) NOT NULL,
 				`idZasob` int(11) NOT NULL,
+				`nsPrefix` varchar(255) DEFAULT '',
 				`name` varchar(255) DEFAULT '',
 				`name` varchar(255) DEFAULT '',
 				`description` varchar(255) DEFAULT '',
 				`description` varchar(255) DEFAULT '',
         `hasConfig` tinyint(1) DEFAULT 0,
         `hasConfig` tinyint(1) DEFAULT 0,
@@ -37,6 +40,8 @@ class Schema_SystemSourceStorageAcl extends Core_AclSimpleSchemaBase {
 				UNIQUE KEY `idZasob` (idZasob)
 				UNIQUE KEY `idZasob` (idZasob)
 			) ENGINE=MyISAM  DEFAULT CHARSET=latin2
 			) ENGINE=MyISAM  DEFAULT CHARSET=latin2
     ");
     ");
+
+    // database from config files
     $host = V::get('SERVER_NAME', '', $_SERVER);
     $host = V::get('SERVER_NAME', '', $_SERVER);
     if (!$host) die('Missing SERVER_NAME!');
     if (!$host) die('Missing SERVER_NAME!');
     function hideConfPass($line) {
     function hideConfPass($line) {
@@ -56,6 +61,7 @@ class Schema_SystemSourceStorageAcl extends Core_AclSimpleSchemaBase {
       if (in_array(V::get('type', '', $conf), ['mysql', 'pgsql', 'mssql'])) {
       if (in_array(V::get('type', '', $conf), ['mysql', 'pgsql', 'mssql'])) {
         DB::getPDO()->insertOrUpdate($this->_rootTableName, 'idZasob', $idZasob, [
         DB::getPDO()->insertOrUpdate($this->_rootTableName, 'idZasob', $idZasob, [
           'idZasob' => $idZasob,
           'idZasob' => $idZasob,
+          'nsPrefix' => "zasob_{$idZasob}",
           'name' => V::get('database', $idZasob, $conf),
           'name' => V::get('database', $idZasob, $conf),
           'hasConfig' => 1,
           'hasConfig' => 1,
           '@insert' => [
           '@insert' => [
@@ -70,6 +76,8 @@ class Schema_SystemSourceStorageAcl extends Core_AclSimpleSchemaBase {
       }
       }
       // DBG::nicePrint(implode("\n", array_map( hideConfPass, explode("\n", var_export($conf, true)) ) ), '$conf');
       // DBG::nicePrint(implode("\n", array_map( hideConfPass, explode("\n", var_export($conf, true)) ) ), '$conf');
     }
     }
+
+    // source from CRM_LISTA_ZASOBOW
     foreach (DB::getPDO()->fetchAll("
     foreach (DB::getPDO()->fetchAll("
       select z.`ID`, z.`DESC`, z.OPIS
       select z.`ID`, z.`DESC`, z.OPIS
       from CRM_LISTA_ZASOBOW z
       from CRM_LISTA_ZASOBOW z
@@ -79,6 +87,7 @@ class Schema_SystemSourceStorageAcl extends Core_AclSimpleSchemaBase {
       $desc = V::get('DESC', $item['ID'], $item);
       $desc = V::get('DESC', $item['ID'], $item);
       DB::getPDO()->insertOrUpdate($this->_rootTableName, 'idZasob', $item['ID'], [
       DB::getPDO()->insertOrUpdate($this->_rootTableName, 'idZasob', $item['ID'], [
         'idZasob' => $item['ID'],
         'idZasob' => $item['ID'],
+        'nsPrefix' => "zasob_{$item['ID']}",
         'name' => $desc,
         'name' => $desc,
         'description' => V::get('OPIS', $desc, $item),
         'description' => V::get('OPIS', $desc, $item),
         '@insert' => [
         '@insert' => [
@@ -92,16 +101,78 @@ class Schema_SystemSourceStorageAcl extends Core_AclSimpleSchemaBase {
         ]
         ]
       ]);
       ]);
     }
     }
+    $idMainDb = DB::getPDO()->getZasobId();
+    DB::getPDO()->update($this->_rootTableName, 'idZasob', $idMainDb, [
+      'nsPrefix' => 'default_db'
+    ]);
+
+    // default_objects: StorageAcl, AntAcl, ...
+    $id = DB::getPDO()->fetchValue(" select idZasob from `{$this->_rootTableName}` where name = 'default_objects' ");
+    if (!$id) {
+      $item = DB::getPDO()->fetchFirst("
+        select z.`ID`
+        from CRM_LISTA_ZASOBOW z
+        where z.`TYPE` in ('BAZA_DANYCH')
+          and z.A_STATUS not in ('DELETED')
+          and z.`DESC` = 'default_objects'
+      ");
+      if ($item) {
+        $id = $item['ID'];
+      } else {
+        $idMainDbParent = DB::getPDO()->fetchValue(" select PARENT_ID from CRM_LISTA_ZASOBOW where ID = '" . DB::getPDO()->getZasobId() . "' ");
+        $id = DB::getPDO()->insert('CRM_LISTA_ZASOBOW', [
+          'DESC' => 'default_objects',
+          'TYPE' => 'BAZA_DANYCH',
+          'OPIS' => "Obiekty systemowe",
+          'PARENT_ID' => $idMainDbParent,
+          'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+          'A_RECORD_CREATE_DATE' => 'NOW()',
+          'A_ADM_COMPANY' => 'system',// edit not allowed
+        ]);
+      }
+    }
+    if (!$id) throw new Exception("Missing default_objects ID");
+    DB::getPDO()->insertOrUpdate($this->_rootTableName, 'idZasob', $id, [
+      'idZasob' => $id,
+      'nsPrefix' => 'default_objects',
+      'name' => 'default_objects',
+      'description' => "Obiekty systemowe",
+      'hasConfig' => 1,
+      '@insert' => [
+        'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
+        'A_RECORD_CREATE_DATE' => 'NOW()',
+      ],
+      '@update' => [
+        'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
+        'A_RECORD_UPDATE_DATE' => 'NOW()',
+      ]
+    ]);
   }
   }
 
 
   public function getTotal($params = []) {
   public function getTotal($params = []) {
     return DB::getPDO()->fetchValue(" select count(1) as cnt from `{$this->_rootTableName}` ");
     return DB::getPDO()->fetchValue(" select count(1) as cnt from `{$this->_rootTableName}` ");
   }
   }
 
 
+  public function getItem($pk, $params = []) {
+    $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_INT);
+    $item = DB::getPDO()->fetchFirst("
+      select t.*
+      from `{$this->_rootTableName}` t
+      where t.idZasob = {$sqlPk}
+    ");
+    return $item;
+  }
+
   public function getItems($params = []) {
   public function getItems($params = []) {
+    $sqlWhere = [];
+    if (array_key_exists('f_hasConfig', $params)) {
+      $sqlWhere[] = "t.hasConfig = " . DB::getPDO()->convertValueToSqlSafe($params['f_hasConfig']);
+    }
+    $sqlWhere = (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : "";
     $items = DB::getPDO()->fetchAll("
     $items = DB::getPDO()->fetchAll("
       select t.*
       select t.*
       from `{$this->_rootTableName}` t
       from `{$this->_rootTableName}` t
+      {$sqlWhere}
     ");
     ");
     $currSortCol = V::get('order_by', 'ID', $params);
     $currSortCol = V::get('order_by', 'ID', $params);
     $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
     $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));