UI.php 29 KB

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