Status.php 16 KB

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