UI.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. <?php
  2. Lib::loadClass('Theme');
  3. require_once dirname(__FILE__) . '/' . 'UITagInterface.php';
  4. class UI {
  5. public static function getTitle() {
  6. $title = 'SE';
  7. $host = $_SERVER['SERVER_NAME'];
  8. if (substr($host, 0, 5) == 'biuro') {
  9. $host = substr($host, 6);
  10. }
  11. $title = "{$host}-SE";
  12. return $title;
  13. }
  14. public static function gora($params = []) {
  15. UI::startHtml($params);
  16. }
  17. public static function startHtml($params = []) { // @params: { title: string, childrens: string }
  18. Lib::loadClass('S');
  19. UI::loadTemplate('_layout_gora', $params);
  20. }
  21. public static function dol() {
  22. UI::endHtml();
  23. }
  24. public static function fixFooterPosition($type) {
  25. $fixFooterPosition = true;// from config?
  26. if (!$fixFooterPosition) return;
  27. switch ($type) {
  28. case 'footer_style': return 'position:absolute; bottom:0; left:0; width:100%; ';
  29. case 'body_style': return 'position:relative; padding-bottom:32px;';
  30. case 'body_css_style': return 'body { position:relative; padding-bottom:32px }';
  31. case 'footer_js_tag': return "\n<script>document.body.style.minHeight = '' + (window.innerHeight - 2) + 'px';</script>";
  32. }
  33. }
  34. public static function endHtml() {
  35. Theme::footer();
  36. if ('POST' === V::get('REQUEST_METHOD', '', $_SERVER) && 'LOGIN' === V::get('LOGIN', '', $_POST)) {
  37. echo "\n" . UI::h('script', [], "history.replaceState(null, '', window.location.href)");
  38. }
  39. echo "\n</body></html>";
  40. }
  41. public static function menu() {
  42. if (!User::logged()) {
  43. self::printUserMessage();
  44. return;
  45. }
  46. if (User::hasAccess('menu')) {
  47. Theme::top();
  48. }
  49. else {
  50. UI::loadTemplate('menuLevel6');
  51. }
  52. self::printUserMessage();
  53. }
  54. static function printUserMessage() {
  55. $usrMsg = S::getUserMessage();
  56. if (!$usrMsg) return;
  57. switch ($usrMsg[0]) {
  58. case 'AlertInfoException': UI::alertWithCloseBtn('info', $usrMsg[1]); return;
  59. case 'AlertSuccessException': UI::alertWithCloseBtn('success', $usrMsg[1]); return;
  60. case 'AlertWarningException': UI::alertWithCloseBtn('warning', $usrMsg[1]); return;
  61. case 'AlertDangerException': UI::alertWithCloseBtn('danger', $usrMsg[1]); return;
  62. case 'Exception': UI::alertWithCloseBtn('danger', $usrMsg[1]); return;
  63. default: UI::alertWithCloseBtn('danger', "Not implemented: " . $usrMsg[1]); return;
  64. }
  65. }
  66. public static function loadTemplate($tmplName, $data = array()) {
  67. if ('defaultPage' === $tmplName) { // TODO: replace UI::loadTemplate('defaultPage') => Theme::home($data)
  68. Theme::home($data);
  69. return;
  70. }
  71. if ('login' === $tmplName) { // TODO: replace UI::loadTemplate('login') => Theme::home($data)
  72. Theme::login($data);
  73. return;
  74. }
  75. if ('logout' === $tmplName) { // TODO: replace UI::loadTemplate('logout') => Theme::home($data)
  76. Theme::logout($data);
  77. return;
  78. }
  79. if (is_array($data) && !empty($data)) {
  80. extract($data);
  81. }
  82. include APP_PATH_LIB . "/tmpl/{$tmplName}.php";
  83. }
  84. public static function hotKeyDBG($str) {}
  85. public static function showMessagesForTable($tblName) {
  86. if (empty($tblName)) return;
  87. Lib::loadClass('Router');
  88. $msgsRoute = Router::getRoute('Msgs');
  89. $msgs = $msgsRoute->getActiveMessagesForTable($tblName);
  90. if (!empty($msgs)) {
  91. self::loadTemplate('msgsForTable', array('msgs' => $msgs));
  92. }
  93. }
  94. static function alert($alertType, $msg, $outputHtml = true) {
  95. if (!$outputHtml) {
  96. $type = ('danger' == $alertType) ? "ERROR" : strtoupper($alertType);
  97. echo "{$type}: {$msg}\n";
  98. return;
  99. }
  100. UI::tag('div', ['class'=>"alert alert-{$alertType}"], $msg, "\n");
  101. }
  102. static function alertWithCloseBtn($alertType, $msg, $outputHtml = true) {
  103. if (!$outputHtml) {
  104. $type = ('danger' == $alertType) ? "ERROR" : strtoupper($alertType);
  105. echo "{$type}: {$msg}\n";
  106. return;
  107. }
  108. $closeBtn = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
  109. UI::tag('div', ['class'=>"alert alert-{$alertType}"], $closeBtn . "\n" . $msg, "\n");
  110. }
  111. public static function setTitleJsTag($title) { self::setTitle($title); }
  112. public static function setTitle($title) { self::tag('script', null, "document.title = '{$title}';", "\n"); }
  113. public static function hTable($params) {
  114. ob_start();
  115. UI::table($params);
  116. return ob_get_clean();
  117. }
  118. /**
  119. * $params - Array
  120. * $params['caption'] (optional) -> <caption>...</caption>
  121. * $params['cols'] (optional) -> cols, if not set read from first row
  122. * $params['rows'] -> rows, if not set - empty table
  123. * $params['rows'] -> rows, if not set - empty table
  124. * $params['disable_lp'] -> disable lp. col
  125. */
  126. public static function table($params) {
  127. $cols = V::get('cols', array(), $params);
  128. $rows = V::get('rows', array(), $params);
  129. $cols_help = V::get('cols_help', array(), $params);
  130. $cols_label = V::get('cols_label', array(), $params);
  131. $caption = V::get('caption', '', $params);
  132. $cellPadding = V::get('cell_padding', 2, $params, 'int');
  133. $showLp = (!V::get('disable_lp', false, $params));
  134. $cssClassTable = V::get('@class', 'table table-bordered table-hover', $params);
  135. $countCols = 1;
  136. if (empty($cols) && !empty($rows)) {
  137. $firstRow = array();
  138. foreach ($rows as $row) {
  139. $firstRow = $row;
  140. break;
  141. }
  142. $cols = array_filter(
  143. array_keys((array)$firstRow),
  144. function ($col) {
  145. return ('@' != substr($col, 0, 1));
  146. }
  147. );
  148. }
  149. $countCols = count($cols);
  150. $countCols = ($showLp) ? $countCols + 1 : $countCols;
  151. {
  152. $help = array();
  153. foreach ($cols as $name) {
  154. $helpMsg = V::get($name, '', $cols_help);
  155. if (empty($helpMsg)) continue;
  156. $help[$name] = self::h('i', [
  157. 'class' => "glyphicon glyphicon-question-sign",
  158. 'title' => $helpMsg
  159. ], "");
  160. }
  161. }
  162. {
  163. $label = array();
  164. foreach ($cols as $name) {
  165. $label[$name] = V::get($name, $name, $cols_label);
  166. }
  167. }
  168. // if (empty($cols)) return;
  169. $hiddenCols = V::get('hidden_cols', array(), $params);
  170. $tableAttrs = [ 'class' => $cssClassTable, 'style' => V::get('style', '', $params) ];
  171. $html_id = V::get('__html_id', '', $params);
  172. if ($html_id) $tableAttrs['id'] = $html_id;
  173. self::startTag('table', $tableAttrs); echo "\n";
  174. if ($caption) { self::tag('caption', null, $caption); echo "\n"; }
  175. if (!empty($cols)) {
  176. self::startTag('thead', null); echo "\n";
  177. self::startTag('tr', null); echo "\n";
  178. if ($showLp) { self::tag('th', [ 'style' => "padding:{$cellPadding}px" ], "Lp."); echo "\n"; }
  179. foreach ($cols as $colName) {
  180. if (in_array($colName, $hiddenCols)) continue;
  181. $attrs = [ 'style' => "padding:{$cellPadding}px" ];
  182. if (!empty($params["@class[{$colName}]"])) $attrs['class'] = $params["@class[{$colName}]"];
  183. if (!empty($params["@style[{$colName}]"])) $attrs['style'] .= "; " . $params["@style[{$colName}]"];
  184. echo self::h('th', $attrs, [
  185. $label[$colName],
  186. " " . V::get($colName, '', $help)
  187. ]);
  188. echo "\n";
  189. }
  190. self::endTag('tr'); echo "\n";
  191. self::endTag('thead'); echo "\n";
  192. }
  193. $tbodyAttrs = [];
  194. if (array_key_exists('@tbody.id', $params)) $tbodyAttrs['id'] = $params['@tbody.id'];
  195. self::startTag('tbody', $tbodyAttrs); echo "\n";
  196. if (empty($rows)) {
  197. self::startTag('tr'); echo "\n";
  198. self::tag('td', [ 'style' => "padding:{$cellPadding}px", 'colspan' => $countCols ], V::get('empty_msg', "Brak danych", $params)); echo "\n";
  199. self::endTag('tr'); echo "\n";
  200. } else {
  201. $i = 0;
  202. foreach ($rows as $row) {
  203. $i++;
  204. $trAttrs = array();
  205. if (!empty($row['@onClick'])) $trAttrs['onClick'] = $row['@onClick'];
  206. if (!empty($row['@class'])) $trAttrs['class'] = $row['@class'];
  207. if (!empty($row['@style'])) $trAttrs['style'] = $row['@style'];
  208. if (!empty($row['@data'])) foreach ($row['@data'] as $k => $v) $trAttrs["data-{$k}"] = $v;
  209. self::startTag('tr', $trAttrs); echo "\n";
  210. if ($showLp) { self::tag('th', [ 'style' => "padding:2px; color:#ccc" ], $i); echo "\n"; }
  211. foreach ($cols as $colName) {
  212. $rowAttrs = [ 'style' => "padding:{$cellPadding}px" ];
  213. if (!empty($row["@onClick[{$colName}]"])) $rowAttrs['onClick'] = $row["@onClick[{$colName}]"];
  214. if (!empty($row["@class[{$colName}]"])) $rowAttrs['class'] = $row["@class[{$colName}]"];
  215. if (!empty($row["@style[{$colName}]"])) $rowAttrs['style'] .= "; " . $row["@style[{$colName}]"];
  216. if (in_array($colName, $hiddenCols)) continue;
  217. self::tag('td', $rowAttrs, V::get($colName, '', $row)); echo "\n";
  218. }
  219. self::endTag('tr'); echo "\n";
  220. }
  221. }
  222. self::endTag('tbody'); echo "\n";
  223. self::endTag('table'); echo "\n";
  224. }
  225. public static function startContainer($attrs = array()) {// echo '<div class="container">' . "\n";
  226. $attrs['class'] = (!empty($attrs['class']))
  227. ? $attrs['class'] . ' ' . 'container'
  228. : 'container';
  229. self::startTag('div', $attrs, "\n");
  230. }
  231. public static function endContainer() { self::endTag('div', "\n"); }
  232. public static function startTag($tag, $attrs = array(), $addWhiteSpace = false) {
  233. $outAttrs = '';
  234. if (is_array($attrs)) {
  235. foreach ($attrs as $attrName => $val) $outAttrs .= " {$attrName}=\"{$val}\"";
  236. }
  237. echo '<' . $tag . $outAttrs . '>' . self::whiteSpace($addWhiteSpace);
  238. }
  239. public static function whiteSpace($addWhiteSpace = false) {
  240. return (!$addWhiteSpace)
  241. ? ''
  242. : (true === $addWhiteSpace) ? " " : $addWhiteSpace;
  243. }
  244. public static function endTag($tag, $addWhiteSpace = false) {
  245. echo '</' . $tag . '>' . self::whiteSpace($addWhiteSpace);
  246. }
  247. public static function tag($tag, $attrs = array(), $childrens = array(), $addWhiteSpace = false) {
  248. $whiteSpace = self::whiteSpace($addWhiteSpace);
  249. self::startTag($tag, $attrs);
  250. echo $whiteSpace;
  251. if (!empty($childrens) && is_array($childrens)) throw new Exception("UI::tag() children as nodes not implemented".json_encode($childrens));
  252. if (is_scalar($childrens)) echo $childrens;
  253. echo $whiteSpace;
  254. self::endTag($tag);
  255. echo $whiteSpace;
  256. }
  257. public static function emptyTag($tag, $attrs = array(), $addWhiteSpace = false) {
  258. $outAttrs = '';
  259. if (is_array($attrs)) {
  260. foreach ($attrs as $attrName => $val) $outAttrs .= " {$attrName}=\"{$val}\"";
  261. }
  262. echo '<' . $tag . $outAttrs . '/>' . self::whiteSpace($addWhiteSpace);
  263. }
  264. public static function link($type, $content, $href, $attrs = array()) {
  265. $attrs['class'] = V::get('class', '', $attrs);
  266. $attrs['class'] .= "btn btn-{$type}";
  267. if (!empty($attrs['className'])) {
  268. foreach ($attrs['className'] as $cls => $bool) {
  269. if ($bool) $attrs['class'] .= " {$cls}";
  270. }
  271. unset($attrs['className']);
  272. }
  273. $attrs['href'] = $href;
  274. UI::tag('a', $attrs, $content);
  275. }
  276. public static function jsAjaxTable($params) {
  277. }
  278. public static function price($value, $dec = ',') {
  279. // TODO: if not number type - string wwith wrong format - try to convert?
  280. return number_format($value, 2, $dec, ' ');
  281. }
  282. public static function inlineJS($jsFile, $jsonVars = []) {
  283. echo self::hScript($jsFile, $jsonVars);
  284. }
  285. public static function hScript($jsFile, $jsonVars = []) {
  286. if (!file_exists($jsFile)) throw new Exception("js file '" . basename($jsFile) . "' not exists!");
  287. $ret = '<script>' . "\n";
  288. $ret .= "(function (global) {" . "\n";
  289. $ret .= " var module = {}; module.exports = {};\n";
  290. foreach ($jsonVars as $name => $var) {
  291. $ret .= " var {$name} = " . json_encode($var) . ";\n";
  292. }
  293. $ret .= file_get_contents($jsFile);
  294. $ret .= "\n;\n";
  295. $ret .= " if (module && module.exports && Object.keys(module.exports).length) {" . "\n";
  296. $ret .= " Object.keys(module.exports).forEach(function (key) {" . "\n";
  297. $ret .= " global[key] = module.exports[key];" . "\n";
  298. $ret .= " })" . "\n";
  299. $ret .= " }" . "\n";
  300. $ret .= "})(window)" . "\n";
  301. $ret .= '</script>' . "\n";
  302. return $ret;
  303. }
  304. public static function inlineRawJS($jsFile) {
  305. if (!file_exists($jsFile)) throw new Exception("js file '" . basename($jsFile) . "' not exists!");
  306. UI::startTag('script', [], "\n");
  307. echo file_get_contents($jsFile);
  308. UI::endTag('script', "\n");
  309. }
  310. public static function hStyle($cssFile) {
  311. $ret = '<style type="text/css">' . "\n";
  312. $ret .= file_get_contents($cssFile);
  313. $ret .= '</style>' . "\n";
  314. return $ret;
  315. }
  316. public static function inlineCSS($cssFile) {
  317. UI::startTag('style', ['type'=>"text/css"], "\n");
  318. echo file_get_contents($cssFile);
  319. UI::endTag('style', "\n");
  320. }
  321. public static function inlineRawCSS($cssContent) {
  322. echo UI::h('style', [ 'type' => "text/css" ], $cssContent) . "\n";
  323. }
  324. public static function includeView($viewPath, $data = array()) {
  325. if (!file_exists($viewPath)) throw new Exception("view file '" . basename($viewPath) . "' not exists!");
  326. if (false === strpos($viewPath, APP_PATH_ROOT)) throw new Exception("Access Denied to include view '" . basename($viewPath) . "'!");
  327. if (is_array($data) && !empty($data)) {
  328. extract($data);
  329. }
  330. include $viewPath;
  331. }
  332. public static function postButton($label, $params = []) {
  333. UI::startTag('form', [
  334. 'action' => V::get('action', '', $params),
  335. 'method' => V::get('method', 'post', $params),
  336. 'style' => "display:inline"
  337. ]);
  338. foreach (V::get('data', [], $params, 'array') as $name => $value) {
  339. UI::emptyTag('input', ['type'=>'hidden', 'name'=>$name, 'value'=>$value]);
  340. }
  341. UI::tag('button', ['type'=>'submit', 'class' => 'btn ' . V::get('class', 'btn-default btn-xs', $params)], $label);
  342. UI::endTag('form');
  343. }
  344. public static function hButtonPost($label, $params = [], $childrens = []) {
  345. if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
  346. if (!empty($params['fields'])) {
  347. foreach ($params['fields'] as $fieldParams) {
  348. $childrens[] = self::h('input', $fieldParams);
  349. }
  350. }
  351. $childrens[] = self::h('button', array_merge(
  352. [
  353. 'type' => 'submit',
  354. 'class' => 'btn ' . V::get('class', 'btn-default', $params),
  355. 'style' => V::get('style', '', $params)
  356. ],
  357. (!empty($params['title'])) ? ['title' => $params['title']] : []
  358. ), $label);
  359. return self::h('form', [
  360. 'action' => V::get('action', '', $params),
  361. 'method' => V::get('method', 'post', $params),
  362. 'style' => V::get('form.style', 'display:inline', $params),
  363. 'class' => "form-inline " . V::get('form.class', '', $params),
  364. ], $childrens);
  365. }
  366. public static function hSimplePostTaskButton($label, $postTaskName, $params = [], $childrens = []) {
  367. $childrens[] = self::h('input', [ 'type' => 'hidden', 'name' => '_postTask', 'value' => $postTaskName ]);
  368. if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
  369. if (!empty($params['fields'])) {
  370. foreach ($params['fields'] as $fieldParams) {
  371. $childrens[] = self::h('input', $fieldParams);
  372. }
  373. }
  374. $childrens[] = self::h('button', array_merge(
  375. [
  376. 'type' => 'submit',
  377. 'class' => 'btn ' . V::get('class', 'btn-default', $params),
  378. 'style' => V::get('style', '', $params)
  379. ],
  380. (!empty($params['title'])) ? ['title' => $params['title']] : []
  381. ), $label);
  382. return self::h('form', [
  383. 'action' => V::get('action', '', $params),
  384. 'method' => V::get('method', 'post', $params),
  385. 'style' => V::get('form.style', 'display:inline', $params),
  386. 'class' => "form-inline"
  387. ], $childrens);
  388. }
  389. public static function hButtonAjax($label, $jsEventPrefix, $params = []) {
  390. if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
  391. $query = V::get('data', '', $params);
  392. return self::h('a', [
  393. 'class' => V::get('class', 'btn btn-default', $params),
  394. 'style' => V::get('style', '', $params),
  395. 'href' => V::get('href', '', $params),
  396. 'onClick' => "return p5UI__hButtonAjax(this, 'p5UIBtnAjax:{$jsEventPrefix}', '', '" . http_build_query($query) . "')",
  397. ], $label);
  398. }
  399. public static function hButtonAjaxOnResponse($jsEventPrefix, $jsCode) {
  400. echo self::h('script', [], "
  401. jQuery(document).on('p5UIBtnAjax:{$jsEventPrefix}:response', function(e, n, payload) {
  402. {$jsCode}
  403. })
  404. ");
  405. }
  406. public static function hButtonAjaxJsFunction() {
  407. echo UI::h('script', [], "
  408. function p5UI__hButtonAjax(n, eventNamespace, url, query) {
  409. var dbg = " . ( DBG::isActive() ? 1 : 0 ) . ";
  410. var jqNode = jQuery(n);
  411. var state = {
  412. href: url || n.href,
  413. data: query || ''
  414. }
  415. jQuery(document).trigger('p5UIBtnAjax:' + eventNamespace + ':click', [n, state])
  416. if (jqNode.hasClass('disabled')) { // bootstrap already prevent this action
  417. if (dbg) console.log('WARNING: btn disabled - waiting for response - Cancel?')
  418. return false
  419. }
  420. jqNode.addClass('disabled btn-loading')
  421. window.fetch(state.href, {
  422. method: 'POST',
  423. headers: {
  424. 'Content-Type': 'application/x-www-form-urlencoded' // query string
  425. },
  426. credentials: 'same-origin',
  427. body: state.data // new URLSearchParams(state.data)
  428. }).then(function(response) {
  429. return response.json()
  430. }).then(function(payload) {
  431. jqNode.removeClass('disabled btn-loading');
  432. jQuery(document).trigger(eventNamespace + ':response', [n, payload]);
  433. }).catch(function(e) {
  434. jQuery(document).trigger(eventNamespace + ':response', [n, 'error' + e]);
  435. jqNode.removeClass('disabled btn-loading');
  436. p5UI__notifyAjaxCallback({
  437. type: 'error',
  438. msg: 'Request error ' + e
  439. });
  440. console.log('loadDataAjax:fetch: ERR:', e);
  441. })
  442. return false;
  443. }
  444. ");
  445. }
  446. public static function h($tagName, $params = [], $childrens = []) {
  447. if (null === $tagName && empty($params)) return self::hChildrens($childrens);
  448. $emptyTags = [];
  449. $emptyTags[] = 'hr';
  450. $emptyTags[] = 'br';
  451. $emptyTags[] = 'input';
  452. $emptyTags[] = 'link';
  453. $emptyTags[] = 'area';
  454. $emptyTags[] = 'base';
  455. $emptyTags[] = 'col';
  456. $emptyTags[] = 'embed';
  457. $emptyTags[] = 'img';
  458. $emptyTags[] = 'keygen';
  459. $emptyTags[] = 'meta';
  460. $emptyTags[] = 'param';
  461. $emptyTags[] = 'source';
  462. $emptyTags[] = 'track';
  463. $emptyTags[] = 'wbr';
  464. if (in_array($tagName, $emptyTags)) return '<' . $tagName . (empty($params) ? '' : ' ' . self::hAttributes($params)) . '/>';
  465. if ('p5:' === substr($tagName, 0, 3)) return self::hCustomTag($tagName, $params, $childrens);
  466. return '<' . $tagName . (empty($params) ? '' : ' ' . self::hAttributes($params)) . '>' . self::hChildrens($childrens) . '</' . $tagName . '>';
  467. }
  468. public static function hCustomTag($tagName, $params = [], $childrens = []) {
  469. if ('p5:' === substr($tagName, 0, 3)) {
  470. $tagClass = "UI_" . substr($tagName, 3);
  471. if (!class_exists($tagClass)) Lib::tryLoadClass($tagClass);
  472. if (!class_exists($tagClass)) throw new Exception("Not implemented custom tag '{$tagName}'");
  473. return $tagClass::h($tagName, $params, $childrens);
  474. }
  475. throw new Exception("Not implemented custom tag prefix '{$tagName}'");
  476. }
  477. public static function hAttributes($params = []) {
  478. $attr = [];
  479. if (null === $params) return '';
  480. if (!is_array($params)) {
  481. try {
  482. throw new Exception("Wrong params type in UI::hAttributes");
  483. } catch (Exception $e) {
  484. DBG::log($e);
  485. }
  486. }
  487. foreach ($params as $k => $v) {
  488. if (is_array($v)) {
  489. $attr[] = "{$k}=\"" . implode(" ", $v) . "\"";
  490. } else if (true === $v) { // eg. open => true : 'open'
  491. $attr[] = $k;
  492. } else if (false === $v) { // skip if false value
  493. } else if (!empty($v)) {
  494. $attr[] = "{$k}=\"{$v}\"";
  495. }
  496. }
  497. return implode(" ", $attr);
  498. }
  499. public static function hChildrens($childrens = []) {
  500. if (empty($childrens)) {
  501. if (is_int($childrens)) return "{$childrens}";
  502. if (is_string($childrens)) return $childrens;
  503. return '';
  504. }
  505. if (is_scalar($childrens)) return "{$childrens}";
  506. if (!is_array($childrens)) throw new Exception("Unsupported children type");
  507. return array_reduce(
  508. $childrens,
  509. function ($curry, $child) {
  510. return "{$curry}{$child}";
  511. },
  512. ""
  513. );
  514. }
  515. /**
  516. * @param $taskPerm - 'C', 'W'
  517. */
  518. public static function hGetFormItem($acl, $fieldName, $taskPerm, $fieldID, $fName, $fValue, $params = array(), $record = null) {
  519. $fValue = (string)$fValue;
  520. Lib::loadClass('Typespecial');
  521. DBG::log(['$fieldName'=>$fieldName, '$taskPerm'=>$taskPerm, '$fieldID'=>$fieldID, '$fName'=>$fName, '$fValue'=>$fValue, '$params'=>$params, '$record'=>$record], 'array', "hGetFormItem()");
  522. if (!$acl->isAllowed($fieldID, $taskPerm, $record)) {
  523. switch ($taskPerm) {
  524. case 'R': return "Brak uprawnień do odczytu";
  525. case 'W': return "Brak uprawnień do zapisu";
  526. case 'C': return "Brak uprawnień";
  527. default: return "Brak uprawnień do tego pola ({$taskPerm})";
  528. }
  529. }
  530. if ($fieldName == 'ID') return ''; // TODO: hide primaryKey?
  531. // $colType = $acl->getFieldTypeById($fieldID);
  532. // if (!$colType) return "Error - unknown type";
  533. $xsdType = $acl->getXsdFieldType($fieldName);
  534. DBG::log("DBG: field({$fieldName}) xsdType({$xsdType})");
  535. $html = new stdClass();
  536. $html->_params = array();
  537. $html->tag = 'input';
  538. $html->childrens = [];
  539. $html->attrs = array();
  540. $html->attrs['id'] = $fName;
  541. $html->attrs['name'] = $fName;
  542. $html->attrs['type'] = 'text';
  543. $html->attrs['value'] = $fValue;// BUG htmlspecialchars($fValue); - convert chars in edit form (" to &quot; and & to &amp;)
  544. if (isset($params['tabindex'])) $html->attrs['tabindex'] = $params['tabindex'];
  545. // if (!$acl->hasFieldPerm($fieldID, $taskPerm)) {
  546. // $html->attrs['disabled'] = 'disabled';
  547. // }
  548. $maxGrid = V::get('maxGrid', 10, $params);
  549. switch ($xsdType) {
  550. case 'xsd:long':
  551. case 'xsd:int':
  552. case 'xsd:integer': {
  553. $html->attrs['type'] = 'number';
  554. $html->attrs['class'][] = 'input-small';
  555. } break;
  556. case 'xsd:decimal':
  557. case 'xsd:double':
  558. case 'xsd:float':
  559. case 'p5:price': {
  560. $html->attrs['type'] = 'text';
  561. $html->attrs['class'][] = 'input-small';
  562. } break;
  563. case 'xsd:string':
  564. case 'p5:www_link':
  565. case 'p5:string': {
  566. $html->attrs['type'] = 'text';
  567. $maxLength = (int)$acl->getXsdFieldParam($fieldName, 'maxLength');
  568. if ($maxLength > 0) {
  569. $html->attrs['maxlength'] = $maxLength;
  570. }
  571. $valLength = strlen($fValue);
  572. if (isset($params['widthClass'])) {
  573. if ($params['widthClass'] == 'inside-modal') {
  574. $html->attrs['style'] = 'width:98%;';
  575. } else {
  576. $html->attrs['style'] = 'width:98%;';
  577. }
  578. }
  579. if ($maxLength > 255) {// Fix for long varchar - use textarea
  580. $html->tag = 'textarea';
  581. $html->childrens[] = $fValue;
  582. $html->attrs['rows'] = '3';
  583. unset($html->attrs['type']);
  584. unset($html->attrs['value']);
  585. }
  586. } break;
  587. case 'xsd:dateTime':
  588. case 'xsd:date': {
  589. $testDatePicker = true;
  590. if ($testDatePicker) {
  591. $html->attrs['type'] = 'text';
  592. $html->_params[] = 'date';
  593. if ('xsd:dateTime' === $xsdType) {
  594. $html->attrs['class'][] = 'se_type-datetime'; // datetimepicker';
  595. $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  596. $html->attrs['maxlength'] = 19;
  597. } else {
  598. $html->attrs['class'][] = 'se_type-date'; // datetimepicker';
  599. $html->attrs['maxlength'] = 10;
  600. }
  601. if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  602. $html->attrs['value'] = '';
  603. }
  604. } else {
  605. $html->attrs['type'] = 'date';
  606. }
  607. } break;
  608. case 'xsd:time': {
  609. $testDatePicker = true;
  610. if ($testDatePicker) {
  611. $html->attrs['type'] = 'text';
  612. $html->_params[] = 'time';
  613. $html->attrs['class'][] = 'se_type-time';// datetimepicker';
  614. $html->attrs['data-format'] = 'hh:mm:ss';
  615. $html->attrs['maxlength'] = 8;
  616. if (substr($html->attrs['value'], 0, 8) == '00:00:00') {
  617. $html->attrs['value'] = '';
  618. }
  619. } else {
  620. $html->attrs['type'] = 'time';
  621. }
  622. } break;
  623. // case 'timestamp': { // TODO: timestamp is xsd:integer or xsd:dateTime?
  624. // $testDatePicker = true;
  625. // if ($testDatePicker) {
  626. // $html->attrs['type'] = 'text';
  627. // $html->_params[] = 'date';
  628. // $html->attrs['class'][] = 'se_type-datetime';// datetimepicker';
  629. // $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  630. // $html->attrs['maxlength'] = 19;
  631. // if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  632. // $html->attrs['value'] = '';
  633. // }
  634. // } else {
  635. // $html->attrs['type'] = 'date';
  636. // }
  637. // } break;
  638. case 'p5:enum': {
  639. DBG::log($acl->getField($fieldID), 'array', "\$field($fieldName)");
  640. unset($html->attrs['type']);
  641. unset($html->attrs['value']);
  642. $html->tag = 'select';
  643. $defaultValue = $acl->getFieldDefaultValue($fieldName);
  644. $values = $acl->getEnumerations($fieldName);
  645. // $values = explode(',', str_replace(array('(',')',"'",'"'), '', substr($colType['type'], 5)));
  646. $selValue = $fValue;
  647. if (empty($selValue) && $selValue !== '0' && !empty($defaultValue)) {
  648. if ($taskPerm == 'C') {
  649. $selValue = $defaultValue;
  650. } else if ($taskPerm == 'W' && $acl->isAllowed($fieldID, 'R', $record)) {
  651. $selValue = $defaultValue;
  652. }
  653. }
  654. $html->childrens[] = [ 'option', [ 'value' => "" ], "" ];
  655. if (!empty($selValue) && !array_key_exists($selValue, $values)) {
  656. $html->childrens[] = [ 'option', [ 'value' => $selValue, 'selected' => "selected" ], $selValue ];
  657. }
  658. foreach ($values as $val => $label) {
  659. $html->childrens[] = [ 'option', array_merge(
  660. [ 'value' => $val ],
  661. ((!empty($selValue) || '0' === $selValue) && (string)$selValue === (string)$val) ? [ 'selected' => "selected" ] : []
  662. ), $label ];
  663. }
  664. } break;
  665. case 'p5:text': {
  666. $html->tag = 'textarea';
  667. $html->childrens[] = $fValue;
  668. if (isset($params['widthClass'])) {
  669. if ($params['widthClass'] == 'inside-modal') {
  670. $html->attrs['style'] = 'width:98%;';
  671. } else {
  672. $html->attrs['style'] = 'width:98%;';
  673. }
  674. } else {
  675. //$html->attrs['class'][] = (8 <= $maxGrid)? 'span8' : "span{$maxGrid}";
  676. }
  677. $html->attrs['rows'] = '3';
  678. unset($html->attrs['type']);
  679. unset($html->attrs['value']);
  680. } break;
  681. case 'gml:GeometryPropertyType':
  682. case 'gml:LineStringPropertyType':
  683. case 'gml:PointPropertyType':
  684. case 'gml:PolygonPropertyType': {
  685. return '...';
  686. } break;
  687. case 'xsd:base64Binary': {
  688. return '...';
  689. } break;
  690. default: {
  691. if ('ref:' === substr($xsdType, 0, 4)) {
  692. return "Funkcja w trakcie przygotowanie (ref do '" . substr($xsdType, 4) . "')";
  693. }
  694. return "unknown Type \"{$xsdType}\"";
  695. }
  696. }
  697. $html->attrs['class'][] = 'form-control';
  698. if (!empty($html->attrs['class'])) $html->attrs['class'] = implode(" ", $html->attrs['class']);
  699. $nodeHtml = (in_array($html->tag, array('select', 'textarea')))
  700. ? [ $html->tag, $html->attrs, $html->childrens ]
  701. : $nodeHtml = [ $html->tag, $html->attrs ]
  702. ;
  703. if (in_array('date', $html->_params)) {
  704. $nodeHtml = [ 'div', [ 'class' => "input-group" ], [
  705. $nodeHtml,
  706. [ 'span', [ 'class' => "input-group-addon" ], [
  707. [ 'span', [ 'class' => "glyphicon glyphicon-calendar" ] ]
  708. ] ]
  709. ] ];
  710. }
  711. else if (in_array('time', $html->_params)) {
  712. $nodeHtml = [ 'div', [ 'class' => "input-group" ], [
  713. $nodeHtml,
  714. [ 'span', [ 'class' => "input-group-addon" ], [
  715. [ 'span', [ 'class' => "glyphicon glyphicon-time" ] ]
  716. ] ]
  717. ] ];
  718. }
  719. if (true == V::get('appendBack', '', $params)
  720. && !in_array('date', $html->_params)
  721. && !in_array('time', $html->_params)
  722. ) {
  723. if ($html->tag == 'input' && $taskPerm == 'W') {
  724. $nodeHtml = [ 'div', [ 'class' => "input-group show-last-value" ], [
  725. $nodeHtml,
  726. [ 'span', [ 'class' => "input-group-addon button-appendBack", 'title' => htmlspecialchars($fValue) ], [
  727. [ 'span', [ 'class' => "glyphicon glyphicon-arrow-left" ] ]
  728. ] ]
  729. ] ];
  730. }
  731. }
  732. $typeSpecial = Typespecial::getInstance($fieldID, $fieldName);
  733. if ($typeSpecial) {
  734. $tsParams = array();
  735. $tsValue = V::get('typespecialValue', '', $params);
  736. if (!empty($tsValue)) {
  737. $tsParams['typespecialValue'] = $tsValue;
  738. }
  739. $nodeHtml = [ 'div', [ 'class' => "field-with-typespecial" ], [
  740. $nodeHtml,
  741. $typeSpecial->hGetFormItem($acl, $fieldName, $acl->_zasobID, $fName, $fValue, $tsParams, $record),
  742. ] ];
  743. }
  744. return $nodeHtml;
  745. }
  746. public static function convertHtmlToArray($html) {
  747. $nodes = [];
  748. // <a href="index.php?_route=Users&_task=userGroups&usrLogin=michal.podejko">ustal stanowisko</a>
  749. // [ 'a', [ 'href' => "index.php?_route=Users&_task=userGroups&usrLogin=michal.podejko" ], "ustal stanowisko" ]
  750. $DBG = 0;
  751. $pos = 0;
  752. // TODO: while (true)
  753. if ('<' === substr($html, $pos, 1)) { // parse tag
  754. $tagName = ''; $attrs = []; $content = [];
  755. $endTagOpen = strpos($html, '>', $pos + 1);
  756. $endTagName = min(strpos($html, ' ', $pos + 1), $endTagOpen); // '<tag>' or '<tag attr="..">'
  757. if (false === $pos) throw new Exception("Error Processing Html - missing tagName");
  758. $tagName = substr($html, $pos + 1, $endTagName - $pos - 1);
  759. if($DBG){echo "\ntagName: '{$tagName}'";}
  760. if ('>' === substr($html, $endTagName, 1)) {
  761. } else if (' ' === substr($html, $endTagName, 1)) {
  762. if (false === $endTagOpen) throw new Exception("Error Processing Html - missing open tag end char");
  763. $attrs = UI::convertHtmlAttrsToArray(trim(substr($html, $endTagName + 1, $endTagOpen - $endTagName - 1)));
  764. } else {
  765. throw new Exception("Error Processing Html - unexpected end tag name char '" . substr($html, $endTagName, 1) . "'");
  766. }
  767. if($DBG){echo "\nattrs: '" . json_encode($attrs), "'";}
  768. // TODO: empty tags '<br>', '<br/>', '<br />', '<input ... />', '<input ... >', img, hr, etc.
  769. // TODO: nested same tags '<tagName> ... <tagName> ... </tagName> ... </tagName>'
  770. $closeTagStart = strpos($html, "</{$tagName}>", $endTagOpen + 1);
  771. if (false === $closeTagStart) throw new Exception("Error Processing Html - missing close tagName");
  772. if($DBG){echo "\nDBG \$endTagOpen: " . substr($html, $endTagOpen, 5) . "...";}
  773. if($DBG){echo "\nDBG \$endTagOpen: " . substr($html, $endTagOpen) . ".EOL";}
  774. if($DBG){echo "\nDBG \$closeTagStart strpos(\$html, '</{$tagName}>', {$endTagOpen} + 1) = '{$closeTagStart}': " . substr($html, $closeTagStart, 5) . "...";}
  775. $content = substr($html, $endTagOpen + 1, $closeTagStart - $endTagOpen - 1);
  776. $tag = [ $tagName, $attrs, $content ];
  777. if($DBG){echo "\n\$tag: ";print_r($tag);}
  778. $nodes = $tag;
  779. }
  780. return $nodes;
  781. }
  782. public static function convertHtmlAttrsToArray($strAttrs) {
  783. $attrs = [];
  784. if (!preg_match_all('((\w+)=\"([^"]*)\")', $strAttrs, $matches)) {
  785. // echo "DBG:: empty attrs or wrong syntax";
  786. return [];
  787. }
  788. $total = (count($matches) - 1) / 2;
  789. // echo "\n\$matches (total = {$total}) = ";print_r($matches);
  790. for ($i = 0; $i < $total; $i++) {
  791. $idx = $i * 2 + 1;
  792. // echo "\n\$attrs[ '{$matches[$idx][0]}' ] = '{$matches[$idx+1][0]}';";
  793. $attrs[ $matches[ $idx ][0] ] = $matches[ $idx + 1 ][0];
  794. }
  795. return $attrs;
  796. }
  797. /**
  798. * Execute callback in try/catch block and view output as page layout (content inside html > body)
  799. * @param array $params
  800. * @param bool $params['showMenu']
  801. * @param bool $params['showContainer']
  802. * @param string $params['containerClass'] : [ 'fluid' ], default ''
  803. */
  804. public static function layout($callback, $params = []) {
  805. $params['showMenu'] = V::get('showMenu', true, $params, 'bool');
  806. $params['showContainer'] = V::get('showContainer', true, $params, 'bool');
  807. $params['containerClass'] = V::get('containerClass', '', $params);
  808. $args = V::get('args', [], $params, 'array');
  809. UI::gora(); // Theme::head();
  810. if ($params['showMenu']) UI::menu(); // TODO: Theme::top()
  811. if ($params['showContainer']) UI::startContainer( $params['containerClass'] ? [ 'class' => $params['containerClass'] ] : [] );
  812. try {
  813. // call_user_func($callback);
  814. $callback($args);
  815. } catch (AlertSuccessException $e) {
  816. DBG::log($e);
  817. UI::alert('success', $e->getMessage());
  818. } catch (AlertWarningException $e) {
  819. DBG::log($e);
  820. UI::alert('warning', $e->getMessage());
  821. } catch (AlertInfoException $e) {
  822. DBG::log($e);
  823. UI::alert('info', $e->getMessage());
  824. } catch (Exception $e) {
  825. DBG::log($e);
  826. UI::alert('danger', $e->getMessage());
  827. }
  828. if ($params['showContainer']) UI::endContainer();
  829. UI::dol(); // UI::dol must include Theme::footer();
  830. }
  831. /**
  832. * Execute callback inside try/catch block.
  833. * @param array $params
  834. * @param bool $params['showContainer']
  835. * @param string $params['containerClass'] : [ 'fluid' ], default ''
  836. */
  837. static function tryCatchView($callback, $params = []) {
  838. $params['showContainer'] = V::get('showContainer', false, $params, 'bool');
  839. $params['containerClass'] = V::get('containerClass', '', $params);
  840. $args = V::get('args', [], $params, 'array');
  841. if ($params['showContainer']) UI::startContainer( $params['containerClass'] ? [ 'class' => $params['containerClass'] ] : [] );
  842. try {
  843. // call_user_func($callback);
  844. $callback($args);
  845. } catch (AlertSuccessException $e) {
  846. DBG::log($e);
  847. UI::alert('success', $e->getMessage());
  848. } catch (AlertWarningException $e) {
  849. DBG::log($e);
  850. UI::alert('warning', $e->getMessage());
  851. } catch (AlertInfoException $e) {
  852. DBG::log($e);
  853. UI::alert('info', $e->getMessage());
  854. } catch (Exception $e) {
  855. DBG::log($e);
  856. UI::alert('danger', $e->getMessage());
  857. }
  858. if ($params['showContainer']) UI::endContainer();
  859. }
  860. public static function startDetails($opts, $summaryChildrens) {
  861. $attrs = array_reduce(array_keys($opts), function ($ret, $optionKey) use ($opts) {
  862. $option = $opts[$optionKey];
  863. if (false !== strpos($optionKey, '.')) {
  864. list($mainKey, $attrName) = explode('.', $optionKey, 2);
  865. $ret[$mainKey][$attrName] = $option;
  866. } else {
  867. $ret['details'][$optionKey] = $option;
  868. }
  869. return $ret;
  870. }, [
  871. 'details' => [],
  872. 'summary' => [],
  873. 'content' => [],
  874. ]);
  875. return '<details' . ( empty($attrs['details']) ? '' : ' ' . self::hAttributes($attrs['details']) ) . '>' .
  876. '<summary' . ( empty($attrs['summary']) ? '' : ' ' . self::hAttributes($attrs['summary']) ) . '>' . self::hChildrens($summaryChildrens) . '</summary>' . "\n" .
  877. '<div' . ( empty($attrs['content']) ? '' : ' ' . self::hAttributes($attrs['content']) ) . '>' . "\n";
  878. }
  879. public static function endDetails() {
  880. return '</div></details>';
  881. }
  882. }