UI.php 28 KB

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