AclHelper.php 28 KB

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