UI.php 28 KB

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