123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947 |
- <?php
- Lib::loadClass('Theme');
- require_once dirname(__FILE__) . '/' . 'UITagInterface.php';
- class UI {
- public static function getTitle() {
- $title = 'SE';
- $host = $_SERVER['SERVER_NAME'];
- if (substr($host, 0, 5) == 'biuro') {
- $host = substr($host, 6);
- }
- $title = "{$host}-SE";
- return $title;
- }
- public static function gora($params = []) {
- UI::startHtml($params);
- }
- public static function startHtml($params = []) { // @params: { title: string, childrens: string }
- Lib::loadClass('S');
- UI::loadTemplate('_layout_gora', $params);
- }
- public static function dol() {
- UI::endHtml();
- }
- public static function fixFooterPosition($type) {
- $fixFooterPosition = true;// from config?
- if (!$fixFooterPosition) return;
- switch ($type) {
- case 'footer_style': return 'position:absolute; bottom:0; left:0; width:100%; ';
- case 'body_style': return 'position:relative; padding-bottom:32px;';
- case 'body_css_style': return 'body { position:relative; padding-bottom:32px }';
- case 'footer_js_tag': return "\n<script>document.body.style.minHeight = '' + (window.innerHeight - 2) + 'px';</script>";
- }
- }
- public static function endHtml() {
- Theme::footer();
- if ('POST' === V::get('REQUEST_METHOD', '', $_SERVER) && 'LOGIN' === V::get('LOGIN', '', $_POST)) {
- echo "\n" . UI::h('script', [], "history.replaceState(null, '', window.location.href)");
- }
- echo "\n</body></html>";
- }
- public static function menu() {
- if (!User::logged()) {
- self::printUserMessage();
- return;
- }
- if (User::hasAccess('menu')) {
- Theme::top();
- }
- else {
- UI::loadTemplate('menuLevel6');
- }
- self::printUserMessage();
- }
- static function printUserMessage() {
- $usrMsg = S::getUserMessage();
- if (!$usrMsg) return;
- switch ($usrMsg[0]) {
- case 'AlertInfoException': UI::alertWithCloseBtn('info', $usrMsg[1]); return;
- case 'AlertSuccessException': UI::alertWithCloseBtn('success', $usrMsg[1]); return;
- case 'AlertWarningException': UI::alertWithCloseBtn('warning', $usrMsg[1]); return;
- case 'AlertDangerException': UI::alertWithCloseBtn('danger', $usrMsg[1]); return;
- case 'Exception': UI::alertWithCloseBtn('danger', $usrMsg[1]); return;
- default: UI::alertWithCloseBtn('danger', "Not implemented: " . $usrMsg[1]); return;
- }
- }
- public static function loadTemplate($tmplName, $data = array()) {
- if ('defaultPage' === $tmplName) { // TODO: replace UI::loadTemplate('defaultPage') => Theme::home($data)
- Theme::home($data);
- return;
- }
- if ('login' === $tmplName) { // TODO: replace UI::loadTemplate('login') => Theme::home($data)
- Theme::login($data);
- return;
- }
- if ('logout' === $tmplName) { // TODO: replace UI::loadTemplate('logout') => Theme::home($data)
- Theme::logout($data);
- return;
- }
- if (is_array($data) && !empty($data)) {
- extract($data);
- }
- include APP_PATH_LIB . "/tmpl/{$tmplName}.php";
- }
- public static function hotKeyDBG($str) {}
- public static function showMessagesForTable($tblName) {
- if (empty($tblName)) return;
- Lib::loadClass('Router');
- $msgsRoute = Router::getRoute('Msgs');
- $msgs = $msgsRoute->getActiveMessagesForTable($tblName);
- if (!empty($msgs)) {
- self::loadTemplate('msgsForTable', array('msgs' => $msgs));
- }
- }
- static function alert($alertType, $msg, $outputHtml = true) {
- if (!$outputHtml) {
- $type = ('danger' == $alertType) ? "ERROR" : strtoupper($alertType);
- echo "{$type}: {$msg}\n";
- return;
- }
- UI::tag('div', ['class'=>"alert alert-{$alertType}"], $msg, "\n");
- }
- static function alertWithCloseBtn($alertType, $msg, $outputHtml = true) {
- if (!$outputHtml) {
- $type = ('danger' == $alertType) ? "ERROR" : strtoupper($alertType);
- echo "{$type}: {$msg}\n";
- return;
- }
- $closeBtn = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>';
- UI::tag('div', ['class'=>"alert alert-{$alertType}"], $closeBtn . "\n" . $msg, "\n");
- }
- public static function setTitleJsTag($title) { self::setTitle($title); }
- public static function setTitle($title) { self::tag('script', null, "document.title = '{$title}';", "\n"); }
- public static function hTable($params) {
- ob_start();
- UI::table($params);
- return ob_get_clean();
- }
- /**
- * $params - Array
- * $params['caption'] (optional) -> <caption>...</caption>
- * $params['cols'] (optional) -> cols, if not set read from first row
- * $params['rows'] -> rows, if not set - empty table
- * $params['rows'] -> rows, if not set - empty table
- * $params['disable_lp'] -> disable lp. col
- */
- public static function table($params) {
- $cols = V::get('cols', array(), $params);
- $rows = V::get('rows', array(), $params);
- $cols_help = V::get('cols_help', array(), $params);
- $cols_label = V::get('cols_label', array(), $params);
- $caption = V::get('caption', '', $params);
- $cellPadding = V::get('cell_padding', 2, $params, 'int');
- $showLp = (!V::get('disable_lp', false, $params));
- $cssClassTable = V::get('@class', 'table table-bordered table-hover', $params);
- $countCols = 1;
- if (empty($cols) && !empty($rows)) {
- $firstRow = array();
- foreach ($rows as $row) {
- $firstRow = $row;
- break;
- }
- $cols = array_filter(
- array_keys((array)$firstRow),
- function ($col) {
- return ('@' != substr($col, 0, 1));
- }
- );
- }
- $countCols = count($cols);
- $countCols = ($showLp) ? $countCols + 1 : $countCols;
- {
- $help = array();
- foreach ($cols as $name) {
- $helpMsg = V::get($name, '', $cols_help);
- if (empty($helpMsg)) continue;
- $help[$name] = self::h('i', [
- 'class' => "glyphicon glyphicon-question-sign",
- 'title' => $helpMsg
- ], "");
- }
- }
- {
- $label = array();
- foreach ($cols as $name) {
- $label[$name] = V::get($name, $name, $cols_label);
- }
- }
- // if (empty($cols)) return;
- $hiddenCols = V::get('hidden_cols', array(), $params);
- $tableAttrs = [ 'class' => $cssClassTable, 'style' => V::get('style', '', $params) ];
- $html_id = V::get('__html_id', '', $params);
- if ($html_id) $tableAttrs['id'] = $html_id;
- self::startTag('table', $tableAttrs); echo "\n";
- if ($caption) { self::tag('caption', null, $caption); echo "\n"; }
- if (!empty($cols)) {
- self::startTag('thead', null); echo "\n";
- self::startTag('tr', null); echo "\n";
- if ($showLp) { self::tag('th', [ 'style' => "padding:{$cellPadding}px" ], "Lp."); echo "\n"; }
- foreach ($cols as $colName) {
- if (in_array($colName, $hiddenCols)) continue;
- $attrs = [ 'style' => "padding:{$cellPadding}px" ];
- if (!empty($params["@class[{$colName}]"])) $attrs['class'] = $params["@class[{$colName}]"];
- if (!empty($params["@style[{$colName}]"])) $attrs['style'] .= "; " . $params["@style[{$colName}]"];
- echo self::h('th', $attrs, [
- $label[$colName],
- " " . V::get($colName, '', $help)
- ]);
- echo "\n";
- }
- self::endTag('tr'); echo "\n";
- self::endTag('thead'); echo "\n";
- }
- $tbodyAttrs = [];
- if (array_key_exists('@tbody.id', $params)) $tbodyAttrs['id'] = $params['@tbody.id'];
- self::startTag('tbody', $tbodyAttrs); echo "\n";
- if (empty($rows)) {
- self::startTag('tr'); echo "\n";
- self::tag('td', [ 'style' => "padding:{$cellPadding}px", 'colspan' => $countCols ], V::get('empty_msg', "Brak danych", $params)); echo "\n";
- self::endTag('tr'); echo "\n";
- } else {
- $i = 0;
- foreach ($rows as $row) {
- $i++;
- $trAttrs = array();
- if (!empty($row['@onClick'])) $trAttrs['onClick'] = $row['@onClick'];
- if (!empty($row['@class'])) $trAttrs['class'] = $row['@class'];
- if (!empty($row['@style'])) $trAttrs['style'] = $row['@style'];
- if (!empty($row['@data'])) foreach ($row['@data'] as $k => $v) $trAttrs["data-{$k}"] = $v;
- self::startTag('tr', $trAttrs); echo "\n";
- if ($showLp) { self::tag('th', [ 'style' => "padding:2px; color:#ccc" ], $i); echo "\n"; }
- foreach ($cols as $colName) {
- $rowAttrs = [ 'style' => "padding:{$cellPadding}px" ];
- if (!empty($row["@onClick[{$colName}]"])) $rowAttrs['onClick'] = $row["@onClick[{$colName}]"];
- if (!empty($row["@class[{$colName}]"])) $rowAttrs['class'] = $row["@class[{$colName}]"];
- if (!empty($row["@style[{$colName}]"])) $rowAttrs['style'] .= "; " . $row["@style[{$colName}]"];
- if (in_array($colName, $hiddenCols)) continue;
- self::tag('td', $rowAttrs, V::get($colName, '', $row)); echo "\n";
- }
- self::endTag('tr'); echo "\n";
- }
- }
- self::endTag('tbody'); echo "\n";
- self::endTag('table'); echo "\n";
- }
- public static function startContainer($attrs = array()) {// echo '<div class="container">' . "\n";
- $attrs['class'] = (!empty($attrs['class']))
- ? $attrs['class'] . ' ' . 'container'
- : 'container';
- self::startTag('div', $attrs, "\n");
- }
- public static function endContainer() { self::endTag('div', "\n"); }
- public static function startTag($tag, $attrs = array(), $addWhiteSpace = false) {
- $outAttrs = '';
- if (is_array($attrs)) {
- foreach ($attrs as $attrName => $val) $outAttrs .= " {$attrName}=\"{$val}\"";
- }
- echo '<' . $tag . $outAttrs . '>' . self::whiteSpace($addWhiteSpace);
- }
- public static function whiteSpace($addWhiteSpace = false) {
- return (!$addWhiteSpace)
- ? ''
- : (true === $addWhiteSpace) ? " " : $addWhiteSpace;
- }
- public static function endTag($tag, $addWhiteSpace = false) {
- echo '</' . $tag . '>' . self::whiteSpace($addWhiteSpace);
- }
- public static function tag($tag, $attrs = array(), $childrens = array(), $addWhiteSpace = false) {
- $whiteSpace = self::whiteSpace($addWhiteSpace);
- self::startTag($tag, $attrs);
- echo $whiteSpace;
- if (!empty($childrens) && is_array($childrens)) throw new Exception("UI::tag() children as nodes not implemented".json_encode($childrens));
- if (is_scalar($childrens)) echo $childrens;
- echo $whiteSpace;
- self::endTag($tag);
- echo $whiteSpace;
- }
- public static function emptyTag($tag, $attrs = array(), $addWhiteSpace = false) {
- $outAttrs = '';
- if (is_array($attrs)) {
- foreach ($attrs as $attrName => $val) $outAttrs .= " {$attrName}=\"{$val}\"";
- }
- echo '<' . $tag . $outAttrs . '/>' . self::whiteSpace($addWhiteSpace);
- }
- public static function link($type, $content, $href, $attrs = array()) {
- $attrs['class'] = V::get('class', '', $attrs);
- $attrs['class'] .= "btn btn-{$type}";
- if (!empty($attrs['className'])) {
- foreach ($attrs['className'] as $cls => $bool) {
- if ($bool) $attrs['class'] .= " {$cls}";
- }
- unset($attrs['className']);
- }
- $attrs['href'] = $href;
- UI::tag('a', $attrs, $content);
- }
- public static function jsAjaxTable($params) {
- }
- public static function price($value, $dec = ',') {
- // TODO: if not number type - string wwith wrong format - try to convert?
- return number_format($value, 2, $dec, ' ');
- }
- public static function inlineJS($jsFile, $jsonVars = []) {
- echo self::hScript($jsFile, $jsonVars);
- }
- public static function hScript($jsFile, $jsonVars = []) {
- if (!file_exists($jsFile)) throw new Exception("js file '" . basename($jsFile) . "' not exists!");
- $ret = '<script>' . "\n";
- $ret .= "(function (global) {" . "\n";
- $ret .= " var module = {}; module.exports = {};\n";
- foreach ($jsonVars as $name => $var) {
- $ret .= " var {$name} = " . json_encode($var) . ";\n";
- }
- $ret .= file_get_contents($jsFile);
- $ret .= "\n;\n";
- $ret .= " if (module && module.exports && Object.keys(module.exports).length) {" . "\n";
- $ret .= " Object.keys(module.exports).forEach(function (key) {" . "\n";
- $ret .= " global[key] = module.exports[key];" . "\n";
- $ret .= " })" . "\n";
- $ret .= " }" . "\n";
- $ret .= "})(window)" . "\n";
- $ret .= '</script>' . "\n";
- return $ret;
- }
- public static function inlineRawJS($jsFile) {
- if (!file_exists($jsFile)) throw new Exception("js file '" . basename($jsFile) . "' not exists!");
- UI::startTag('script', [], "\n");
- echo file_get_contents($jsFile);
- UI::endTag('script', "\n");
- }
- public static function hStyle($cssFile) {
- $ret = '<style type="text/css">' . "\n";
- $ret .= file_get_contents($cssFile);
- $ret .= '</style>' . "\n";
- return $ret;
- }
- public static function inlineCSS($cssFile) {
- UI::startTag('style', ['type'=>"text/css"], "\n");
- echo file_get_contents($cssFile);
- UI::endTag('style', "\n");
- }
- public static function inlineRawCSS($cssContent) {
- echo UI::h('style', [ 'type' => "text/css" ], $cssContent) . "\n";
- }
- public static function includeView($viewPath, $data = array()) {
- if (!file_exists($viewPath)) throw new Exception("view file '" . basename($viewPath) . "' not exists!");
- if (false === strpos($viewPath, APP_PATH_ROOT)) throw new Exception("Access Denied to include view '" . basename($viewPath) . "'!");
- if (is_array($data) && !empty($data)) {
- extract($data);
- }
- include $viewPath;
- }
- public static function postButton($label, $params = []) {
- UI::startTag('form', [
- 'action' => V::get('action', '', $params),
- 'method' => V::get('method', 'post', $params),
- 'style' => "display:inline"
- ]);
- foreach (V::get('data', [], $params, 'array') as $name => $value) {
- UI::emptyTag('input', ['type'=>'hidden', 'name'=>$name, 'value'=>$value]);
- }
- UI::tag('button', ['type'=>'submit', 'class' => 'btn ' . V::get('class', 'btn-default btn-xs', $params)], $label);
- UI::endTag('form');
- }
- public static function hButtonPost($label, $params = [], $childrens = []) {
- if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
- if (!empty($params['fields'])) {
- foreach ($params['fields'] as $fieldParams) {
- $childrens[] = self::h('input', $fieldParams);
- }
- }
- $childrens[] = self::h('button', array_merge(
- [
- 'type' => 'submit',
- 'class' => 'btn ' . V::get('class', 'btn-default', $params),
- 'style' => V::get('style', '', $params)
- ],
- (!empty($params['title'])) ? ['title' => $params['title']] : []
- ), $label);
- return self::h('form', [
- 'action' => V::get('action', '', $params),
- 'method' => V::get('method', 'post', $params),
- 'style' => V::get('form.style', 'display:inline', $params),
- 'class' => "form-inline " . V::get('form.class', '', $params),
- ], $childrens);
- }
- public static function hSimplePostTaskButton($label, $postTaskName, $params = [], $childrens = []) {
- $childrens[] = self::h('input', [ 'type' => 'hidden', 'name' => '_postTask', 'value' => $postTaskName ]);
- if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
- if (!empty($params['fields'])) {
- foreach ($params['fields'] as $fieldParams) {
- $childrens[] = self::h('input', $fieldParams);
- }
- }
- $childrens[] = self::h('button', array_merge(
- [
- 'type' => 'submit',
- 'class' => 'btn ' . V::get('class', 'btn-default', $params),
- 'style' => V::get('style', '', $params)
- ],
- (!empty($params['title'])) ? ['title' => $params['title']] : []
- ), $label);
- return self::h('form', [
- 'action' => V::get('action', '', $params),
- 'method' => V::get('method', 'post', $params),
- 'style' => V::get('form.style', 'display:inline', $params),
- 'class' => "form-inline"
- ], $childrens);
- }
- public static function hButtonAjax($label, $jsEventPrefix, $params = []) {
- if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
- $query = V::get('data', '', $params);
- return self::h('a', [
- 'class' => V::get('class', 'btn btn-default', $params),
- 'style' => V::get('style', '', $params),
- 'href' => V::get('href', '', $params),
- 'onClick' => "return p5UI__hButtonAjax(this, 'p5UIBtnAjax:{$jsEventPrefix}', '', '" . http_build_query($query) . "')",
- ], $label);
- }
- public static function hButtonAjaxOnResponse($jsEventPrefix, $jsCode) {
- echo self::h('script', [], "
- jQuery(document).on('p5UIBtnAjax:{$jsEventPrefix}:response', function(e, n, payload) {
- {$jsCode}
- })
- ");
- }
- public static function hButtonAjaxJsFunction() {
- echo UI::h('script', [], "
- function p5UI__hButtonAjax(n, eventNamespace, url, query) {
- var dbg = " . ( DBG::isActive() ? 1 : 0 ) . ";
- var jqNode = jQuery(n);
- var state = {
- href: url || n.href,
- data: query || ''
- }
- jQuery(document).trigger('p5UIBtnAjax:' + eventNamespace + ':click', [n, state])
- if (jqNode.hasClass('disabled')) { // bootstrap already prevent this action
- if (dbg) console.log('WARNING: btn disabled - waiting for response - Cancel?')
- return false
- }
- jqNode.addClass('disabled btn-loading')
- window.fetch(state.href, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded' // query string
- },
- credentials: 'same-origin',
- body: state.data // new URLSearchParams(state.data)
- }).then(function(response) {
- return response.json()
- }).then(function(payload) {
- jqNode.removeClass('disabled btn-loading');
- jQuery(document).trigger(eventNamespace + ':response', [n, payload]);
- }).catch(function(e) {
- jQuery(document).trigger(eventNamespace + ':response', [n, 'error' + e]);
- jqNode.removeClass('disabled btn-loading');
- p5UI__notifyAjaxCallback({
- type: 'error',
- msg: 'Request error ' + e
- });
- console.log('loadDataAjax:fetch: ERR:', e);
- })
- return false;
- }
- ");
- }
- public static function h($tagName, $params = [], $childrens = []) {
- if (null === $tagName && empty($params)) return self::hChildrens($childrens);
- $emptyTags = [];
- $emptyTags[] = 'hr';
- $emptyTags[] = 'br';
- $emptyTags[] = 'input';
- $emptyTags[] = 'link';
- $emptyTags[] = 'area';
- $emptyTags[] = 'base';
- $emptyTags[] = 'col';
- $emptyTags[] = 'embed';
- $emptyTags[] = 'img';
- $emptyTags[] = 'keygen';
- $emptyTags[] = 'meta';
- $emptyTags[] = 'param';
- $emptyTags[] = 'source';
- $emptyTags[] = 'track';
- $emptyTags[] = 'wbr';
- if (in_array($tagName, $emptyTags)) return '<' . $tagName . (empty($params) ? '' : ' ' . self::hAttributes($params)) . '/>';
- if ('p5:' === substr($tagName, 0, 3)) return self::hCustomTag($tagName, $params, $childrens);
- return '<' . $tagName . (empty($params) ? '' : ' ' . self::hAttributes($params)) . '>' . self::hChildrens($childrens) . '</' . $tagName . '>';
- }
- public static function hCustomTag($tagName, $params = [], $childrens = []) {
- if ('p5:' === substr($tagName, 0, 3)) {
- $tagClass = "UI_" . substr($tagName, 3);
- if (!class_exists($tagClass)) Lib::tryLoadClass($tagClass);
- if (!class_exists($tagClass)) throw new Exception("Not implemented custom tag '{$tagName}'");
- return $tagClass::h($tagName, $params, $childrens);
- }
- throw new Exception("Not implemented custom tag prefix '{$tagName}'");
- }
- public static function hAttributes($params = []) {
- $attr = [];
- if (null === $params) return '';
- if (!is_array($params)) {
- try {
- throw new Exception("Wrong params type in UI::hAttributes");
- } catch (Exception $e) {
- DBG::log($e);
- }
- }
- foreach ($params as $k => $v) {
- if (is_array($v)) {
- $attr[] = "{$k}=\"" . implode(" ", $v) . "\"";
- } else if (true === $v) { // eg. open => true : 'open'
- $attr[] = $k;
- } else if (false === $v) { // skip if false value
- } else if (!empty($v)) {
- $attr[] = "{$k}=\"{$v}\"";
- }
- }
- return implode(" ", $attr);
- }
- public static function hChildrens($childrens = []) {
- if (empty($childrens)) {
- if (is_int($childrens)) return "{$childrens}";
- if (is_string($childrens)) return $childrens;
- return '';
- }
- if (is_scalar($childrens)) return "{$childrens}";
- if (!is_array($childrens)) throw new Exception("Unsupported children type");
- return array_reduce(
- $childrens,
- function ($curry, $child) {
- return "{$curry}{$child}";
- },
- ""
- );
- }
- /**
- * @param $taskPerm - 'C', 'W'
- */
- public static function hGetFormItem($acl, $fieldName, $taskPerm, $fieldID, $fName, $fValue, $params = array(), $record = null) {
- $fValue = (string)$fValue;
- Lib::loadClass('Typespecial');
- DBG::log(['$fieldName'=>$fieldName, '$taskPerm'=>$taskPerm, '$fieldID'=>$fieldID, '$fName'=>$fName, '$fValue'=>$fValue, '$params'=>$params, '$record'=>$record], 'array', "hGetFormItem()");
- if (!$acl->isAllowed($fieldID, $taskPerm, $record)) {
- switch ($taskPerm) {
- case 'R': return "Brak uprawnień do odczytu";
- case 'W': return "Brak uprawnień do zapisu";
- case 'C': return "Brak uprawnień";
- default: return "Brak uprawnień do tego pola ({$taskPerm})";
- }
- }
- if ($fieldName == 'ID') return ''; // TODO: hide primaryKey?
- // $colType = $acl->getFieldTypeById($fieldID);
- // if (!$colType) return "Error - unknown type";
- $xsdType = $acl->getXsdFieldType($fieldName);
- DBG::log("DBG: field({$fieldName}) xsdType({$xsdType})");
- $html = new stdClass();
- $html->_params = array();
- $html->tag = 'input';
- $html->childrens = [];
- $html->attrs = array();
- $html->attrs['id'] = $fName;
- $html->attrs['name'] = $fName;
- $html->attrs['type'] = 'text';
- $html->attrs['value'] = $fValue;// BUG htmlspecialchars($fValue); - convert chars in edit form (" to " and & to &)
- if (isset($params['tabindex'])) $html->attrs['tabindex'] = $params['tabindex'];
- // if (!$acl->hasFieldPerm($fieldID, $taskPerm)) {
- // $html->attrs['disabled'] = 'disabled';
- // }
- $maxGrid = V::get('maxGrid', 10, $params);
- switch ($xsdType) {
- case 'xsd:long':
- case 'xsd:int':
- case 'xsd:integer': {
- $html->attrs['type'] = 'number';
- $html->attrs['class'][] = 'input-small';
- } break;
- case 'xsd:decimal':
- case 'xsd:double':
- case 'xsd:float':
- case 'p5:price': {
- $html->attrs['type'] = 'text';
- $html->attrs['class'][] = 'input-small';
- } break;
- case 'xsd:string':
- case 'p5:www_link':
- case 'p5:string': {
- $html->attrs['type'] = 'text';
- $maxLength = (int)$acl->getXsdFieldParam($fieldName, 'maxLength');
- if ($maxLength > 0) {
- $html->attrs['maxlength'] = $maxLength;
- }
- $valLength = strlen($fValue);
- if (isset($params['widthClass'])) {
- if ($params['widthClass'] == 'inside-modal') {
- $html->attrs['style'] = 'width:98%;';
- } else {
- $html->attrs['style'] = 'width:98%;';
- }
- }
- if ($maxLength > 255) {// Fix for long varchar - use textarea
- $html->tag = 'textarea';
- $html->childrens[] = $fValue;
- $html->attrs['rows'] = '3';
- unset($html->attrs['type']);
- unset($html->attrs['value']);
- }
- } break;
- case 'xsd:dateTime':
- case 'xsd:date': {
- $testDatePicker = true;
- if ($testDatePicker) {
- $html->attrs['type'] = 'text';
- $html->_params[] = 'date';
- if ('xsd:dateTime' === $xsdType) {
- $html->attrs['class'][] = 'se_type-datetime'; // datetimepicker';
- $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
- $html->attrs['maxlength'] = 19;
- } else {
- $html->attrs['class'][] = 'se_type-date'; // datetimepicker';
- $html->attrs['maxlength'] = 10;
- }
- if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
- $html->attrs['value'] = '';
- }
- } else {
- $html->attrs['type'] = 'date';
- }
- } break;
- case 'xsd:time': {
- $testDatePicker = true;
- if ($testDatePicker) {
- $html->attrs['type'] = 'text';
- $html->_params[] = 'time';
- $html->attrs['class'][] = 'se_type-time';// datetimepicker';
- $html->attrs['data-format'] = 'hh:mm:ss';
- $html->attrs['maxlength'] = 8;
- if (substr($html->attrs['value'], 0, 8) == '00:00:00') {
- $html->attrs['value'] = '';
- }
- } else {
- $html->attrs['type'] = 'time';
- }
- } break;
- // case 'timestamp': { // TODO: timestamp is xsd:integer or xsd:dateTime?
- // $testDatePicker = true;
- // if ($testDatePicker) {
- // $html->attrs['type'] = 'text';
- // $html->_params[] = 'date';
- // $html->attrs['class'][] = 'se_type-datetime';// datetimepicker';
- // $html->attrs['data-format'] = 'yyyy-MM-dd hh:mm';
- // $html->attrs['maxlength'] = 19;
- // if (substr($html->attrs['value'], 0, 10) == '0000-00-00') {
- // $html->attrs['value'] = '';
- // }
- // } else {
- // $html->attrs['type'] = 'date';
- // }
- // } break;
- case 'p5:enum': {
- DBG::log($acl->getField($fieldID), 'array', "\$field($fieldName)");
- unset($html->attrs['type']);
- unset($html->attrs['value']);
- $html->tag = 'select';
- $defaultValue = $acl->getFieldDefaultValue($fieldName);
- $values = $acl->getEnumerations($fieldName);
- // $values = explode(',', str_replace(array('(',')',"'",'"'), '', substr($colType['type'], 5)));
- $selValue = $fValue;
- if (empty($selValue) && $selValue !== '0' && !empty($defaultValue)) {
- if ($taskPerm == 'C') {
- $selValue = $defaultValue;
- } else if ($taskPerm == 'W' && $acl->isAllowed($fieldID, 'R', $record)) {
- $selValue = $defaultValue;
- }
- }
- $html->childrens[] = [ 'option', [ 'value' => "" ], "" ];
- if (!empty($selValue) && !array_key_exists($selValue, $values)) {
- $html->childrens[] = [ 'option', [ 'value' => $selValue, 'selected' => "selected" ], $selValue ];
- }
- foreach ($values as $val => $label) {
- $html->childrens[] = [ 'option', array_merge(
- [ 'value' => $val ],
- ((!empty($selValue) || '0' === $selValue) && (string)$selValue === (string)$val) ? [ 'selected' => "selected" ] : []
- ), $label ];
- }
- } break;
- case 'p5:text': {
- $html->tag = 'textarea';
- $html->childrens[] = $fValue;
- if (isset($params['widthClass'])) {
- if ($params['widthClass'] == 'inside-modal') {
- $html->attrs['style'] = 'width:98%;';
- } else {
- $html->attrs['style'] = 'width:98%;';
- }
- } else {
- //$html->attrs['class'][] = (8 <= $maxGrid)? 'span8' : "span{$maxGrid}";
- }
- $html->attrs['rows'] = '3';
- unset($html->attrs['type']);
- unset($html->attrs['value']);
- } break;
- case 'gml:GeometryPropertyType':
- case 'gml:LineStringPropertyType':
- case 'gml:PointPropertyType':
- case 'gml:PolygonPropertyType': {
- return '...';
- } break;
- case 'xsd:base64Binary': {
- return '...';
- } break;
- default: {
- if ('ref:' === substr($xsdType, 0, 4)) {
- return "Funkcja w trakcie przygotowanie (ref do '" . substr($xsdType, 4) . "')";
- }
- return "unknown Type \"{$xsdType}\"";
- }
- }
- $html->attrs['class'][] = 'form-control';
- if (!empty($html->attrs['class'])) $html->attrs['class'] = implode(" ", $html->attrs['class']);
- $nodeHtml = (in_array($html->tag, array('select', 'textarea')))
- ? [ $html->tag, $html->attrs, $html->childrens ]
- : $nodeHtml = [ $html->tag, $html->attrs ]
- ;
- if (in_array('date', $html->_params)) {
- $nodeHtml = [ 'div', [ 'class' => "input-group" ], [
- $nodeHtml,
- [ 'span', [ 'class' => "input-group-addon" ], [
- [ 'span', [ 'class' => "glyphicon glyphicon-calendar" ] ]
- ] ]
- ] ];
- }
- else if (in_array('time', $html->_params)) {
- $nodeHtml = [ 'div', [ 'class' => "input-group" ], [
- $nodeHtml,
- [ 'span', [ 'class' => "input-group-addon" ], [
- [ 'span', [ 'class' => "glyphicon glyphicon-time" ] ]
- ] ]
- ] ];
- }
- if (true == V::get('appendBack', '', $params)
- && !in_array('date', $html->_params)
- && !in_array('time', $html->_params)
- ) {
- if ($html->tag == 'input' && $taskPerm == 'W') {
- $nodeHtml = [ 'div', [ 'class' => "input-group show-last-value" ], [
- $nodeHtml,
- [ 'span', [ 'class' => "input-group-addon button-appendBack", 'title' => htmlspecialchars($fValue) ], [
- [ 'span', [ 'class' => "glyphicon glyphicon-arrow-left" ] ]
- ] ]
- ] ];
- }
- }
- $typeSpecial = Typespecial::getInstance($fieldID, $fieldName);
- if ($typeSpecial) {
- $tsParams = array();
- $tsValue = V::get('typespecialValue', '', $params);
- if (!empty($tsValue)) {
- $tsParams['typespecialValue'] = $tsValue;
- }
- $nodeHtml = [ 'div', [ 'class' => "field-with-typespecial" ], [
- $nodeHtml,
- $typeSpecial->hGetFormItem($acl, $fieldName, $acl->_zasobID, $fName, $fValue, $tsParams, $record),
- ] ];
- }
- return $nodeHtml;
- }
- public static function convertHtmlToArray($html) {
- $nodes = [];
- // <a href="index.php?_route=Users&_task=userGroups&usrLogin=michal.podejko">ustal stanowisko</a>
- // [ 'a', [ 'href' => "index.php?_route=Users&_task=userGroups&usrLogin=michal.podejko" ], "ustal stanowisko" ]
- $DBG = 0;
- $pos = 0;
- // TODO: while (true)
- if ('<' === substr($html, $pos, 1)) { // parse tag
- $tagName = ''; $attrs = []; $content = [];
- $endTagOpen = strpos($html, '>', $pos + 1);
- $endTagName = min(strpos($html, ' ', $pos + 1), $endTagOpen); // '<tag>' or '<tag attr="..">'
- if (false === $pos) throw new Exception("Error Processing Html - missing tagName");
- $tagName = substr($html, $pos + 1, $endTagName - $pos - 1);
- if($DBG){echo "\ntagName: '{$tagName}'";}
- if ('>' === substr($html, $endTagName, 1)) {
- } else if (' ' === substr($html, $endTagName, 1)) {
- if (false === $endTagOpen) throw new Exception("Error Processing Html - missing open tag end char");
- $attrs = UI::convertHtmlAttrsToArray(trim(substr($html, $endTagName + 1, $endTagOpen - $endTagName - 1)));
- } else {
- throw new Exception("Error Processing Html - unexpected end tag name char '" . substr($html, $endTagName, 1) . "'");
- }
- if($DBG){echo "\nattrs: '" . json_encode($attrs), "'";}
- // TODO: empty tags '<br>', '<br/>', '<br />', '<input ... />', '<input ... >', img, hr, etc.
- // TODO: nested same tags '<tagName> ... <tagName> ... </tagName> ... </tagName>'
- $closeTagStart = strpos($html, "</{$tagName}>", $endTagOpen + 1);
- if (false === $closeTagStart) throw new Exception("Error Processing Html - missing close tagName");
- if($DBG){echo "\nDBG \$endTagOpen: " . substr($html, $endTagOpen, 5) . "...";}
- if($DBG){echo "\nDBG \$endTagOpen: " . substr($html, $endTagOpen) . ".EOL";}
- if($DBG){echo "\nDBG \$closeTagStart strpos(\$html, '</{$tagName}>', {$endTagOpen} + 1) = '{$closeTagStart}': " . substr($html, $closeTagStart, 5) . "...";}
- $content = substr($html, $endTagOpen + 1, $closeTagStart - $endTagOpen - 1);
- $tag = [ $tagName, $attrs, $content ];
- if($DBG){echo "\n\$tag: ";print_r($tag);}
- $nodes = $tag;
- }
- return $nodes;
- }
- public static function convertHtmlAttrsToArray($strAttrs) {
- $attrs = [];
- if (!preg_match_all('((\w+)=\"([^"]*)\")', $strAttrs, $matches)) {
- // echo "DBG:: empty attrs or wrong syntax";
- return [];
- }
- $total = (count($matches) - 1) / 2;
- // echo "\n\$matches (total = {$total}) = ";print_r($matches);
- for ($i = 0; $i < $total; $i++) {
- $idx = $i * 2 + 1;
- // echo "\n\$attrs[ '{$matches[$idx][0]}' ] = '{$matches[$idx+1][0]}';";
- $attrs[ $matches[ $idx ][0] ] = $matches[ $idx + 1 ][0];
- }
- return $attrs;
- }
- /**
- * Execute callback in try/catch block and view output as page layout (content inside html > body)
- * @param array $params
- * @param bool $params['showMenu']
- * @param bool $params['showContainer']
- * @param string $params['containerClass'] : [ 'fluid' ], default ''
- */
- public static function layout($callback, $params = []) {
- $params['showMenu'] = V::get('showMenu', true, $params, 'bool');
- $params['showContainer'] = V::get('showContainer', true, $params, 'bool');
- $params['containerClass'] = V::get('containerClass', '', $params);
- $args = V::get('args', [], $params, 'array');
- UI::gora(); // Theme::head();
- if ($params['showMenu']) UI::menu(); // TODO: Theme::top()
- if ($params['showContainer']) UI::startContainer( $params['containerClass'] ? [ 'class' => $params['containerClass'] ] : [] );
- try {
- // call_user_func($callback);
- $callback($args);
- } catch (AlertSuccessException $e) {
- DBG::log($e);
- UI::alert('success', $e->getMessage());
- } catch (AlertWarningException $e) {
- DBG::log($e);
- UI::alert('warning', $e->getMessage());
- } catch (AlertInfoException $e) {
- DBG::log($e);
- UI::alert('info', $e->getMessage());
- } catch (Exception $e) {
- DBG::log($e);
- UI::alert('danger', $e->getMessage());
- }
- if ($params['showContainer']) UI::endContainer();
- UI::dol(); // UI::dol must include Theme::footer();
- }
- /**
- * Execute callback inside try/catch block.
- * @param array $params
- * @param bool $params['showContainer']
- * @param string $params['containerClass'] : [ 'fluid' ], default ''
- */
- static function tryCatchView($callback, $params = []) {
- $params['showContainer'] = V::get('showContainer', false, $params, 'bool');
- $params['containerClass'] = V::get('containerClass', '', $params);
- $args = V::get('args', [], $params, 'array');
- if ($params['showContainer']) UI::startContainer( $params['containerClass'] ? [ 'class' => $params['containerClass'] ] : [] );
- try {
- // call_user_func($callback);
- $callback($args);
- } catch (AlertSuccessException $e) {
- DBG::log($e);
- UI::alert('success', $e->getMessage());
- } catch (AlertWarningException $e) {
- DBG::log($e);
- UI::alert('warning', $e->getMessage());
- } catch (AlertInfoException $e) {
- DBG::log($e);
- UI::alert('info', $e->getMessage());
- } catch (Exception $e) {
- DBG::log($e);
- UI::alert('danger', $e->getMessage());
- }
- if ($params['showContainer']) UI::endContainer();
- }
- public static function startDetails($opts, $summaryChildrens) {
- $attrs = array_reduce(array_keys($opts), function ($ret, $optionKey) use ($opts) {
- $option = $opts[$optionKey];
- if (false !== strpos($optionKey, '.')) {
- list($mainKey, $attrName) = explode('.', $optionKey, 2);
- $ret[$mainKey][$attrName] = $option;
- } else {
- $ret['details'][$optionKey] = $option;
- }
- return $ret;
- }, [
- 'details' => [],
- 'summary' => [],
- 'content' => [],
- ]);
- return '<details' . ( empty($attrs['details']) ? '' : ' ' . self::hAttributes($attrs['details']) ) . '>' .
- '<summary' . ( empty($attrs['summary']) ? '' : ' ' . self::hAttributes($attrs['summary']) ) . '>' . self::hChildrens($summaryChildrens) . '</summary>' . "\n" .
- '<div' . ( empty($attrs['content']) ? '' : ' ' . self::hAttributes($attrs['content']) ) . '>' . "\n";
- }
- public static function endDetails() {
- return '</div></details>';
- }
- }
|