_tbl = $tblAcl->getName();
$this->_acl = $tblAcl;
$this->_zasobID = $tblAcl->getID();
$this->_pageSize = 10;
{
UserProfile::load();
$tableAjaxSettings = UserProfile::getTableAjaxSettings();
$this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
}
$this->_pageSizes = array(10, 20, 50, 100);// default page sizes
$this->_filterInit = new stdClass();
$hash = V::get('_hash', '', $_GET);
if ($hash) {
$this->_htmlID = $hash;
$this->_readState();
} else {
$this->_htmlID = $this->generateHtmlID();
$this->_readState();
}
}
public function setSyncUrl($syncUrl) {
$this->syncUrl = $syncUrl;
}
public function showProcesInit($bool = true) {
$this->_showProcesInit = $bool;
}
public function showUserTableFilter($url = null) {
$this->_useUserTableFilter = $url;
}
private function _hasStateFilterInit() {
return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
}
// TODO: read state from cache by key $this->_htmlID
// TODO: load filters and state: table, edit, add, etc.
// TODO: save this data in Workspace 1, 2, 3, etc.
// TODO: default filters in VIEWTABLE_AJAX
// $tbl->setLabel($zasobObj->OPIS);
// $tbl->setFilterInit($filterInit);
// $tbl->addRowFunction('edit');
// $tbl->addRowFunction('hist');
// $tbl->addRowFunction('files');
// $tbl->addRowFunction('cp');
private function _readState() {
if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
$_SESSION['TableAjax_Cache'] = array();
}
//trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
//trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
//trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
switch ($k) {
case '_label':
$this->_label = $v;
break;
case '_filterInit':
$this->_filterInit = $v;
break;
case '_rowFunctions':
$this->_rowFunctions = $v;
break;
default:
}
}
}
}
protected function _saveState($key = null) {
if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
$_SESSION['TableAjax_Cache'] = array();
}
if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
$_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
}
if (!$key) {
$_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
$_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
$_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
} else if ($key == '_label') {
$_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
} else if ($key == '_filterInit') {
$_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
} else if ($key == '_rowFunctions') {
$_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
}
}
public function setPageSizes($pageSizes) {
$this->_pageSizes = $pageSizes;
}
public function setFilterInit($filterInit) {
if ($this->_hasStateFilterInit()) {
return;
}
$this->_filterInit = (object)$filterInit;
$this->_saveState();
}
/**
* @param array $forceFilterInit
*/
public function setForceFilterInit($forceFilterInit) {
$this->_forceFilterInit = (object)$forceFilterInit;
}
private function setFilters($filterInit) {
$this->_filterInit = (object)$filterInit;
$this->_saveState();
}
public function setRowFunctions($functions) {
$this->_rowFunctions = [];
$defaultRowFunction = array();
$defaultRowFunction['edit'] = [ 'href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord', 'class' => "btn btn-xs btn-link" ];
$defaultRowFunction['hist'] = [ 'href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia', 'class' => "btn btn-xs btn-link" ];
$defaultRowFunction['files'] = [ 'href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki', 'class' => "btn btn-xs btn-link" ];
$defaultRowFunction['cp'] = [ 'href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});', 'class' => "btn btn-xs btn-link" ];
$defaultRowFunction['msgs'] = [ 'href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości', 'class' => "btn btn-xs btn-link" ];
foreach ($functions as $funName => $params) {
if (true === $params) {
if (array_key_exists($funName, $defaultRowFunction)) {
$this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
} else {
throw new Exception("Row function not defined '{$funName}'");
}
}
if (is_array($params)) {
$this->_rowFunctions[$funName] = $params;
}
}
$this->_saveState('_rowFunctions');
}
public function addRowFunction($funName, $funParams = array()) {
$defaultRowFunction = array();
//$defaultRowFunction['edit'] = '';
//$defaultRowFunction['hist'] = '';
//$defaultRowFunction['files'] = '';
//$defaultRowFunction['cp'] = '';
$defaultRowFunction['edit'] = [ 'href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord', 'class' => "btn btn-xs btn-link" ];
$defaultRowFunction['hist'] = [ 'href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia', 'class' => "btn btn-xs btn-link" ];
$defaultRowFunction['files'] = [ 'href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki', 'class' => "btn btn-xs btn-link" ];
$defaultRowFunction['cp'] = [ 'href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});', 'class' => "btn btn-xs btn-link" ];
$defaultRowFunction['msgs'] = [ 'href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości', 'class' => "btn btn-xs btn-link" ];
if (array_key_exists($funName, $defaultRowFunction)) {
$this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
}
else {
$this->_rowFunctions[$funName] = $funParams;
}
$this->_saveState('_rowFunctions');
}
private function _parseRowFunctions($idRecord = null, $pomin = array(), $showLabel = false) {
$rowFunctions = array();
foreach ($this->_rowFunctions as $kFunName => $vParams) {
if (in_array($kFunName, $pomin)) continue;
//$rowFunctionsOut .= str_replace('{0}', $idRecord, $vUrl);
$attrs = array();
// $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
$label = '';
$ico = '';
foreach ($vParams as $kParamName => $v) {
if ($kParamName == 'ico') {
$ico = '';
continue;
}
$attr = $v;
if ($idRecord > 0) {
$attr = str_replace('{0}', $idRecord, $attr);
}
if ($showLabel && $kParamName == 'title') {
$label = $attr;
}
$attr = $kParamName . '="' . $attr . '"';
$attrs[] = $attr;
}
$rowFunctions[$kFunName] = '' . "{$ico} {$label} " . '';
}
return $rowFunctions;
}
private function _showRowFunctions($idRecord = null, $pomin = array(), $showLabel = false) {
$rowFunctionsOut = $this->_parseRowFunctions($idRecord, $pomin, $showLabel);
$rowFunctionsOut = implode('', $rowFunctionsOut);
return $rowFunctionsOut;
}
private function _showRowFunctionsJson($idRecord = null, $pomin = array(), $showLabel = false) {
$rowFunctions = $this->_parseRowFunctions($idRecord, $pomin, $showLabel);
$rowFunctions = (object)$rowFunctions;
return $rowFunctions;
}
private function getProcesInitSelected() {
$userAcl = User::getAcl();
return $userAcl->getPermsFiltrProcesId();
}
public function allowTreeView() {
if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
if ($this->_tbl == 'CRM_PROCES') return true;
return false;
}
public function renderStatic($tblAjaxMap = null) {
static $_rendered = false;
if ($_rendered) return;
if ($tblAjaxMap) $tblAjaxMap->printCSS();
if ($tblAjaxMap) $tblAjaxMap->printJS();
echo UI::h('script', ['src'=>"stuff/jquery-ui-1.10.4.custom.min.js"]);
echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
echo UI::h('script', ['src'=>"static/jquery.doubleScroll.js"]);
echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css"]);
echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
echo UI::h('style', ['type'=>"text/css"], "
.AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
.AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
.AjaxTable *,
.AjaxTable.table {white-space:nowrap; width:auto;}
.AjaxTable .popover * {white-space:normal;}
.AjaxTable p {margin:0;}
.AjaxTable td, .AjaxTable th {line-height:18px;}
.AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
.AjaxTable span.filter {background-color:#999;}
.AjaxTable .indeterminate {opacity: 0.4;-ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)\";filter:alpha(opacity=40);}
.AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
.AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
.AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
.AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
.AjaxTable input[type=text].filter {margin:0;padding:0 5px;box-shadow:none;width:100%;background:#eee;color:#000;}
.AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
.AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
.AjaxTable .date-wrap {width:100%;min-width:115px;}
.AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
.AjaxTable .actions a {padding:0;margin:0;}
.AjaxTableCont .text-right {text-align:right}
.AjaxTableCont .breadcrumb em {color:#bbb;}
.AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
.AjaxTable-loading .loading-info,
.AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
.AjaxTableCont .loading-info {display:none;}
.AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block;}
.AjaxTableCont .table {margin-bottom:0px;}
.AjaxTableCont .stickyCol1 a { color:#333; }
.AjaxTableCont .stickyCol1 a:hover { color:#337AB7; text-decoration:none; }
.AjaxTableTaskCnt {padding:0 10px 10px 10px;}
.AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
.AjaxTable .tbl-short-txt span{display:block; height:18px;}
.AjaxTable .tooltip-inner{white-space:normal;}
.AjaxTable thead .sort .ta-ordering {cursor:pointer;}
.AjaxTable thead .sort .ta-ordering span {margin:0 10px 0 0; padding:0; background-repeat:no-repeat; background-position:right top;}
.AjaxTable thead .sort .ta-ordering-down span:after{content:\"\\e252\";font-family:\"Glyphicons Halflings\";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
.AjaxTable thead .sort .ta-ordering-up span:after{content:\"\\e253\";font-family:\"Glyphicons Halflings\";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
.AjaxTable thead .sort .ta-ordering {position:relative;}
.AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
.AjaxTable thead .sort th .hover-show{display:none;}
.AjaxTable thead .sort th:hover .hover-show{display:inline;}
.AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none; color:#f00;}
.AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}
.AjaxTableCont .pagination { margin:0; }
.AjaxTableCont .pagination a { line-height:16px; }
.AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
.AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
.AjaxTableCont .AjaxTableEdit .show-last-value .button-appendBack .glyphicon,
.AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .button-appendBack .glyphicon {display:none;}
.AjaxTableHist em {color:silver;}
.AjaxTableCont .foot * { font-size:12px !important; }
.AjaxTableCont .foot { margin:10px; }
.AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
.AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
.AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
.tblAjax__head__specialFilter {margin:0;padding:4px 4px 4px 127px;}
.tblAjax__head__specialFilter .btn-group {margin:0 4px;padding:0;}
.tblAjax__head__specialFilter .btn-group .glyphicon-remove {color:#f00;}
.tblAjax__head__specialFilter .btn-group button.disabled .glyphicon-remove {color:#bbb;}
/* overwrite bootstrap table border */
.AjaxTable, .AjaxTableEdit,
.AjaxTable td, .AjaxTableEdit td,
.AjaxTable th, .AjaxTableEdit th { border-color:#999; }
/* cell A_STATUS */
.AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
.AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
.AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
.AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
.AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
.AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
.AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }
/* cell Status */
.AjaxTable .cell-Status-U { background:rgb(0,176,80); color:#000; text-align:center; }
.AjaxTable .cell-Status-NU { background:#f00; color:#000; text-align:center; }
.AjaxTable .cell-Status-P { background:rgb(112,48,160); color:#000; text-align:center; }
.AjaxTable .cell-Status-PT { background:rgb(127,127,127); color:#000; text-align:center; }
.AjaxTable .cell-Status-O { background:rgb(0,176,240); color:#000; text-align:center; }
.AjaxTable .cell-Status-DZ { background:rgb(0,112,192); color:#000; text-align:center; }
.AjaxTable .cell-Status-Z {}
/* map */
.AjaxTable .cell-mapfld { cursor:pointer; }
.AjaxTable .cell-mapfld:hover { opacity:1; }
.AjaxTable .cell-mapfld-remove { display:none; }
.AjaxTable .cell-mapfld-hasValue .cell-mapfld-select { color:#f00; }
.AjaxTable .cell-mapfld-hasValue .cell-mapfld-remove { display:inline-block; }
.AjaxTableCont .mapEditor { position:absolute; bottom:0; right:6px; width:512px; height:318px; overflow:hidden; color:#eee; border:1px solid #999; }
.AjaxTableCont .mapEditor-panel { height:16px; padding:0 6px; background:#999; border-bottom:1px solid #eee; }
.AjaxTableCont .mapEditor-panel a { display:block; float:right; padding:0 6px; font-weight:bold; font-size:12px; line-height:16px; color:#fff; }
.AjaxTableCont .mapEditor-panel a:hover { color:#006CD7; text-decoration:none; }
.AjaxTableCont .mapEditor-panel a.mapEditor-panel-close:hover { color:#f00; }
.AjaxTableCont .mapEditor-map { background:#fff; height:400px; }
.AjaxTableCont-mapEditorContainer .mapEditor-map { border:1px solid #999; overflow:hidden; }
/* .mapEditor-btnBackToWindow \"olControlSave\",overview_replacement */
.olControlEditingToolbar .mapEditor-btnBackToWindowItemInactive,
.olControlEditingToolbar .mapEditor-btnBackToWindowItemActive {
background-image: url(icon/map.window.png);
background-position: 0 0;
background-repeat: no-repeat;
}
/*
.mapEditor-btnBackToWindowItemInactive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
.mapEditor-btnBackToWindowItemActive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
*/
.ui-dialog-content .mapEditor-btnBackToWindowItemInactive,
.ui-dialog-content .mapEditor-btnBackToWindowItemActive { display:none; }
.AjaxTableCont .valign-btns-bottom .btn { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
.ui-resizable-s { bottom:0; }
.ui-resizable-e { right:0; }
.AjaxTableCont-mapEditorContainer .ui-resizable-s { background-color:#ddd; }
.AjaxTableCont-mapEditorContainer .ui-resizable-s:hover { background-color:#888; }
");
echo UI::h('script', ['src'=>"static/vendor.js"]);
echo UI::h('script', ['src'=>"static/p5UI/buildDom.js?_ts=".time()]); // TODO: DBG load js
$_rendered = true;
}
public function render() {
$acl = $this->_acl;
$hasGeomFlds = Core_AclHelper::hasGeomFields($acl);
$tblAjaxMap = ($hasGeomFlds) ? new TableAjaxMap($acl, 512, 400) : null;
$hasPermCreate = Core_AclHelper::hasCreatePerms($acl);
$jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
ob_start();
$this->renderStatic($tblAjaxMap);
UI::startContainer();
UI::showMessagesForTable($this->_tbl);
UI::endContainer();
$namespace = $acl->getNamespace();
?>
_filterInit;
$forceFilterInit = $this->_forceFilterInit;
$pageSizes = $this->_pageSizes;
$pageSize = $this->_pageSize;
$rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
$exportFields = Core_AclHelper::getExportFieldList($acl);
?>
= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}).then(function (response) {
return response.json()
}).then(function (response) {
p5UI__notifyAjaxCallback(response)
}).catch(function(error) {
p5UI__notifyAjaxCallback({ type: 'error', msg: error })
})
}
function p5TA_onDrop(e, pk, ns) {
e.preventDefault();
// If dropped items aren't files, reject them
var dt = e.dataTransfer;
var files = []
if (dt.items) { // Use DataTransferItemList interface to access the file(s)
for (var i = 0; i < dt.items.length; i++) {
if (dt.items[i].kind == 'file') {
var file = dt.items[i].getAsFile();
files.push(file)
}
}
} else { // Use DataTransfer interface to access the file(s)
for (var i=0; i < dt.files.length; i++) {
files.push(dt.files[i])
}
}
if (!files) {
p5UI__notifyAjaxCallback({
type: 'info',
msg: 'brak plików',
})
return false
}
p5TA_uploadFiles(files, ns, pk);
this__dragOverChecker.removeOverlay()
}
function p5TA_onDragOver(e, n, pk, ns) {
e.preventDefault();
this__dragOverChecker.update(n, pk, ns)
}
function p5TA_overlay_onDragOver(e, n, pk, ns) {
e.preventDefault();
this__dragOverChecker.update(null, pk, ns)
}
function p5TA_onDragEnd(e, n, pk, ns) {
var dt = e.dataTransfer;
if (dt.items) { // Use DataTransferItemList interface to remove the drag data
for (var i = 0; i < dt.items.length; i++) {
dt.items.remove(i);
}
} else { // Use DataTransfer interface to remove the drag data
e.dataTransfer.clearData();
}
}
global.p5TA_onDrop = p5TA_onDrop
global.p5TA_onDragOver = p5TA_onDragOver
global.p5TA_onDragEnd = p5TA_onDragEnd
global.p5TA_overlay_onDragOver = p5TA_overlay_onDragOver
})(window);
");
UI::setTitle($this->_acl->getRawLabel(100) . " - " . UI::getTitle());
$out = ob_get_contents();
ob_end_clean();
return $out;
}
public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
$vLabel = $pInitList[$vInitId];
$kId = $vInitId;
echo UI::h('a', [
'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
], [
UI::h('i', [
'class' => "glyphicon glyphicon-info-sign",
'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
'style' => "color:#aaa",
'onmouseover' => "this.style.color='#337AB7'",
'onmouseout' => "this.style.color='#aaa'"]),
"{{$kId}} {$vLabel}"
]);
}
public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
$vLabel = $pInitList[$vGotoId];
$kId = $vGotoId;
// TODO:?: prevent to execute procedure
echo UI::h('a', [
'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
], [
UI::h('span', [ 'style' => "padding:10px;"]),
UI::h('i', [ 'class' => "glyphicon glyphicon-arrow-right", 'style' => "color:#aaa"]),
UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign",
'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
'style' => "color:#aaa",
'onmouseover' => "this.style.color='#337AB7'",
'onmouseout' => "this.style.color='#aaa'"]),
"{{$kId}} {$vLabel}",
]);
}
public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
$vLabel = $pInitList[$vGotoLvl2Id];
$kId = $vGotoLvl2Id;
// TODO:?: prevent to execute procedure
echo UI::h('a', [
'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
], [
UI::h('span', [ 'style' => "padding:20px;" ]),
UI::h('i', [ 'class' => "glyphicon glyphicon-arrow-right", 'style' => "color:#aaa" ]),
UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign",
'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
'style' => "color:#aaa",
'onmouseover' => "this.style.color='#337AB7'",
'onmouseout' => "this.style.color='#aaa'"]),
"{{$kId}} {$vLabel}",
]);
}
public function hasAdditionalLayers() {
$layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
return !empty($layers);
}
public function ajaxTask($task) {
switch ($task) {
case 'EDIT_INLINE': {
$this->sendAjaxResponseJson('ajaxInlineEdit', $_REQUEST);
break;
}
case 'EDIT_INLINE_SAVE': {
$this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
break;
}
case 'COPY': {
$this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
break;
}
case 'CREATE': {
$this->sendAjaxCreate($_REQUEST);
break;
}
case 'CREATE_SAVE': {
$this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
break;
}
case 'HIST': {
$this->sendAjaxResponseJson('ajaxHist', $_REQUEST);
break;
}
case 'FILES': {
try {
$id = V::get('ID', 0, $_REQUEST, 'int');
if ($id <= 0) throw new HttpException("404", 404);
$this->sendAjaxFiles($id, $_REQUEST);
} catch (HttpException $e) {
Http::sendHeaderByCode($e->getCode());
echo $e->getMessage();
//UI::alert('danger', $e->getMessage());
} catch (Exception $e) {
echo '';
UI::alert('danger', $e->getMessage());
echo '
';
}
break;
}
case 'FILES_UPLOAD': {
$this->sendAjaxResponseJson('ajaxFileUpload', $_REQUEST);
break;
}
case 'FILES_LIST': {
$this->sendAjaxResponseJson('ajaxFileList', $_REQUEST);
break;
}
case 'FILE_REMOVE': {
$args = array();
$args['ID'] = V::get('ID', '', $_REQUEST);
$args['filename'] = V::get('filename', '', $_POST);
$this->sendAjaxResponseJson('ajaxFileRemove', $args);
break;
}
case 'filePermsRefresh': {
$this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
break;
}
case 'FILES_CONN_TBL_LIST': {
$id = V::get('ID', 0, $_REQUEST, 'int');
if ($id > 0) {
$this->sendAjaxFilesConnTblList($id, $_REQUEST);
} else {
echo '404';
}
break;
}
case 'TYPESPECIAL': {
$fldID = V::get('fldID', 0, $_REQUEST, 'int');
if ($fldID > 0) {
$this->sendTypeSpecial($fldID, $_REQUEST);
} else {
echo '404';
}
break;
}
case 'HIDDEN_COLS_SAVE': {
$this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
break;
}
case 'PAGE_SIZE_SAVE': {
$this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
break;
}
case 'THE_GEOM_SAVE': {
$this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
break;
}
case 'PROCES_INIT_FILTR': {
$this->sendAjaxResponseJson('ajaxProcesInitFiltr', $_REQUEST);
break;
}
default:
$this->sendAjaxResponseJson('ajaxData', $_REQUEST);
}
}
/**
* ajax url: &_task=EDIT_INLINE
* @param $rowID - $_GET['ID']
* @param $fieldName - $_GET['col']
*/
private function ajaxInlineEdit() {
$DBG = ('1' == V::get('DBG', '', $_REQUEST));
$args = $_REQUEST;
$idRecord = V::get('ID', 0, $_REQUEST, 'int');
$fieldName = V::get('col', '', $_REQUEST);
if ($idRecord <= 0 || empty($fieldName)) throw new HttpException("404", 404);
$response = array();
ob_start();
$fieldID = $this->_acl->getFieldIdByName($fieldName);
if (!$fieldID) die("404: No field by name ({$fieldName})");
$response['idZasob'] = $fieldID;
$response['htmlFieldName'] = "f{$fieldID}";
if ($DBG) echo "fieldID: {$fieldID}\n";
$record = $this->_acl->buildQuery([])->getItem($idRecord);
if (!$record) die("404: No item ID({$idRecord})");
$fieldVal = '';
if ($this->_acl->canReadObjectField($fieldName, $record)) {
$fieldVal = V::get($fieldName, $fieldVal, $record);
} else {
$fieldVal = '*****';
}
$fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
$vCol = $this->_acl->getField($fieldID);
$vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
$response['fieldLabel'] = $vCol['label'];
$tsValues = array();
$typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
if ($typeSpecial) {
if($DBG){echo'Typespecial('.$fieldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'';}
$specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $fieldName, V::get($fieldName, $fieldVal, $record));
if($DBG){echo'Typespecial('.$fieldID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'';}
if (!empty($specialValues)) {
$tsValues[ $record['ID'] ] = implode('
', $specialValues);
}
}
$fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
if (!empty($tsValues[ $record['ID'] ])) $fieldParams['typespecialValue'] = $tsValues[ $record['ID'] ];
if (!empty($tsValues[ $record['ID'] ])) $response['typespecialValue'] = $tsValues[ $record['ID'] ];
$vDefault = $this->_acl->getColDefault($fieldName);
if (!empty($vDefault)) $fieldParams['default'] = $vDefault;
if (!empty($vDefault)) $response['defaultValue'] = $vDefault;
{
try {
$item = $this->_acl->getFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $record);
$response['formItem'] = $item;
if (!empty($item['rawColType']['simpleType'])) $response['simpleType'] = $item['rawColType']['simpleType'];
if (!empty($item['rawColType']['restrictions'])) $response['restrictions'] = $item['rawColType']['restrictions'];
echo '';
DBG::_(true, true, "item", $item, __CLASS__, __FUNCTION__, __LINE__);
echo '
';
} catch (Exception $e) {
echo '';
UI::alert('danger', $e->getMessage());
echo '
';
}
}
?>
_acl->canWriteObjectField($fieldName, $record)) {
// TODO: hide Zapisz btn on frontend side
if (!$this->_acl->canReadObjectField($fieldName, $record)) {
UI::alert('warning', "Brak uprawnień do odczytu i zapisu");
} else {
echo '' . $fieldVal . '
';
UI::alert('warning', "Brak uprawnień do zapisu");
}
} else {
echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $record);
if ($typeSpecial
|| $this->_acl->isDateField($fieldName)
|| $this->_acl->isDateTimeField($fieldName)
) {
echo '';
}
}
$response['legacy_html'] = ob_get_clean();
//$response['legacy_html'] = utf8_encode($response['legacy_html']);// pl chars bug
return $response;
}
private function ajaxEditInlineSave($args) {
$primaryKeyField = $this->_acl->getPrimaryKeyField();
$primaryKey = V::get($primaryKeyField, 0, $args, 'int');
$fieldName = V::get('col', '', $_REQUEST);
if (empty($primaryKey)) throw new HttpException("Wrong param id!", 400);
if (empty($fieldName)) throw new HttpException("Wrong param col!", 400);
$fieldID = $this->_acl->getFieldIdByName($fieldName);
if (!$fieldID) throw new HttpException("Field not exists!", 404);
$item = $this->_acl->buildQuery([])->getItem($primaryKey);
if (!$item) throw new HttpException("Item not exists!", 404);
$itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
if (!isset($itemFromUser[$fieldName])) throw new HttpException("Field not set!", 400);
$itemPatch = array();
$itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
$itemPatch[$primaryKeyField] = $primaryKey;
$response = new stdClass();
try {
$affected = $this->_acl->updateItem($itemPatch);
if ($affected > 0) {
$response->type = 'success';
$response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
} else if ($affected == 0) {
$response->type = 'info';
$response->msg = "Nie wprowadzono żadnych zmian";
}
$response->record = $this->_acl->buildQuery([])->getItem($primaryKey);
}
catch (Exception $e) {
$response->type = 'error';
$response->msg = $e->getMessage();
}
return $response;
}
public function sendAjaxEdit($id, $args) {
header("Content-type: text/plain");
$acl = $this->_acl;
$record = $acl->buildQuery([])->getItem($id);
if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
UI::alert('danger', "Brak dostępu do rekordu");// TODO: more info - reason
return;
}
$fieldsList = array();
foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
if ($fieldName == 'ID') continue;
$field['name'] = $fieldName;
$field['opis'] = $acl->getFieldOpis($fieldName);
$field['label'] = $acl->getFieldLabel($fieldName);
if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
$fieldsList[$kID] = $field;
}
$cols = array();
foreach ($fieldsList as $kID => $field) {
$cols[$kID] = '';
if ($this->_acl->canReadObjectField($field['name'], $record)) {
$cols[$kID] = V::get($field['name'], '', $record);
} else {
$cols[$kID] = '*****';
}
// if ($acl->canReadObjectField($field['name'])) {
// $cols[$kID] = V::get($field['name'], '', $record);
// } else {
// $cols[$kID] = '*****';
// }
$cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
}
$tsValues = array();
if (!empty($fieldsList)) {
foreach ($fieldsList as $vColID => $vCol) {
$typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
if ($typeSpecial) {
$colValue = V::get($vCol['name'], '', $record);
$specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $vCol['name'], $colValue);
if (!empty($specialValues)) {
$tsValues[$vColID] = implode('
', $specialValues);
}
}
}
}
$rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
?>
_acl;
header("Content-type: text/plain");
$DBG = ('1' == V::get('DBG', '', $_REQUEST));
if (!Core_AclHelper::hasCreatePerms($acl)) {
?>
Brak uprawnień do utworzenia nowego rekordu.
$v) {
if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
$fldName = substr($k, 3);
$forceFilterInit[$fldName] = $v;
}
}
$fieldsList = $this->_acl->getFields();
foreach ($fieldsList as $kID => $vCol) {
$defaultValue = '';
if ($vCol['name'] == 'ID') {
unset($fieldsList[$kID]);
continue;
}
if (!empty($forceFilterInit[$vCol['name']])) {
$defaultValue = $forceFilterInit[$vCol['name']];
}
// TODO: read from session cache
$cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
$fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
}
?>
_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
$createdId = $this->_acl->addItem($item);
if ($createdId) {
$response->type = 'success';
$response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
$response->id = $createdId;
$response->record = $this->_acl->buildQuery([])->getItem($createdId);
}
else {
$response->type = 'error';
$response->msg = "Nie udało się utworzyć nowego rekordu!";
}
}
catch (Exception $e) {
$response->type = 'error';
$response->msg = $e->getMessage();
}
return $response;
}
private function ajaxCopy($args) {
$id = V::get('ID', 0, $_REQUEST, 'int');
if ($id <= 0) {
throw new HttpException("Wrong param ID!", 404);
}
$item = $this->_acl->buildQuery([])->getItem($id);
if (!$item) {
throw new HttpException("Item '{$id}' not exists!", 404);
}
$response = new stdClass();
$itemCopy = $this->_acl->createItemCopy($item);
$createdId = null;
try {
$createdId = $this->_acl->addItem($itemCopy);
if ($createdId) {
$response->type = 'success';
$response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
$response->id = $createdId;
$response->record = $this->_acl->buildQuery([])->getItem($createdId);
}
else {
$response->type = 'error';
$response->msg = "Nie udało się skopiować rekordu!";
}
}
catch (Exception $e) {
$response->type = 'error';
$response->msg = "Wystąpiły błędy!";
$response->msg = $e->getMessage();
}
return $response;
}
private function ajaxHist($args) {
$jsonResponse = array();
$id = V::get('ID', 0, $args, 'int');
$acl = $this->_acl;
$record = $acl->buildQuery([])->getItem($id);
if (!$record) throw new HttpException("404: No item ID({$id})", 404);
$visibleCols = $acl->getRealFieldList();
$rowsHist = $acl->getHistItems($id);
$jsonResponse['row_functions'] = $this->_parseRowFunctions($record['ID'], array('hist', 'cp'), $showLabel = true);
$visibleColsWithIds = array();
$visibleColsLabels = array();
foreach ($visibleCols as $vColName) {
$fldId = $acl->getFieldIdByName($vColName);
if ($fldId) {
$visibleColsWithIds[$fldId] = $vColName;
$label = $acl->getFieldLabel($vColName);
$label = (!$label)? $vColName : '' . $label . '';
$visibleColsLabels[$fldId] = $label;
}
}
$jsonResponse['label'] = "Historia rekordu Nr {$id}";
$jsonResponse['fields'] = array_values($visibleColsWithIds);
$jsonResponse['field_label'] = $visibleColsLabels;
if (empty($rowsHist)) return $jsonResponse;
$jsonResponse['rows'] = array();
foreach ($rowsHist as $histRow) {
$histItem = array();
$histItem['ID'] = V::get('ID', '', $histRow);
$histItem['_created'] = V::get('_created', '', $histRow);
$histItem['_author'] = V::get('_author', '', $histRow);
$histItem['changes'] = array();
foreach ($visibleColsWithIds as $fldId => $fieldName) {
if (!array_key_exists($fieldName, (array)$histRow)) continue;
$value = V::get($fieldName, '', $histRow);
if ('N/S;' == $value) continue;
$changeItem = array();
$changeItem['fieldName'] = $fieldName;
$changeItem['acl_read'] = $acl->canReadObjectField($fieldName, $record);
if ($changeItem['acl_read']) {
$changeItem['value'] = V::get($fieldName, '', $histRow);
}
if ('the_geom' == $fieldName && $acl->canWriteObjectField($fieldName, $record)) {
$sourceName = $acl->getSourceName();
if ('default_db' == $sourceName && !empty($value)) {
$typeName = $acl->getName();
$idHist = V::get('ID', '', $histRow);
$changeItem['revert_function_url'] = Request::getPathUri() . "index.php?_route=ViewTableAjax&typeName=p5_{$sourceName}:{$typeName}&_task=revertFromHistAjax&ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
$changeItem['revert_function_data'] = "ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
}
}
$histItem['changes'][$fieldName] = $changeItem;
}
$jsonResponse['rows'][] = $histItem;
}
return $jsonResponse;
}
public function ajaxFileUpload($args) {
$id = V::get('ID', 0, $args, 'int');
if ($id <= 0) throw new HttpException("404", 404);
$dbID = $this->_acl->getDB();
$db = DB::getDB($dbID);
if (!$db) throw new HttpException("No DB ({$dbID})", 406);
$record = $this->_acl->buildQuery([])->getItem($id);
if (!$record) throw new HttpException("No item ID({$id})", 404);
if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
$tblName = $this->_acl->getName();
$confTblName = "{$tblName}_COLUMN";
$folderConfAll = FoldersConfig::getRawData();
if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
$folderConf = FoldersConfig::getAll($confTblName);
$uploader = new FileUploader($confTblName, (object)$record);
if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
$uploader->findFolder();
$errorMsg = '';
if (!empty($args['SCANS_COLUMN_ADD'])) {
$uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
}
else {
$uploaded = $uploader->tryUploadAjax($errorMsg);
}
$retJson = new stdClass();
if (!$uploaded) throw new Exception($errorMsg);
$uploadedFileName = '';
$uploadedFile = $uploader->getLastUploadedFile();
if ($uploadedFile) {
$uploadedFileName = explode('/', $uploadedFile);
$uploadedFileName = end($uploadedFileName);
}
//echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
$retJson->type = 'SUCCESS';
$retJson->msg = "Plik został poprawnie wgrany do odpowiedniego katalogu {$uploadedFileName}";
if (!empty($uploadedFileName)) {
$sqlObj = new stdClass();
$sqlObj->ID = $record['ID'];
$sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
$db->UPDATE_OBJ($this->_tbl, $sqlObj);
}
return $retJson;
}
public function ajaxFileRemove($args) {
$id = V::get('ID', 0, $args, 'int');
if ($id <= 0) throw new HttpException("404", 404);
$filename = V::get('filename', '', $args);
if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
$dbID = $this->_acl->getDB();
$db = DB::getDB($dbID);
if (!$db) throw new HttpException("No DB ({$dbID})", 406);
$record = $this->_acl->buildQuery([])->getItem($id);
if (!$record) throw new HttpException("No item ID({$id})", 404);
if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
$tblName = $this->_acl->getName();
$confTblName = "{$tblName}_COLUMN";
$folderConfAll = FoldersConfig::getRawData();
if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
$folderConf = FoldersConfig::getAll($confTblName);
$uploader = new FileUploader($confTblName, (object)$record);
if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
$uploader->findFolder();
$errorMsg = '';
$removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
if (!$removed) throw new Exception($errorMsg);
$retJson = new stdClass();
$retJson->type = 'SUCCESS';
$retJson->msg = 'Plik został poprawnie usunięty';
return $retJson;
}
public function ajaxFileList($args) {
$id = V::get('ID', 0, $args, 'int');
if ($id <= 0) throw new HttpException("404", 404);
$dbID = $this->_acl->getDB();
$db = DB::getDB($dbID);
if (!$db) throw new HttpException("No DB ({$dbID})", 406);
$record = $this->_acl->buildQuery([])->getItem($id);
if (!$record) throw new HttpException("No item ID({$id})", 404);
if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
$tblName = $this->_acl->getName();
$confTblName = "{$tblName}_COLUMN";
$folderConfAll = FoldersConfig::getRawData();
if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
$folderConf = FoldersConfig::getAll($confTblName);
$uploader = new FileUploader($confTblName, (object)$record);
if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
$uploader->findFolder();
$mainFolder = $uploader->getDestFolder();
$files = $uploader->getFilesFromFolder($mainFolder, false, true);
$localPath = $uploader->getLocalPath();
$folderWeb = $uploader->getFolderWeb();
$jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
return $jsonFiles;
}
private function ajaxFilePermsRefresh($args) {
$id = V::get('ID', 0, $args, 'int');
if ($id <= 0) throw new HttpException("Wrong param ID", 404);
$dbID = $this->_acl->getDB();
$db = DB::getDB($dbID);
if (!$db) throw new HttpException("No DB", 406);
$record = $this->_acl->buildQuery([])->getItem($id);
if (!$record) throw new Exception("No item ID({$id})", 404);
$tblName = $this->_acl->getName();
// TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
$sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
$sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
$sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
$mainDB = DB::getDB();
if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
$sql = "insert into `_SYNC_FILE_PERMS` (
`ID_PROJECT`,
`A_SYNCHRONIZED`
)
values (
'{$record['ID']}'
, 0
)
ON DUPLICATE KEY UPDATE
`A_SYNCHRONIZED`=0
";
}
else if ('IN7_DZIENNIK_KORESP' == $tblName) {
$sql = "insert into `_SYNC_FILE_PERMS` (
`ID_PROJECT`,
`A_SYNCHRONIZED`
)
values (
'{$record['ID_PROJECT']}'
, 0
)
ON DUPLICATE KEY UPDATE
`A_SYNCHRONIZED`=0
";
}
else {
$sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
`TBL_NAME`,
`TBL_ID`,
`L_APPOITMENT_USER`,
`A_ADM_COMPANY`,
`A_CLASSIFIED`,
`A_SYNCHRONIZED`
)
values (
'{$tblName}'
, '{$id}'
, '{$sql_L_APPOITMENT_USER}'
, '{$sql_A_ADM_COMPANY}'
, '{$sql_A_CLASSIFIED}'
, 0
)
ON DUPLICATE KEY UPDATE
`A_SYNCHRONIZED`=0
";
}
$res = $mainDB->query($sql);
if ($mainDB->has_errors()) {
//echo' (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'';
//echo' (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainDB->get_errors());echo'';
throw new Exception("Nie udało się dodać zadania");
}
// TODO: this blocks browser ajax query
//$limit = 3;
//while ($limit--) {
// sleep(10);
// TODO: check if task is done
//}
$confTblName = "{$tblName}_COLUMN";
$folderConfAll = FoldersConfig::getRawData();
if (!FoldersConfig::hasConfig($confTblName)) {
throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
}
$folderConf = FoldersConfig::getAll($confTblName);
$uploader = new FileUploader($confTblName, (object)$record);
if (!$uploader->setConfig($folderConf)) {
throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
}
$uploader->findFolder();
$mainFolder = $uploader->getDestFolder();
$files = $uploader->getFilesFromFolder($mainFolder, false, true);
$localPath = $uploader->getLocalPath();
$folderWeb = $uploader->getFolderWeb();
$jsonData = new stdClass();
$jsonData->msg = 'Zadanie dodane';
$jsonData->type = 'success';
$jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
return $jsonData;
}
private function sendAjaxFilesConnTblList($id, $args) {
header("Content-type: application/json");
$DBG = ('1' == V::get('DBG', '', $_REQUEST));
$dbID = $this->_acl->getDB();
$db = DB::getDB($dbID);
if (!$db) {
header('HTTP/1.0 406 Not Acceptable');
echo 'No DB (' . $dbID . ')';
exit;
}
$record = $this->_acl->buildQuery([])->getItem($id);
if (!$record) {
header('HTTP/1.0 404 Not Found');
echo 'No item ID(' . $rowID . ')';
exit;
}
$connTblName = '';
$connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
if ($connTblID <= 0) {
header('HTTP/1.0 406 Not Acceptable');
echo 'No conn Table ID';
exit;
}
$connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
if (empty($connTblTypespecials)) {
header('HTTP/1.0 406 Not Acceptable');
echo "No conn Table (ID={$connTblID})";
exit;
}
if($DBG){echo'connTblTypespecials (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($connTblTypespecials);echo'';}
if(1) {
header('HTTP/1.0 404 Not Found');
echo 'TODO: ...';
exit;
}
$tblName = $this->_acl->getName();
$confTblName = "{$tblName}_COLUMN";
$folderConfAll = FoldersConfig::getRawData();
if (!FoldersConfig::hasConfig($confTblName)) {
header('HTTP/1.0 404 Not Found');
echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
exit;
}
$folderConf = FoldersConfig::getAll($confTblName);
$uploader = new FileUploader($confTblName, (object)$record);
if (!$uploader->setConfig($folderConf)) {
header('HTTP/1.0 404 Not Found');
echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
exit;
}
$uploader->findFolder();
$mainFolder = $uploader->getDestFolder();
$files = $uploader->getFilesFromFolder($mainFolder, false, true);
$localPath = $uploader->getLocalPath();
$folderWeb = $uploader->getFolderWeb();
$jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
echo json_encode($jsonFiles);
exit;
}
public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
$jsonFiles = array();
if (!is_array($files) || empty($files)) {
return $jsonFiles;
}
sort($files);
foreach ($files as $vFilePath) {
$file = new stdClass();
$file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
//$file->name = explode('/', $vFilePath);
//$file->name = end($file->name);
$file->size = filesize($vFilePath);
$file->sizeStr = V::humanFileSize($file->size);
$file->type = '';
$file->created = date("Y-m-d H:i:s", filectime($vFilePath));
$file->web = str_replace($localPath, $folderWeb, $vFilePath);
$jsonFiles[] = $file;
}
return $jsonFiles;
}
private function getConnectedTables() {
$connTbls = array();
return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
$fields = $this->_acl->getVirtualFieldListByIdZasob();
if (!empty($fields)) {
foreach ($fields as $vColID => $vCol) {
$typeSpecial = Typespecial::getInstance($vColID);
if ($typeSpecial) {
$tsConnTbls = $typeSpecial->getTblAliasList();
if (!empty($tsConnTbls)) {
foreach ($tsConnTbls as $kID => $vName) {
$connTbls[$kID] = $vName;
}
}
}
}
}
return $connTbls;
}
private function getConnectedTblTypespecials($connTblID) {
$connTblTypespecials = array();
$fields = $this->_acl->getVirtualFieldListByIdZasob();
if (!empty($fields)) {
foreach ($fields as $vColID => $vCol) {
$typeSpecial = Typespecial::getInstance($vColID);
if ($typeSpecial) {
$tsConnTbls = $typeSpecial->getTblAliasList();
if (array_key_exists($connTblID, $tsConnTbls)) {
$connTblTypespecials[] = $typeSpecial;
}
}
}
}
return $connTblTypespecials;
}
private function sendAjaxFiles($id, $args) {
header("Content-type: text/plain");
$DBG = ('1' == V::get('DBG', '', $_REQUEST));
$dbID = $this->_acl->getDB();
$db = DB::getDB($dbID);
if (!$db) throw new HttpException("", 406);
$record = $this->_acl->buildQuery([])->getItem($id);
if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
$tblName = $this->_acl->getName();
$confTblName = "{$tblName}_COLUMN";
$folderConfAll = FoldersConfig::getRawData();
if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych", 404);
$folderConf = FoldersConfig::getAll($confTblName);
//echo'$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'';
$uploader = new FileUploader($confTblName, (object)$record);
$errMsg = '';
if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})" . '
' . "\n" . $errMsg, 404);
$uploader->findFolder();
if($DBG){ echo'uploader (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($uploader);echo'
'; }
$mainFolder = $uploader->getDestFolder();
if($DBG){ echo'mainFolder (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainFolder);echo'
'; }
if (!$mainFolder) {
$destFolderPath = $uploader->getDestLocalPath(true);
$folderCreated = $uploader->tryCreateDestFolder($destFolderPath);
if ($folderCreated) {
//UI::alert('info', "Utworzono katalog");
$uploader->findFolder();
$mainFolder = $uploader->getDestFolder();
} else {
UI::alert('warning', "Nie udało się utworzyć katalogu");
}
}
$files = $uploader->getFilesFromFolder($mainFolder, false, true);
if($DBG){ echo'files (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($files);echo''; }
$sharePoint = V::get('share_point', null, $folderConf);
if ($sharePoint) {
if ('//' == substr($mainFolder, 0, 2)) {
$sharePoint = FoldersConfig::getNfsOsPath() . "{$mainFolder}";
} else {
$sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
}
}
$localPath = $uploader->getLocalPath();
$folderWeb = $uploader->getFolderWeb();
$jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
if($DBG){ echo'jsonFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonFiles);echo''; }
$folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
$skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
$skanySharePoint = V::get('share_point', null, $folderSkanyConf);
$skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
$skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
sort($skanyFiles);
$fileTypes = FoldersConfig::getAll('m_dist_files_types');
$rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('files', 'cp'), true);
$fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
$fileIndex = V::get($fileIndexField, $record['ID'], $record);
echo UI::h('div', [ 'class' => "container" ], [
UI::h('h4', [ 'style' => "margin:20px 0 3px 0;" ], [
"Pliki w katalogu ",
($sharePoint)
? UI::h('a', [ 'href' => $sharePoint ], [
UI::h('span', [ 'class' => "glyphicon glyphicon-folder-open" ]),
UI::h('code', [], $mainFolder),
])
: UI::h('code', [], $mainFolder),
UI::h('span', [ 'class' => "pull-right valign-btns-bottom" ], [
UI::h('span', [ 'id' => "FILES_LIST_ACTIONS_{$this->_htmlID}" ]),
" {$rowFunctionsOut}",
]),
]),
UI::h('div', [ 'style' => "clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;" ], [
UI::h('table', [ 'class' => "table table-bordered table-hover" ], [
UI::h('colgroup', [], [
UI::h('col', [ 'style' => "" ]),
UI::h('col', [ 'style' => "width:30px" ]),
($sharePoint)
? UI::h('col', [ 'style' => "width:30px" ])
: '',
UI::h('col', [ 'style' => "width:80px" ]),
UI::h('col', [ 'style' => "width:140px" ]),
]),
UI::h('tbody', [ 'id' => "FILES_LIST_{$this->_htmlID}" ], [
(empty($mainFolder) || empty($files))
? UI::h('tr', [], [
UI::h('td', [ 'colspan' => "5" ], [
(empty($mainFolder))
? UI::h('div', [ 'class' => "alert alert-warning" ], [
UI::h('h4', [], "Brak folderu!"),
"Folder dla tego rekordu nie został utworzony."
])
: UI::h('div', [ 'class' => "alert alert-info" ], [
UI::h('h4', [], "Brak plików!"),
])
]),
])
: '',
]),
]),
]),
UI::h('br'),
UI::h('br'),
(!$this->_acl->canWriteRecord($record))
? UI::h('div', [ 'class' => "alert alert-warning" ], [
"Brak uprawnień do dodawania plików",
])
: UI::h('div', [ 'id' => "FILES_CONN_TBLS_{$this->_htmlID}" ]),
(!$this->_acl->canWriteRecord($record))
? ''
: UI::h('form', [ 'enctype' => "multipart/form-data", 'method' => "POST", 'action' => "", 'id' => "FILES_FRM_{$this->_htmlID}", 'class' => "form-inline" ], [
UI::h('input', [ 'type' => "hidden", 'name' => "M_DIST_UPLOAD_SOURCE", 'value' => "local" ]),
UI::h('ul', [ 'id' => "FILES_TAB_{$this->_htmlID}", 'class' => "nav nav-tabs", 'style' => "margin:0;"], [
UI::h('li', [ 'class' => "active" ], [ UI::h('a', [ 'href' => "#local", 'data-toggle' => "local" ], "Wybierz plik lokalny"), ]),
UI::h('li', [], [ UI::h('a', [ 'href' => "#scan", 'data-toggle' => "scan" ], "Wybierz plik ze skanów" ), ]),
]),
UI::h('div', [ 'id' => "myTabContent", 'class' => "tab-content" ], [
UI::h('div', [ 'class' => "tab-pane fade in active", 'id' => "local", 'style' => "text-align: center;" ], [
UI::h('input', [ 'name' => "M_DIST_FILES_NAME", 'type' => "file", 'size' => "60", 'class' => "field-upload btn",
'style' => "width:86%;margin:10px auto;padding:10px 4%;background:#eee;text-align:center",
'ondragover' => "this.style.backgroundColor='#D9EDF7'",
'ondragleave' => "this.style.backgroundColor='#eee'",
'ondragend' => "this.style.backgroundColor='#eee'",
]),
]),
UI::h('div', [ 'class' => "tab-pane fade", 'id' => "scan" ], [
(empty($skanyFiles))
? UI::h('div', [ 'class' => "alert alert-info" ], [
UI::h('h4', [], "Brak plików"),
(!empty($skanyFolderWeb))
? "skonfiguruj urządzenie biurowe aby wysyłało skany na ftp://skaner:(h*a*s*l*o)@".$_SERVER['SERVER_NAME']."
lub ".FoldersConfig::getNfsOsPath().$skanySharePoint.""
: '',
])
: UI::h('div', [ 'style' => "max-height:150px; overflow:auto; border-bottom:1px solid #ddd;" ], [
UI::h('table', [ 'class' => "table table-bordered table-hover" ], [
UI::h('colgroup', [], [
UI::h('col', [ 'style' => "width:30px;" ]),
UI::h('col', [ 'style' => "" ]),
UI::h('col', [ 'style' => "width:30px;" ]),
UI::h('col', [ 'style' => "width:80px;" ]),
UI::h('col', [ 'style' => "width:140px;" ]),
]),
UI::h('tbody', [], array_map(function ($vFilePath) use ($skanyLocalPath, $skanyFolderWeb) {
$vFileName = explode('/', $vFilePath);
$vFileName = end($vFileName);
$vFileSize = filesize($vFilePath);
$vFileSizeOut = V::humanFileSize($vFileSize);
return UI::h('tr', [], [
UI::h('td', [], [ UI::h('input', [ 'style' => "margin:0", 'type' => "radio", 'name' => "SCANS_COLUMN_ADD", 'value' => $vFileName]) ]),
UI::h('td', [], [ UI::h('div', [ 'style' => "overflow:hidden; white-space:nowrap", 'title' => $vFileName ], $vFileName) ]),
UI::h('td', [ 'style' => "white-space:nowrap; text-align:center" ], [
UI::h('a', [ 'href' => str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath), 'target' => "_blank", 'class' => "glyphicon glyphicon-download-alt" ])
]),
UI::h('td', [ 'style' => "white-space:nowrap; text-align:right" ], $vFileSizeOut),
UI::h('td', [ 'style' => "white-space:nowrap" ], date("Y-m-d H:i:s", filectime($vFilePath))),
]);
}, $skanyFiles)),
])
]),
])
]),
UI::h('br'),
UI::h('h4', [], [
"Ustal nazwę pliku zgodną z obiegiem dokumentów",
//TODO: link do procesu o obiegu dokumentów
]),
UI::h('table', [ 'style' => "width:100%", 'class' => "table table-bordered" ], [
UI::h('tr', [], [
UI::h('th', [], "Nr"),
UI::h('th', [], "Typ"),
UI::h('th', [ 'style' => "width:40%" ], [
"Opis ",
UI::h('i', [ 'class' => "glyphicon glyphicon-question-sign", 'title' => "kogo dotyczy / czego / sprawa / nazwa_firmy itp" ]),
]),
UI::h('th', [ 'style' => "width:16%" ], "Data wersji"),
UI::h('th', [ 'style' => "width:12%" ], "Numer wersji"),
]),
UI::h('tr', [], [
UI::h('td', [], $fileIndex),
UI::h('td', [], [
UI::h('select', [ 'class' => "form-control", 'name' => "M_DIST_FILES_TYPE" ], array_map(function ($vLabel, $kType) {
return UI::h('option', array_merge([ 'value' => $kType],
($kType == 'TODO')
? [ 'selected' => "selected"]
: []
), $vLabel);
}, $fileTypes, array_keys($fileTypes)) ),
UI::h('br'),
UI::h('label', [ 'class' => "checkbox" ], [
UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_TYPE_AUTO" ]),
" Wykrycie automatyczne typu z wysylanego pliku",
]),
UI::h('label', [ 'class' => "checkbox" ], [
UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_TEMP" ]),
" Plik tymczasowy / roboczy / nieoficjalny (_TEMP)",
]),
]),
UI::h('td', [], [
UI::h('input', [ 'class' => "form-control", 'style' => "width:100%", 'type' => "text", 'name' => "M_DIST_FILES_DESCRIPTION", 'value' => "", 'maxlength' => "50" ]),
"
",
]),
UI::h('td', [], [
UI::h('div', [ 'class' => "input-group" ], [
UI::h('input', [ 'name' => "M_DIST_FILES_DATE", 'type' => "text", 'value' => date('Y-m-d'), 'class' => "se_type-date form-control", 'data-format' => "yyyy-MM-dd", 'maxlength' => "10" ]),
UI::h('span', [ 'class' => "input-group-addon" ], [
UI::h('span', [ 'class' => "glyphicon glyphicon-calendar" ]),
]),
]),
// UI::h('input', [ 'class' => "form-control", 'type' => "date", 'name' => "M_DIST_FILES_DATE", 'value' => date('Y-m-d'), 'maxlength' => "10" ]),
"
",
]),
UI::h('td', [], [
UI::h('input', [ 'class' => "form-control", 'style' => "width:100%", 'type' => "number", 'name' => "M_DIST_FILES_VERSION" ]),
UI::h('br'),
UI::h('label', [ 'class' => "checkbox" ], [
UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_VERSION_AUTO" ]),
" Automatycznie dodaj wersje",
]),
]),
]),
UI::h('tr', [], [
UI::h('td', [ 'colspan' => "5" ], [
UI::h('div', [ 'id' => "FRM_UPLOAD_RESULTS_{$this->_htmlID}" ]),
UI::h('p', [], [
UI::h('input', [ 'type' => "submit", 'value' => "Wyślij", 'class' => "btn btn-primary" ], "wybrany plik do folderu:"),
]),
UI::h('p', [], [
UI::h('code', [], [
UI::h('b', [], $uploader->getDestPathShare(true)),
]),
UI::h('br'),
UI::h('i', [ 'style' => "color:#777" ], "(Jeśli folder nie istnieje to zostanie utworzony automatycznie)"),
]),
]),
]),
]),
]),
]);
$className = __CLASS__;
$jsArgs = [
'CAN_WRITE_RECORD' => (int)$this->_acl->canWriteRecord($record),
'SHARE_POINT' => $sharePoint,
'URL_FILE_LIST_UPDATE_AJAX' => "index-ajax.php?_zasobID={$this->_zasobID};&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_LIST&ID={$record['ID']}",
'URL_CONNECTED_TABLE_LIST' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_CONN_TBL_LIST&ID={$record['ID']}",
// $urlFileRemoveAjax
'URL_FILE_REMOVE_AJAX' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILE_REMOVE&ID={$record['ID']}",
];
echo UI::h('script', [], "
function fileListUpdateAjax{$this->_htmlID}() {
var postData = {};
var URL_FILE_LIST_UPDATE_AJAX = '{$jsArgs['URL_FILE_LIST_UPDATE_AJAX']}';
jQuery.ajax({
url: URL_FILE_LIST_UPDATE_AJAX,
type: 'POST',
data: postData,
success: function(data) {
fileListUpdate{$this->_htmlID}(data);
},
error: function(jhr, textStatus, errorThrown) {
console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
}
});
}
");
echo UI::h('script', [], "
function fileListUpdate{$this->_htmlID}(fileListJson) {
var CAN_WRITE_RECORD = {$jsArgs['CAN_WRITE_RECORD']};
var SHARE_POINT = '{$jsArgs['SHARE_POINT']}';
var URL_FILE_REMOVE_AJAX = '{$jsArgs['URL_FILE_REMOVE_AJAX']}';
var fileListNode = jQuery('#FILES_LIST_{$this->_htmlID}');
fileListNode.empty();
fileListJson.map(function(file){
var node = $('
');
var fFun = CAN_WRITE_RECORD
? $('')
: null
;
var fNameCell = $(' | ');
var fName = $('');
if (fFun) fName.append(fFun);
fName.append(file.name);
fName.appendTo(fNameCell);
node.append(fNameCell);
node.append('' + '' + ' | ');
if (SHARE_POINT) {
node.append('' + '' + ' | ');
}
node.append('' + file.sizeStr + ' | ');
node.append('' + file.created + ' | ');
node.appendTo(fileListNode);
if (fFun) {
$(fFun).click(function(e){
var n = $(e.target);
var fname= n.data('filename');
if (!fname) {
return false;
}
if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
var postData = {filename: fname};
jQuery.ajax({
url: URL_FILE_REMOVE_AJAX,
type: 'POST',
data: postData,
success: function(data) {
if (data && data.type) {
if (data.type == 'SUCCESS') {
n.parents('tr').remove();
//console.log('TODO: SUCCESS msg: ', data.msg);
}
else if (data.type == 'error') {
console.log('TODO: ERROR msg: ', data.msg);
}
} else {
console.log('TODO: ??? data: ', data);
}
},
error: function(jhr, textStatus, errorThrown) {
console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
}
});
}
});
}
});
}
");
echo UI::h('script', [], "
function connTblListUpdateAjax{$this->_htmlID}(connTblID) {
var postData = {};
var URL_CONNECTED_TABLE_LIST = '{$jsArgs['URL_CONNECTED_TABLE_LIST']}'
// clear current file list
jQuery('#FILES_CONN_TBLS_{$this->_htmlID}').find('.files-list').empty();
jQuery.ajax({
url: URL_CONNECTED_TABLE_LIST + '&connTblID=' + connTblID,
type: 'POST',
data: postData,
success: function(data) {
connTblListUpdate{$this->_htmlID}(data);
},
error: function(jqXHR, textStatus, errorThrown) {
var txt = jqXHR.responseText || 'Error';
jQuery('#FILES_CONN_TBLS_{$this->_htmlID}').find('.files-list').html('' + txt + ' |
');
if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
}
});
}
");
echo UI::h('script', [], "
function connTblListUpdate{$this->_htmlID}(fileListJson) {
var fileListNode = jQuery('#FILES_CONN_TBLS_{$this->_htmlID}').find('.files-list');
fileListNode.empty();
fileListJson.map(function(file){
var node = $('
');
var fNameCell = $(' | ');
var fName = $('');
fName.append(file.name);
fName.appendTo(fNameCell);
node.append(fNameCell);
node.append('' + '' + ' | ');
node.append('' + file.sizeStr + ' | ');
node.append('' + file.created + ' | ');
node.appendTo(fileListNode);
});
}
");
?>
_acl->getField($fldID);
DBG::log($fld, 'array', "\$fld({$fldID})");
if (!$fld) {
// 404
} else {
$fldName = $fld['name'];
}
$jsonData = array();
$typeSpecial = Typespecial::getInstance($fldID, $fldName);
if ($typeSpecial) {
$query = V::get('q', '', $_REQUEST);
DBG::log("\$query({$query})");
$rawRows = null;
$rows = $typeSpecial->getValuesWithExports($query);
DBG::log($rows, 'array', "\$rows({$query})");
foreach ($rows as $kID => $vItem) {
$itemJson = new stdClass();
$itemJson->id = $vItem->id;
$itemJson->name = $vItem->param_out;
if (!empty($vItem->exports)) {
$itemJson->exports = $vItem->exports;
}
if (!empty($vItem->{'$order'})) {
$itemJson->{'$order'} = $vItem->{'$order'};
}
$jsonData[] = $itemJson;
}
}
/*
MENU_INIT:VIEWTABLE_AJAX
ZASOB_ID:1188
_task:TYPESPECIAL
fldID:3866
Form Dataview sourceview URL encoded
q:te
*/
echo json_encode($jsonData);
exit;
}
public function ajaxData($args) {// executed from url: "{$this->syncUrl"&_hash={$this->_htmlID}&_task=loadDataAjax"
$acl = $this->_acl;
$pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
$page = V::get('page', 0, $args, 'int');
$page = ($page > 0) ? $page - 1 : $page;
$currSortCol = V::get('currSortCol', '', $args);
$currSortFlip = V::get('currSortFlip', '', $args);
$params = array();
$params['limit'] = $pageSize;
$params['limitstart'] = $page * $params['limit'];
$params['order_by'] = ($currSortCol)? $currSortCol : '';
$params['order_dir'] = $currSortFlip;
foreach ($args as $k => $v) {
if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
$params[$k] = $v;
}
else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
$params[$k] = $v;
}
}
$filters = new stdClass();
$filters->currSortCol = $currSortCol;
$filters->currSortFlip = $currSortFlip;
foreach ($args as $k => $v) {
if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
$filters->{$k} = $v;
}
else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
$filters->{$k} = $v;
}
}
$this->setFilters($filters);
$vCols = $acl->getVirtualFieldListByIdZasob();
DBG::log($vCols, 'array', "\$vCols");
$visibleCols = $acl->getVisibleFieldListByIdZasob();
DBG::log($visibleCols, 'array', "\$visibleCols");
$jsonData = new stdClass();
$jsonData->page = $page + 1;
$jsonData->pageSize = $pageSize;
$jsonData->filters = $filters;
$jsonData->cols = new stdClass();
$jsonData->primaryKey = $acl->getPrimaryKeyField();
$ind = 0;
foreach ($visibleCols as $fieldID => $col) {
$ind++;
$columnConfig = (object)array('index'=>$ind);
if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
$columnConfig->format = '{0}
';
}
else if (in_array($col, array('Status'))) {
// Ahmes problems Status colors
$columnConfig->format = '{0}
';
}
else if ($acl->isGeomField($col)) {
$columnConfig->type = 'geom';
}
if ('' !== ($label = $acl->getFieldLabel($col))) {
$columnConfig->friendly = $label;
}
$colType = $acl->getFieldType($col);
if ($colType) {// @see MarkTableAjaxFilterColType
if ($colType['type'] == 'date') {
// $columnConfig->type = 'date';// TODO: require datetimepicker
}
if (!empty($colType['simpleType'])) $columnConfig->type = $colType['simpleType'];
} else {// typespecial - no type
$columnConfig->type = 'special';
}
$columnConfig->xsdType = $acl->getXsdFieldType($col);
if ($columnConfig->xsdType) {
list($prefix, $typeName, $refTypeName) = explode(":", $columnConfig->xsdType);
DBG::log([$prefix, $typeName, $refTypeName], 'array', "col '{$col}' xsdType");
switch ($prefix) {
case 'ref':
case 'alias_ref':
if (!$refTypeName) throw new HttpException("Schema Error for field({$col}) xsdType({$columnConfig->xsdType})", 500);
$columnConfig->type = 'ref';
$columnConfig->xsdRefUri = Api_WfsNs::getNsUri($typeName);
$columnConfig->xsdRefType = $refTypeName;
$columnConfig->xsdRefNsPrefix = $typeName;
break;
case 'xsd':
switch ($typeName) {
case 'string': $columnConfig->type = 'string'; break;
case 'NMTOKEN': $columnConfig->type = 'string'; break; // xsd:NMTOKEN - non empty string without space - pattern: \c+
case 'NCName': $columnConfig->type = 'string'; break; // xsd:NCName - non empty without ':' and not started with '-' - pattern: [\i-[:]][\c-[:]]*
case 'integer': $columnConfig->type = 'number'; break;
case 'int': $columnConfig->type = 'number'; break;
case 'long': $columnConfig->type = 'number'; break;
}
break;
case 'p5':
switch ($typeName) {
case 'enum': $columnConfig->type = 'string'; break;
case 'alias': {
$format = $acl->getXsdFieldParam($col, 'format');
if ($format) $columnConfig->format = $format;
} break;
case 'string': {
$columnConfig->type = 'p5:string';
$columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
} break;
}
break;
}
}
$typeSpecial = Typespecial::getInstance($fieldID, $col);
if ($typeSpecial) {
DBG::log($typeSpecial, 'array', "\$typeSpecial id({$fieldID}) col({$col})");
$columnConfig->_tsRetId = $typeSpecial->getReturnId();
if ($columnConfig->_tsRetId == 0) {
$tsParamOut = V::get('param_out', null, $typeSpecial);
if ($tsParamOut) {
$tsFormat = V::get('format', null, $tsParamOut);
$tsValues = V::get('values', null, $tsParamOut);
$tsAliases = V::get('alias', null, $tsParamOut);
if (false !== strpos($tsFormat, ' Array([ID] => 1467), [alias] => Array([1467] => ID) */
$bugTsColsNotVisible = array();
foreach ($tsValues as $kVarName => $vIdZasob) {
if (array_key_exists($vIdZasob, $tsAliases)) {
$tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
} else {
$bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
}
if (!array_key_exists($vIdZasob, $visibleCols)) {
$bugTsColsNotVisible[] = $vIdZasob;
}
}
if (empty($bugTsColsNotVisible)) {
$tsSimpleLink = new stdClass();
$tsSimpleLink->format = $tsFormat;
$tsSimpleLink->aliasMap = $tsAliasMap;
$columnConfig->_tsSimpleLink = $tsSimpleLink;
$columnConfig->type = 'simpleLink';
} else {
$columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
}
}
}
}
}
if ($columnConfig->xsdType) {// fix fields type p5:typeSpecialSimpleLink (previously defined by Typespecial)
switch ($columnConfig->xsdType) {
case 'p5:typeSpecialSimpleLink': {
$columnConfig->type = 'simpleLink';
$columnConfig->_tsRetId = 0;
$columnConfig->_tsSimpleLink = new stdClass();
$columnConfig->_tsSimpleLink->format = $acl->getXsdFieldParam($col, 'format');
$columnConfig->_tsSimpleLink->aliasMap = $acl->getXsdFieldParam($col, 'aliasMap');
} break;
}
}
// @see ajaxHiddenColsSave
if (UserProfile::isHiddenColumn($acl->getID(), $fieldID)) {
$columnConfig->hidden = true;
}
$columnConfig->description = $acl->getFieldOpis($col);
$jsonData->cols->{$col} = $columnConfig;
}
DBG::log($jsonData->cols, 'array', "\$jsonData->cols");
$jsonData->rows = array();
$queryFeatures = $acl->buildQuery($params);
$jsonData->total = $queryFeatures->getTotal();
$listItems = $queryFeatures->getItems();
$primaryKeyField = $acl->getPrimaryKeyField();
$items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
// TODO: add virtual data by Typespecial
if (!empty($vCols) && !empty($items)) {
foreach ($vCols as $vColID => $vCol) {
$colType = $acl->getFieldTypeById($vColID);
if ($colType) continue;// pomin Typespecial dla realnych komorek w bazie danych
$typeSpecial = Typespecial::getInstance($vColID, $vCol);
if ($typeSpecial) {
$columnConfig = V::get($vCol, null, $jsonData->cols);
if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
// pomin simple link values - mved to js render
} else {
DBG::log($typeSpecial, 'array', "Typespecial({$vColID})");
$ids = array_keys($items);
$specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
DBG::log($specialValues, 'array', "Typespecial({$vColID}) \$specialValues");
if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
$tsValue = implode('
', $vValues);
DBG::log($items[$kItemID], 'array', "Typespecial({$vColID}) Item[{$kItemID}].{$vCol}");
if (!empty($items[$kItemID][$vCol]) && !empty($tsValue)) {
$items[$kItemID][$vCol] .= ": {$tsValue}";
} else {
$items[$kItemID][$vCol] = $tsValue;
}
}
}
}
}
}
{
if(V::get('DBG', '', $_GET)){$jsonData->__DBG__ = [];}
$p5Alias = [];
foreach ((array)$jsonData->cols as $fieldName => $conf) {
if ('p5:alias' == V::get('xsdType', '', $conf)) {
if(V::get('DBG', '', $_GET)){$jsonData->__DBG__[$fieldName] = $conf;}
$aliasType = $acl->getXsdFieldParam($fieldName, 'type');// 'type' => 'sql_table_alias',
if ('sql_table_alias' == $aliasType) {
$p5Alias[$fieldName] = (array)$conf;
$p5Alias[$fieldName]['type'] = 'sql_table_alias';
$p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');// 'local_join_key' => 'ID',
$p5Alias[$fieldName]['remote_table_name'] = $acl->getXsdFieldParam($fieldName, 'remote_table_name');// 'remote_table_name' => 'CRM_LISTA_ZASOBOW_ORDERS_summary_view',
$p5Alias[$fieldName]['remote_join_key'] = $acl->getXsdFieldParam($fieldName, 'remote_join_key');// 'remote_join_key' => 'ID',
$p5Alias[$fieldName]['remote_column_value'] = $acl->getXsdFieldParam($fieldName, 'remote_column_value');// 'remote_column_value' => 'SUM_POS',
} else if ('sql_query_alias' == $aliasType) {
$p5Alias[$fieldName] = (array)$conf;
$p5Alias[$fieldName]['type'] = 'sql_query_alias';
$p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');
$p5Alias[$fieldName]['join_query_format'] = $acl->getXsdFieldParam($fieldName, 'join_query_format');
}
}
}
if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$p5Alias'] = $p5Alias;}
if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'] = [];}
if ($p5Alias) {
$sqlLocalTableName = $acl->getRootTableName();
$primaryKeyField = $acl->getPrimaryKeyField();
foreach ($p5Alias as $fieldName => $conf) {
$aliasValuesRaw = [];
if ('sql_table_alias' == $conf['type']) {
$localKeys = [];
$localKeyName = V::get('local_join_key', '', $conf);
if ($localKeyName) {
if (!array_key_exists($localKeyName, $localKeys)) {
$localKeys[$localKeyName] = [];
foreach ($items as $item) {
$keyLocal = V::get($localKeyName, 0, $item);
if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
}
}
if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$localKeys'] = $localKeys;}
if (!empty($localKeys[$localKeyName])) {
$sqlRemoteTable = V::get('remote_table_name', '', $conf);
$sqlRemoteValueFieldName = V::get('remote_column_value', '', $conf);
$sqlRemoteKeyName = V::get('remote_join_key', '', $conf);
$sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
$aliasValuesRaw = DB::getPDO()->fetchAllByKey("
select r.{$sqlRemoteKeyName} as {$sqlLocalKeyName}, r.{$sqlRemoteValueFieldName} as remote_value
from {$sqlRemoteTable} r
where r.{$sqlRemoteKeyName} in(" . implode(",", $localKeys[$localKeyName]) . ")
", $sqlLocalKeyName);
if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'][$fieldName] = $aliasValuesRaw;}
}
}
} else if ('sql_query_alias' == $conf['type']) {
$localKeys = [];
$localKeyName = V::get('local_join_key', '', $conf);
$sqlFormat = V::get('join_query_format', '', $conf);
if ($localKeyName && $sqlFormat) {
if (!array_key_exists($localKeyName, $localKeys)) {
$localKeys[$localKeyName] = [];
foreach ($items as $item) {
$keyLocal = V::get($localKeyName, 0, $item);
if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
}
}
}
if (!empty($localKeys[$localKeyName])) {
$sql = str_replace('{sql_in_local_join_key}', implode(",", $localKeys[$localKeyName]), $sqlFormat);
$sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
$aliasValuesRaw = DB::getPDO()->fetchAllByKey($sql, $sqlLocalKeyName);
}
}
DBG::log($aliasValuesRaw, 'array', '$aliasValuesRaw');
if (!empty($aliasValuesRaw)) {
DBG::log($aliasValuesRaw, 'array', "DBG_P5: \$aliasValuesRaw");
array_walk($items, function (&$item) use ($fieldName, $sqlLocalKeyName, $aliasValuesRaw) {
$sqlValue = V::get($sqlLocalKeyName, null, $item);
DBG::log($sqlValue, 'array', "DBG_P5: \$sqlValue");
DBG::log($aliasValuesRaw[$sqlValue]['remote_value'], 'array', "DBG_P5: \$aliasValuesRaw[{$sqlValue}]['remote_value']");
DBG::log($item, 'array', "DBG_P5: \$item");
if ($sqlValue !== null && array_key_exists($sqlValue, $aliasValuesRaw)) {
DBG::log($aliasValuesRaw[$sqlValue]['remote_value'], 'array', "DBG_P5: TODO_update_value");
$item[$fieldName] = $aliasValuesRaw[$sqlValue]['remote_value'];
DBG::log($item[$fieldName], 'array', "DBG_P5: TODO_updated_value");
}
});
}
}
}
}
foreach ($items as $item) {
// TODO: hide items without 'R'
foreach ($visibleCols as $fieldName) {
// TODO: ID default 'R'
if (!$acl->canReadObjectField($fieldName, $item)) $item[$fieldName] = '*****';
// null => empty string
if (!isset($item[$fieldName]) || (!$item[$fieldName] && $item[$fieldName] !== '0')) {
// DBG::log($item[$fieldName], 'array', "isEmptyString[{$fieldName}]");
$item[$fieldName] = '';
}
}
$jsonData->rows[] = $item;
}
$jsonData->type = 'success';
$jsonData->msg = 'pobrano nowe dane';
return $jsonData;
}
private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
$value = '';
$type = $this->_acl->getFieldTypeById($fieldID);
if ($type) {
if ($type['type'] == 'date') {
$value = $type['default'];
}
// fix bug when field is unique and is null allowed: change empty string to null
if ($type['null']) {
$value = 'NULL';
}
// fix bug when field is enum and is set to '0': for php '0' is empty
if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
if (false !== strpos($type['type'], "''")) {
// enum('', '1','2')
$value = '';
} else if (false !== strpos($type['type'], "'0'")) {
// enum('0', '1','2')
$value = '0';
} else {
$value = $type['default'];
}
}
}
return $value;
}
/**
* set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
* $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
*/
private function ajaxHiddenColsSave($args) {
$response = new stdClass();
if (empty($args)) {
$response->type = 'info';
return $response;
}
UserProfile::load();
// clean up old, wrong values
if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
}
$colVis = UserProfile::getHiddenCols($this->_zasobID);
$fields = $this->_acl->getFieldListByIdZasob();
foreach ($fields as $idField => $fieldName) {
if (isset($args[$fieldName])) {
if ($args[$fieldName] == 'SHOW') {
$colVis[$idField] = 1;
} else if ($args[$fieldName] == 'HIDE') {
$colVis[$idField] = 0;
}
}
}
UserProfile::setHiddenCols($this->_zasobID, $colVis);
UserProfile::save();
$response->type = 'success';
return $response;
}
private function ajaxPageSizeSave($args) {
$response = new stdClass();
if (empty($args)) {
$response->type = 'info';
return $response;
}
$pageSize = V::get('pageSize', 0, $args, 'int');
UserProfile::load();
// clean up old, wrong values
if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
}
$tableAjaxSettings = UserProfile::getTableAjaxSettings();
$tableAjaxSettings['pageSize'] = $pageSize;
UserProfile::setTableAjaxSettings($tableAjaxSettings);
UserProfile::save();
$response->type = 'success';
return $response;
}
private function ajaxTheGeomSave($args) {
$primaryKeyField = $this->_acl->getPrimaryKeyField();
$primaryKey = V::get($primaryKeyField, 0, $args, 'int');
$polygon = V::get('polygon', 0, $args);
$geomFieldName = 'the_geom';
if ($primaryKey <= 0) {
throw new HttpException("Wrong param ID", 404);
}
// TODO: validate polygon - ex.: POLYGON((2072030.2315435 7234115.910678,2072029.4815435 7234093.660678,2072115.2315435 7234091.160678,2072115.4815435 7234113.660678,2072115.2315435 7234113.660678,2072094.2315435 7234113.910678,2072030.2315435 7234115.910678)))
$record = $this->_acl->buildQuery([])->getItem($primaryKey);
if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
throw new HttpException("Brak dostępu do rekordu", 403);
}
if (!$this->_acl->canWriteObjectField($geomFieldName, $record)) {
throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
}
$itemPatch = array();
$itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
$itemPatch[$primaryKeyField] = $primaryKey;
$response = new stdClass();
try {
$affected = $this->_acl->updateItem($itemPatch);
if ($affected > 0) {
$response->type = 'success';
$response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
} else if ($affected == 0) {
$response->type = 'info';
$response->msg = "Nie wprowadzono żadnych zmian";
}
$response->record = $this->_acl->buildQuery([])->getItem($primaryKey);
}
catch (Exception $e) {
$response->type = 'error';
$response->msg = $e->getMessage();
}
return $response;
}
private function sendAjaxResponseJson($method, $args) {
try {
$response = $this->{$method}($args);
}
catch (HttpException $e) {
$response = new stdClass();
$response->type = 'error';
$response->msg = $e->getMessage();
$response->errorCode = $e->getCode();
Http::sendHeaderByCode($e->getCode());
}
catch (Exception $e) {
$response = new stdClass();
$response->type = 'error';
$response->msg = $e->getMessage();
$response->errorCode = $e->getCode();
}
header('Content-type: application/json');
if (!$response) $response = new stdClass();
echo json_encode($response);
exit;
}
private function ajaxProcesInitFiltr($args) {// ajax task 'PROCES_INIT_FILTR'
$response = new stdClass();
$pInitList = array();// [proces_init_id] => label (DESC)
if (!$this->_showProcesInit) {
$response->type = 'error';
return $response;
}
$userAcl = User::getAcl();
$pInitList = $userAcl->getTableProcesInitList($this->_zasobID);
if (!empty($pInitList)) {
$procesIds = array_keys($pInitList);
$mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
DBG::_('DBG_MAP', '1', "mapTree", $mapTree, __CLASS__, __FUNCTION__, __LINE__);
DBG::_('DBG_MAP', '1', "pInitList", $pInitList, __CLASS__, __FUNCTION__, __LINE__);
$pInitListSelected = $this->getProcesInitSelected();
$response->pInitData = new stdClass();
$response->pInitData->pInitList = $pInitList;
$response->pInitData->mapTree = $mapTree;
$response->pInitData->pInitListSelected = $pInitListSelected;
}
$response->type = 'success';
return $response;
}
}