AclHelper.php 28 KB

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