Status.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('UI');
  4. Lib::loadClass('Response');
  5. Lib::loadClass('SchemaFactory');
  6. class Route_Status extends RouteBase {
  7. public function defaultAction() {
  8. UI::gora();
  9. UI::startTag('div', ['class' => "container"]);
  10. echo UI::h('h1', [], [
  11. UI::h('a', ['href'=>"index.php"], "SE"),
  12. " &raquo; ",
  13. " Status systemu procesy5"
  14. ]);
  15. try {
  16. DB::getPDO();
  17. $this->runPostTask();
  18. $this->viewStatusDatabase();
  19. if (in_array(User::get('ADM_ADMIN_LEVEL'), ['0', '1'])) {
  20. $this->viewStatusUsers();
  21. }
  22. // UI::table([
  23. // 'caption' => 'Baza danych',
  24. // 'rows' => DB::getPDO()->fetchAll(" SHOW VARIABLES ")
  25. // ]);
  26. } catch (Exception $e) {
  27. UI::alert('danger', $e->getMessage());
  28. }
  29. UI::endTag('div');// .container
  30. UI::dol();
  31. }
  32. function runPostTask() {
  33. if ($postTask = V::get('_postTask', '', $_REQUEST)) {
  34. DBG::log($args, 'array', "exec '{$postTask}'");
  35. if (!method_exists($this, "{$postTask}PostTask")) throw new Exception("Post Task not exists!");
  36. ob_start();
  37. $this->{"{$postTask}PostTask"}($args);
  38. $outputPostTask = ob_get_clean();
  39. if ($outputPostTask) {
  40. echo UI::h('details', [], [
  41. UI::h('summary', [], "Wynik '{$postTask}' <i>(rozwiń)</i>"),
  42. $outputPostTask,
  43. ]);
  44. }
  45. }
  46. }
  47. public function viewStatusDatabase() {
  48. $dbEvents = DB::getPDO()->fetchFirst(" SHOW VARIABLES WHERE VARIABLE_NAME = 'event_scheduler' ");
  49. // DBG::nicePrint($dbEvents, '$dbEvents');
  50. // [Variable_name] => event_scheduler
  51. // [Value] => ON
  52. $aclObjectCacheExists = false;
  53. $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  54. $aclCacheTableName = $objectStorage->getRootTableName();
  55. if ($aclCacheTableName) {
  56. try {
  57. $totalObjects = DB::getPDO()->fetchValue("select count(*) as cnt from `{$aclCacheTableName}`");
  58. if ($totalObjects > 0) $aclObjectCacheExists = true;
  59. } catch (Exception $e) {
  60. DBG::log($e);
  61. }
  62. }
  63. DBG::log($objectStorage, 'array', "\$objectStorage");
  64. DBG::log($objectStorage->getRootTableName(), 'array', "\$objectStorage->getRootTableName()");
  65. Lib::loadClass('RefConfig');
  66. $totalToUpdateRef = RefConfig::getToUpdateTotal();
  67. UI::table([
  68. 'caption' => UI::h('b', ['style' => "color:#000"], 'Baza danych'),
  69. 'rows' => [
  70. [
  71. 'nazwa' => "Event Scheduler (generowanie Grafika, itp.)",
  72. 'wartość' => ('ON' == $dbEvents['Value'])
  73. ? UI::h('span', ['class' => "label label-success"], "ON")
  74. : UI::h('span', ['class' => "label label-danger"], "OFF"),
  75. '#' => UI::hButtonPost("Włącz", [
  76. 'class' => "btn btn-xs btn-default",
  77. 'data' => [
  78. '_postTask' => 'fixEventSheduler',
  79. ]
  80. ])
  81. ],
  82. [
  83. 'nazwa' => "System obiektów (xsd)",
  84. 'wartość' => ($aclObjectCacheExists)
  85. ? UI::h('span', ['class' => "label label-success"], "ON")
  86. : UI::h('span', ['class' => "label label-danger"], "OFF"),
  87. '#' => UI::hButtonPost("Aktualizuj cache", [
  88. 'class' => "btn btn-xs btn-default",
  89. 'data' => [
  90. '_postTask' => 'updateObjectCache'
  91. ]
  92. ])
  93. ],
  94. [
  95. 'nazwa' => "Tabela z relacjami (REF)",
  96. 'wartość' => ($totalToUpdateRef)
  97. ? UI::h('span', ['class' => "label label-danger"], "wymaga aktualizacji ({$totalToUpdateRef})")
  98. : UI::h('span', ['class' => "label label-success"], "akualne"),
  99. '#' => UI::hButtonPost("Aktualizuj tabele relacyjne", [
  100. 'class' => "btn btn-xs btn-default",
  101. 'data' => [
  102. '_postTask' => 'updateRefTables'
  103. ]
  104. ])
  105. ],
  106. ]
  107. ]);
  108. }
  109. public function fixEventShedulerPostTask() {
  110. DB::getPDO()->execSql(" SET GLOBAL event_scheduler='ON' ");
  111. }
  112. public function updateObjectCachePostTask() {
  113. DBG::log("updateObjectCachePostTask...");
  114. SchemaFactory::loadDefaultObject('SystemSource')->updateCache();
  115. SchemaFactory::loadDefaultObject('SystemObject')->updateCache();
  116. SchemaFactory::loadDefaultObject('SystemObjectField')->updateCache();
  117. UI::alert('info', "Lista obiketów zaktualizowana");
  118. }
  119. function updateRefTablesPostTask() {
  120. Lib::loadClass('RefConfig');
  121. DBG::log("DBG:updateRefTablesPostTask...");
  122. $toUpdateStep = 10;
  123. $baseRefOffset = V::get('baseref_offset', 0, $_POST, 'int');
  124. $backRefOffset = V::get('backref_offset', 0, $_POST, 'int');
  125. $todoBaseRefOffset = $baseRefOffset;
  126. $todoBackRefOffset = $backRefOffset;
  127. $baseRefToUpdate = RefConfig::getToUpdateItems();
  128. DBG::log($baseRefToUpdate, 'array', "DBG:updateRefTablesPostTask \$baseRefToUpdate");
  129. if ($baseRefOffset > count($baseRefToUpdate)) {
  130. $backRefToUpdate = RefConfig::getToUpdateItems('backRef');
  131. $listBackRefConf = array_slice($backRefToUpdate, $backRefOffset, $toUpdateStep);
  132. DBG::log($listBackRefConf, 'array', "DBG:updateRefTablesPostTask \$listBackRefConf ({$backRefOffset}, {$toUpdateStep})");
  133. self::_updateRefTables($listBackRefConf);
  134. $todoBackRefOffset = $backRefOffset + $toUpdateStep;
  135. } else {
  136. $listBaseRefConf = array_slice($baseRefToUpdate, $baseRefOffset, $toUpdateStep);
  137. DBG::log($listBaseRefConf, 'array', "DBG:updateRefTablesPostTask \$listBaseRefConf ({$baseRefOffset}, {$toUpdateStep})");
  138. self::_updateRefTables($listBaseRefConf);
  139. $todoBaseRefOffset = $baseRefOffset + $toUpdateStep;
  140. }
  141. $totalToUpdateRef = RefConfig::getToUpdateTotal();
  142. echo ($totalToUpdateRef)
  143. ? UI::h('div', [ 'class' => 'alert alert-warning'], [
  144. "Uwaga: Struktura tabel z relacjami częściowo zaktualizowana. Pozostało {$totalToUpdateRef}. ",
  145. UI::hButtonPost("Uruchom dla kolejnych", [
  146. 'class' => "btn btn-xs btn-default",
  147. 'data' => [
  148. '_postTask' => 'updateRefTables',
  149. 'baseref_offset' => $todoBaseRefOffset,
  150. 'backref_offset' => $todoBackRefOffset,
  151. ]
  152. ])
  153. ])
  154. : UI::h('div', [ 'class' => 'alert alert-info' ], "Struktura tabel z relacjami zaktualizowana");
  155. }
  156. static function _updateRefTables($listRefConf) {
  157. Lib::loadClass('RefConfig');
  158. // $listRefConf = array_slice($listRefConf, 0, 10);
  159. $totalTableSkippedNotAcl = 0;
  160. $totalTableSkippedMissingAclType = 0;
  161. $totalTableSkippedFieldNotFound = 0;
  162. DBG::nicePrint($listRefConf, '$listRefConf');
  163. foreach ($listRefConf as $refConf) {
  164. try {
  165. UI::alert('info', "Aktualizuje ['{$refConf['ID']}'] od '{$refConf['ROOT_OBJECT_NS']}' do '{$refConf['CHILD_NAME']}' ...");
  166. RefConfig::getRefConfig($refConf['ROOT_OBJECT_NS'], $refConf['CHILD_NAME'], $refConf['CHILD_NS']);
  167. } catch (\Exception $e) {
  168. DBG::log($e);
  169. if ('Ref allowed only for AntAcl objects' === $e->getMessage()) {
  170. $totalTableSkippedNotAcl++;
  171. } else if ('Field ' === substr($e->getMessage(), 0, strlen('Field ')) && false !== strpos($e->getMessage(), 'not found')) {
  172. $totalTableSkippedFieldNotFound++;
  173. } else if ("Not Implemented acl type ''" === substr($e->getMessage(), 0, strlen("Not Implemented acl type ''"))) {
  174. $totalTableSkippedMissingAclType++;
  175. }
  176. UI::alert('danger', "Problem z aktualizacją tabeli z relacjami ['{$refConf['ID']}'] od '{$refConf['ROOT_OBJECT_NS']}' do '{$refConf['CHILD_NAME']}'");
  177. }
  178. }
  179. if ($totalTableSkippedNotAcl) UI::alert('warning', "Nie zaktualizowano {$totalTableSkippedNotAcl} tabeli z relajami - obiekty różnego typu od 'Acl'");
  180. if ($totalTableSkippedFieldNotFound) UI::alert('warning', "Nie zaktualizowano {$totalTableSkippedFieldNotFound} tabeli z relajami - pola 'do' nie istnieją");
  181. if ($totalTableSkippedMissingAclType) UI::alert('warning', "Nie zaktualizowano {$totalTableSkippedMissingAclType} tabeli z relajami - brak typu obiektu (Instance config)");
  182. }
  183. public function viewStatusUsers() {
  184. $nowMinus3Months = date("Y-m-d", mktime(0,0,0, date('m') - 1, date('d'), date('Y')));
  185. $sesUsers = DB::getPDO()->fetchAll("
  186. select c.ID, c.CONF_KEY, c.CONF_VAL
  187. from CRM_CONFIG c
  188. where c.CONF_KEY like 'acl_user_%_%_cache_update'
  189. and c.CONF_VAL > '{$nowMinus3Months}'
  190. ");
  191. $sesUsers = array_reduce( $sesUsers, function ($ret, $record) {
  192. // $format = "acl_user_{ID_USERS}_{ID_PROCES}_cache_update";
  193. list($idUser, $idProces) = explode('_', substr($record['CONF_KEY'], strlen('acl_user_'), -1 * strlen('_cache_update')));
  194. if (!array_key_exists($idUser, $ret)) {
  195. $ret[$idUser] = [
  196. 'idUser' => $idUser,
  197. 'lastUpdateAclCache' => $record['CONF_VAL'],
  198. 'log' => []
  199. ];
  200. } else {
  201. $ret[$idUser]['lastUpdateAclCache'] = ($record['CONF_VAL'] > $ret[$idUser]['lastUpdateAclCache'])
  202. ? $record['CONF_VAL']
  203. : $ret[$idUser]['lastUpdateAclCache'];
  204. }
  205. $ret[$idUser]['log'][] = [ 'ID_PROCES' => $idProces, 'data' => $record['CONF_VAL'] ];
  206. return $ret;
  207. }, [] );
  208. $sesUsers = array_map(function ($sesGroup) {
  209. return [
  210. 'idUser' => $sesGroup['idUser'],
  211. 'user' => DB::getPDO()->fetchValue("select u.ADM_ACCOUNT from ADMIN_USERS u where u.ID = {$sesGroup['idUser']}"),
  212. 'lastUpdateAclCache' => $sesGroup['lastUpdateAclCache'],
  213. 'log' => UI::h('span', [ 'style' => "color:#bbb" ], implode('<br>', array_map(function ($log) {
  214. return ($log['ID_PROCES'] > 0)
  215. ? "Filtr procesu {$log['ID_PROCES']} uruchomiony {$log['data']}"
  216. : "Filtr ogólny uruchomiony {$log['data']}";
  217. }, $sesGroup['log']))),
  218. ];
  219. }, $sesUsers);
  220. usort($sesUsers, function ($ua, $ub) {
  221. $a = $ua['lastUpdateAclCache'];
  222. $b = $ub['lastUpdateAclCache'];
  223. return ($a === $b)
  224. ? 0
  225. : ( ($a < $b)
  226. ? 1
  227. : -1
  228. ) ;
  229. });
  230. if ('0' == User::get('ADM_ADMIN_LEVEL')) {
  231. $sesUsers = array_map(function ($row) {
  232. $row['#'] = UI::h('div', [ 'style' => "display:inline-block", 'class' => "activateUserDebugBtn" . ( DBG::hasUserDebug($row['idUser'], User::getID()) ? ' active' : '' ) ], [
  233. UI::h('label', ['style' => "padding-right:6px; font-weight:normal"], "Debug"),
  234. UI::hButtonAjax("Włącz", "activateUserDebug", [
  235. 'class' => "btn btn-xs btn-default activateUserDebugBtn-activate",
  236. 'href' => $this->getLink('startUserDebugAjax'),
  237. 'data' => [ 'idUser' => $row['idUser'], 'do' => 'activate' ]
  238. ]),
  239. UI::hButtonAjax("Wyłącz", "activateUserDebug", [
  240. 'class' => "btn btn-xs btn-default activateUserDebugBtn-deactivate",
  241. 'href' => $this->getLink('startUserDebugAjax'),
  242. 'data' => [ 'idUser' => $row['idUser'], 'do' => 'deactivate' ]
  243. ]),
  244. ]);
  245. return $row;
  246. }, $sesUsers);
  247. }
  248. UI::table([
  249. 'caption' => UI::h('b', ['style' => "color:#000"], "Ostatnie logowania do aplikacji") . " <small>(update acl cache)</small>", // TODO: Aktualnie zalogowani użytkownicy
  250. 'rows' => $sesUsers
  251. ]);
  252. echo UI::h('style', ['type' => "text/css"], "
  253. .activateUserDebugBtn .activateUserDebugBtn-activate { display:inline }
  254. .activateUserDebugBtn .activateUserDebugBtn-deactivate { display:none }
  255. .activateUserDebugBtn.active .activateUserDebugBtn-activate { display:none }
  256. .activateUserDebugBtn.active .activateUserDebugBtn-deactivate { display:inline }
  257. ");
  258. echo UI::h('script', ['src'=>"static/vendor.js?_v=b636cab1", 'type'=>"text/javascript"]);
  259. echo UI::h('script', [], "
  260. (function (global) {
  261. if (!global.p5VendorJs.React) throw 'Missing p5VendorJs.React'
  262. if (!global.p5VendorJs.ReactDOM) throw 'Missing p5VendorJs.ReactDOM'
  263. if (!global.p5VendorJs.ToggleButton) throw 'Missing p5VendorJs.ToggleButton'
  264. if (!global.fetch) throw 'Missing global.fetch'
  265. var React = global.p5VendorJs.React
  266. var ReactDOM = global.p5VendorJs.ReactDOM
  267. var h = React.createElement
  268. function convertToReactToggle(n, activateBtn, deactivateBtn, isActive) {
  269. var toggleReact = document.createElement('div')
  270. toggleReact.style.display = 'inline-block'
  271. n.parentNode.insertBefore(toggleReact, n.nextSibling)
  272. deactivateBtn.style.display = 'none'
  273. activateBtn.style.display = 'none'
  274. function reactToggleBtnOnToggle(value) {
  275. if (value) {
  276. deactivateBtn.onclick()
  277. } else {
  278. activateBtn.onclick()
  279. }
  280. render_reactToggleBtn(!value)
  281. }
  282. function render_reactToggleBtn(state) {
  283. ReactDOM.render(
  284. h(global.p5VendorJs.ToggleButton, {
  285. value: state,
  286. onToggle: reactToggleBtnOnToggle
  287. })
  288. , toggleReact
  289. )
  290. }
  291. render_reactToggleBtn(isActive)
  292. }
  293. var toggles = document.querySelectorAll('.activateUserDebugBtn')
  294. for (var i = 0; i < toggles.length; i++) {
  295. var btns = toggles[i].querySelectorAll('a')
  296. if (2 !== btns.length) contiune;
  297. var activateBtn = btns[0]
  298. var deactivateBtn = btns[1]
  299. convertToReactToggle(toggles[i], activateBtn, deactivateBtn, toggles[i].classList.contains('active'))
  300. }
  301. })(window)
  302. ");
  303. UI::hButtonAjaxOnResponse("activateUserDebug", /* payload, n */ "
  304. p5UI__notifyAjaxCallback(payload)
  305. // console.log('activateUserDebug :: payload', payload)
  306. if ('success' !== payload.type) return false
  307. if (payload.body && 'active' in payload.body) {
  308. if (payload.body.active) {
  309. n.parentNode.classList.add('active')
  310. } else {
  311. n.parentNode.classList.remove('active')
  312. }
  313. }
  314. ");
  315. }
  316. public function startUserDebugAjaxAction() {
  317. Response::sendTryCatchJson(array($this, 'startUserDebugAjax'), $_POST);
  318. }
  319. public function startUserDebugAjax($args) {
  320. if ('0' !== (string)User::get('ADM_ADMIN_LEVEL')) throw new Exception("Access Denied");
  321. $idUser = V::get('idUser', 0, $args);
  322. if ($idUser <= 0) throw new Exception("Missing idUser");
  323. $do = V::get('do', 0, $args);
  324. if (!in_array($do, ['activate', 'deactivate'])) throw new Exception("Missing do");
  325. $hasDebug = DBG::hasUserDebug($idUser, User::getID());
  326. switch ($do) {
  327. case 'activate': DBG::startUserDebug($idUser, User::getID()); break;
  328. case 'deactivate': DBG::stopUserDebug($idUser, User::getID()); break;
  329. }
  330. return [
  331. 'type' => 'success',
  332. '__args' => $args,
  333. '__$hasDebug' => $hasDebug,
  334. 'body' => [
  335. 'active' => DBG::hasUserDebug($idUser, User::getID())
  336. ]
  337. ];
  338. }
  339. }