UI.php 28 KB

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