UI.php 30 KB

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