Status.php 15 KB

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