UI.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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. return (!$addWhiteSpace)
  243. ? ''
  244. : (true === $addWhiteSpace) ? " " : $addWhiteSpace;
  245. }
  246. public static function endTag($tag, $addWhiteSpace = false) {
  247. echo '</' . $tag . '>' . self::whiteSpace($addWhiteSpace);
  248. }
  249. public static function tag($tag, $attrs = array(), $childrens = array(), $addWhiteSpace = false) {
  250. $whiteSpace = self::whiteSpace($addWhiteSpace);
  251. self::startTag($tag, $attrs);
  252. echo $whiteSpace;
  253. if (!empty($childrens) && is_array($childrens)) throw new Exception("UI::tag() children as nodes not implemented".json_encode($childrens));
  254. if (is_scalar($childrens)) echo $childrens;
  255. echo $whiteSpace;
  256. self::endTag($tag);
  257. echo $whiteSpace;
  258. }
  259. public static function emptyTag($tag, $attrs = array(), $addWhiteSpace = false) {
  260. $outAttrs = '';
  261. if (is_array($attrs)) {
  262. foreach ($attrs as $attrName => $val) $outAttrs .= " {$attrName}=\"{$val}\"";
  263. }
  264. echo '<' . $tag . $outAttrs . '/>' . self::whiteSpace($addWhiteSpace);
  265. }
  266. public static function link($type, $content, $href, $attrs = array()) {
  267. $attrs['class'] = V::get('class', '', $attrs);
  268. $attrs['class'] .= "btn btn-{$type}";
  269. if (!empty($attrs['className'])) {
  270. foreach ($attrs['className'] as $cls => $bool) {
  271. if ($bool) $attrs['class'] .= " {$cls}";
  272. }
  273. unset($attrs['className']);
  274. }
  275. $attrs['href'] = $href;
  276. UI::tag('a', $attrs, $content);
  277. }
  278. public static function jsAjaxTable($params) {
  279. }
  280. public static function price($value, $dec = ',') {
  281. // TODO: if not number type - string wwith wrong format - try to convert?
  282. return number_format($value, 2, $dec, ' ');
  283. }
  284. public static function inlineJS($jsFile, $jsonVars = []) {
  285. echo self::hScript($jsFile, $jsonVars);
  286. }
  287. public static function hScript($jsFile, $jsonVars = []) {
  288. if (!file_exists($jsFile)) throw new Exception("js file '" . basename($jsFile) . "' not exists!");
  289. $ret = '<script>' . "\n";
  290. $ret .= "(function (global) {" . "\n";
  291. $ret .= " var module = {}; module.exports = {};\n";
  292. foreach ($jsonVars as $name => $var) {
  293. $ret .= " var {$name} = " . json_encode($var) . ";\n";
  294. }
  295. $ret .= file_get_contents($jsFile);
  296. $ret .= "\n;\n";
  297. $ret .= " if (module && module.exports && Object.keys(module.exports).length) {" . "\n";
  298. $ret .= " Object.keys(module.exports).forEach(function (key) {" . "\n";
  299. $ret .= " global[key] = module.exports[key];" . "\n";
  300. $ret .= " })" . "\n";
  301. $ret .= " }" . "\n";
  302. $ret .= "})(window)" . "\n";
  303. $ret .= '</script>' . "\n";
  304. return $ret;
  305. }
  306. public static function inlineRawJS($jsFile) {
  307. if (!file_exists($jsFile)) throw new Exception("js file '" . basename($jsFile) . "' not exists!");
  308. UI::startTag('script', [], "\n");
  309. echo file_get_contents($jsFile);
  310. UI::endTag('script', "\n");
  311. }
  312. public static function hStyle($cssFile) {
  313. $ret = '<style type="text/css">' . "\n";
  314. $ret .= file_get_contents($cssFile);
  315. $ret .= '</style>' . "\n";
  316. return $ret;
  317. }
  318. public static function inlineCSS($cssFile) {
  319. UI::startTag('style', ['type'=>"text/css"], "\n");
  320. echo file_get_contents($cssFile);
  321. UI::endTag('style', "\n");
  322. }
  323. public static function inlineRawCSS($cssContent) {
  324. echo UI::h('style', [ 'type' => "text/css" ], $cssContent) . "\n";
  325. }
  326. public static function includeView($viewPath, $data = array()) {
  327. if (!file_exists($viewPath)) throw new Exception("view file '" . basename($viewPath) . "' not exists!");
  328. if (false === strpos($viewPath, APP_PATH_ROOT)) throw new Exception("Access Denied to include view '" . basename($viewPath) . "'!");
  329. if (is_array($data) && !empty($data)) {
  330. extract($data);
  331. }
  332. include $viewPath;
  333. }
  334. public static function postButton($label, $params = []) {
  335. UI::startTag('form', [
  336. 'action' => V::get('action', '', $params),
  337. 'method' => V::get('method', 'post', $params),
  338. 'style' => "display:inline"
  339. ]);
  340. foreach (V::get('data', [], $params, 'array') as $name => $value) {
  341. UI::emptyTag('input', ['type'=>'hidden', 'name'=>$name, 'value'=>$value]);
  342. }
  343. UI::tag('button', ['type'=>'submit', 'class' => 'btn ' . V::get('class', 'btn-default btn-xs', $params)], $label);
  344. UI::endTag('form');
  345. }
  346. public static function hButtonPost($label, $params = [], $childrens = []) {
  347. if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
  348. if (!empty($params['fields'])) {
  349. foreach ($params['fields'] as $fieldParams) {
  350. $childrens[] = self::h('input', $fieldParams);
  351. }
  352. }
  353. $childrens[] = self::h('button', array_merge(
  354. [
  355. 'type' => 'submit',
  356. 'class' => 'btn ' . V::get('class', 'btn-default', $params),
  357. 'style' => V::get('style', '', $params)
  358. ],
  359. (!empty($params['title'])) ? ['title' => $params['title']] : [],
  360. (!empty($params['onclick'])) ? ['onclick' => $params['onclick']] : []
  361. ), $label);
  362. return self::h('form', [
  363. 'action' => V::get('action', '', $params),
  364. 'method' => V::get('method', 'post', $params),
  365. 'style' => V::get('form.style', 'display:inline', $params),
  366. 'class' => "form-inline " . V::get('form.class', '', $params),
  367. ], $childrens);
  368. }
  369. public static function hSimplePostTaskButton($label, $postTaskName, $params = [], $childrens = []) {
  370. $childrens[] = self::h('input', [ 'type' => 'hidden', 'name' => '_postTask', 'value' => $postTaskName ]);
  371. if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
  372. if (!empty($params['fields'])) {
  373. foreach ($params['fields'] as $fieldParams) {
  374. $childrens[] = self::h('input', $fieldParams);
  375. }
  376. }
  377. $childrens[] = self::h('button', array_merge(
  378. [
  379. 'type' => 'submit',
  380. 'class' => 'btn ' . V::get('class', 'btn-default', $params),
  381. 'style' => V::get('style', '', $params)
  382. ],
  383. (!empty($params['title'])) ? ['title' => $params['title']] : []
  384. ), $label);
  385. return self::h('form', [
  386. 'action' => V::get('action', '', $params),
  387. 'method' => V::get('method', 'post', $params),
  388. 'style' => V::get('form.style', 'display:inline', $params),
  389. 'class' => "form-inline"
  390. ], $childrens);
  391. }
  392. public static function hButtonAjax($label, $jsEventPrefix, $params = []) {
  393. if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
  394. $query = V::get('data', '', $params);
  395. return self::h('a', [
  396. 'class' => V::get('class', 'btn btn-default', $params),
  397. 'style' => V::get('style', '', $params),
  398. 'href' => V::get('href', '', $params),
  399. 'onClick' => "return p5UI__hButtonAjax(this, 'p5UIBtnAjax:{$jsEventPrefix}', '', '" . http_build_query($query) . "')",
  400. ], $label);
  401. }
  402. public static function hButtonAjaxOnResponse($jsEventPrefix, $jsCode) {
  403. echo self::h('script', [], "
  404. jQuery(document).on('p5UIBtnAjax:{$jsEventPrefix}:response', function(e, n, payload) {
  405. {$jsCode}
  406. })
  407. ");
  408. }
  409. public static function hButtonAjaxJsFunction() {
  410. echo UI::h('script', [], "
  411. function p5UI__hButtonAjax(n, eventNamespace, url, query) {
  412. var dbg = " . ( DBG::isActive() ? 1 : 0 ) . ";
  413. var jqNode = jQuery(n);
  414. var state = {
  415. href: url || n.href,
  416. data: query || ''
  417. }
  418. jQuery(document).trigger('p5UIBtnAjax:' + eventNamespace + ':click', [n, state])
  419. if (jqNode.hasClass('disabled')) { // bootstrap already prevent this action
  420. if (dbg) console.log('WARNING: btn disabled - waiting for response - Cancel?')
  421. return false
  422. }
  423. jqNode.addClass('disabled btn-loading')
  424. window.fetch(state.href, {
  425. method: 'POST',
  426. headers: {
  427. 'Content-Type': 'application/x-www-form-urlencoded' // query string
  428. },
  429. credentials: 'same-origin',
  430. body: state.data // new URLSearchParams(state.data)
  431. }).then(function(response) {
  432. return response.json()
  433. }).then(function(payload) {
  434. jqNode.removeClass('disabled btn-loading');
  435. jQuery(document).trigger(eventNamespace + ':response', [n, payload]);
  436. }).catch(function(e) {
  437. jQuery(document).trigger(eventNamespace + ':response', [n, 'error' + e]);
  438. jqNode.removeClass('disabled btn-loading');
  439. p5UI__notifyAjaxCallback({
  440. type: 'error',
  441. msg: 'Request error ' + e
  442. });
  443. console.log('loadDataAjax:fetch: ERR:', e);
  444. })
  445. return false;
  446. }
  447. ");
  448. }
  449. // @return UI_Node({tagName, params, childrens}): struct HTML tag
  450. public static function node($tagName = null, $params = null, $childrens = null) {
  451. if (null === $tagName && empty($params)) return new UI_Node(null, null, $childrens);
  452. if ('p5:' === substr($tagName, 0, 3)) return self::customNode($tagName, $params, $childrens);
  453. switch ($tagName) {
  454. case 'hr': // Defines a single change in line of content
  455. case 'br': // Defines Single line breaks
  456. case 'input': // Defines a input tag
  457. case 'link': // Define link connection between two files
  458. case 'area': // Defines clickable area inside a image map
  459. case 'base': // Defines specific base or root path
  460. case 'col': // Defines column properties within each column
  461. case 'embed': // That adds or embeds other elements such as Flash
  462. case 'img': // Defines a image
  463. case 'keygen': // Defines reference from data after the form is submitted
  464. case 'meta': // Defines meta data inside the HTML web page
  465. case 'param': // Defines passing parameters for an embedded project
  466. case 'source': // Defines source for media files
  467. case 'track': // Define text track for video or audio files
  468. case 'wbr': // Define word break opportunity within a text for adding a line-break
  469. case 'command': // Defines a command that users can invoke
  470. case 'menuitem': // Defines command or menu item that users invoke from popup menu
  471. {
  472. return new UI_NodeSelfClosing($tagName, $params);
  473. }
  474. default:
  475. {
  476. return new UI_Node($tagName, $params, $childrens);
  477. }
  478. }
  479. }
  480. public static function customNode($tagName, $params = null, $childrens = null) {
  481. if ('p5:' === substr($tagName, 0, 3)) {
  482. $nodeClassName = "UI_" . substr($tagName, 3);
  483. if (!class_exists($nodeClassName)) Lib::tryLoadClass($nodeClassName);
  484. if (!class_exists($nodeClassName)) throw new Exception("Not implemented custom tag '{$tagName}'");
  485. return new $nodeClassName($tagName, $params, $childrens);
  486. }
  487. throw new Exception("Not implemented custom tag prefix '{$tagName}'");
  488. }
  489. public static function h($tagName, $params = [], $childrens = []) { // TODO: return (string)UI::node($tagName, $params, $childrens);
  490. if (null === $tagName && empty($params)) return self::hChildrens($childrens);
  491. $emptyTags = [];
  492. $emptyTags[] = 'hr';
  493. $emptyTags[] = 'br';
  494. $emptyTags[] = 'input';
  495. $emptyTags[] = 'link';
  496. $emptyTags[] = 'area';
  497. $emptyTags[] = 'base';
  498. $emptyTags[] = 'col';
  499. $emptyTags[] = 'embed';
  500. $emptyTags[] = 'img';
  501. $emptyTags[] = 'keygen';
  502. $emptyTags[] = 'meta';
  503. $emptyTags[] = 'param';
  504. $emptyTags[] = 'source';
  505. $emptyTags[] = 'track';
  506. $emptyTags[] = 'wbr';
  507. if (in_array($tagName, $emptyTags)) return '<' . $tagName . (empty($params) ? '' : ' ' . self::hAttributes($params)) . '/>';
  508. if ('p5:' === substr($tagName, 0, 3)) return self::hCustomTag($tagName, $params, $childrens);
  509. return '<' . $tagName . (empty($params) ? '' : ' ' . self::hAttributes($params)) . '>' . self::hChildrens($childrens) . '</' . $tagName . '>';
  510. }
  511. public static function hCustomTag($tagName, $params = [], $childrens = []) {
  512. if ('p5:' === substr($tagName, 0, 3)) {
  513. $tagClass = "UI_" . substr($tagName, 3);
  514. if (!class_exists($tagClass)) Lib::tryLoadClass($tagClass);
  515. if (!class_exists($tagClass)) throw new Exception("Not implemented custom tag '{$tagName}'");
  516. return $tagClass::h($tagName, $params, $childrens);
  517. }
  518. throw new Exception("Not implemented custom tag prefix '{$tagName}'");
  519. }
  520. public static function hAttributes($params = []) {
  521. $attr = [];
  522. if (null === $params) return '';
  523. if (!is_array($params)) {
  524. try {
  525. throw new Exception("Wrong params type in UI::hAttributes");
  526. } catch (Exception $e) {
  527. DBG::log($e);
  528. }
  529. }
  530. foreach ($params as $k => $v) {
  531. if (is_array($v)) {
  532. $attr[] = "{$k}=\"" . implode(" ", $v) . "\"";
  533. } else if (true === $v) { // eg. open => true : 'open'
  534. $attr[] = $k;
  535. } else if (false === $v) { // skip if false value
  536. } else if (!empty($v)) {
  537. $attr[] = "{$k}=\"{$v}\"";
  538. }
  539. }
  540. return implode(" ", $attr);
  541. }
  542. public static function hChildrens($childrens = []) {
  543. if (empty($childrens)) {
  544. if (is_int($childrens)) return "{$childrens}";
  545. if (is_string($childrens)) return $childrens;
  546. return '';
  547. }
  548. if (is_scalar($childrens)) return "{$childrens}";
  549. if (!is_array($childrens)) throw new Exception("Unsupported children type");
  550. return array_reduce(
  551. $childrens,
  552. function ($curry, $child) {
  553. return "{$curry}{$child}";
  554. },
  555. ""
  556. );
  557. }
  558. /**
  559. * @param $taskPerm - 'C', 'W'
  560. */
  561. public static function hGetFormItem($acl, $fieldName, $taskPerm, $fieldID, $fName, $fValue, $params = array(), $record = null) {
  562. $fValue = (string)$fValue;
  563. Lib::loadClass('Typespecial');
  564. DBG::log(['$fieldName'=>$fieldName, '$taskPerm'=>$taskPerm, '$fieldID'=>$fieldID, '$fName'=>$fName, '$fValue'=>$fValue, '$params'=>$params, '$record'=>$record], 'array', "hGetFormItem()");
  565. if (!$acl->isAllowed($fieldID, $taskPerm, $record)) {
  566. switch ($taskPerm) {
  567. case 'R': return "Brak uprawnień do odczytu";
  568. case 'W': return "Brak uprawnień do zapisu";
  569. case 'C': return "Brak uprawnień";
  570. default: return "Brak uprawnień do tego pola ({$taskPerm})";
  571. }
  572. }
  573. if ($fieldName == 'ID') return ''; // TODO: hide primaryKey?
  574. // $colType = $acl->getFieldTypeById($fieldID);
  575. // if (!$colType) return "Error - unknown type";
  576. $xsdType = $acl->getXsdFieldType($fieldName);
  577. DBG::log("DBG: field({$fieldName}) xsdType({$xsdType})");
  578. $html = new stdClass();
  579. $html->_params = array();
  580. $html->tag = 'input';
  581. $html->childrens = [];
  582. $html->attrs = array();
  583. $html->attrs['id'] = $fName;
  584. $html->attrs['name'] = $fName;
  585. $html->attrs['type'] = 'text';
  586. $html->attrs['value'] = $fValue;// BUG htmlspecialchars($fValue); - convert chars in edit form (" to &quot; and & to &amp;)
  587. if (isset($params['tabindex'])) $html->attrs['tabindex'] = $params['tabindex'];
  588. // if (!$acl->hasFieldPerm($fieldID, $taskPerm)) {
  589. // $html->attrs['disabled'] = 'disabled';
  590. // }
  591. $maxGrid = V::get('maxGrid', 10, $params);
  592. switch ($xsdType) {
  593. case 'xsd:long':
  594. case 'xsd:int':
  595. case 'xsd:integer': {
  596. $html->attrs['type'] = 'number';
  597. $html->attrs['class'][] = 'input-small';
  598. } break;
  599. case 'xsd:decimal':
  600. case 'xsd:double':
  601. case 'xsd:float':
  602. case 'p5:price': {
  603. $html->attrs['type'] = 'text';
  604. $html->attrs['class'][] = 'input-small';
  605. } break;
  606. case 'xsd:string':
  607. case 'p5:www_link':
  608. case 'p5:string': {
  609. $html->attrs['type'] = 'text';
  610. $maxLength = (int)$acl->getXsdFieldParam($fieldName, 'maxLength');
  611. if ($maxLength > 0) {
  612. $html->attrs['maxlength'] = $maxLength;
  613. }
  614. $valLength = strlen($fValue);
  615. if (isset($params['widthClass'])) {
  616. if ($params['widthClass'] == 'inside-modal') {
  617. $html->attrs['style'] = 'width:98%;';
  618. } else {
  619. $html->attrs['style'] = 'width:98%;';
  620. }
  621. }
  622. if ($maxLength > 255) {// Fix for long varchar - use textarea
  623. $html->tag = 'textarea';
  624. $html->childrens[] = $fValue;
  625. $html->attrs['rows'] = '3';
  626. unset($html->attrs['type']);
  627. unset($html->attrs['value']);
  628. }
  629. } break;
  630. case 'xsd:dateTime':
  631. case 'xsd:date': {
  632. $testDatePicker = true;
  633. if ($testDatePicker) {
  634. $html->attrs['type'] = 'text';
  635. $html->_params[] = 'date';
  636. if ('xsd:dateTime' === $xsdType) {
  637. $html->attrs['class'][] = 'se_type-datetime'; // datetimepicker';
  638. $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  639. $html->attrs['maxlength'] = 19;
  640. } else {
  641. $html->attrs['class'][] = 'se_type-date'; // datetimepicker';
  642. $html->attrs['maxlength'] = 10;
  643. }
  644. if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  645. $html->attrs['value'] = '';
  646. }
  647. } else {
  648. $html->attrs['type'] = 'date';
  649. }
  650. } break;
  651. case 'xsd:time': {
  652. $testDatePicker = true;
  653. if ($testDatePicker) {
  654. $html->attrs['type'] = 'text';
  655. $html->_params[] = 'time';
  656. $html->attrs['class'][] = 'se_type-time';// datetimepicker';
  657. $html->attrs['data-format'] = 'hh:mm:ss';
  658. $html->attrs['maxlength'] = 8;
  659. if (substr($html->attrs['value'], 0, 8) == '00:00:00') {
  660. $html->attrs['value'] = '';
  661. }
  662. } else {
  663. $html->attrs['type'] = 'time';
  664. }
  665. } break;
  666. // case 'timestamp': { // TODO: timestamp is xsd:integer or xsd:dateTime?
  667. // $testDatePicker = true;
  668. // if ($testDatePicker) {
  669. // $html->attrs['type'] = 'text';
  670. // $html->_params[] = 'date';
  671. // $html->attrs['class'][] = 'se_type-datetime';// datetimepicker';
  672. // $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  673. // $html->attrs['maxlength'] = 19;
  674. // if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  675. // $html->attrs['value'] = '';
  676. // }
  677. // } else {
  678. // $html->attrs['type'] = 'date';
  679. // }
  680. // } break;
  681. case 'p5:enum': {
  682. DBG::log($acl->getField($fieldID), 'array', "\$field($fieldName)");
  683. unset($html->attrs['type']);
  684. unset($html->attrs['value']);
  685. $html->tag = 'select';
  686. $defaultValue = $acl->getFieldDefaultValue($fieldName);
  687. $values = $acl->getEnumerations($fieldName);
  688. // $values = explode(',', str_replace(array('(',')',"'",'"'), '', substr($colType['type'], 5)));
  689. $selValue = $fValue;
  690. if (empty($selValue) && $selValue !== '0' && !empty($defaultValue)) {
  691. if ($taskPerm == 'C') {
  692. $selValue = $defaultValue;
  693. } else if ($taskPerm == 'W' && $acl->isAllowed($fieldID, 'R', $record)) {
  694. $selValue = $defaultValue;
  695. }
  696. }
  697. $html->childrens[] = [ 'option', [ 'value' => "" ], "" ];
  698. if (!empty($selValue) && !array_key_exists($selValue, $values)) {
  699. $html->childrens[] = [ 'option', [ 'value' => $selValue, 'selected' => "selected" ], $selValue ];
  700. }
  701. foreach ($values as $val => $label) {
  702. $html->childrens[] = [ 'option', array_merge(
  703. [ 'value' => $val ],
  704. ((!empty($selValue) || '0' === $selValue) && (string)$selValue === (string)$val) ? [ 'selected' => "selected" ] : []
  705. ), $label ];
  706. }
  707. } break;
  708. case 'p5:text': {
  709. $html->tag = 'textarea';
  710. $html->childrens[] = $fValue;
  711. if (isset($params['widthClass'])) {
  712. if ($params['widthClass'] == 'inside-modal') {
  713. $html->attrs['style'] = 'width:98%;';
  714. } else {
  715. $html->attrs['style'] = 'width:98%;';
  716. }
  717. } else {
  718. //$html->attrs['class'][] = (8 <= $maxGrid)? 'span8' : "span{$maxGrid}";
  719. }
  720. $html->attrs['rows'] = '3';
  721. unset($html->attrs['type']);
  722. unset($html->attrs['value']);
  723. } break;
  724. case 'gml:GeometryPropertyType':
  725. case 'gml:LineStringPropertyType':
  726. case 'gml:PointPropertyType':
  727. case 'gml:PolygonPropertyType': {
  728. return '...';
  729. } break;
  730. case 'xsd:base64Binary': {
  731. return '...';
  732. } break;
  733. default: {
  734. if ('ref:' === substr($xsdType, 0, 4)) {
  735. return "Funkcja w trakcie przygotowanie (ref do '" . substr($xsdType, 4) . "')";
  736. }
  737. return "unknown Type \"{$xsdType}\"";
  738. }
  739. }
  740. $html->attrs['class'][] = 'form-control';
  741. if (!empty($html->attrs['class'])) $html->attrs['class'] = implode(" ", $html->attrs['class']);
  742. $nodeHtml = (in_array($html->tag, array('select', 'textarea')))
  743. ? [ $html->tag, $html->attrs, $html->childrens ]
  744. : $nodeHtml = [ $html->tag, $html->attrs ]
  745. ;
  746. if (in_array('date', $html->_params)) {
  747. $nodeHtml = [ 'div', [ 'class' => "input-group" ], [
  748. $nodeHtml,
  749. [ 'span', [ 'class' => "input-group-addon" ], [
  750. [ 'span', [ 'class' => "glyphicon glyphicon-calendar" ] ]
  751. ] ]
  752. ] ];
  753. }
  754. else if (in_array('time', $html->_params)) {
  755. $nodeHtml = [ 'div', [ 'class' => "input-group" ], [
  756. $nodeHtml,
  757. [ 'span', [ 'class' => "input-group-addon" ], [
  758. [ 'span', [ 'class' => "glyphicon glyphicon-time" ] ]
  759. ] ]
  760. ] ];
  761. }
  762. if (true == V::get('appendBack', '', $params)
  763. && !in_array('date', $html->_params)
  764. && !in_array('time', $html->_params)
  765. ) {
  766. if ($html->tag == 'input' && $taskPerm == 'W') {
  767. $nodeHtml = [ 'div', [ 'class' => "input-group show-last-value" ], [
  768. $nodeHtml,
  769. [ 'span', [ 'class' => "input-group-addon button-appendBack", 'title' => htmlspecialchars($fValue) ], [
  770. [ 'span', [ 'class' => "glyphicon glyphicon-arrow-left" ] ]
  771. ] ]
  772. ] ];
  773. }
  774. }
  775. $typeSpecial = Typespecial::getInstance($fieldID, $fieldName);
  776. if ($typeSpecial) {
  777. $tsParams = array();
  778. $tsValue = V::get('typespecialValue', '', $params);
  779. if (!empty($tsValue)) {
  780. $tsParams['typespecialValue'] = $tsValue;
  781. }
  782. $nodeHtml = [ 'div', [ 'class' => "field-with-typespecial" ], [
  783. $nodeHtml,
  784. $typeSpecial->hGetFormItem($acl, $fieldName, $acl->_zasobID, $fName, $fValue, $tsParams, $record),
  785. ] ];
  786. }
  787. return $nodeHtml;
  788. }
  789. public static function convertHtmlToArray($html) {
  790. $nodes = [];
  791. // <a href="index.php?_route=Users&_task=userGroups&usrLogin=michal.podejko">ustal stanowisko</a>
  792. // [ 'a', [ 'href' => "index.php?_route=Users&_task=userGroups&usrLogin=michal.podejko" ], "ustal stanowisko" ]
  793. $DBG = 0;
  794. $pos = 0;
  795. // TODO: while (true)
  796. if ('<' === substr($html, $pos, 1)) { // parse tag
  797. $tagName = ''; $attrs = []; $content = [];
  798. $endTagOpen = strpos($html, '>', $pos + 1);
  799. $endTagName = min(strpos($html, ' ', $pos + 1), $endTagOpen); // '<tag>' or '<tag attr="..">'
  800. if (false === $pos) throw new Exception("Error Processing Html - missing tagName");
  801. $tagName = substr($html, $pos + 1, $endTagName - $pos - 1);
  802. if($DBG){echo "\ntagName: '{$tagName}'";}
  803. if ('>' === substr($html, $endTagName, 1)) {
  804. } else if (' ' === substr($html, $endTagName, 1)) {
  805. if (false === $endTagOpen) throw new Exception("Error Processing Html - missing open tag end char");
  806. $attrs = UI::convertHtmlAttrsToArray(trim(substr($html, $endTagName + 1, $endTagOpen - $endTagName - 1)));
  807. } else {
  808. throw new Exception("Error Processing Html - unexpected end tag name char '" . substr($html, $endTagName, 1) . "'");
  809. }
  810. if($DBG){echo "\nattrs: '" . json_encode($attrs), "'";}
  811. // TODO: empty tags '<br>', '<br/>', '<br />', '<input ... />', '<input ... >', img, hr, etc.
  812. // TODO: nested same tags '<tagName> ... <tagName> ... </tagName> ... </tagName>'
  813. $closeTagStart = strpos($html, "</{$tagName}>", $endTagOpen + 1);
  814. if (false === $closeTagStart) throw new Exception("Error Processing Html - missing close tagName");
  815. if($DBG){echo "\nDBG \$endTagOpen: " . substr($html, $endTagOpen, 5) . "...";}
  816. if($DBG){echo "\nDBG \$endTagOpen: " . substr($html, $endTagOpen) . ".EOL";}
  817. if($DBG){echo "\nDBG \$closeTagStart strpos(\$html, '</{$tagName}>', {$endTagOpen} + 1) = '{$closeTagStart}': " . substr($html, $closeTagStart, 5) . "...";}
  818. $content = substr($html, $endTagOpen + 1, $closeTagStart - $endTagOpen - 1);
  819. $tag = [ $tagName, $attrs, $content ];
  820. if($DBG){echo "\n\$tag: ";print_r($tag);}
  821. $nodes = $tag;
  822. }
  823. return $nodes;
  824. }
  825. public static function convertHtmlAttrsToArray($strAttrs) {
  826. $attrs = [];
  827. if (!preg_match_all('((\w+)=\"([^"]*)\")', $strAttrs, $matches)) {
  828. // echo "DBG:: empty attrs or wrong syntax";
  829. return [];
  830. }
  831. $total = (count($matches) - 1) / 2;
  832. // echo "\n\$matches (total = {$total}) = ";print_r($matches);
  833. for ($i = 0; $i < $total; $i++) {
  834. $idx = $i * 2 + 1;
  835. // echo "\n\$attrs[ '{$matches[$idx][0]}' ] = '{$matches[$idx+1][0]}';";
  836. $attrs[ $matches[ $idx ][0] ] = $matches[ $idx + 1 ][0];
  837. }
  838. return $attrs;
  839. }
  840. /**
  841. * Execute callback in try/catch block and view output as page layout (content inside html > body)
  842. * @param array $params
  843. * @param bool $params['showMenu']
  844. * @param bool $params['showContainer']
  845. * @param string $params['containerClass'] : [ 'fluid' ], default ''
  846. */
  847. public static function layout($callback, $params = []) {
  848. $params['showMenu'] = V::get('showMenu', true, $params, 'bool');
  849. $params['showContainer'] = V::get('showContainer', true, $params, 'bool');
  850. $params['containerClass'] = V::get('containerClass', '', $params);
  851. $args = V::get('args', [], $params, 'array');
  852. UI::gora(); // Theme::head();
  853. if ($params['showMenu']) UI::menu(); // TODO: Theme::top()
  854. if ($params['showContainer']) UI::startContainer( $params['containerClass'] ? [ 'class' => $params['containerClass'] ] : [] );
  855. try {
  856. // call_user_func($callback);
  857. $callback($args);
  858. } catch (AlertSuccessException $e) {
  859. DBG::log($e);
  860. UI::alert('success', $e->getMessage());
  861. } catch (AlertWarningException $e) {
  862. DBG::log($e);
  863. UI::alert('warning', $e->getMessage());
  864. } catch (AlertInfoException $e) {
  865. DBG::log($e);
  866. UI::alert('info', $e->getMessage());
  867. } catch (Exception $e) {
  868. DBG::log($e);
  869. UI::alert('danger', $e->getMessage());
  870. }
  871. if ($params['showContainer']) UI::endContainer();
  872. UI::dol(); // UI::dol must include Theme::footer();
  873. }
  874. /**
  875. * Execute callback inside try/catch block.
  876. * @param array $params
  877. * @param bool $params['showContainer']
  878. * @param string $params['containerClass'] : [ 'fluid' ], default ''
  879. */
  880. static function tryCatchView($callback, $params = []) {
  881. $params['showContainer'] = V::get('showContainer', false, $params, 'bool');
  882. $params['containerClass'] = V::get('containerClass', '', $params);
  883. $args = V::get('args', [], $params, 'array');
  884. if ($params['showContainer']) UI::startContainer( $params['containerClass'] ? [ 'class' => $params['containerClass'] ] : [] );
  885. try {
  886. // call_user_func($callback);
  887. $callback($args);
  888. } catch (AlertSuccessException $e) {
  889. DBG::log($e);
  890. UI::alert('success', $e->getMessage());
  891. } catch (AlertWarningException $e) {
  892. DBG::log($e);
  893. UI::alert('warning', $e->getMessage());
  894. } catch (AlertInfoException $e) {
  895. DBG::log($e);
  896. UI::alert('info', $e->getMessage());
  897. } catch (Exception $e) {
  898. DBG::log($e);
  899. UI::alert('danger', $e->getMessage());
  900. }
  901. if ($params['showContainer']) UI::endContainer();
  902. }
  903. public static function startDetails($opts, $summaryChildrens) {
  904. $attrs = array_reduce(array_keys($opts), function ($ret, $optionKey) use ($opts) {
  905. $option = $opts[$optionKey];
  906. if (false !== strpos($optionKey, '.')) {
  907. list($mainKey, $attrName) = explode('.', $optionKey, 2);
  908. $ret[$mainKey][$attrName] = $option;
  909. } else {
  910. $ret['details'][$optionKey] = $option;
  911. }
  912. return $ret;
  913. }, [
  914. 'details' => [],
  915. 'summary' => [],
  916. 'content' => [],
  917. ]);
  918. return '<details' . ( empty($attrs['details']) ? '' : ' ' . self::hAttributes($attrs['details']) ) . '>' .
  919. '<summary' . ( empty($attrs['summary']) ? '' : ' ' . self::hAttributes($attrs['summary']) ) . '>' . self::hChildrens($summaryChildrens) . '</summary>' . "\n" .
  920. '<div' . ( empty($attrs['content']) ? '' : ' ' . self::hAttributes($attrs['content']) ) . '>' . "\n";
  921. }
  922. public static function endDetails() {
  923. return '</div></details>';
  924. }
  925. }