| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830 |
- <?php
- Lib::loadClass('RouteBase');
- Lib::loadClass('ProcesHelper');
- Lib::loadClass('TableAjax');
- // Lib::loadClass('Request');
- Lib::loadClass('Response');
- Lib::loadClass('UI');
- Lib::loadClass('Api_WfsNs');
- Lib::loadClass('Core_AclHelper');
- Lib::loadClass('Route_UrlAction');
- Lib::loadClass('Router');
- Lib::loadClass('Typespecial');
- Lib::loadClass('UserProfile');
- class Route_ViewTableAjax extends RouteBase {
- public function getTableAjaxWidget($acl) {
- $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
- $tbl = new TableAjax($acl);
- $tblLabel = $acl->getNamespace();
- if ('default_db' == $acl->getSourceName()) {
- $tblLabel = array();
- $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
- if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
- if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
- if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
- $tblLabel = implode(" - ", $tblLabel);
- }
- $tbl->setSyncUrl($syncUrl);
- $tbl->showUserTableFilter($this->getLink("getUserTableFilterAjax"));
- $tbl->setLabel($tblLabel);
- $tbl->addRowFunction('edit');
- $tbl->addRowFunction('hist');
- $tbl->addRowFunction('files');
- $tbl->addRowFunction('cp');
- $tbl->addRowFunction('msgs');
- return $tbl;
- }
- public function defaultAction() {
- UI::gora();
- UI::menu();
- try {
- $namespace = V::get('namespace', '', $_GET, 'word');
- if (!$namespace) {
- $typeName = V::get('typeName', '', $_GET, 'word');
- if (!$typeName) throw new Exception("Wrong param typeName");
- $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
- }
- $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
- $forceFilterInit = array();
- $filterInit = new stdClass();
- $filterInit->currSortCol = $acl->getPrimaryKeyField();
- $filterInit->currSortFlip = 'desc';
- foreach ($_GET as $k => $v) {
- if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
- $filterInit->$k = $v;
- }
- else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
- $filterInit->$k = $v;
- }
- else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
- $fldName = substr($k, 3);
- $forceFilterInit[$fldName] = $v;
- }
- }
- $tbl = $this->getTableAjaxWidget($acl);
- $tbl->setFilterInit($filterInit);
- if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
- echo $tbl->render();
- if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
- Lib::loadClass('DebugExecutionTime');
- $dbgExecTime = new DebugExecutionTime();
- $dbgExecTime->activate();
- $dbgExecTime->log('start');
- UI::startContainer(['style'=>'border:1px solid red']);
- UI::tag('p', null, "TEST - load perms from db");
- $idTable = $acl->getID();
- UI::tag('p', null, "DBG idTable({$idTable})");
- if ($idTable > 0) {
- $dbgExecTime->log('before sql');
- $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
- $dbgExecTime->log('after sql', ['sql']);
- UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
- $csvIdProces = array();
- foreach ($aclTableRows as $row) {
- if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
- }
- }
- $tableName = $acl->getName();
- $databaseName = DB::getPDO()->getDatabaseName();
- UI::table([
- 'caption' => "Cell to process",
- 'rows' => array_map(
- function ($row) use ($aclTableRows, $idTable) {
- $row['proces'] = array();
- $row['id_zasob'] = 0;
- $row['PERM_R'] = 0;
- $row['PERM_W'] = 0;
- $row['PERM_X'] = 0;
- $row['PERM_C'] = 0;
- $row['PERM_S'] = 0;
- $row['PERM_O'] = 0;
- $row['PERM_V'] = 0;
- $row['PERM_E'] = 0;
- foreach ($aclTableRows as $aclInfo) {
- if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
- $row['proces'][] = $aclInfo['ID_PROCES'];
- $row['id_zasob'] = $aclInfo['ID_CELL'];
- $row['PERM_R'] += $aclInfo['PERM_R'];
- $row['PERM_W'] += $aclInfo['PERM_W'];
- $row['PERM_X'] += $aclInfo['PERM_X'];
- $row['PERM_C'] += $aclInfo['PERM_C'];
- $row['PERM_S'] += $aclInfo['PERM_S'];
- $row['PERM_O'] += $aclInfo['PERM_O'];
- $row['PERM_V'] += $aclInfo['PERM_V'];
- $row['PERM_E'] += $aclInfo['PERM_E'];
- }
- }
- $row['proces'] = (empty($row['proces']))
- ? "<i style=\"color:red\">Brak</i>"
- : implode(", ", $row['proces']);
- if (!$row['id_zasob']) $row['id_zasob'] = DB::getPDO()->fetchValue("select ID from CRM_LISTA_ZASOBOW where `DESC` = '{$row['COLUMN_NAME']}' and PARENT_ID = {$idTable} limit 1");
- return $row;
- }, DB::getPDO()->fetchAll("
- select t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
- from `information_schema`.`COLUMNS` t
- where t.TABLE_SCHEMA = '{$databaseName}'
- and t.TABLE_NAME like '{$tableName}'
- ")
- )
- ]);
- if (!empty($csvIdProces)) {
- $csvIdProces = implode(",", $csvIdProces);
- UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
- $userLogin = User::getLogin();
- $dbgExecTime->log('before sql');
- $rows = DB::getPDO()->fetchAll("select ID_PROCES from `CRM_PROCES_idx_USER_to_PROCES_VIEW` where ADM_ACCOUNT = '{$userLogin}' and ID_PROCES in({$csvIdProces}) group by ID_PROCES");
- $dbgExecTime->log('after sql', ['sql']);
- UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
- $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
- $userTablePerms = array();
- foreach ($aclTableRows as $row) {
- if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
- if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
- $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
- $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
- $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
- $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
- $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
- $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
- $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
- $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
- } else {
- $userTablePerms[ $row['CELL_NAME'] ] = $row;
- unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
- unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
- unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
- }
- }
- UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
- } else UI::alert('warning', "brak \$csvIdProces");
- $dbgExecTime->printDebug();
- UI::endContainer();
- }
- } catch (Exception $e) {
- UI::startContainer();
- UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
- UI::endContainer();
- DBG::log($e);
- }
- UI::dol();
- }
- public function rmUserTableFilterAjaxAction() {
- Response::sendTryCatchJson(array($this, 'rmUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function rmUserTableFilterAjax($args) {
- $namespace = V::get('namespace', '', $args);
- $filtrName = V::get('filtrName', '', $args);
- if (!$namespace) throw new Exception("Missing namespace");
- if (!$filtrName) throw new Exception("Missing filtrName");
- $userFltrConfKey = "tableColFilters__" . User::getLogin();
- $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
- if (!$currentFilters) return [
- 'type' => 'warning',
- 'msg' => "Brak filtrów w bazie",
- ];
- $currentFilters = json_decode($currentFilters, 'assoc');
- unset($currentFilters[$namespace][$filtrName]);
- $affeced = DB::getPDO()->update('CRM_CONFIG', 'CONF_KEY', $userFltrConfKey, [
- 'CONF_VAL' => json_encode($currentFilters)
- ]);
- return [
- 'type' => 'success',
- 'msg' => 'Zapisano nowy filtr',
- 'data' => $currentFilters[$namespace]
- ];
- }
- public function addUserTableFilterAjaxAction() {
- Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function addUserTableFilterAjax($args) {
- $namespace = V::get('namespace', '', $args);
- $filtrName = V::get('filtrName', '', $args);
- $visibleCols = V::get('visibleCols', '', $args);
- if (!$namespace) throw new Exception("Missing namespace");
- if (!$filtrName) throw new Exception("Missing filtrName");
- if (!$visibleCols) throw new Exception("Missing visibleCols");
- $userFltrConfKey = "tableColFilters__" . User::getLogin();
- $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
- $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
- $currentFilters[$namespace][$filtrName] = $visibleCols;
- $sqlFltr = json_encode($currentFilters);
- DB::getPDO()->execSql("
- insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
- values ('$userFltrConfKey', '{$sqlFltr}')
- on duplicate key update CONF_VAL = '{$sqlFltr}'
- ");
- return [
- 'type' => 'success',
- 'msg' => 'Zapisano nowy filtr',
- 'data' => $currentFilters[$namespace]
- ];
- }
- public function getUserTableFilterAjaxAction() {
- Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function getUserTableFilterAjax($args) {
- $namespace = V::get('namespace', '', $args);
- if (!$namespace) throw new Exception("Missing namespace");
- $userFltrConfKey = "tableColFilters__" . User::getLogin();
- $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
- $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
- return [
- 'type' => 'success',
- 'msg' => 'Odczytano filtry użytkownika',
- 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
- ];
- }
- public function revertFromHistAjaxAction() {
- Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
- }
- public function revertFromHistAjax() {
- $typeName = V::get('typeName', '', $_REQUEST, 'word');
- if (!$typeName) throw new Exception("Wrong param typeName");
- // TODO: use namespace from url
- // $namespace = V::get('namespace', '', $_GET, 'word');
- // if (!$namespace) {
- // $typeName = V::get('typeName', '', $_GET, 'word');
- // if (!$typeName) throw new Exception("Wrong param typeName");
- // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
- // }
- // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
- $id = V::get('ID', '', $_REQUEST, 'word');
- if (!$id) throw new Exception("Wrong param ID");
- $idHist = V::get('idHist', '', $_REQUEST, 'word');
- if (!$idHist) throw new Exception("Wrong param idHist");
- $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
- if (!$fieldName) throw new Exception("Wrong param fieldName");
- $acl = Core_AclHelper::getAclByTypeName($typeName);
- $item = $acl->getItem($id);
- if (!$item) throw new HttpException("Item not found", 404);
- if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
- $histItem = $acl->getHistItem($id, $idHist);
- if (!$histItem) throw new HttpException("Hist Item not found", 404);
- $histValue = V::get($fieldName, 'N/S;', $histItem);
- if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
- if ($acl->isGeomField($fieldName)) {
- $wktType = strtoupper($acl->getGeomFieldType($fieldName));
- if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
- if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
- $coords = trim(substr($histValue, strlen($wktType)), '()');
- $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
- if (!$wktValue) throw new Exception("BUG in hist record");
- $sqlObj = array();
- $sqlObj['ID'] = $id;
- $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
- $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
- if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
- else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
- $jsonResponse = array();
- $jsonResponse['type'] = 'success';
- $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
- $jsonResponse['actions'] = array();
- $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
- return $jsonResponse;
- } else {
- throw new HttpException("Not implemented - update from hist only for the geom field", 501);
- }
- throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
- }
- public function removeTheGeomAjaxAction() {
- Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function removeTheGeomAjax($args) {
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
- $primaryKeyField = $acl->getPrimaryKeyField();
- $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
- $geomFieldName = 'the_geom';
- $response = new stdClass();
- if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
- $record = $acl->getItem($primaryKey);
- if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
- if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
- if (empty($record->{$geomFieldName})) {
- $response->type = 'info';
- $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
- $response->record = $record;
- return $response;
- }
- $itemPatch = array();
- $itemPatch[$geomFieldName] = "NULL";
- $itemPatch[$primaryKeyField] = $primaryKey;
- $response = new stdClass();
- try {
- $affected = $acl->updateItem($itemPatch);
- if ($affected > 0) {
- $response->type = 'success';
- $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
- } else if ($affected == 0) {
- $response->type = 'info';
- $response->msg = "Nie wprowadzono żadnych zmian";
- }
- $response->record = $acl->getItem($primaryKey);
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- public function moreFunctionsCellAjaxAction() {
- Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
- }
- public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
- $id = V::get('ID', 0, $args, 'int');
- if ($id <= 0) throw new HttpException("404", 404);
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
- $response = new stdClass();
- $response->type = 'success';
- $response->msg = 'Funkcje';
- $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
- return $response;
- }
- public function editFormAction() {// namespace, _hash, _primaryKey
- try {
- $args = $_REQUEST;
- $id = V::get('_primaryKey', 0, $args, 'int');
- if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $tbl = $this->getTableAjaxWidget($acl);
- $tbl->sendAjaxEdit($id, $args);
- } catch (Exception $e) {
- DBG::log($e);
- throw $e;
- }
- }
- public function editFormJsonAction() {
- Response::sendTryCatchJson(array($this, 'editFormJson'), $args = $_REQUEST);
- }
- public function editFormJson($args) {// namespace, _hash, _primaryKey
- $id = V::get('_primaryKey', 0, $args, 'int');
- if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $tbl = $this->getTableAjaxWidget($acl);
- $record = $acl->buildQuery([])->getItem($id);
- if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) throw new Exception("Brak dostępu do rekordu");
- $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 ($acl->canReadObjectField($field['name'], $record)) {
- $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($acl->getID(), $record['ID'], $vCol['name'], $colValue);
- if (!empty($specialValues)) {
- $tsValues[$vColID] = implode('<br>', $specialValues);
- }
- }
- }
- }
- DBG::log($tsValues, 'array', "editFormJson::tsValues");
- foreach ($tsValues as $idx => $value) {
- if ('<' === substr($value, 0, 1)) {
- // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
- $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
- }
- }
- DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
- $featureFunctions = [
- // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
- 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
- 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
- // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
- 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
- ];
- $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
- 'id' => $record['ID'],
- 'functions' => $featureFunctions,
- 'showLabels' => true,
- 'viewMoreDropdown' => [
- 'primaryKey' => $record['ID'],
- 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
- ],
- ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
- $jsFields = [];
- $tabindex = 0;
- foreach ($fieldsList as $kID => $vCol) {
- $fieldName = $vCol['name'];
- if ($acl->canWriteObjectField($fieldName, $record)) {
- DBG::log("editFormJson::field({$fieldName})");
- $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
- if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
- $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
- [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
- [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label'] ],
- [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
- ] ],
- [ 'div', [ 'class' => "" ], [
- UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
- ] ]
- ] ];
- } else if ($acl->canReadObjectField($fieldName, $record)) {
- $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
- [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
- [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label']],
- [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
- ] ],
- [ 'div', [ 'class' => "" ], [
- ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
- (!empty($tsValues[$kID]))
- ? $tsValues[$kID]
- : V::get($fieldName, '', $record)
- ] ],
- ] ]
- ] ];
- } else {
- $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
- "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
- ]];
- }
- }
- $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
- [ 'div', [ 'class' => "" ], [
- ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
- ] ]
- ] ];
- $tblLabel = $acl->getNamespace();
- if ('default_db' == $acl->getSourceName()) {
- $tblLabel = array();
- $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
- if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
- if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
- if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
- $tblLabel = implode(" - ", $tblLabel);
- }
- $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
- $jsGui = [
- 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
- [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
- "Edycja rekordu Nr {$record['ID']}",
- [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
- ] ],
- [ 'P5UI__FeatureEditForm', [
- 'class' => "", 'action' => "", 'method' => "post",
- 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
- 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
- 'namespace' => $acl->getNamespace(),
- 'idRecord' => $record['ID'],
- 'tableLabelHtml' => $tblLabel,
- ], [
- [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
- ] ] // form
- ] ] // .container
- ];
- return [
- 'type' => "success",
- 'msg' => "Edycja rekordu nr {$id}",
- 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
- ];
- }
- public function editSaveAjaxAction() {
- Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function editSaveAjax($args) {
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $primaryKeyField = $acl->getPrimaryKeyField();
- $primaryKey = V::get('primaryKey', 0, $args, 'int');
- if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
- $item = $acl->getItem($primaryKey);
- if (!$item) throw new HttpException("Item not exists!", 404);
- $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
- $response = new stdClass();
- $response->primaryKey = $primaryKey;
- try {
- $itemFromUser[$primaryKeyField] = $primaryKey;
- $affected = $acl->updateItem($itemFromUser);
- 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 = $acl->getItem($primaryKey);
- $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
- if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = "Wystąpiły błędy!";
- $response->msg .= $e->getMessage();
- }
- return $response;
- }
- public function typeSpecialCellAction() {
- Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
- }
- public function typeSpecialCell($args) {
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $id = V::get('ID', 0, $args, 'int');
- $fieldName = V::get('col', '', $args);
- if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
- $col = $fieldName;// TODO: RM $col
- $jsonData = new stdClass();
- $idField = $acl->getFieldIdByName($fieldName);
- if (!$idField) throw new Exception("Wrong field");
- $item = $acl->getItem($id);
- if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
- $typeSpecial = Typespecial::getInstance($idField, $fieldName);
- if ($typeSpecial) {
- $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
- $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
- }
- return $jsonData;
- }
- /**
- * @param $_GET['namespace'] = AclNamespace
- * @param $_GET['format'] = 'csv' | 'html'
- * @param $_GET['flds'] = csv - coma separated field names
- * @param $_GET['sortCol'] = FieldName
- * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
- * @param $_GET['f_{$fieldName}'] = filter
- * @param $_GET['sf_{$fieldName}'] = force filter
- */
- public function exportAction() {
- $args = $_GET;
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $exportLimit = 10000;
- $params = array();
- $params['limit'] = $exportLimit;
- // $params['limitstart'] = 0;
- $params['order_by'] = V::get('sortCol', '', $args);
- $params['order_dir'] = V::get('sortDir', '', $args);
- $params['cols'] = array($acl->getPrimaryKeyField());
- $toExportFields = explode(',', V::get('flds', '', $_GET));
- if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
- $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
- foreach ($toExportFields as $fieldName) {
- if ($fieldName == $acl->getPrimaryKeyField()) continue;
- if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
- $params['cols'][] = $fieldName;
- }
- $labels = array();
- foreach ($toExportFields as $fieldName) {
- $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
- }
- 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;
- }
- }
- try {
- $queryFeatures = $acl->buildQuery($params);
- $total = $queryFeatures->getTotal();
- $listItems = $queryFeatures->getItems();
- $primaryKeyField = $acl->getPrimaryKeyField();
- $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
- } catch (Exception $e) {
- DBG::log($e);
- throw $e;
- }
- $format = V::get('format', 'html', $_GET);
- switch ($format) {
- case 'html': {
- UI::gora();
- echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
- UI::h('thead', [], [
- UI::h('tr', [], array_map(function ($label) {
- return UI::h('th', [], $label);
- }, $labels))
- ]),
- UI::h('tbody', [], array_map(function ($item) use($labels) {
- return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
- return UI::h('td', [], V::get($fieldName, '', $item));
- }, array_keys($labels)));
- }, $items)),
- ]);
- UI::dol();
- exit;
- }
- case 'csv_cp1250':
- case 'csv': {
- $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
- header('Content-Type: text/csv; charset=utf-8');
- header("Content-Disposition: attachment; filename={$csvFileName}.csv");
- $csvSeparator = ';';
- $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
- return '"' . addslashes($label) . '"';
- }, array_values($labels)));
- $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
- return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
- return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
- }, array_keys($labels)));
- }, $items));
- switch ($format) {
- case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
- case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
- die("Nieobsługiwane kodowanie danych csv.");
- }
- exit;
- }
- }
- die("Nieobsługiwany format danych.");
- }
- public function loadDataAjaxAction() {
- $namespace = V::get('namespace', '', $_REQUEST, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $tbl = $this->getTableAjaxWidget($acl);
- Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
- }
- public function uploadFilesAjaxAction() {
- Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
- }
- public function uploadFilesAjax($args) {
- DBG::log($_FILES, 'array', "\$_FILES");
- DBG::log($args, 'array', "\$args");
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new Exception("Missing namespace");
- $primaryKey = V::get('primaryKey', '', $args, 'int');
- if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
- if (empty($_FILES)) throw new Exception("Missing files");
- $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
- Lib::loadClass('FileUploader');
- Lib::loadClass('FoldersConfig');
- // $dbID = $acl->getDB();
- // $db = DB::getDB($dbID);
- // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
- $record = $acl->buildQuery([])->getItem($primaryKey);
- DBG::log($record, 'array', "\$record");
- if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
- if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
- if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
- $rootTableName = $acl->getRootTableName();
- $confTblName = "{$rootTableName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
- $folderConf = FoldersConfig::getAll($confTblName);
- DBG::log($folderConf, 'array', "\$folderConf");
- $uploader = new FileUploader($confTblName, (object)$record);
- if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
- $uploader->findFolder();
- DBG::log($uploader, 'array', "\$uploader");
- // $errorMsg = '';
- // if (!empty($args['SCANS_COLUMN_ADD'])) {
- // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
- // }
- // else {
- // $uploaded = $uploader->tryUploadAjax($errorMsg);
- // }
- $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
- DBG::log($destPath, 'array', "\$destPath");
- if (!file_exists($destPath)) {
- if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
- }
- $generateSafeFileName = function($path) {
- if (!file_exists($path)) return $path;
- $infoPath = pathinfo($path);
- // pathinfo('/path/t1/t2/fileName.ext') = [
- // [dirname] => /path/t1/t2
- // [basename] => fileName.ext
- // [extension] => ext
- // [filename] => fileName
- // ]
- return $infoPath['dirname'] . "/" . $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
- };
- $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
- return [
- $file['tmp_name'],
- $generateSafeFileName("{$destPath}/{$file['name']}"),
- $file['name'],
- ];
- }, $_FILES);
- DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
- $errorMsgs = [];
- $pkField = $acl->getSqlPrimaryKeyField();
- foreach ($moveActions as $fileMoveAction) {
- if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
- $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
- } else {
- try {
- $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
- 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
- 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
- 'A_RECORD_UPDATE_DATE' => 'NOW()',
- ]);
- if ($affected) {
- DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
- 'ID_USERS2' => $primaryKey,
- 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
- 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
- 'A_RECORD_UPDATE_DATE' => 'NOW()',
- ]);
- }
- } catch (Exception $e) {
- DBG::log($e);
- $errorMsgs[] = $e->getMessage();
- }
- }
- }
- if (!empty($errorMsgs)) {
- return [
- 'type' => "error",
- 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
- 'errors' => $errorMsgs,
- ];
- }
- return [
- 'type' => "success",
- 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
- ];
- }
- }
|