AclHelper.php 29 KB

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