UI.php 27 KB

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