UI.php 36 KB

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