UI.php 32 KB

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