UI.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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 'xsd:double':
  476. case 'xsd:float':
  477. case 'p5:price': {
  478. $html->attrs['type'] = 'text';
  479. $html->attrs['class'][] = 'input-small';
  480. } break;
  481. case 'xsd:string':
  482. case 'p5:www_link':
  483. case 'p5:string': {
  484. $html->attrs['type'] = 'text';
  485. $maxLength = (int)$acl->getXsdFieldParam($fieldName, 'maxLength');
  486. if ($maxLength > 0) {
  487. $html->attrs['maxlength'] = $maxLength;
  488. }
  489. $valLength = strlen($fValue);
  490. if (isset($params['widthClass'])) {
  491. if ($params['widthClass'] == 'inside-modal') {
  492. $html->attrs['style'] = 'width:98%;';
  493. } else {
  494. $html->attrs['style'] = 'width:98%;';
  495. }
  496. }
  497. if ($maxLength > 255) {// Fix for long varchar - use textarea
  498. $html->tag = 'textarea';
  499. $html->childrens[] = $fValue;
  500. $html->attrs['rows'] = '3';
  501. unset($html->attrs['type']);
  502. unset($html->attrs['value']);
  503. }
  504. } break;
  505. case 'xsd:dateTime':
  506. case 'xsd:date': {
  507. $testDatePicker = true;
  508. if ($testDatePicker) {
  509. $html->attrs['type'] = 'text';
  510. $html->_params[] = 'date';
  511. if ('xsd:dateTime' === $xsdType) {
  512. $html->attrs['class'][] = 'se_type-datetime'; // datetimepicker';
  513. $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  514. $html->attrs['maxlength'] = 19;
  515. } else {
  516. $html->attrs['class'][] = 'se_type-date'; // datetimepicker';
  517. $html->attrs['maxlength'] = 10;
  518. }
  519. if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  520. $html->attrs['value'] = '';
  521. }
  522. } else {
  523. $html->attrs['type'] = 'date';
  524. }
  525. } break;
  526. case 'xsd:time': {
  527. $testDatePicker = true;
  528. if ($testDatePicker) {
  529. $html->attrs['type'] = 'text';
  530. $html->_params[] = 'time';
  531. $html->attrs['class'][] = 'se_type-time';// datetimepicker';
  532. $html->attrs['data-format'] = 'hh:mm:ss';
  533. $html->attrs['maxlength'] = 8;
  534. if (substr($html->attrs['value'], 0, 8) == '00:00:00') {
  535. $html->attrs['value'] = '';
  536. }
  537. } else {
  538. $html->attrs['type'] = 'time';
  539. }
  540. } break;
  541. // case 'timestamp': { // TODO: timestamp is xsd:integer or xsd:dateTime?
  542. // $testDatePicker = true;
  543. // if ($testDatePicker) {
  544. // $html->attrs['type'] = 'text';
  545. // $html->_params[] = 'date';
  546. // $html->attrs['class'][] = 'se_type-datetime';// datetimepicker';
  547. // $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
  548. // $html->attrs['maxlength'] = 19;
  549. // if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
  550. // $html->attrs['value'] = '';
  551. // }
  552. // } else {
  553. // $html->attrs['type'] = 'date';
  554. // }
  555. // } break;
  556. case 'p5:enum': {
  557. DBG::log($acl->getField($fieldID), 'array', "\$field($fieldName)");
  558. unset($html->attrs['type']);
  559. unset($html->attrs['value']);
  560. $html->tag = 'select';
  561. $defaultValue = $acl->getFieldDefaultValue($fieldName);
  562. $values = $acl->getEnumerations($fieldName);
  563. // $values = explode(',', str_replace(array('(',')',"'",'"'), '', substr($colType['type'], 5)));
  564. $selValue = $fValue;
  565. if (empty($selValue) && $selValue !== '0' && !empty($defaultValue)) {
  566. if ($taskPerm == 'C') {
  567. $selValue = $defaultValue;
  568. } else if ($taskPerm == 'W' && $acl->isAllowed($fieldID, 'R', $record)) {
  569. $selValue = $defaultValue;
  570. }
  571. }
  572. $html->childrens[] = [ 'option', [ 'value' => "" ], "" ];
  573. if (!empty($selValue) && !array_key_exists($selValue, $values)) {
  574. $html->childrens[] = [ 'option', [ 'value' => $selValue, 'selected' => "selected" ], $selValue ];
  575. }
  576. foreach ($values as $val => $label) {
  577. $html->childrens[] = [ 'option', array_merge(
  578. [ 'value' => $val ],
  579. (!empty($selValue) && $selValue == $val) ? [ 'selected' => "selected" ] : []
  580. ), $label ];
  581. }
  582. } break;
  583. case 'p5:text': {
  584. $html->tag = 'textarea';
  585. $html->childrens[] = $fValue;
  586. if (isset($params['widthClass'])) {
  587. if ($params['widthClass'] == 'inside-modal') {
  588. $html->attrs['style'] = 'width:98%;';
  589. } else {
  590. $html->attrs['style'] = 'width:98%;';
  591. }
  592. } else {
  593. //$html->attrs['class'][] = (8 <= $maxGrid)? 'span8' : "span{$maxGrid}";
  594. }
  595. $html->attrs['rows'] = '3';
  596. unset($html->attrs['type']);
  597. unset($html->attrs['value']);
  598. } break;
  599. case 'gml:GeometryPropertyType':
  600. case 'gml:LineStringPropertyType':
  601. case 'gml:PointPropertyType':
  602. case 'gml:PolygonPropertyType': {
  603. return '...';
  604. } break;
  605. case 'xsd:base64Binary': {
  606. return '...';
  607. } break;
  608. default: {
  609. if ('ref:' === substr($xsdType, 0, 4)) {
  610. return "Funkcja w trakcie przygotowanie (ref do '" . substr($xsdType, 4) . "')";
  611. }
  612. return "unknown Type \"{$xsdType}\"";
  613. }
  614. }
  615. $html->attrs['class'][] = 'form-control';
  616. if (!empty($html->attrs['class'])) $html->attrs['class'] = implode(" ", $html->attrs['class']);
  617. $nodeHtml = (in_array($html->tag, array('select', 'textarea')))
  618. ? [ $html->tag, $html->attrs, $html->childrens ]
  619. : $nodeHtml = [ $html->tag, $html->attrs ]
  620. ;
  621. if (in_array('date', $html->_params)) {
  622. $nodeHtml = [ 'div', [ 'class' => "input-group" ], [
  623. $nodeHtml,
  624. [ 'span', [ 'class' => "input-group-addon" ], [
  625. [ 'span', [ 'class' => "glyphicon glyphicon-calendar" ] ]
  626. ] ]
  627. ] ];
  628. }
  629. else if (in_array('time', $html->_params)) {
  630. $nodeHtml = [ 'div', [ 'class' => "input-group" ], [
  631. $nodeHtml,
  632. [ 'span', [ 'class' => "input-group-addon" ], [
  633. [ 'span', [ 'class' => "glyphicon glyphicon-time" ] ]
  634. ] ]
  635. ] ];
  636. }
  637. if (true == V::get('appendBack', '', $params)
  638. && !in_array('date', $html->_params)
  639. && !in_array('time', $html->_params)
  640. ) {
  641. if ($html->tag == 'input' && $taskPerm == 'W') {
  642. $nodeHtml = [ 'div', [ 'class' => "input-group show-last-value" ], [
  643. $nodeHtml,
  644. [ 'span', [ 'class' => "input-group-addon button-appendBack", 'title' => htmlspecialchars($fValue) ], [
  645. [ 'span', [ 'class' => "glyphicon glyphicon-arrow-left" ] ]
  646. ] ]
  647. ] ];
  648. }
  649. }
  650. $typeSpecial = Typespecial::getInstance($fieldID, $fieldName);
  651. if ($typeSpecial) {
  652. $tsParams = array();
  653. $tsValue = V::get('typespecialValue', '', $params);
  654. if (!empty($tsValue)) {
  655. $tsParams['typespecialValue'] = $tsValue;
  656. }
  657. $nodeHtml = [ 'div', [ 'class' => "field-with-typespecial" ], [
  658. $nodeHtml,
  659. $typeSpecial->hGetFormItem($acl, $fieldName, $acl->_zasobID, $fName, $fValue, $tsParams, $record),
  660. ] ];
  661. }
  662. return $nodeHtml;
  663. }
  664. public static function convertHtmlToArray($html) {
  665. $nodes = [];
  666. // <a href="index.php?_route=Users&_task=userGroups&usrLogin=michal.podejko">ustal stanowisko</a>
  667. // [ 'a', [ 'href' => "index.php?_route=Users&_task=userGroups&usrLogin=michal.podejko" ], "ustal stanowisko" ]
  668. $DBG = 0;
  669. $pos = 0;
  670. // TODO: while (true)
  671. if ('<' === substr($html, $pos, 1)) { // parse tag
  672. $tagName = ''; $attrs = []; $content = [];
  673. $endTagOpen = strpos($html, '>', $pos + 1);
  674. $endTagName = min(strpos($html, ' ', $pos + 1), $endTagOpen); // '<tag>' or '<tag attr="..">'
  675. if (false === $pos) throw new Exception("Error Processing Html - missing tagName");
  676. $tagName = substr($html, $pos + 1, $endTagName - $pos - 1);
  677. if($DBG){echo "\ntagName: '{$tagName}'";}
  678. if ('>' === substr($html, $endTagName, 1)) {
  679. } else if (' ' === substr($html, $endTagName, 1)) {
  680. if (false === $endTagOpen) throw new Exception("Error Processing Html - missing open tag end char");
  681. $attrs = UI::convertHtmlAttrsToArray(trim(substr($html, $endTagName + 1, $endTagOpen - $endTagName - 1)));
  682. } else {
  683. throw new Exception("Error Processing Html - unexpected end tag name char '" . substr($html, $endTagName, 1) . "'");
  684. }
  685. if($DBG){echo "\nattrs: '" . json_encode($attrs), "'";}
  686. // TODO: empty tags '<br>', '<br/>', '<br />', '<input ... />', '<input ... >', img, hr, etc.
  687. // TODO: nested same tags '<tagName> ... <tagName> ... </tagName> ... </tagName>'
  688. $closeTagStart = strpos($html, "</{$tagName}>", $endTagOpen + 1);
  689. if (false === $closeTagStart) throw new Exception("Error Processing Html - missing close tagName");
  690. if($DBG){echo "\nDBG \$endTagOpen: " . substr($html, $endTagOpen, 5) . "...";}
  691. if($DBG){echo "\nDBG \$endTagOpen: " . substr($html, $endTagOpen) . ".EOL";}
  692. if($DBG){echo "\nDBG \$closeTagStart strpos(\$html, '</{$tagName}>', {$endTagOpen} + 1) = '{$closeTagStart}': " . substr($html, $closeTagStart, 5) . "...";}
  693. $content = substr($html, $endTagOpen + 1, $closeTagStart - $endTagOpen - 1);
  694. $tag = [ $tagName, $attrs, $content ];
  695. if($DBG){echo "\n\$tag: ";print_r($tag);}
  696. $nodes = $tag;
  697. }
  698. return $nodes;
  699. }
  700. public static function convertHtmlAttrsToArray($strAttrs) {
  701. $attrs = [];
  702. if (!preg_match_all('((\w+)=\"([^"]*)\")', $strAttrs, $matches)) {
  703. // echo "DBG:: empty attrs or wrong syntax";
  704. return [];
  705. }
  706. $total = (count($matches) - 1) / 2;
  707. // echo "\n\$matches (total = {$total}) = ";print_r($matches);
  708. for ($i = 0; $i < $total; $i++) {
  709. $idx = $i * 2 + 1;
  710. // echo "\n\$attrs[ '{$matches[$idx][0]}' ] = '{$matches[$idx+1][0]}';";
  711. $attrs[ $matches[ $idx ][0] ] = $matches[ $idx + 1 ][0];
  712. }
  713. return $attrs;
  714. }
  715. /**
  716. * @param array $params
  717. * @param bool $params['showMenu']
  718. * @param bool $params['showContainer']
  719. * @param string $params['containerClass'] : [ 'fluid' ], default ''
  720. */
  721. public static function layout($callback, $params = []) {
  722. $params['showMenu'] = V::get('showMenu', true, $params, 'bool');
  723. $params['showContainer'] = V::get('showContainer', true, $params, 'bool');
  724. $params['containerClass'] = V::get('containerClass', '', $params);
  725. UI::gora(); // Theme::head();
  726. if ($params['showMenu']) UI::menu(); // TODO: Theme::top()
  727. if ($params['showContainer']) UI::startContainer( $params['containerClass'] ? [ 'class' => $params['containerClass'] ] : [] );
  728. try {
  729. call_user_func($callback);
  730. } catch (Exception $e) {
  731. DBG::log($e);
  732. UI::alert('danger', $e->getMessage());
  733. }
  734. if ($params['showContainer']) UI::endContainer();
  735. UI::dol(); // UI::dol must include Theme::footer();
  736. }
  737. public static function startDetails($opts, $summaryChildrens) {
  738. $attrs = array_reduce(array_keys($opts), function ($ret, $optionKey) use ($opts) {
  739. $option = $opts[$optionKey];
  740. if (false !== strpos($optionKey, '.')) {
  741. list($mainKey, $attrName) = explode('.', $optionKey, 2);
  742. $ret[$mainKey][$attrName] = $option;
  743. } else {
  744. $ret['details'][$optionKey] = $option;
  745. }
  746. return $ret;
  747. }, [
  748. 'details' => [],
  749. 'summary' => [],
  750. 'content' => [],
  751. ]);
  752. return '<details' . ( empty($attrs['details']) ? '' : ' ' . self::hAttributes($attrs['details']) ) . '>' .
  753. '<summary' . ( empty($attrs['summary']) ? '' : ' ' . self::hAttributes($attrs['summary']) ) . '>' . self::hChildrens($summaryChildrens) . '</summary>' . "\n" .
  754. '<div' . ( empty($attrs['content']) ? '' : ' ' . self::hAttributes($attrs['content']) ) . '>' . "\n";
  755. }
  756. public static function endDetails() {
  757. return '</div></details>';
  758. }
  759. }