| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526 |
- <?php
- Lib::loadClass('Core_AclSimpleSchemaBase');
- Lib::loadClass('ParseOgcFilter');
- Lib::loadClass('Router');
- class Schema_SystemObjectStorageAcl extends Core_AclSimpleSchemaBase {
- public $_simpleSchema = [
- 'root' => [
- '@namespace' => 'default_objects/SystemObject',
- '@primaryKey' => 'namespace',
- 'idZasob' => [ '@type' => 'xsd:integer' ],
- 'idDatabase' => [ '@type' => 'xsd:integer' ],
- 'namespace' => [ '@type' => 'xsd:string' ],
- '_rootTableName' => [ '@type' => 'xsd:string' ],
- '_type' => [ '@type' => 'xsd:string' ],
- 'hasStruct' => [ '@type' => 'xsd:integer' ], // 0 - removed, old, 1 - has config, structure
- 'isStructInstalled' => [ '@type' => 'xsd:integer' ], // installed
- 'isObjectActive' => [ '@type' => 'xsd:integer' ], // (0,1) - admin settings with restrictions: (hasStruct, isStructInstalled, all fields installed and with idZasob)
- 'description' => [ '@type' => 'xsd:string' ],
- 'name' => [ '@type' => 'p5:string' ],
- 'typeName' => [ '@type' => 'p5:string' ],
- 'nsPrefix' => [ '@type' => 'p5:string' ],
- 'reinstallLink' => [ '@type' => 'p5:www_link' ],
- // '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' ],
- 'field' => [ '@ref' => 'default_objects/SystemObjectField', '@maxOccurs' => 'unbounded' ]
- ]
- ];
- // public $_rootTableName = 'CRM_LISTA_ZASOBOW';
- public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT';
- public $_version = '1';
- // public function __construct($simpleSchema = null) {
- // parent::__construct($simpleSchema);
- // 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($idDatabase = null) {
- DBG::simpleLog('schema', "SystemObject::updateCache...");
- // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
- DB::getPDO()->execSql("
- create table if not exists `{$this->_rootTableName}` (
- `idZasob` int(11) DEFAULT NULL,
- `idDatabase` int(11) NOT NULL,
- `namespace` varchar(255) DEFAULT '',
- `_rootTableName` varchar(255) DEFAULT '',
- `_type` varchar(255) DEFAULT '',
- `hasStruct` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'has structure',
- `isStructInstalled` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'has installed structure',
- `isObjectActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'object is active',
- `description` varchar(255) DEFAULT '',
- `primaryKey` varchar(255) DEFAULT '',
- UNIQUE KEY `idZasob` (idZasob),
- UNIQUE KEY `namespace` (namespace),
- KEY `isObjectActive` (isObjectActive)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin2
- ");
- try {
- DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `primaryKey` VARCHAR(255) NOT NULL DEFAULT '' AFTER `description` ");
- } catch (Exception $e) {
- DBG::log($e);
- }
- DB::getPDO()->execSql(" update `{$this->_rootTableName}` set hasStruct = 0 ");
- $idDefDB = DB::getPDO()->getZasobId();
- $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
- foreach ($sourceStorage->getItems([ 'f_hasConfig' => 1 ]) as $source) {
- if ('default_objects' == $source['nsPrefix']) {
- $clsFiles = array_map(function ($clsFile) {
- return substr($clsFile, strlen(APP_PATH_LIB . "/Schema/"), -1 * strlen('StorageAcl.php'));
- // return str_replace('/', '_', substr($clsFile, strlen(APP_PATH_LIB . "/Schema/"), -1 * strlen('StorageAcl.php')));
- }, array_merge(
- glob(APP_PATH_LIB . "/Schema/*StorageAcl.php", GLOB_NOSORT),
- glob(APP_PATH_LIB . "/Schema/*/*StorageAcl.php", GLOB_NOSORT)
- ));
- DBG::log($clsFiles, 'array', "DBG glob default_objects");
- foreach ($clsFiles as $clsName) {
- try {
- $acl = SchemaFactory::loadDefaultObject($clsName);
- $namespace = $acl->getNamespace();
- DB::getPDO()->insertOrUpdate($this->_rootTableName, [
- 'namespace' => $namespace,
- 'idDatabase' => $source['idZasob'],
- '_type' => "StorageAcl",
- '_rootTableName' => $acl->getRootTableName(),
- 'hasStruct' => 1
- ]);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- }
- }
- DB::getPDO()->execSql("
- insert into `{$this->_rootTableName}` (namespace, idZasob, idDatabase, description, hasStruct)
- select concat('{$source['nsPrefix']}/', t.`DESC`)
- , t.ID as idZasob
- , '{$source['idZasob']}' as idDatabase
- , t.`OPIS` as description
- , 1 as hasStruct
- 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
- , hasStruct = 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}` (namespace, idDatabase, _rootTableName, _type, description)
- select concat('{$source['nsPrefix']}/', t.TABLE_NAME) as namespace
- , '{$source['idZasob']}' as idDatabase
- , t.TABLE_NAME as _rootTableName
- , 'TableAcl' as _type
- , t.TABLE_COMMENT as description
- from INFORMATION_SCHEMA.TABLES t
- where t.TABLE_SCHEMA = '{$dbName}'
- and t.TABLE_NAME not like '%#%'
- on duplicate key update _rootTableName = t.TABLE_NAME
- ");
- DB::getPDO()->execSql("
- insert into `{$this->_rootTableName}` (namespace, idZasob, idDatabase, description, hasStruct)
- select IF(t.`DESC` like 'default_db/%',
- t.`DESC`,
- concat('{$source['nsPrefix']}/', t.`DESC`)
- ) as namespace
- , t.ID as idZasob
- , '{$source['idZasob']}' as idDatabase
- , t.`OPIS` as description
- , 1 as hasStruct
- 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
- , hasStruct = 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;
- }
- }
- }
- // Ant objects in: SE/schema/ant-object/
- foreach (glob(APP_PATH_SCHEMA . "/ant-object/*/*/build.xml", GLOB_NOSORT) as $buildXmlPath) {
- // SE/schema/ant-object/default_db.test_perms/TestPermsAnt/build.xml
- $file = substr($buildXmlPath, strlen(APP_PATH_SCHEMA . '/ant-object/'), -1 * strlen('/build.xml'));
- DBG::nicePrint($file, "file({$file})");
- list($partSource, $name) = explode('/', $file);
- list($sourceName, $rootTableName) = explode('.', $partSource);
- DBG::nicePrint([$sourceName, $rootTableName], "\$name='{$name}' - [\$lowerSource, \$rootTableName]");
- // $clsName = substr(basename($file), 0, -1 * strlen('StorageAcl.php'));
- try {
- // Lib::loadClass('AntAclBase');
- // $acl = AntAclBase::buildInstance(0, [
- // 'source' => $sourceName,
- // 'rootTableName' => $rootTableName,
- // 'name' => $name
- // ]);
- // $acl = SchemaFactory::loadDefaultObject($clsName);
- // $namespace = $acl->getNamespace();
- // $name = $acl->getName();
- $idDatabase = DB::getPDO($sourceName)->getZasobId();
- $namespace = "{$sourceName}/{$rootTableName}/{$name}";
- DB::getPDO()->insertOrUpdate($this->_rootTableName, [
- 'namespace' => $namespace,
- 'idDatabase' => $idDatabase,
- '_type' => "AntAcl",
- '_rootTableName' => $rootTableName,
- 'hasStruct' => 1
- ]);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- }
- }
- if ($activeProject = Config::getProjectPath()) {
- $baseAntObjectPath = "{$activeProject}/schema/ant-object";
- DBG::nicePrint($baseAntObjectPath, "\$baseAntObjectPath");
- foreach (glob("{$baseAntObjectPath}/*/*/build.xml", GLOB_NOSORT) as $file) {
- // SE/schema/ant-object/default_db.test_perms/TestPermsAnt/build.xml
- $file = substr($file, strlen("{$baseAntObjectPath}/"), -1 * strlen('/build.xml'));
- DBG::nicePrint($file, '$file');
- list($partSource, $name) = explode('/', $file);
- list($sourceName, $rootTableName) = explode('.', $partSource);
- DBG::nicePrint([$sourceName, $rootTableName, $name], '[$lowerSource, $rootTableName, $name]');
- // $clsName = substr(basename($file), 0, -1 * strlen('StorageAcl.php'));
- try {
- // Lib::loadClass('AntAclBase');
- // $acl = AntAclBase::buildInstance(0, [
- // 'source' => $sourceName,
- // 'rootTableName' => $rootTableName,
- // 'name' => $name
- // ]);
- // $acl = SchemaFactory::loadDefaultObject($clsName);
- // $namespace = $acl->getNamespace();
- // $name = $acl->getName();
- $idDatabase = DB::getPDO($sourceName)->getZasobId();
- $namespace = "{$sourceName}/{$rootTableName}/{$name}";
- DB::getPDO()->insertOrUpdate($this->_rootTableName, [
- 'namespace' => $namespace,
- 'idDatabase' => $idDatabase,
- '_type' => "AntAcl",
- '_rootTableName' => $rootTableName,
- 'hasStruct' => 1
- ]);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage());
- }
- }
- }
- // Fix objects AntAcl which struct is not installed
- $listAntAclObjectsToFix = DB::getPDO()->fetchAll("
- select t.*
- from `CRM_#CACHE_ACL_OBJECT` t
- where t._type = 'AntAcl'
- and t.idZasob is not NULL
- and t.hasStruct = 1
- and t.isStructInstalled = 0
- ");
- if (!empty($listAntAclObjectsToFix)) {
- UI::alert('info', "Fix AntAcl objects which is not installed (total: ".count($listAntAclObjectsToFix).")");
- foreach ($listAntAclObjectsToFix as $antAclInfo) {
- $namespace = $antAclInfo['namespace'];
- DBG::nicePrint($antAclInfo, "\$antAclInfo ({$namespace})");
- $zasobyStruct = DB::getPDO()->fetchAll("
- select z.ID, z.`DESC`
- from `CRM_LISTA_ZASOBOW` z
- where z.PARENT_ID = :parent_id
- and z.`TYPE` = 'KOMORKA'
- and z.A_STATUS not in ('DELETED')
- ", [ ':parent_id' => $antAclInfo['idZasob'] ]);
- DBG::nicePrint($zasobyStruct, "\$zasobyStruct ({$namespace})");
- ob_start();
- {
- Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
- $objFieldAcl = new Schema_SystemObjectFieldStorageAcl();
- $objFieldAcl->updateCache($namespace);
- $reinstallLog = ob_get_clean();
- }
- // DBG::nicePrint($reinstallLog, "\$reinstallLog ({$namespace})");
- $fieldCacheStruct = DB::getPDO()->fetchAll("
- select t.namespace, t.fieldNamespace
- from `CRM_#CACHE_ACL_OBJECT_FIELD` t
- where t.objectNamespace = :namespace
- and t.idZasob is NULL
- ", [ ':namespace' => $namespace ]);
- DBG::nicePrint($fieldCacheStruct, "\$fieldCacheStruct ({$namespace})");
- $fieldsToFix = [];
- foreach ($fieldCacheStruct as $cacheField) {
- $fieldName = $cacheField['fieldNamespace'];
- foreach ($zasobyStruct as $fieldZasob) {
- if ($fieldZasob['DESC'] === $fieldName) {
- $fieldsToFix[] = [
- 'idZasob' => $fieldZasob['ID'],
- 'namespace' => $cacheField['namespace'],
- ];
- }
- }
- }
- DBG::nicePrint($fieldsToFix, "\$fieldsToFix ({$namespace})");
- foreach ($fieldsToFix as $fixField) {
- $affected = SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
- 'namespace' => $fixField['namespace'],
- 'idZasob' => $fixField['idZasob']
- ]);
- if (!$affected) UI::alert('warning', "field ({$fixField['namespace']}) update idZasob failed");
- }
- $affected = SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
- 'namespace' => $namespace,
- 'isObjectActive' => 1
- ]);
- ($affected)
- ? UI::alert('success', "object ({$namespace}) activated")
- : UI::alert('warning', "object ({$namespace}) activation failed");
- }
- }
- // // foreach ... DB::getPDO($idDatabase)->fetchAll(select real _rootTableName)
- // foreach (Core_AclHelper::getCustomAclList() 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 = [];
- DBG::log($params, 'array', "SystemObject::_parseWhere");
- 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[] = "t.idDatabase = " . DB::getPDO()->quote($params['#refFrom']['primaryKey'], PDO::PARAM_INT);
- }
- {
- $filterParams = [];
- $xsdFields = $this->getXsdTypes();
- 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:www_link' == $xsdFields[$fieldName]) {
- 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 clearGetItemCache($pk = null) {
- if (!$this->_cache) return;
- 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 (1 === count($params) && "*,field" === V::get('propertyName', '', $params)) {
- if (array_key_exists($pk, $this->_cache)) return $this->_cache[$pk];
- $this->_cache[$pk] = $this->_fetchItem($pk, $params);
- } else {
- return $this->_fetchItem($pk, $params);
- }
- return $this->_cache[$pk];
- }
- public function _fetchItem($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);
- $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}"
- : '';
- Lib::loadClass('AclQueryItems');
- $query = new AclQueryItems($this);
- $query->setParams($params);
- $query->setSource('default_db');
- $query->setRawSql("
- select t.*
- from `{$this->_rootTableName}` t
- {$sqlWhere}
- {$sqlOrderBy}
- {$sqlLimit}
- ");
- return $query->fetchAll();
- }
- public function buildFeatureFromSqlRow($item, $params = []) {
- DBG::log($params, 'array', "buildFeatureFromSqlRow... '{$item['namespace']}'");
- $exNs = explode('/', $item['namespace']);
- $item['name'] = array_pop($exNs);
- $item['nsPrefix'] = implode('__x3A__', $exNs);
- $item['typeName'] = implode('__x3A__', $exNs) . ':' . $item['name'];
- $item['reinstallLink'] = Router::getRoute('Storage_AclReinstall')->getLink('', [ 'namespace' => $item['namespace'] ]);
- if (!empty($params['propertyName'])) {
- if (is_string($params['propertyName'])) $params['propertyName'] = explode(',', $params['propertyName']);
- if (!is_array($params['propertyName'])) throw new Exception("Wrong param propertyName - expected array or string");
- foreach ($params['propertyName'] as $fetchField) {
- if ('*' == $fetchField) continue;
- if ('field' == $fetchField) {
- $item['field'] = SchemaFactory::loadDefaultObject('SystemObjectField')->getItems([
- '__backRef' => [
- 'namespace' => 'default_objects/SystemObject',
- 'primaryKey' => $item['namespace']
- ]
- ]);
- }
- }
- }
- return $item;
- }
- 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;
- foreach ($itemPatch as $fieldName => $value) {
- if ('isStructInstalled' == $fieldName) continue;
- if ('isObjectActive' == $fieldName) continue;
- if ('primaryKey' == $fieldName) continue;
- throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
- }
- return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
- }
- }
|