AclHelper.php 27 KB

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