UI.php 32 KB

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