AclHelper.php 30 KB

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