AclHelper.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. <?php
  2. Lib::loadClass('Api_WfsNs');
  3. Lib::loadClass('ProcesHelper');
  4. Lib::loadClass('Router');
  5. Lib::loadClass('Route_UrlAction');
  6. class Core_AclHelper {// Helper class for Acl
  7. public static function hasCreatePerms($acl) {
  8. foreach ($acl->getFieldListByIdZasob() as $fieldName) {// TODO: use getFieldList
  9. // echo"<p>\$acl->canCreateField({$fieldName}): (".$acl->canCreateField($fieldName).")</p>";
  10. DBG::log($acl->canCreateField($fieldName), 'array', "\$acl->canCreateField({$fieldName})");
  11. if ($acl->canCreateField($fieldName)) return true;
  12. }
  13. return false;
  14. }
  15. public static function hasGeomFields($acl) {
  16. foreach ($acl->getFieldListByIdZasob() as $fieldName) {
  17. // echo"<p>\$acl->isGeomField({$fieldName}): (".$acl->isGeomField($fieldName).") \$acl->canReadField({$fieldName}): (".$acl->canReadField($fieldName).")</p>";
  18. if ($acl->isGeomField($fieldName) && $acl->canReadField($fieldName)) return true;
  19. }
  20. return false;
  21. }
  22. // @returns array [ field => string(perms like 'RWX') ]
  23. public static function getFieldPerms($acl) {// TODO: fetch perms for given Acl by namespace
  24. // TODO:? cache session or only current request (static)
  25. $fieldPerms = array();
  26. foreach ($acl->getFields() as $idField => $field) {
  27. $fieldPerms[ $field['name'] ] = $field['perms'];
  28. }
  29. return $fieldPerms;
  30. }
  31. public static function getExportFieldList($acl) {
  32. $exportFields = array();
  33. foreach (self::getFieldPerms($acl) as $fieldName => $perms) {
  34. if (false !== strpos($perms, 'E')) {
  35. $exportFields[] = $fieldName;
  36. }
  37. }
  38. return $exportFields;
  39. }
  40. public static function getAclByTypeName($typeName, $forceTblAclInit = false) {// TODO: replace getAclFromTypeName in WFS
  41. return self::getAclByNamespace(str_replace(':', '/', $typeName), $forceTblAclInit);
  42. }
  43. public static function getAclByNamespace($namespace, $forceTblAclInit = false, $objItem = null) { // TODO: mv to ACL
  44. try {
  45. if (!$objItem) {
  46. Lib::loadClass('SchemaFactory');
  47. $objItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem(str_replace('__x3A__', '/', $namespace), ['propertyName'=>"*,field"]);
  48. }
  49. DBG::log($objItem, 'array', "DBG objItem({$namespace})");
  50. if (!$objItem['idZasob']) throw new Exception("Missing idZasob for namespace '{$namespace}'");
  51. if (!in_array($objItem['_type'], [
  52. // 'TableAcl', // TODO: TEST - to replace TableAcl by AntAcl or use object with namespace + '/tableName'?
  53. 'AntAcl',
  54. ])) throw new Exception("Not Implemented acl type '{$objItem['_type']}'");
  55. if (!$objItem['isObjectActive']) {
  56. if (!$objItem['hasStruct']) throw new Exception("namespace has no structure '{$namespace}'");
  57. if (!$objItem['isStructInstalled']) throw new Exception("namespace structure not installed '{$namespace}'");
  58. throw new Exception("namespace is not activated '{$namespace}'");
  59. }
  60. Lib::loadClass('AntAclBase');
  61. $acl = AntAclBase::buildInstance($objItem['idZasob'], $objItem);
  62. return $acl;
  63. } catch (Exception $e) {
  64. DBG::log($e);
  65. }
  66. $ns = self::parseNamespaceUrl($namespace);
  67. DBG::log($ns, 'array', "parseNamespaceUrl({$namespace})");
  68. $acl = User::getAcl()->getObjectAcl($ns['prefix'], $ns['name']);
  69. $acl->init($forceTblAclInit);
  70. return $acl;
  71. }
  72. public static function getMoreFunctionsCell($acl, $args) {
  73. $id = V::get('primary_key', 0, $args, 'int');
  74. if ($id <= 0) throw new HttpException("404", 404);
  75. $record = V::get('record', null, $args);
  76. $rowFunList = array();
  77. $tableName = $acl->getName();
  78. $record = ($record)? $record : $acl->getItem($id);
  79. if(1){// TODO: fetch $totalMsgs from TableMsgs
  80. $msgs = Router::getRoute('Msgs');
  81. $msgsList = $msgs->getActiveMessagesForTableRecord($tableName, $id);
  82. $totalMsgs = count($msgsList);
  83. $rowFunc = new stdClass();
  84. $rowFunc->id = 'msgs';
  85. $rowFunc->ico = 'glyphicon glyphicon-envelope';
  86. $rowFunc->href = 'index.php?_route=TableMsgs&_task=tableRow&idTable=' . $acl->getID() . '&idRow=' . $id;
  87. $rowFunc->title = "Wiadomości ({$totalMsgs})";
  88. $rowFunc->label = "Wiadomości <span class=\"badge\">{$totalMsgs}</span>";
  89. $rowFunList[] = $rowFunc;
  90. }
  91. if ('CRM_PROCES' == $acl->getName()) {// TODO: mv to table gui xml or php class
  92. // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
  93. $rowFunc = new stdClass();
  94. $rowFunc->ico = 'glyphicon glyphicon-eye-open';
  95. $rowFunc->href = "procesy5.php?task=CRM_PROCES&filtr_id={$id}";
  96. $rowFunc->title = "Zobacz na drzewie procesów {{$id}}";
  97. $rowFunList[] = $rowFunc;
  98. $wskazniki = ProcesHelper::get_wskazniki($id);
  99. $connectedZasobyTotal = count($wskazniki);
  100. $rowFunc = new stdClass();
  101. $rowFunc->ico = 'glyphicon glyphicon-random';
  102. $rowFunc->href = "index.php?MENU_INIT=PROCES_ADD_ZASOB&procesID={$id}";
  103. $rowFunc->title = "Powiązane zasoby ({$connectedZasobyTotal})";
  104. $rowFunc->label = "Powiązane zasoby <span class=\"badge\">{$connectedZasobyTotal}</span>";
  105. $rowFunList[] = $rowFunc;
  106. }
  107. if ('CRM_LISTA_ZASOBOW' == $acl->getName()) {// TODO: mv to table gui xml or php class
  108. // procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id=22001
  109. $rowFunc = new stdClass();
  110. $rowFunc->ico = 'glyphicon glyphicon-eye-open';
  111. $rowFunc->href = "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$id}";
  112. $rowFunc->title = "Zobacz na drzewie zasobów [{$id}]";
  113. $rowFunList[] = $rowFunc;
  114. // index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob=22001
  115. $rowFunc = new stdClass();
  116. $rowFunc->ico = 'glyphicon glyphicon-random';
  117. $rowFunc->href = "index.php?MENU_INIT=ZASOB_OBOWIAZKI&id_zasob={$id}";
  118. $rowFunc->title = "Powiązane procesy (OB)";
  119. $rowFunList[] = $rowFunc;
  120. // index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob=22001
  121. $rowFunc = new stdClass();
  122. $rowFunc->ico = 'glyphicon glyphicon-random';
  123. $rowFunc->href = "index.php?MENU_INIT=ZASOB_EXTERNAL_IDS&id_zasob={$id}";
  124. $rowFunc->title = "Powiązane dane (IDS)";
  125. $rowFunList[] = $rowFunc;
  126. $groupTypeList = array();
  127. $groupTypeList[] = 'STANOWISKO';
  128. $groupTypeList[] = 'PODMIOT';
  129. $groupTypeList[] = 'DZIAL';
  130. if (in_array($record->TYPE, $groupTypeList)) {
  131. $rowFunc = new stdClass();
  132. $rowFunc->ico = 'glyphicon glyphicon-retweet';
  133. $rowFunc->href = "index.php?_route=Users&_task=syncGroup&idGroup={$id}";
  134. $rowFunc->title = "Synchronizuj do LDAP";
  135. $rowFunList[] = $rowFunc;
  136. }
  137. }
  138. if ('ADMIN_USERS' == $acl->getName()) {// TODO: mv to table gui xml
  139. if ($acl->canReadRecord($record) && $acl->canReadObjectField('ADM_ACCOUNT', $record)) {
  140. $rowFunc = new stdClass();
  141. $rowFunc->ico = 'glyphicon glyphicon-user';
  142. $rowFunc->href = 'index.php?_route=Users&_task=userGroups&usrLogin=' . $record->ADM_ACCOUNT;
  143. $rowFunc->title = "Ustal stanowisko";
  144. $rowFunList[] = $rowFunc;
  145. $rowFunc = new stdClass();
  146. $rowFunc->ico = 'glyphicon glyphicon-retweet';
  147. $rowFunc->href = 'index.php?_route=Users&_task=syncUser&usrLogin=' . $record->ADM_ACCOUNT;
  148. $rowFunc->title = "Synchronizuj do LDAP";
  149. $rowFunList[] = $rowFunc;
  150. $rowFunc = new stdClass();
  151. $rowFunc->ico = 'glyphicon glyphicon-minus';
  152. $rowFunc->href = 'index.php?MENU_INIT=USER_OCENA_PRACOWNIKA&usrLogin=' . $record->ADM_ACCOUNT;
  153. $rowFunc->title = "Ocena pracownika";
  154. $rowFunList[] = $rowFunc;
  155. }
  156. }
  157. if ($urlFunctions = Route_UrlAction::getTableFunctions($acl->getID(), $id, $acl->getName(), User::getLogin())) {
  158. foreach ($urlFunctions as $urlFunction) {
  159. // TODO: is allowed to view - test by Router::getRoute('UrlAction')->isFunctionAllowedForRecord($routeName = $urlFunction['name'], $acl->getID(), $id);
  160. $rowFunction = array();
  161. $rowFunction['href'] = $urlFunction['baseLink'];
  162. $rowFunction['ico'] = V::get('ico', 'glyphicon glyphicon-share', $urlFunction);
  163. $rowFunction['label'] = $urlFunction['label'];
  164. $rowFunction['title'] = V::get('title', $urlFunction['label'], $urlFunction);
  165. if (!empty($urlFunction['link_target'])) $rowFunction['target'] = $urlFunction['link_target'];
  166. if (!empty($urlFunction['cell_id_params'])) {
  167. $urlParams = array();// [ "{$urlParamName}={$paramValue}" ]
  168. foreach ($urlFunction['cell_id_params'] as $idField => $urlParamName) {
  169. $paramValue = '';
  170. $fld = $acl->getField($idField);
  171. if ($fld) {
  172. $fldName = $fld['name'];
  173. $paramValue = V::get($fldName, '', $record);
  174. $urlParams[] = "{$urlParamName}={$paramValue}";
  175. }
  176. }
  177. if (!empty($urlParams)) $rowFunction['href'] .= "&" . implode("&", $urlParams);
  178. }
  179. $rowFunList[] = $rowFunction;
  180. }
  181. }
  182. if (1) {// Druki
  183. $parsedNs = self::parseNamespaceUrl($acl->getNamespace());
  184. // array (
  185. // 'name' => 'TEST_PERMS',
  186. // 'prefix' => 'default_db',
  187. // 'url' => 'https://biuro.biall-net.pl/wfs/default_db',
  188. // 'sourceName' => 'default_db',
  189. // ),
  190. $typeName = "{$parsedNs['prefix']}:{$parsedNs['name']}";
  191. DBG::log([
  192. 'msg' => "getMoreFunctionsCell Druki",
  193. 'namespace' => $acl->getNamespace(),
  194. 'typeName' => $typeName,
  195. 'primaryKey' => $id,
  196. 'parseNamespace' => $parsedNs,
  197. ]);
  198. $rowFunList[] = [
  199. 'href' => Request::getPathUri() . "index.php?_route=UrlAction_Ant&typeName={$typeName}&primaryKey={$id}",
  200. 'ico' => 'glyphicon glyphicon-file',
  201. 'label' => "Druki",
  202. 'title' => "Druki"
  203. ];
  204. }
  205. DBG::log(['msg'=>"\$rowFunList", '$rowFunList'=>$rowFunList]);
  206. $ns = $acl->getNamespace();
  207. $partsNs = explode('/', $ns);
  208. $typeName = Api_WfsNs::typeName($acl->getNamespace());
  209. // DBG::log([
  210. // 'Api_WfsNs::typeName' => Api_WfsNs::typeName($acl->getNamespace()),
  211. // 'self::parseNamespaceUrl' => self::parseNamespaceUrl($acl->getNamespace()),
  212. // ], 'array', "DBG typeName");
  213. if (count($partsNs) > 2) { // is AntAcl
  214. $backRefList = ACL::getBackRefList($ns);
  215. DBG::log($backRefList, 'array', "\$backRefList");
  216. foreach ($backRefList as $backRef) { // [ namespace, idInstance ]
  217. $backRefLabel = $backRef['namespace']; // TODO: get DESC from Zasoby
  218. $backRefShort = explode("/", $backRefLabel);
  219. $backRefShort = array_pop($backRefShort);
  220. $backRefShort = (strlen($backRefShort) > 20) ? substr($backRefShort, 0, 20) . "..." : $backRefShort;
  221. // 'namespace' => 'default_db/BI_audit_KRS/BI_audit_KRS',
  222. // 'idInstance' => '24'
  223. $totalBackRefs = ACL::fetchBackRefs($acl->getNamespace(), $id, $backRef['namespace'], [ 'total' => true ]);
  224. DBG::log($backRefs, 'array', "\$backRefs {$backRef['namespace']} pk({$id})");
  225. $rowFunList[] = [
  226. 'ico' => 'glyphicon glyphicon-random',
  227. 'href' => Router::getRoute('ViewTableAjax')->getLink('', [
  228. 'namespace' => $backRef['namespace'],
  229. 'childRefNS' => $acl->getNamespace(),
  230. 'childRefPK' => $id,
  231. ]),
  232. 'title' => "Wyszukaj powiązania z '{$backRefLabel}'",
  233. 'label' => "Wyszukaj powiązania z '{$backRefShort}' <span class=\"badge\">{$totalBackRefs}</span>",
  234. ];
  235. }
  236. }
  237. return $rowFunList;
  238. }
  239. public static function getAclList() { return self::getCustomAclList(); } // TODO: RMME renamed to getCustomAclList
  240. public static function getCustomAclList() {// @usage Core_AclHelper::getCustomAclList();// @returns array [ $typeName , ... ]
  241. $aclList = array();
  242. // Schema_AccessGroupStorageAcl, load by User::getAcl()->getObjectAcl('default_objects', $objName);
  243. // $objClassName = "Schema_{$objName}StorageAcl";
  244. // if (!Lib::tryLoadClass($objClassName)) throw new HttpException("Not implemented", 501);
  245. // $ grep -r 'class ' SE/se-lib/Schema/*Acl.php
  246. // SE/se-lib/Schema/AccessGroupStorageAcl.php:class Schema_AccessGroupStorageAcl extends Core_AclBase
  247. // SE/se-lib/Schema/AccessOwnerStorageAcl.php:class Schema_AccessOwnerStorageAcl extends Core_AclBase
  248. // SE/se-lib/Schema/FileStorageAcl.php:class Schema_FileStorageAcl extends Core_AclBase
  249. // SE/se-lib/Schema/KorespondencjaStorageAcl.php:class Schema_KorespondencjaStorageAcl extends Core_AclBase
  250. // SE/se-lib/Schema/TestPermsStorageAcl.php:class Schema_TestPermsStorageAcl extends Core_AclBase
  251. $aclList[] = 'default_objects:AccessGroupRead';
  252. $aclList[] = 'default_objects:AccessGroupWrite';
  253. $aclList[] = 'default_objects:AccessOwner';
  254. $aclList[] = 'default_objects:SystemObject';// tabele i obiekty możliwe do podłączenia do procesu (default_db/*, default_objects/*)
  255. $aclList[] = 'default_objects:SystemFunction';// funkcje możliwe do podłączenia do procesu UrlAction
  256. // $aclList[] = 'default_objects:UserFunction';// TODO: funkcje możliwe do uruchomienia przez usera
  257. // $aclList[] = 'default_objects:UserObject';// TODO: tabele i obiekty widoczne dla aktualnego usera
  258. $aclList[] = 'default_objects:SystemProcess';// wszystkie proces init
  259. $aclList[] = 'default_objects:UserProcess';// proces init przypisane do aktualnego usera
  260. $aclList[] = 'default_objects:UserTestStats';// TODO: testy stats by user proces init
  261. $aclList[] = 'default_objects:File';
  262. $aclList[] = 'default_objects:Korespondencja';
  263. $aclList[] = 'default_objects:TestPerms';
  264. // TODO: read from Database
  265. // $aclList[] = 'default_db__x3A__TEST_PERMS:TEST_PERMS';// uproszczona wersja: default_db:TEST_PERMS
  266. $cleanHostName = str_replace(array(".", "-"), '_', $_SERVER['SERVER_NAME']);
  267. if (file_exists(APP_PATH_SCHEMA . "/gui/company/{$cleanHostName}/get_object_list.php")) {
  268. $objList = include APP_PATH_SCHEMA . "/gui/company/{$cleanHostName}/get_object_list.php";
  269. if (!empty($objList) && is_array($objList)) {
  270. foreach ($objList as $objectName) {
  271. if (!in_array($objectName, $aclList)) $aclList[] = $objectName;
  272. }
  273. }
  274. }
  275. return $aclList;
  276. }
  277. public static function parseTypeName($typeName) {
  278. return self::parseNamespaceUrl(str_replace(':', '/', $typeName));
  279. }
  280. /**
  281. * Parse namespace url into parts.
  282. *
  283. * @param $namespace - absolute or relative url
  284. * @return array:
  285. * name: element name
  286. * url: url wihtout name
  287. * prefix: xml prefix
  288. * sourceName: used by engine - maybe to remove (used by Core_AclHelper::getAclByNamespace($namespace))
  289. *
  290. * @example - create xmlns attribute:
  291. * xmlns:{$ns['prefix']}="{$ns['url']}"
  292. *
  293. * @example - wfs typeName:
  294. * typeName = "{$ns['prefix']}:{$ns['name']}"
  295. *
  296. * @example 'default_db/TEST_PERMS' => Array:
  297. * [name] => TEST_PERMS
  298. * [prefix] => default_db
  299. * [url] => https://biuro.biall-net.pl/wfs/default_db
  300. * [sourceName] => default_db
  301. *
  302. * @example 'default_objects/AccessOwner' => Array:
  303. * [name] => AccessOwner
  304. * [prefix] => default_objects
  305. * [url] => https://biuro.biall-net.pl/wfs/default_objects
  306. * [sourceName] => default_objects
  307. *
  308. * @example 'default_db/ZALICZKA/Zaliczka' => Array:
  309. * [name] => Zaliczka
  310. * [prefix] => default_db__x3A__Zaliczka
  311. * [url] => https://biuro.biall-net.pl/wfs/default_db/ZALICZKA
  312. * [sourceName] => table_objects
  313. *
  314. */
  315. public static function parseNamespaceUrl($namespace) {// returns assoc array: [ 'name', 'url', 'prefix', 'sourceName' ]
  316. // TODO: the same algo like getAclByNamespace($namespace)
  317. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  318. if ('http' != substr($namespace, 0, 4)) $namespace = "{$baseNsUri}/{$namespace}";//Request::getHostUri() . '/' . $namespace;
  319. $nsUrl = $baseNsUri . '/' . '';
  320. if ("{$baseNsUri}/" != substr($namespace, 0, strlen($baseNsUri) + 1)) throw new HttpException("Zasoby zewnętrzenj systemu nie są jeszcze zaimplementowane", 501);
  321. $relativeNsUrl = substr($namespace, strlen($baseNsUri) + 1);
  322. // convert '__x3A__' to '/' in url
  323. $nsEx = explode('/', str_replace('__x3A__', '/', $relativeNsUrl));// "http://biuro.biall-net.pl/wfs/ default_db/{$nazwa_tabeli}/{$nazwa_obj}
  324. // default_db__x3A__ZALICZKA/Zaliczka => default_db/ZALICZKA/Zaliczka
  325. $sourceName = array_shift($nsEx);// remove first element - source name
  326. $objName = array_pop($nsEx);// name is always last part from url
  327. if ('default_db' == $sourceName || 'p5_default_db' == $sourceName) {
  328. if (count($nsEx) > 1) throw new Exception("Nieznany namespace default_db: '{$relativeNsUrl}'", 501);
  329. $sourceName = 'default_db';
  330. $nsPrefix = $sourceName;
  331. if (1 == count($nsEx)) {
  332. $sourceName = 'table_objects';// TODO: another source name to read from simpleSchema @see Core_AclSimpleSchemaBase
  333. $nsPrefix = 'default_db__x3A__' . $nsEx[0];
  334. }
  335. // $objName = $nsEx[1];// 'default_db/ZALICZKA:Zaliczka' => ('objects', 'Zaliczka') - possible name conflicts
  336. $nsUrl = trim($baseNsUri . '/default_db/' . implode("/", $nsEx), '/');
  337. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  338. }
  339. else if ('default_objects' == $sourceName || 'SystemObjects' == $sourceName) {
  340. if (count($nsEx) > 1) throw new Exception("Nieznany namespace SystemObjects: '{$relativeNsUrl}'", 501);
  341. $sourceName = 'default_objects';
  342. $nsUrl = trim($baseNsUri . '/default_objects/' . implode("/", $nsEx), '/');
  343. $nsPrefix = 'default_objects';
  344. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  345. }
  346. else if ('p5_objects' == $sourceName || 'objects' == $sourceName) {
  347. if (count($nsEx) > 1) throw new Exception("Nieznany namespace SystemObjects: '{$relativeNsUrl}'", 501);
  348. $sourceName = 'default_objects';
  349. $nsUrl = trim($baseNsUri . '/default_objects/' . implode("/", $nsEx), '/');
  350. $nsPrefix = 'default_objects';
  351. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  352. }
  353. else if ('zasob_' == substr($sourceName, 0, 6)) {
  354. $dbName = substr($sourceName, 6);// database id
  355. $remotePdo = DB::getPDO($dbName);
  356. DBG::log($remotePdo, 'array', '$remotePdo');
  357. if (!$remotePdo || $remotePdo->getZasobId() <= 0) throw new Exception("Database [{$dbName}] not exists - namespace '{$relativeNsUrl}'", 501);
  358. if (count($nsEx) > 0) throw new Exception("Nieznany namespace {$sourceName}: '{$relativeNsUrl}'", 501);
  359. return [ 'name' => $objName, 'prefix' => $sourceName, 'url' => implode('/', [$baseNsUri, $sourceName, $objName]), 'sourceName' => $sourceName ];
  360. }
  361. else throw new Exception("Nieznany namespace '{$relativeNsUrl}'", 501);
  362. }
  363. public static function getIdDatabaseFromNamespace($namespace) {
  364. $ns = self::parseNamespaceUrl($namespace);
  365. if ('default_db' == substr($ns['sourceName'], 0, strlen('default_db'))) {
  366. return DB::getPDO()->getZasobId();
  367. } else if ('default_objects' == substr($ns['sourceName'], 0, strlen('default_objects'))) {
  368. return DB::getPDO()->getZasobId();
  369. } else if ('table_objects' == $ns['sourceName']) {
  370. if ('default_db' == substr($ns['prefix'], 0, strlen('default_db'))) {
  371. return DB::getPDO()->getZasobId();
  372. }
  373. } else if ('zasob_' == substr($ns['sourceName'], 0, strlen('zasob_'))) {
  374. // 'zasob_931', 'zasob_931__x3A__...'
  375. $idDatabase = substr($ns['sourceName'], strlen('zasob_'));
  376. if (false !== strpos($idDatabase, '_')) $idDatabase = substr($idDatabase, 0, strpos($idDatabase, '_'));
  377. if (!$idDatabase || !is_numeric($idDatabase)) throw new Exception("Not implemented idDatabase({$idDatabase})");
  378. return $idDatabase;
  379. }
  380. throw new Exception("Not implemented idDatabase for namespace({$namespace})");
  381. }
  382. public static function insertRef($objectName, $pk, $childName, $childPk) {// TODO: $idTransaction
  383. $refTable = self::getRefTable($objectName, $childName);
  384. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  385. $sqlChildPk = DB::getPDO()->quote($childPk, PDO::PARAM_STR);
  386. DB::getPDO()->exec("
  387. insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`)
  388. values ({$sqlPk}, {$sqlChildPk})
  389. ");
  390. }
  391. public static function cleanRefs($objectName, $pk, $childName) {// TODO: $idTransaction
  392. $refTable = self::getRefTable($objectName, $childName);
  393. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  394. DB::getPDO()->exec("
  395. update `{$refTable}` set `A_STATUS` = 'DELETED'
  396. where `PRIMARY_KEY` = {$sqlPk}
  397. ");
  398. }
  399. public static function getRefTable($objectName, $childName) {// TODO: wrong - add prefix to avoid name collisions or generate unique hash
  400. static $cacheRefTables = array();
  401. $refTable = "{$objectName}__#REF__{$childName}";
  402. if (in_array($refTable, $cacheRefTables)) return $refTable;
  403. DB::getPDO()->exec("
  404. CREATE TABLE IF NOT EXISTS `{$refTable}` (
  405. `PRIMARY_KEY` int(11) NOT NULL,
  406. `REMOTE_PRIMARY_KEY` int(11) NOT NULL,
  407. `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT '',
  408. `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING',
  409. `A_RECORD_UPDATE_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  410. -- TODO `TRANACTION_ID` int(11) NOT NULL
  411. KEY `PRIMARY_KEY` (`PRIMARY_KEY`),
  412. KEY `REMOTE_PRIMARY_KEY` (`REMOTE_PRIMARY_KEY`)
  413. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  414. ");
  415. try {
  416. DB::getPDO()->exec(" ALTER TABLE `{$refTable}` ADD `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING' ");
  417. } catch (Exception $e) {
  418. // echo 'C.'.get_class($this).' L.' . __LINE__ . " Error:";print_r($e->getMessage());echo "\n";
  419. }
  420. try {
  421. DB::getPDO()->exec(" ALTER TABLE `{$refTable}` ADD `A_RECORD_UPDATE_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ");
  422. } catch (Exception $e) {
  423. // echo 'C.'.get_class($this).' L.' . __LINE__ . " Error:";print_r($e->getMessage());echo "\n";
  424. }
  425. try {
  426. DB::getPDO()->exec(" ALTER TABLE `{$refTable}` ADD `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT '' ");
  427. } catch (Exception $e) {
  428. // echo 'C.'.get_class($this).' L.' . __LINE__ . " Error:";print_r($e->getMessage());echo "\n";
  429. }
  430. $cacheRefTables[] = $refTable;
  431. return $refTable;
  432. }
  433. public static function getInstanceTable($rootTableName) {
  434. static $cacheInstanceTables = array();
  435. $instanceTable = "{$rootTableName}__#INSTANCE";
  436. if (in_array($instanceTable, $cacheInstanceTables)) return $instanceTable;
  437. DB::getPDO()->execSql("
  438. CREATE TABLE IF NOT EXISTS `{$instanceTable}` (
  439. `PRIMARY_KEY` int(11) NOT NULL,
  440. `A_RECORD_UPDATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  441. `INSTANCE_NAME` varchar(255) NOT NULL,
  442. UNIQUE KEY `PRIMARY_KEY` (`PRIMARY_KEY`),
  443. KEY `INSTANCE_NAME` (`INSTANCE_NAME`)
  444. -- TODO `A_TRANACTION_ID` int(11) NOT NULL DEFAULT 0
  445. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  446. ");
  447. DB::getPDO()->execSql("
  448. CREATE TABLE IF NOT EXISTS `{$instanceTable}_HIST` (
  449. `ID` int(11) NOT NULL AUTO_INCREMENT,
  450. `PRIMARY_KEY` int(11) NOT NULL,
  451. `A_TRANACTION_ID` int(11) NOT NULL DEFAULT 0,
  452. `A_RECORD_UPDATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  453. `INSTANCE_NAME` varchar(255) NOT NULL,
  454. PRIMARY KEY (`ID`),
  455. KEY `PRIMARY_KEY` (`PRIMARY_KEY`)
  456. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  457. ");
  458. $cacheInstanceTables[] = $instanceTable;
  459. return $instanceTable;
  460. }
  461. public static function setInstance($rootTableName, $pk, $instanceName, $idTransaction = 0) {
  462. $instanceTable = self::getInstanceTable($rootTableName);
  463. $pk = intval($pk);
  464. // TODO: if $pk < 0 throw new Exception("...");
  465. $sql = [
  466. 'instanceName' => DB::getPDO()->quote($instanceName, PDO::PARAM_STR),
  467. 'idTransaction' => intval($idTransaction)
  468. ];
  469. DB::getPDO()->exec("
  470. insert into `{$instanceTable}_HIST` (`PRIMARY_KEY`, `INSTANCE_NAME`, `A_TRANACTION_ID`)
  471. values({$pk}, {$sql['instanceName']}, {$idTransaction})
  472. ");
  473. }
  474. public static function getChildHistTable($rootTableName, $childName, $schema) {
  475. // $childName(id) => Array:
  476. // [@type] => xsd:integer
  477. // $childName(created) => Array:
  478. // [@type] => xsd:date
  479. // $childName(worker) => Array:
  480. // [@ref] => default_objects/AccessOwner
  481. // $childName(kwota) => Array:
  482. // [@type] => xsd:decimal
  483. // [@totalDigits] => 16
  484. // [@fractionDigits] => 2
  485. // $childName(nierozliczona_kwota) => Array:
  486. // [@type] => xsd:decimal
  487. // [@totalDigits] => 16
  488. // [@fractionDigits] => 2
  489. // $childName(pozycja) => Array:
  490. // [@ref] => ZaliczkaPozycja
  491. // [@maxOccurs] => unbounded
  492. static $cacheHistTables = array();
  493. $histTable = "{$rootTableName}__#HIST__{$childName}";
  494. if (in_array($histTable, $cacheHistTables)) return $histTable;
  495. $sqlType = '';
  496. switch ($schema['@type']) {
  497. case 'xsd:integer': $sqlType = "int(11) NOT NULL DEFAULT 0"; break;
  498. case 'xsd:date': $sqlType = "date DEFAULT NULL"; break;
  499. case 'xsd:decimal': $sqlType = "decimal(" . V::get('@totalDigits', 16, $schema) . ", " . V::get('@fractionDigits', 2, $schema) . ") NOT NULL DEFAULT 0"; break;
  500. case 'xsd:string': $sqlType = "varchar(255) NOT NULL DEFAULT ''"; break;
  501. // TODO: type alias like enum fields: @type => "{$prefix}:{$field_name}Type"
  502. }
  503. if (!$sqlType && !empty($schema['@ref'])) $sqlType = "int(11) NOT NULL DEFAULT 0";// TODO: type from ref instance @primaryKey - mostly int
  504. if (!$sqlType) throw new Exception("Unimplemented schema to sql for '{$rootTableName}/{$childName}' schema(".json_encode($schema).")");
  505. DB::getPDO()->exec("
  506. CREATE TABLE IF NOT EXISTS `{$histTable}` (
  507. `ID` int(11) NOT NULL AUTO_INCREMENT,
  508. `VALUE` {$sqlType},
  509. `A_TRANSACTION_ID` int(11) NOT NULL DEFAULT 0,
  510. PRIMARY KEY (`ID`)
  511. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  512. ");
  513. $cacheHistTables[] = $histTable;
  514. return $histTable;
  515. }
  516. public static function getTransactionTable($rootTableName) {
  517. static $cacheTransactionTables = array();
  518. $transactionTable = "{$rootTableName}__#TRANSACTION";
  519. if (in_array($transactionTable, $cacheTransactionTables)) return $transactionTable;
  520. DB::getPDO()->exec("
  521. CREATE TABLE IF NOT EXISTS `{$transactionTable}` (
  522. `ID` int(11) NOT NULL AUTO_INCREMENT,
  523. `A_ACTION_ID_USER` int(11) DEFAULT NULL, -- NULL for scripts
  524. `A_ACTION_AUTHOR` varchar(255) NOT NULL DEFAULT '',
  525. `A_ACTION_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  526. `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING',
  527. `A_CONTEXT_TRANSACTION` varchar(255) NOT NULL DEFAULT '',
  528. PRIMARY KEY (`ID`)
  529. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  530. ");
  531. $cacheTransactionTables[] = $transactionTable;
  532. return $transactionTable;
  533. }
  534. public static function startTransaction($rootTableName, $idUser, $author = '') {
  535. $refTable = self::getTransactionTable($rootTableName);
  536. $sqlIdUser = ((int)$idUser > 0) ? DB::getPDO()->quote($idUser, PDO::PARAM_INT) : 'NULL';
  537. $sqlAuthor = DB::getPDO()->quote($author, PDO::PARAM_STR);
  538. DB::getPDO()->exec("
  539. insert into `{$refTable}` (`A_ACTION_ID_USER`, `A_ACTION_AUTHOR`)
  540. values ({$sqlIdUser}, {$sqlAuthor})
  541. ");
  542. return DB::getPDO()->lastInsertId();
  543. }
  544. public static function rollbackTransaction($rootTableName, $idTransaction) {
  545. // TODO: ROLLBACK - do nothing
  546. }
  547. public static function commitTransaction($idTransaction, $simpleSchema_or_acl) {
  548. // TODO: COMMIT
  549. // TODO: save changes to rootTableName and every childrens - recurence
  550. }
  551. public static function commitContextTransaction($rootTableName, $rootIdTransaction, $simpleSchema_or_acl_for_child) {
  552. // TODO: COMMIT - changes for childrens
  553. // TODO: find transaction with context transaction like "{$rootTableName}.{$rootIdTransaction}" = A_CONTEXT_TRANSACTION
  554. // TODO: save changes to rootTableName and every childrens - recurence
  555. }
  556. }