UI.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. class UI {
  3. public static function getTitle() {
  4. $title = 'SE';
  5. $host = $_SERVER['SERVER_NAME'];
  6. if (substr($host, 0, 5) == 'biuro') {
  7. $host = substr($host, 6);
  8. }
  9. $title = "{$host}-SE";
  10. return $title;
  11. }
  12. public static function gora() {
  13. UI::startHtml();
  14. }
  15. public static function startHtml() {
  16. Lib::loadClass('S');
  17. UI::loadTemplate('_layout_gora');
  18. }
  19. public static function dol() {
  20. UI::endHtml();
  21. }
  22. public static function fixFooterPosition($type) {
  23. $fixFooterPosition = true;// from config?
  24. if (!$fixFooterPosition) return;
  25. switch ($type) {
  26. case 'footer_style': return 'position:absolute; bottom:0; left:0; width:100%; ';
  27. case 'body_style': return 'position:relative; padding-bottom:32px;';
  28. case 'footer_js_tag': return "\n<script>document.body.style.minHeight = '' + (window.innerHeight - 2) + 'px';</script>";
  29. }
  30. }
  31. public static function endHtml() {
  32. $version = (file_exists(APP_PATH_ROOT . '/VERSION'))? file_get_contents(APP_PATH_ROOT . '/VERSION') : null;
  33. if ($version) {
  34. echo '<div style="' . UI::fixFooterPosition('footer_style') . 'border-top:1px solid #ddd; margin-top:10px; padding:0 30px; font-size:xx-small; color:#888">version: '.$version.'</div>';
  35. }
  36. echo UI::fixFooterPosition('footer_js_tag');
  37. echo "\n</body></html>";
  38. }
  39. public static function menu() {
  40. if (!User::logged()) return;
  41. if (User::hasAccess('menu')) {
  42. Lib::loadClass('ProcesMenu');
  43. $procesMenu = ProcesMenu::getInstance();
  44. $procesMenu->show();
  45. // if (!V::get('MENU_INIT', '', $_GET)) {
  46. // Lib::loadClass('UserActivity');
  47. // //echo UserActivity::showListInContainer();
  48. // }
  49. }
  50. else {
  51. UI::loadTemplate('menuLevel6');
  52. }
  53. }
  54. public static function loadTemplate($tmplName, $data = array()) {
  55. if (is_array($data) && !empty($data)) {
  56. extract($data);
  57. }
  58. include APP_PATH_LIB . "/tmpl/{$tmplName}.php";
  59. }
  60. public static function hotKeyDBG($str) {
  61. if (User::hasAccess('dbg')) {
  62. echo '<span class="hidden-dbg">' . htmlspecialchars($str) . '</span>';
  63. }
  64. }
  65. public static function showMessagesForTable($tblName) {
  66. if (empty($tblName)) return;
  67. Lib::loadClass('Router');
  68. $msgsRoute = Router::getRoute('Msgs');
  69. $msgs = $msgsRoute->getActiveMessagesForTable($tblName);
  70. if (!empty($msgs)) {
  71. self::loadTemplate('msgsForTable', array('msgs' => $msgs));
  72. }
  73. }
  74. public static function alert($alertType, $msg, $outputHtml = true) {
  75. if (!$outputHtml) {
  76. $type = ('danger' == $alertType) ? "ERROR" : strtoupper($alertType);
  77. echo "{$type}: {$msg}\n";
  78. return;
  79. }
  80. UI::tag('div', ['class'=>"alert alert-{$alertType}"], $msg, "\n");
  81. }
  82. public static function setTitleJsTag($title) { self::setTitle($title); }
  83. public static function setTitle($title) { self::tag('script', null, "document.title = '{$title}';", "\n"); }
  84. /**
  85. * $params - Array
  86. * $params['caption'] (optional) -> <caption>...</caption>
  87. * $params['cols'] (optional) -> cols, if not set read from first row
  88. * $params['rows'] -> rows, if not set - empty table
  89. * $params['rows'] -> rows, if not set - empty table
  90. * $params['disable_lp'] -> disable lp. col
  91. */
  92. public static function table($params) {
  93. $cols = V::get('cols', array(), $params);
  94. $rows = V::get('rows', array(), $params);
  95. $cols_help = V::get('cols_help', array(), $params);
  96. $caption = V::get('caption', '', $params);
  97. $cellPadding = V::get('cell_padding', 2, $params, 'int');
  98. $showLp = (!V::get('disable_lp', false, $params));
  99. $countCols = 1;
  100. if (empty($cols) && !empty($rows)) {
  101. $firstRow = array();
  102. foreach ($rows as $row) {
  103. $firstRow = $row;
  104. break;
  105. }
  106. $cols = array_filter(
  107. array_keys((array)$firstRow),
  108. function ($col) {
  109. return ('@' != substr($col, 0, 1));
  110. }
  111. );
  112. }
  113. $countCols = count($cols);
  114. $countCols = ($showLp) ? $countCols + 1 : $countCols;
  115. {
  116. $help = array();
  117. foreach ($cols as $name) {
  118. $helpMsg = V::get($name, '', $cols_help);
  119. if (empty($helpMsg)) continue;
  120. $help[$name] = self::h('i', [
  121. 'class' => "glyphicon glyphicon-question-sign",
  122. 'title' => $helpMsg
  123. ], "");
  124. }
  125. }
  126. // if (empty($cols)) return;
  127. $hiddenCols = V::get('hidden_cols', array(), $params);
  128. $tableAttrs = [ 'class' => "table table-bordered table-hover" ];
  129. $html_id = V::get('__html_id', '', $params);
  130. if ($html_id) $tableAttrs['id'] = $html_id;
  131. self::startTag('table', $tableAttrs); echo "\n";
  132. if ($caption) { self::tag('caption', null, $caption); echo "\n"; }
  133. if (!empty($cols)) {
  134. self::startTag('thead', null); echo "\n";
  135. self::startTag('tr', null); echo "\n";
  136. if ($showLp) { self::tag('th', [ 'style' => "padding:2px" ], "Lp."); echo "\n"; }
  137. foreach ($cols as $colName) {
  138. if (in_array($colName, $hiddenCols)) continue;
  139. echo self::h('th', [ 'style' => "padding:2px" ], [
  140. $colName,
  141. " " . V::get($colName, '', $help)
  142. ]);
  143. echo "\n";
  144. }
  145. self::endTag('tr'); echo "\n";
  146. self::endTag('thead'); echo "\n";
  147. }
  148. $tbodyAttrs = [];
  149. if (array_key_exists('@tbody.id', $params)) $tbodyAttrs['id'] = $params['@tbody.id'];
  150. self::startTag('tbody', $tbodyAttrs); echo "\n";
  151. if (empty($rows)) {
  152. self::startTag('tr'); echo "\n";
  153. self::tag('td', [ 'style' => "padding:2px", 'colspan' => $countCols ], V::get('empty_msg', "Brak danych", $params)); echo "\n";
  154. self::endTag('tr'); echo "\n";
  155. } else {
  156. $i = 0;
  157. foreach ($rows as $row) {
  158. $i++;
  159. $trAttrs = array();
  160. if (!empty($row['@onClick'])) $trAttrs['onClick'] = $row['@onClick'];
  161. if (!empty($row['@class'])) $trAttrs['class'] = $row['@class'];
  162. if (!empty($row['@style'])) $trAttrs['style'] = $row['@style'];
  163. self::startTag('tr', $trAttrs); echo "\n";
  164. if ($showLp) { self::tag('th', [ 'style' => "padding:2px; color:#ccc" ], $i); echo "\n"; }
  165. foreach ($cols as $colName) {
  166. $rowAttrs = [ 'style' => "padding:{$cellPadding}px" ];
  167. if (!empty($row["@onClick[{$colName}]"])) $rowAttrs['onClick'] = $row["@onClick[{$colName}]"];
  168. if (!empty($row["@class[{$colName}]"])) $rowAttrs['class'] = $row["@class[{$colName}]"];
  169. if (!empty($row["@style[{$colName}]"])) $rowAttrs['style'] .= "; " . $row["@style[{$colName}]"];
  170. if (in_array($colName, $hiddenCols)) continue;
  171. self::tag('td', $rowAttrs, V::get($colName, '', $row)); echo "\n";
  172. }
  173. self::endTag('tr'); echo "\n";
  174. }
  175. }
  176. self::endTag('tbody'); echo "\n";
  177. self::endTag('table'); echo "\n";
  178. }
  179. public static function startContainer($attrs = array()) {// echo '<div class="container">' . "\n";
  180. $attrs['class'] = (!empty($attrs['class']))
  181. ? $attrs['class'] . ' ' . 'container'
  182. : 'container';
  183. self::startTag('div', $attrs, "\n");
  184. }
  185. public static function endContainer() { self::endTag('div', "\n"); }
  186. public static function startTag($tag, $attrs = array(), $addWhiteSpace = false) {
  187. $outAttrs = '';
  188. if (is_array($attrs)) {
  189. foreach ($attrs as $attrName => $val) $outAttrs .= " {$attrName}=\"{$val}\"";
  190. }
  191. echo '<' . $tag . $outAttrs . '>' . self::whiteSpace($addWhiteSpace);
  192. }
  193. public static function whiteSpace($addWhiteSpace = false) {
  194. return (!$addWhiteSpace)
  195. ? ''
  196. : (true === $addWhiteSpace) ? " " : $addWhiteSpace;
  197. }
  198. public static function endTag($tag, $addWhiteSpace = false) {
  199. echo '</' . $tag . '>' . self::whiteSpace($addWhiteSpace);
  200. }
  201. public static function tag($tag, $attrs = array(), $childrens = array(), $addWhiteSpace = false) {
  202. $whiteSpace = self::whiteSpace($addWhiteSpace);
  203. self::startTag($tag, $attrs);
  204. echo $whiteSpace;
  205. if (!empty($childrens) && is_array($childrens)) throw new Exception("UI::tag() children as nodes not implemented".json_encode($childrens));
  206. if (is_scalar($childrens)) echo $childrens;
  207. echo $whiteSpace;
  208. self::endTag($tag);
  209. echo $whiteSpace;
  210. }
  211. public static function emptyTag($tag, $attrs = array(), $addWhiteSpace = false) {
  212. $outAttrs = '';
  213. if (is_array($attrs)) {
  214. foreach ($attrs as $attrName => $val) $outAttrs .= " {$attrName}=\"{$val}\"";
  215. }
  216. echo '<' . $tag . $outAttrs . '/>' . self::whiteSpace($addWhiteSpace);
  217. }
  218. public static function link($type, $content, $href, $attrs = array()) {
  219. $attrs['class'] = V::get('class', '', $attrs);
  220. $attrs['class'] .= "btn btn-{$type}";
  221. if (!empty($attrs['className'])) {
  222. foreach ($attrs['className'] as $cls => $bool) {
  223. if ($bool) $attrs['class'] .= " {$cls}";
  224. }
  225. unset($attrs['className']);
  226. }
  227. $attrs['href'] = $href;
  228. UI::tag('a', $attrs, $content);
  229. }
  230. public static function jsAjaxTable($params) {
  231. }
  232. public static function price($value, $dec = ',') {
  233. // TODO: if not number type - string wwith wrong format - try to convert?
  234. return number_format($value, 2, $dec, ' ');
  235. }
  236. public static function inlineJS($jsFile, $jsonVars = []) {
  237. if (!file_exists($jsFile)) throw new Exception("js file '" . basename($jsFile) . "' not exists!");
  238. UI::startTag('script', [], "\n");
  239. echo "(function (global) {" . "\n";
  240. foreach ($jsonVars as $name => $var) {
  241. echo "var {$name} = " . json_encode($var) . ";\n";
  242. }
  243. include $jsFile;
  244. echo "})(window)" . "\n";
  245. UI::endTag('script', "\n");
  246. }
  247. public static function includeView($viewPath, $data = array()) {
  248. if (!file_exists($viewPath)) throw new Exception("view file '" . basename($viewPath) . "' not exists!");
  249. if (false === strpos($viewPath, APP_PATH_ROOT)) throw new Exception("Access Denied to include view '" . basename($viewPath) . "'!");
  250. if (is_array($data) && !empty($data)) {
  251. extract($data);
  252. }
  253. include $viewPath;
  254. }
  255. public static function postButton($label, $params = []) {
  256. UI::startTag('form', [
  257. 'action' => V::get('action', '', $params),
  258. 'method' => V::get('method', 'post', $params),
  259. 'style' => "display:inline"
  260. ]);
  261. foreach (V::get('data', [], $params, 'array') as $name => $value) {
  262. UI::emptyTag('input', ['type'=>'hidden', 'name'=>$name, 'value'=>$value]);
  263. }
  264. UI::tag('button', ['type'=>'submit', 'class' => 'btn ' . V::get('class', 'btn-default btn-xs', $params)], $label);
  265. UI::endTag('form');
  266. }
  267. public static function hButtonPost($label, $params = [], $childrens = []) {
  268. if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
  269. if (!empty($params['fields'])) {
  270. foreach ($params['fields'] as $fieldParams) {
  271. $childrens[] = self::h('input', $fieldParams);
  272. }
  273. }
  274. $childrens[] = self::h('button', [
  275. 'type'=>'submit',
  276. 'class' => 'btn ' . V::get('class', 'btn-default', $params),
  277. 'style' => V::get('style', '', $params)
  278. ], $label);
  279. return self::h('form', [
  280. 'action' => V::get('action', '', $params),
  281. 'method' => V::get('method', 'post', $params),
  282. 'style' => V::get('form.style', 'display:inline', $params),
  283. 'class' => "form-inline"
  284. ],
  285. $childrens
  286. );
  287. }
  288. public static function hButtonAjax($label, $jsEventPrefix, $params = []) {
  289. if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
  290. $query = V::get('data', '', $params);
  291. return self::h('a', [
  292. 'class' => V::get('class', 'btn btn-default', $params),
  293. 'style' => V::get('style', '', $params),
  294. 'href' => V::get('href', '', $params),
  295. 'onClick' => "return p5UI__hButtonAjax(this, 'p5UIBtnAjax:{$jsEventPrefix}', '', '" . http_build_query($query) . "')",
  296. ], $label);
  297. }
  298. public static function hButtonAjaxOnResponse($jsEventPrefix, $jsCode) {
  299. echo self::h('script', [], "
  300. jQuery(document).on('p5UIBtnAjax:{$jsEventPrefix}:response', function(e, n, payload) {
  301. {$jsCode}
  302. })
  303. ");
  304. }
  305. public static function hButtonAjaxJsFunction() {
  306. echo UI::h('script', [], "
  307. function p5UI__hButtonAjax(n, eventNamespace, url, query) {
  308. var dbg = " . ( DBG::isActive() ? 1 : 0 ) . ";
  309. var jqNode = jQuery(n);
  310. var state = {
  311. href: url || n.href,
  312. data: query || ''
  313. }
  314. jQuery(document).trigger('p5UIBtnAjax:' + eventNamespace + ':click', [n, state])
  315. if (jqNode.hasClass('disabled')) { // bootstrap already prevent this action
  316. if (dbg) console.log('WARNING: btn disabled - waiting for response - Cancel?')
  317. return false
  318. }
  319. jqNode.addClass('disabled btn-loading')
  320. window.fetch(state.href, {
  321. method: 'POST',
  322. headers: {
  323. 'Content-Type': 'application/x-www-form-urlencoded' // query string
  324. },
  325. credentials: 'same-origin',
  326. body: state.data // new URLSearchParams(state.data)
  327. }).then(function(response) {
  328. return response.json()
  329. }).then(function(payload) {
  330. jqNode.removeClass('disabled btn-loading');
  331. jQuery(document).trigger(eventNamespace + ':response', [n, payload]);
  332. }).catch(function(e) {
  333. jQuery(document).trigger(eventNamespace + ':response', [n, 'error' + e]);
  334. jqNode.removeClass('disabled btn-loading');
  335. p5UI__notifyAjaxCallback({
  336. type: 'error',
  337. msg: 'Request error ' + e
  338. });
  339. console.log('loadDataAjax:fetch: ERR:', e);
  340. })
  341. return false;
  342. }
  343. ");
  344. }
  345. public static function h($tagName, $params = [], $childrens = []) {
  346. $emptyTags = [];
  347. $emptyTags[] = 'hr';
  348. $emptyTags[] = 'br';
  349. $emptyTags[] = 'input';
  350. $emptyTags[] = 'link';
  351. $emptyTags[] = 'area';
  352. $emptyTags[] = 'base';
  353. $emptyTags[] = 'col';
  354. $emptyTags[] = 'embed';
  355. $emptyTags[] = 'img';
  356. $emptyTags[] = 'keygen';
  357. $emptyTags[] = 'meta';
  358. $emptyTags[] = 'param';
  359. $emptyTags[] = 'source';
  360. $emptyTags[] = 'track';
  361. $emptyTags[] = 'wbr';
  362. if (in_array($tagName, $emptyTags)) return '<' . $tagName . (empty($params) ? '' : ' ' . self::hAttributes($params)) . '/>';
  363. return '<' . $tagName . (empty($params) ? '' : ' ' . self::hAttributes($params)) . '>' . self::hChildrens($childrens) . '</' . $tagName . '>';
  364. }
  365. public static function hAttributes($params = []) {
  366. $attr = [];
  367. foreach ($params as $k => $v) {
  368. if (is_array($v)) {
  369. $attr[] = "{$k}=\"" . implode(" ", $v) . "\"";
  370. } else {
  371. $attr[] = "{$k}=\"{$v}\"";
  372. }
  373. }
  374. return implode(" ", $attr);
  375. }
  376. public static function hChildrens($childrens = []) {
  377. if (empty($childrens)) return '';
  378. if (is_string($childrens)) return $childrens;
  379. if (!is_array($childrens)) throw new Exception("Unsupported children type");
  380. return array_reduce(
  381. $childrens,
  382. function ($curry, $child) {
  383. return "{$curry}{$child}";
  384. },
  385. ""
  386. );
  387. }
  388. }