AclHelper.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. try {
  224. $totalBackRefs = ACL::fetchBackRefs($acl->getNamespace(), $id, $backRef['namespace'], [ 'total' => true ]);
  225. } catch (Exception $e) {
  226. DBG::log($e);
  227. continue;
  228. }
  229. DBG::log($totalBackRefs, 'array', "\$totalBackRefs {$backRef['namespace']} pk({$id})");
  230. $rowFunList[] = [
  231. 'ico' => 'glyphicon glyphicon-random',
  232. 'href' => Router::getRoute('ViewTableAjax')->getLink('', [
  233. 'namespace' => $backRef['namespace'],
  234. 'childRefNS' => $acl->getNamespace(),
  235. 'childRefPK' => $id,
  236. ]),
  237. 'title' => "Wyszukaj powiązania z '{$backRefLabel}'",
  238. 'label' => "Wyszukaj powiązania z '{$backRefShort}' <span class=\"badge\">{$totalBackRefs}</span>",
  239. ];
  240. }
  241. }
  242. return $rowFunList;
  243. }
  244. public static function getAclList() { return self::getCustomAclList(); } // TODO: RMME renamed to getCustomAclList
  245. public static function getCustomAclList() {// @usage Core_AclHelper::getCustomAclList();// @returns array [ $typeName , ... ]
  246. $aclList = array();
  247. // Schema_AccessGroupStorageAcl, load by User::getAcl()->getObjectAcl('default_objects', $objName);
  248. // $objClassName = "Schema_{$objName}StorageAcl";
  249. // if (!Lib::tryLoadClass($objClassName)) throw new HttpException("Not implemented", 501);
  250. // $ grep -r 'class ' SE/se-lib/Schema/*Acl.php
  251. // SE/se-lib/Schema/AccessGroupStorageAcl.php:class Schema_AccessGroupStorageAcl extends Core_AclBase
  252. // SE/se-lib/Schema/AccessOwnerStorageAcl.php:class Schema_AccessOwnerStorageAcl extends Core_AclBase
  253. // SE/se-lib/Schema/FileStorageAcl.php:class Schema_FileStorageAcl extends Core_AclBase
  254. // SE/se-lib/Schema/KorespondencjaStorageAcl.php:class Schema_KorespondencjaStorageAcl extends Core_AclBase
  255. // SE/se-lib/Schema/TestPermsStorageAcl.php:class Schema_TestPermsStorageAcl extends Core_AclBase
  256. $aclList[] = 'default_objects:AccessGroupRead';
  257. $aclList[] = 'default_objects:AccessGroupWrite';
  258. $aclList[] = 'default_objects:AccessOwner';
  259. $aclList[] = 'default_objects:SystemObject';// tabele i obiekty możliwe do podłączenia do procesu (default_db/*, default_objects/*)
  260. $aclList[] = 'default_objects:SystemFunction';// funkcje możliwe do podłączenia do procesu UrlAction
  261. // $aclList[] = 'default_objects:UserFunction';// TODO: funkcje możliwe do uruchomienia przez usera
  262. // $aclList[] = 'default_objects:UserObject';// TODO: tabele i obiekty widoczne dla aktualnego usera
  263. $aclList[] = 'default_objects:SystemProcess';// wszystkie proces init
  264. $aclList[] = 'default_objects:UserProcess';// proces init przypisane do aktualnego usera
  265. $aclList[] = 'default_objects:UserTestStats';// TODO: testy stats by user proces init
  266. $aclList[] = 'default_objects:File';
  267. $aclList[] = 'default_objects:Korespondencja';
  268. $aclList[] = 'default_objects:TestPerms';
  269. // TODO: read from Database
  270. // $aclList[] = 'default_db__x3A__TEST_PERMS:TEST_PERMS';// uproszczona wersja: default_db:TEST_PERMS
  271. $cleanHostName = str_replace(array(".", "-"), '_', $_SERVER['SERVER_NAME']);
  272. if (file_exists(APP_PATH_SCHEMA . "/gui/company/{$cleanHostName}/get_object_list.php")) {
  273. $objList = include APP_PATH_SCHEMA . "/gui/company/{$cleanHostName}/get_object_list.php";
  274. if (!empty($objList) && is_array($objList)) {
  275. foreach ($objList as $objectName) {
  276. if (!in_array($objectName, $aclList)) $aclList[] = $objectName;
  277. }
  278. }
  279. }
  280. return $aclList;
  281. }
  282. public static function parseTypeName($typeName) {
  283. return self::parseNamespaceUrl(str_replace(':', '/', $typeName));
  284. }
  285. /**
  286. * Parse namespace url into parts.
  287. *
  288. * @param $namespace - absolute or relative url
  289. * @return array:
  290. * name: element name
  291. * url: url wihtout name
  292. * prefix: xml prefix
  293. * sourceName: used by engine - maybe to remove (used by Core_AclHelper::getAclByNamespace($namespace))
  294. *
  295. * @example - create xmlns attribute:
  296. * xmlns:{$ns['prefix']}="{$ns['url']}"
  297. *
  298. * @example - wfs typeName:
  299. * typeName = "{$ns['prefix']}:{$ns['name']}"
  300. *
  301. * @example 'default_db/TEST_PERMS' => Array:
  302. * [name] => TEST_PERMS
  303. * [prefix] => default_db
  304. * [url] => https://biuro.biall-net.pl/wfs/default_db
  305. * [sourceName] => default_db
  306. *
  307. * @example 'default_objects/AccessOwner' => Array:
  308. * [name] => AccessOwner
  309. * [prefix] => default_objects
  310. * [url] => https://biuro.biall-net.pl/wfs/default_objects
  311. * [sourceName] => default_objects
  312. *
  313. * @example 'default_db/ZALICZKA/Zaliczka' => Array:
  314. * [name] => Zaliczka
  315. * [prefix] => default_db__x3A__Zaliczka
  316. * [url] => https://biuro.biall-net.pl/wfs/default_db/ZALICZKA
  317. * [sourceName] => table_objects
  318. *
  319. */
  320. public static function parseNamespaceUrl($namespace) {// returns assoc array: [ 'name', 'url', 'prefix', 'sourceName' ]
  321. // TODO: the same algo like getAclByNamespace($namespace)
  322. $baseNsUri = Api_WfsNs::getBaseWfsUri();
  323. if ('http' != substr($namespace, 0, 4)) $namespace = "{$baseNsUri}/{$namespace}";//Request::getHostUri() . '/' . $namespace;
  324. $nsUrl = $baseNsUri . '/' . '';
  325. if ("{$baseNsUri}/" != substr($namespace, 0, strlen($baseNsUri) + 1)) throw new HttpException("Zasoby zewnętrzenj systemu nie są jeszcze zaimplementowane", 501);
  326. $relativeNsUrl = substr($namespace, strlen($baseNsUri) + 1);
  327. // convert '__x3A__' to '/' in url
  328. $nsEx = explode('/', str_replace('__x3A__', '/', $relativeNsUrl));// "http://biuro.biall-net.pl/wfs/ default_db/{$nazwa_tabeli}/{$nazwa_obj}
  329. // default_db__x3A__ZALICZKA/Zaliczka => default_db/ZALICZKA/Zaliczka
  330. $sourceName = array_shift($nsEx);// remove first element - source name
  331. $objName = array_pop($nsEx);// name is always last part from url
  332. if ('default_db' == $sourceName || 'p5_default_db' == $sourceName) {
  333. if (count($nsEx) > 1) throw new Exception("Nieznany namespace default_db: '{$relativeNsUrl}'", 501);
  334. $sourceName = 'default_db';
  335. $nsPrefix = $sourceName;
  336. if (1 == count($nsEx)) {
  337. $sourceName = 'table_objects';// TODO: another source name to read from simpleSchema @see Core_AclSimpleSchemaBase
  338. $nsPrefix = 'default_db__x3A__' . $nsEx[0];
  339. }
  340. // $objName = $nsEx[1];// 'default_db/ZALICZKA:Zaliczka' => ('objects', 'Zaliczka') - possible name conflicts
  341. $nsUrl = trim($baseNsUri . '/default_db/' . implode("/", $nsEx), '/');
  342. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  343. }
  344. else if ('default_objects' == $sourceName || 'SystemObjects' == $sourceName) {
  345. if (count($nsEx) > 1) throw new Exception("Nieznany namespace SystemObjects: '{$relativeNsUrl}'", 501);
  346. $sourceName = 'default_objects';
  347. $nsUrl = trim($baseNsUri . '/default_objects/' . implode("/", $nsEx), '/');
  348. $nsPrefix = 'default_objects';
  349. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  350. }
  351. else if ('p5_objects' == $sourceName || 'objects' == $sourceName) {
  352. if (count($nsEx) > 1) throw new Exception("Nieznany namespace SystemObjects: '{$relativeNsUrl}'", 501);
  353. $sourceName = 'default_objects';
  354. $nsUrl = trim($baseNsUri . '/default_objects/' . implode("/", $nsEx), '/');
  355. $nsPrefix = 'default_objects';
  356. return [ 'name' => $objName, 'prefix' => $nsPrefix, 'url' => $nsUrl, 'sourceName' => $sourceName ];
  357. }
  358. else if ('zasob_' == substr($sourceName, 0, 6)) {
  359. $dbName = substr($sourceName, 6);// database id
  360. $remotePdo = DB::getPDO($dbName);
  361. DBG::log($remotePdo, 'array', '$remotePdo');
  362. if (!$remotePdo || $remotePdo->getZasobId() <= 0) throw new Exception("Database [{$dbName}] not exists - namespace '{$relativeNsUrl}'", 501);
  363. if (count($nsEx) > 0) throw new Exception("Nieznany namespace {$sourceName}: '{$relativeNsUrl}'", 501);
  364. return [ 'name' => $objName, 'prefix' => $sourceName, 'url' => implode('/', [$baseNsUri, $sourceName, $objName]), 'sourceName' => $sourceName ];
  365. }
  366. else throw new Exception("Nieznany namespace '{$relativeNsUrl}'", 501);
  367. }
  368. public static function getIdDatabaseFromNamespace($namespace) {
  369. $ns = self::parseNamespaceUrl($namespace);
  370. if ('default_db' == substr($ns['sourceName'], 0, strlen('default_db'))) {
  371. return DB::getPDO()->getZasobId();
  372. } else if ('default_objects' == substr($ns['sourceName'], 0, strlen('default_objects'))) {
  373. return DB::getPDO()->getZasobId();
  374. } else if ('table_objects' == $ns['sourceName']) {
  375. if ('default_db' == substr($ns['prefix'], 0, strlen('default_db'))) {
  376. return DB::getPDO()->getZasobId();
  377. }
  378. } else if ('zasob_' == substr($ns['sourceName'], 0, strlen('zasob_'))) {
  379. // 'zasob_931', 'zasob_931__x3A__...'
  380. $idDatabase = substr($ns['sourceName'], strlen('zasob_'));
  381. if (false !== strpos($idDatabase, '_')) $idDatabase = substr($idDatabase, 0, strpos($idDatabase, '_'));
  382. if (!$idDatabase || !is_numeric($idDatabase)) throw new Exception("Not implemented idDatabase({$idDatabase})");
  383. return $idDatabase;
  384. }
  385. throw new Exception("Not implemented idDatabase for namespace({$namespace})");
  386. }
  387. public static function insertRef($objectName, $pk, $childName, $childPk) {// TODO: $idTransaction
  388. $refTable = self::getRefTable($objectName, $childName);
  389. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  390. $sqlChildPk = DB::getPDO()->quote($childPk, PDO::PARAM_STR);
  391. DB::getPDO()->exec("
  392. insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`)
  393. values ({$sqlPk}, {$sqlChildPk})
  394. ");
  395. }
  396. public static function cleanRefs($objectName, $pk, $childName) {// TODO: $idTransaction
  397. $refTable = self::getRefTable($objectName, $childName);
  398. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  399. DB::getPDO()->exec("
  400. update `{$refTable}` set `A_STATUS` = 'DELETED'
  401. where `PRIMARY_KEY` = {$sqlPk}
  402. ");
  403. }
  404. public static function getRefTable($objectName, $childName) {// TODO: wrong - add prefix to avoid name collisions or generate unique hash
  405. static $cacheRefTables = array();
  406. $refTable = "{$objectName}__#REF__{$childName}";
  407. if (in_array($refTable, $cacheRefTables)) return $refTable;
  408. DB::getPDO()->exec("
  409. CREATE TABLE IF NOT EXISTS `{$refTable}` (
  410. `PRIMARY_KEY` int(11) NOT NULL,
  411. `REMOTE_PRIMARY_KEY` int(11) NOT NULL,
  412. `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT '',
  413. `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING',
  414. `A_RECORD_UPDATE_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  415. -- TODO `TRANACTION_ID` int(11) NOT NULL
  416. KEY `PRIMARY_KEY` (`PRIMARY_KEY`),
  417. KEY `REMOTE_PRIMARY_KEY` (`REMOTE_PRIMARY_KEY`)
  418. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  419. ");
  420. try {
  421. DB::getPDO()->exec(" ALTER TABLE `{$refTable}` ADD `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING' ");
  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 `A_RECORD_UPDATE_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ");
  427. } catch (Exception $e) {
  428. // echo 'C.'.get_class($this).' L.' . __LINE__ . " Error:";print_r($e->getMessage());echo "\n";
  429. }
  430. try {
  431. DB::getPDO()->exec(" ALTER TABLE `{$refTable}` ADD `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT '' ");
  432. } catch (Exception $e) {
  433. // echo 'C.'.get_class($this).' L.' . __LINE__ . " Error:";print_r($e->getMessage());echo "\n";
  434. }
  435. $cacheRefTables[] = $refTable;
  436. return $refTable;
  437. }
  438. public static function getInstanceTable($rootTableName) {
  439. static $cacheInstanceTables = array();
  440. $instanceTable = "{$rootTableName}__#INSTANCE";
  441. if (in_array($instanceTable, $cacheInstanceTables)) return $instanceTable;
  442. DB::getPDO()->execSql("
  443. CREATE TABLE IF NOT EXISTS `{$instanceTable}` (
  444. `PRIMARY_KEY` int(11) NOT NULL,
  445. `A_RECORD_UPDATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  446. `INSTANCE_NAME` varchar(255) NOT NULL,
  447. UNIQUE KEY `PRIMARY_KEY` (`PRIMARY_KEY`),
  448. KEY `INSTANCE_NAME` (`INSTANCE_NAME`)
  449. -- TODO `A_TRANACTION_ID` int(11) NOT NULL DEFAULT 0
  450. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  451. ");
  452. DB::getPDO()->execSql("
  453. CREATE TABLE IF NOT EXISTS `{$instanceTable}_HIST` (
  454. `ID` int(11) NOT NULL AUTO_INCREMENT,
  455. `PRIMARY_KEY` int(11) NOT NULL,
  456. `A_TRANACTION_ID` int(11) NOT NULL DEFAULT 0,
  457. `A_RECORD_UPDATE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  458. `INSTANCE_NAME` varchar(255) NOT NULL,
  459. PRIMARY KEY (`ID`),
  460. KEY `PRIMARY_KEY` (`PRIMARY_KEY`)
  461. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  462. ");
  463. $cacheInstanceTables[] = $instanceTable;
  464. return $instanceTable;
  465. }
  466. public static function setInstance($rootTableName, $pk, $instanceName, $idTransaction = 0) {
  467. $instanceTable = self::getInstanceTable($rootTableName);
  468. $pk = intval($pk);
  469. // TODO: if $pk < 0 throw new Exception("...");
  470. $sql = [
  471. 'instanceName' => DB::getPDO()->quote($instanceName, PDO::PARAM_STR),
  472. 'idTransaction' => intval($idTransaction)
  473. ];
  474. DB::getPDO()->exec("
  475. insert into `{$instanceTable}_HIST` (`PRIMARY_KEY`, `INSTANCE_NAME`, `A_TRANACTION_ID`)
  476. values({$pk}, {$sql['instanceName']}, {$idTransaction})
  477. ");
  478. }
  479. public static function getChildHistTable($rootTableName, $childName, $schema) {
  480. // $childName(id) => Array:
  481. // [@type] => xsd:integer
  482. // $childName(created) => Array:
  483. // [@type] => xsd:date
  484. // $childName(worker) => Array:
  485. // [@ref] => default_objects/AccessOwner
  486. // $childName(kwota) => Array:
  487. // [@type] => xsd:decimal
  488. // [@totalDigits] => 16
  489. // [@fractionDigits] => 2
  490. // $childName(nierozliczona_kwota) => Array:
  491. // [@type] => xsd:decimal
  492. // [@totalDigits] => 16
  493. // [@fractionDigits] => 2
  494. // $childName(pozycja) => Array:
  495. // [@ref] => ZaliczkaPozycja
  496. // [@maxOccurs] => unbounded
  497. static $cacheHistTables = array();
  498. $histTable = "{$rootTableName}__#HIST__{$childName}";
  499. if (in_array($histTable, $cacheHistTables)) return $histTable;
  500. $sqlType = '';
  501. switch ($schema['@type']) {
  502. case 'xsd:integer': $sqlType = "int(11) NOT NULL DEFAULT 0"; break;
  503. case 'xsd:date': $sqlType = "date DEFAULT NULL"; break;
  504. case 'xsd:decimal': $sqlType = "decimal(" . V::get('@totalDigits', 16, $schema) . ", " . V::get('@fractionDigits', 2, $schema) . ") NOT NULL DEFAULT 0"; break;
  505. case 'xsd:string': $sqlType = "varchar(255) NOT NULL DEFAULT ''"; break;
  506. // TODO: type alias like enum fields: @type => "{$prefix}:{$field_name}Type"
  507. }
  508. if (!$sqlType && !empty($schema['@ref'])) $sqlType = "int(11) NOT NULL DEFAULT 0";// TODO: type from ref instance @primaryKey - mostly int
  509. if (!$sqlType) throw new Exception("Unimplemented schema to sql for '{$rootTableName}/{$childName}' schema(".json_encode($schema).")");
  510. DB::getPDO()->exec("
  511. CREATE TABLE IF NOT EXISTS `{$histTable}` (
  512. `ID` int(11) NOT NULL AUTO_INCREMENT,
  513. `VALUE` {$sqlType},
  514. `A_TRANSACTION_ID` int(11) NOT NULL DEFAULT 0,
  515. PRIMARY KEY (`ID`)
  516. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  517. ");
  518. $cacheHistTables[] = $histTable;
  519. return $histTable;
  520. }
  521. public static function getTransactionTable($rootTableName) {
  522. static $cacheTransactionTables = array();
  523. $transactionTable = "{$rootTableName}__#TRANSACTION";
  524. if (in_array($transactionTable, $cacheTransactionTables)) return $transactionTable;
  525. DB::getPDO()->exec("
  526. CREATE TABLE IF NOT EXISTS `{$transactionTable}` (
  527. `ID` int(11) NOT NULL AUTO_INCREMENT,
  528. `A_ACTION_ID_USER` int(11) DEFAULT NULL, -- NULL for scripts
  529. `A_ACTION_AUTHOR` varchar(255) NOT NULL DEFAULT '',
  530. `A_ACTION_DATE` timestamp ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  531. `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING',
  532. `A_CONTEXT_TRANSACTION` varchar(255) NOT NULL DEFAULT '',
  533. PRIMARY KEY (`ID`)
  534. ) ENGINE=MyISAM DEFAULT CHARSET=latin2;
  535. ");
  536. $cacheTransactionTables[] = $transactionTable;
  537. return $transactionTable;
  538. }
  539. public static function startTransaction($rootTableName, $idUser, $author = '') {
  540. $refTable = self::getTransactionTable($rootTableName);
  541. $sqlIdUser = ((int)$idUser > 0) ? DB::getPDO()->quote($idUser, PDO::PARAM_INT) : 'NULL';
  542. $sqlAuthor = DB::getPDO()->quote($author, PDO::PARAM_STR);
  543. DB::getPDO()->exec("
  544. insert into `{$refTable}` (`A_ACTION_ID_USER`, `A_ACTION_AUTHOR`)
  545. values ({$sqlIdUser}, {$sqlAuthor})
  546. ");
  547. return DB::getPDO()->lastInsertId();
  548. }
  549. public static function rollbackTransaction($rootTableName, $idTransaction) {
  550. // TODO: ROLLBACK - do nothing
  551. }
  552. public static function commitTransaction($idTransaction, $simpleSchema_or_acl) {
  553. // TODO: COMMIT
  554. // TODO: save changes to rootTableName and every childrens - recurence
  555. }
  556. public static function commitContextTransaction($rootTableName, $rootIdTransaction, $simpleSchema_or_acl_for_child) {
  557. // TODO: COMMIT - changes for childrens
  558. // TODO: find transaction with context transaction like "{$rootTableName}.{$rootIdTransaction}" = A_CONTEXT_TRANSACTION
  559. // TODO: save changes to rootTableName and every childrens - recurence
  560. }
  561. }