Status.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. if (0) { // TEST
  147. // 5345 is backRef 2411
  148. $todoRef = DB::getPDO()->fetchAll("
  149. select c.ID, c.ROOT_OBJECT_NS, c.CHILD_NAME, c.CHILD_NS
  150. from `CRM_REF_CONFIG` c
  151. where c.A_STATUS = 'NORMAL' and c.ID = :id
  152. ", [
  153. ':id' => 2411,
  154. ]);
  155. self::_updateRefTables($todoRef);
  156. $todoRef = DB::getPDO()->fetchAll("
  157. select c.ID, c.ROOT_OBJECT_NS, c.CHILD_NAME, c.CHILD_NS
  158. from `CRM_REF_CONFIG` c
  159. where c.A_STATUS = 'NORMAL' and c.ID = :id
  160. ", [
  161. ':id' => 5345,
  162. ]);
  163. self::_updateRefTables($todoRef);
  164. return;
  165. }
  166. $toUpdateStep = 100;
  167. $todoType = V::get('type_type', 'base', $_POST); // base | back
  168. $idLast = V::get('id_last', 0, $_POST, 'int');
  169. // $baseRefToUpdate = RefConfig::getToUpdateItems('', $toUpdateStep, $idLast);
  170. $todoRef = [];
  171. if ('base' === $todoType) {
  172. $todoRef = RefConfig::getToUpdateItems('', $toUpdateStep, $idLast);
  173. if (empty($todoRef)) {
  174. $todoType = 'back';
  175. $idLast = 0;
  176. }
  177. }
  178. if ('back' === $todoType) {
  179. $todoRef = RefConfig::getToUpdateItems('backRef', $toUpdateStep, $idLast);
  180. }
  181. if (!empty($todoRef)) {
  182. self::_updateRefTables($todoRef);
  183. $lastRef = end($todoRef);
  184. $idLast = $lastRef['ID'];
  185. }
  186. DBG::nicePrint($todoRef, '$todoRef');
  187. DBG::nicePrint($idLast, '$idLast');
  188. $totalToUpdateRef = RefConfig::getToUpdateTotal();
  189. echo ($totalToUpdateRef)
  190. ? UI::h('div', [ 'class' => 'alert alert-warning'], [
  191. "Uwaga: Struktura tabel z relacjami częściowo zaktualizowana. Pozostało {$totalToUpdateRef}. ",
  192. UI::hButtonPost("Uruchom dla kolejnych", [
  193. 'class' => "btn btn-xs btn-default",
  194. 'data' => [
  195. '_postTask' => 'updateRefTables',
  196. 'id_last' => $idLast,
  197. 'type_type' => $todoType,
  198. ]
  199. ])
  200. ])
  201. : UI::h('div', [ 'class' => 'alert alert-info' ], "Struktura tabel z relacjami zaktualizowana");
  202. }
  203. static function _updateRefTables($listRefConf) {
  204. Lib::loadClass('RefConfig');
  205. // $listRefConf = array_slice($listRefConf, 0, 10);
  206. $totalTableSkippedNotAcl = 0;
  207. $totalTableSkippedMissingAclType = 0;
  208. $totalTableSkippedFieldNotFound = 0;
  209. DBG::nicePrint($listRefConf, '$listRefConf');
  210. foreach ($listRefConf as $refConf) {
  211. try {
  212. UI::alert('info', "Aktualizuje ['{$refConf['ID']}'] od '{$refConf['ROOT_OBJECT_NS']}' do '{$refConf['CHILD_NAME']}' ...");
  213. RefConfig::getRefConfig($refConf['ROOT_OBJECT_NS'], $refConf['CHILD_NAME'], $refConf['CHILD_NS']);
  214. // expected fix ref config and set current version if no errors
  215. } catch (\Exception $e) {
  216. echo UI::h('p', [ 'class' => "p5-refconfig-exception", 'style' => "display:none" ], "#ERROR: " . $e->getMessage());
  217. DBG::log($e);
  218. if ('Ref allowed only for AntAcl objects' === $e->getMessage()) {
  219. $totalTableSkippedNotAcl++;
  220. } else if ('Field ' === substr($e->getMessage(), 0, strlen('Field ')) && false !== strpos($e->getMessage(), 'not found')) {
  221. $totalTableSkippedFieldNotFound++;
  222. } else if ("Not Implemented acl type ''" === substr($e->getMessage(), 0, strlen("Not Implemented acl type ''"))) {
  223. $totalTableSkippedMissingAclType++;
  224. }
  225. UI::alert('danger', "Problem z aktualizacją tabeli z relacjami ['{$refConf['ID']}'] od '{$refConf['ROOT_OBJECT_NS']}' do '{$refConf['CHILD_NAME']}'");
  226. }
  227. }
  228. if ($totalTableSkippedNotAcl) UI::alert('warning', "Nie zaktualizowano {$totalTableSkippedNotAcl} tabeli z relajami - obiekty różnego typu od 'Acl'");
  229. if ($totalTableSkippedFieldNotFound) UI::alert('warning', "Nie zaktualizowano {$totalTableSkippedFieldNotFound} tabeli z relajami - pola 'do' nie istnieją");
  230. if ($totalTableSkippedMissingAclType) UI::alert('warning', "Nie zaktualizowano {$totalTableSkippedMissingAclType} tabeli z relajami - brak typu obiektu (Instance config)");
  231. }
  232. public function viewStatusUsers() {
  233. $nowMinus3Months = date("Y-m-d", mktime(0,0,0, date('m') - 1, date('d'), date('Y')));
  234. $sesUsers = DB::getPDO()->fetchAll("
  235. select c.ID, c.CONF_KEY, c.CONF_VAL
  236. from CRM_CONFIG c
  237. where c.CONF_KEY like 'acl_user_%_%_cache_update'
  238. and c.CONF_VAL > '{$nowMinus3Months}'
  239. ");
  240. $sesUsers = array_reduce( $sesUsers, function ($ret, $record) {
  241. // $format = "acl_user_{ID_USERS}_{ID_PROCES}_cache_update";
  242. list($idUser, $idProces) = explode('_', substr($record['CONF_KEY'], strlen('acl_user_'), -1 * strlen('_cache_update')));
  243. if (!array_key_exists($idUser, $ret)) {
  244. $ret[$idUser] = [
  245. 'idUser' => $idUser,
  246. 'lastUpdateAclCache' => $record['CONF_VAL'],
  247. 'log' => []
  248. ];
  249. } else {
  250. $ret[$idUser]['lastUpdateAclCache'] = ($record['CONF_VAL'] > $ret[$idUser]['lastUpdateAclCache'])
  251. ? $record['CONF_VAL']
  252. : $ret[$idUser]['lastUpdateAclCache'];
  253. }
  254. $ret[$idUser]['log'][] = [ 'ID_PROCES' => $idProces, 'data' => $record['CONF_VAL'] ];
  255. return $ret;
  256. }, [] );
  257. $sesUsers = array_map(function ($sesGroup) {
  258. return [
  259. 'idUser' => $sesGroup['idUser'],
  260. 'user' => DB::getPDO()->fetchValue("select u.ADM_ACCOUNT from ADMIN_USERS u where u.ID = {$sesGroup['idUser']}"),
  261. 'lastUpdateAclCache' => $sesGroup['lastUpdateAclCache'],
  262. 'log' => UI::h('span', [ 'style' => "color:#bbb" ], implode('<br>', array_map(function ($log) {
  263. return ($log['ID_PROCES'] > 0)
  264. ? "Filtr procesu {$log['ID_PROCES']} uruchomiony {$log['data']}"
  265. : "Filtr ogólny uruchomiony {$log['data']}";
  266. }, $sesGroup['log']))),
  267. ];
  268. }, $sesUsers);
  269. usort($sesUsers, function ($ua, $ub) {
  270. $a = $ua['lastUpdateAclCache'];
  271. $b = $ub['lastUpdateAclCache'];
  272. return ($a === $b)
  273. ? 0
  274. : ( ($a < $b)
  275. ? 1
  276. : -1
  277. ) ;
  278. });
  279. if ('0' == User::get('ADM_ADMIN_LEVEL')) {
  280. $sesUsers = array_map(function ($row) {
  281. $row['#'] = UI::h('div', [ 'style' => "display:inline-block", 'class' => "activateUserDebugBtn" . ( DBG::hasUserDebug($row['idUser'], User::getID()) ? ' active' : '' ) ], [
  282. UI::h('label', ['style' => "padding-right:6px; font-weight:normal"], "Debug"),
  283. UI::hButtonAjax("Włącz", "activateUserDebug", [
  284. 'class' => "btn btn-xs btn-default activateUserDebugBtn-activate",
  285. 'href' => $this->getLink('startUserDebugAjax'),
  286. 'data' => [ 'idUser' => $row['idUser'], 'do' => 'activate' ]
  287. ]),
  288. UI::hButtonAjax("Wyłącz", "activateUserDebug", [
  289. 'class' => "btn btn-xs btn-default activateUserDebugBtn-deactivate",
  290. 'href' => $this->getLink('startUserDebugAjax'),
  291. 'data' => [ 'idUser' => $row['idUser'], 'do' => 'deactivate' ]
  292. ]),
  293. ]);
  294. return $row;
  295. }, $sesUsers);
  296. }
  297. UI::table([
  298. 'caption' => UI::h('b', ['style' => "color:#000"], "Ostatnie logowania do aplikacji") . " <small>(update acl cache)</small>", // TODO: Aktualnie zalogowani użytkownicy
  299. 'rows' => $sesUsers
  300. ]);
  301. echo UI::h('style', ['type' => "text/css"], "
  302. .activateUserDebugBtn .activateUserDebugBtn-activate { display:inline }
  303. .activateUserDebugBtn .activateUserDebugBtn-deactivate { display:none }
  304. .activateUserDebugBtn.active .activateUserDebugBtn-activate { display:none }
  305. .activateUserDebugBtn.active .activateUserDebugBtn-deactivate { display:inline }
  306. ");
  307. echo UI::h('script', ['src'=>"static/vendor.js?_v=b636cab1", 'type'=>"text/javascript"]);
  308. echo UI::h('script', [], "
  309. (function (global) {
  310. if (!global.p5VendorJs.React) throw 'Missing p5VendorJs.React'
  311. if (!global.p5VendorJs.ReactDOM) throw 'Missing p5VendorJs.ReactDOM'
  312. if (!global.p5VendorJs.ToggleButton) throw 'Missing p5VendorJs.ToggleButton'
  313. if (!global.fetch) throw 'Missing global.fetch'
  314. var React = global.p5VendorJs.React
  315. var ReactDOM = global.p5VendorJs.ReactDOM
  316. var h = React.createElement
  317. function convertToReactToggle(n, activateBtn, deactivateBtn, isActive) {
  318. var toggleReact = document.createElement('div')
  319. toggleReact.style.display = 'inline-block'
  320. n.parentNode.insertBefore(toggleReact, n.nextSibling)
  321. deactivateBtn.style.display = 'none'
  322. activateBtn.style.display = 'none'
  323. function reactToggleBtnOnToggle(value) {
  324. if (value) {
  325. deactivateBtn.onclick()
  326. } else {
  327. activateBtn.onclick()
  328. }
  329. render_reactToggleBtn(!value)
  330. }
  331. function render_reactToggleBtn(state) {
  332. ReactDOM.render(
  333. h(global.p5VendorJs.ToggleButton, {
  334. value: state,
  335. onToggle: reactToggleBtnOnToggle
  336. })
  337. , toggleReact
  338. )
  339. }
  340. render_reactToggleBtn(isActive)
  341. }
  342. var toggles = document.querySelectorAll('.activateUserDebugBtn')
  343. for (var i = 0; i < toggles.length; i++) {
  344. var btns = toggles[i].querySelectorAll('a')
  345. if (2 !== btns.length) contiune;
  346. var activateBtn = btns[0]
  347. var deactivateBtn = btns[1]
  348. convertToReactToggle(toggles[i], activateBtn, deactivateBtn, toggles[i].classList.contains('active'))
  349. }
  350. })(window)
  351. ");
  352. UI::hButtonAjaxOnResponse("activateUserDebug", /* payload, n */ "
  353. p5UI__notifyAjaxCallback(payload)
  354. // console.log('activateUserDebug :: payload', payload)
  355. if ('success' !== payload.type) return false
  356. if (payload.body && 'active' in payload.body) {
  357. if (payload.body.active) {
  358. n.parentNode.classList.add('active')
  359. } else {
  360. n.parentNode.classList.remove('active')
  361. }
  362. }
  363. ");
  364. }
  365. public function startUserDebugAjaxAction() {
  366. Response::sendTryCatchJson(array($this, 'startUserDebugAjax'), $_POST);
  367. }
  368. public function startUserDebugAjax($args) {
  369. if ('0' !== (string)User::get('ADM_ADMIN_LEVEL')) throw new Exception("Access Denied");
  370. $idUser = V::get('idUser', 0, $args);
  371. if ($idUser <= 0) throw new Exception("Missing idUser");
  372. $do = V::get('do', 0, $args);
  373. if (!in_array($do, ['activate', 'deactivate'])) throw new Exception("Missing do");
  374. $hasDebug = DBG::hasUserDebug($idUser, User::getID());
  375. switch ($do) {
  376. case 'activate': DBG::startUserDebug($idUser, User::getID()); break;
  377. case 'deactivate': DBG::stopUserDebug($idUser, User::getID()); break;
  378. }
  379. return [
  380. 'type' => 'success',
  381. '__args' => $args,
  382. '__$hasDebug' => $hasDebug,
  383. 'body' => [
  384. 'active' => DBG::hasUserDebug($idUser, User::getID())
  385. ]
  386. ];
  387. }
  388. function checkDatabaseTablesPostTask() {
  389. $pdo = DB::getPDO();
  390. // DBG::nicePrint($pdo, "DB Info");
  391. // DBG::nicePrint(get_class_methods($pdo), "pdo methods");
  392. $tblName = V::get('_fixTable', '', $_POST);
  393. if (!empty($tblName)) {
  394. $sqlTableName = DB::getPDO()->identifierQuote($tblName);
  395. $fixReturn = DB::getPDO()->fetchAll(" repair table {$sqlTableName} ");
  396. echo UI::hTable([ 'caption' => "Naprawa tabeli '{$tblName}':", 'rows' => $fixReturn ]);
  397. $lastFixRow = end($fixReturn);
  398. if ('OK' === V::get('Msg_text', '', $lastFixRow)) {
  399. UI::alert('success', "Naprawiono tabelę '{$tblName}'");
  400. } else {
  401. UI::alert('danger', "Nie udało się naprawić tabeli '{$tblName}'");
  402. }
  403. }
  404. $listTables = DB::getPDO()->fetchValuesList("
  405. select TABLE_NAME
  406. from INFORMATION_SCHEMA.TABLES
  407. where TABLE_SCHEMA = :db_name
  408. and TABLE_TYPE = 'BASE TABLE'
  409. ", [
  410. ':db_name' => DB::getPDO()->getDatabaseName(),
  411. ]);
  412. DBG::nicePrint($listTables, "all tables");
  413. // $listTables = array_slice($listTables, 0, 10); // TODO: DBG
  414. UI::table([
  415. 'rows' => array_map(function ($tblName) {
  416. $fixTableBtn = UI::hButtonPost("napraw tabele", [
  417. 'class' => "btn btn-xs btn-primary",
  418. 'data' => [
  419. '_postTask' => 'checkDatabaseTables',
  420. '_fixTable' => $tblName,
  421. ]
  422. ]);
  423. return [
  424. 'table' => $tblName,
  425. 'status' => UI::h('details', [ 'open' => '' ], [
  426. UI::h('summary', [], [
  427. "check table `{$tblName}`",
  428. " ",
  429. $fixTableBtn,
  430. ]),
  431. UI::hTable([ 'rows' => DB::getPDO()->fetchAll(" check table `{$tblName}` ") ]),
  432. ]),
  433. ];
  434. }, $listTables)
  435. ]);
  436. }
  437. }