| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643 |
- <?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 {
- function getTableAjaxWidget($acl, $backRefFilter = [], $childRefFilter = []) {
- $syncUrl = $this->getLink('', [ 'namespace' => $acl->getNamespace() ]);
- $tbl = new TableAjax($acl);
- $tbl->setRootUrl($syncUrl);
- if (!empty($backRefFilter['namespace']) && !empty($backRefFilter['primaryKey'])) {
- $tbl->setBackRefFilter($backRefFilter);
- $syncUrl = $this->getLink('', [
- 'namespace' => $acl->getNamespace(),
- 'backRefNS' => $backRefFilter['namespace'],
- 'backRefPK' => $backRefFilter['primaryKey'],
- 'backRefField' => $backRefFilter['fieldName'],
- ]);
- }
- if (!empty($childRefFilter['namespace']) && !empty($childRefFilter['primaryKey'])) {
- $tbl->setChildRefFilter($childRefFilter);
- $syncUrl = $this->getLink('', [
- 'namespace' => $acl->getNamespace(),
- 'childRefNS' => $childRefFilter['namespace'],
- 'childRefPK' => $childRefFilter['primaryKey'],
- ]);
- }
- $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->showProcesInitFiltr = (Config::get('VIEW_TABLE_HIDE_PROCESS_LIST')) ? null : $this->getLink("procesInitFiltrAjax", [ 'namespace' => $acl->getNamespace() ]);
- $tbl->showTableTools = $this->getLink("tableToolsAjax", [ 'namespace' => $acl->getNamespace() ]);
- $tbl->useUserTableFilter = $this->getLink("getUserTableFilterAjax");
- $tbl->setLabel($tblLabel);
- if (Config::get('VIEW_TABLE_HIDE_BASE_ROW_FUNCTIONS')) {
- // dont show row functions column
- } else if (method_exists($acl, 'getGuiRowFunctions')) {
- foreach ($acl->getGuiRowFunctions() as $funKey => $funParams) {
- $tbl->addRowFunction($funKey, $funParams);
- }
- } else {
- $tbl->addRowFunction('edit');
- $tbl->addRowFunction('hist');
- $tbl->addRowFunction('files');
- $tbl->addRowFunction('cp');
- $tbl->addRowFunction('msgs');
- }
- return $tbl;
- }
- function defaultAction() {
- UI::gora();
- UI::menu();
- try {
- $this->defaultView();
- } catch (Exception $e) {
- UI::startContainer();
- UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
- UI::endContainer();
- DBG::log($e);
- }
- UI::dol();
- }
- function defaultView() {
- $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();
- $requestDataFilters = array();
- $filterInit = new stdClass();
- $filterInit->currSortCol = $acl->getPrimaryKeyField();
- $filterInit->currSortFlip = 'desc';
- foreach ($_REQUEST as $k => $v) {
- if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
- $requestDataFilters[$k] = $v;
- $filterInit->$k = $v;
- }
- else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
- $requestDataFilters[$k] = $v;
- $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;
- }
- }
- $backRefFilter = [
- 'namespace' => V::get('backRefNS', '', $_GET),
- 'primaryKey' => V::get('backRefPK', '', $_GET),
- 'fieldName' => V::get('backRefField', '', $_GET),
- ];
- $childRefFilter = [
- 'namespace' => V::get('childRefNS', '', $_GET),
- 'primaryKey' => V::get('childRefPK', '', $_GET),
- ];
- $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
- $lastDataFilters = $tbl->getFilters();
- DBG::log([
- '$requestDataFilters' => $requestDataFilters,
- '$lastDataFilters' => $lastDataFilters,
- ], 'array', "TODO:BUG?:filters");
- if (empty($lastDataFilters) && empty($requestDataFilters)) {
- DBG::log(['TODO: run setFilterInit', [
- 'currSortCol' => $acl->getPrimaryKeyField(),
- 'currSortFlip' => 'desc',
- ]], 'array', "TODO:BUG?:filters");
- $tbl->setFilterInit([
- 'currSortCol' => $acl->getPrimaryKeyField(),
- 'currSortFlip' => 'desc',
- ]);
- } else if (!empty($requestDataFilters)) {
- $tbl->setFilterInit($filterInit);
- }
- if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
- if (V::get('DBG_INST', '', $_GET)) { // TODO: TEST namespace
- $siblings = ACL::getNamespaceSiblings($namespace);
- DBG::nicePrint($siblings, '$siblings');
- $filtrInstance = V::get('f_instance', [], $_POST, 'array');
- DBG::nicePrint($filtrInstance, '$filtrInstance');
- $sibling = 'default_db/CRM_PROCES/PROCES_INIT'; DBG::nicePrint(array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'YES'], ('YES' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : []), "merge {$sibling} YES");
- $sibling = 'default_db/CRM_PROCES/PROCES_INIT'; DBG::nicePrint(array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'NO'], ('NO' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : []), "merge {$sibling} NO");
- $_ = array(UI, 'h');
- echo $_('form', ['method' => "POST", 'style' => "width:600px; border:1px solid #ddd; border-radius:2px"], [
- $_('div', ['style' => "background-color:#ddd"], "Test Filtr instancji"),
- $_('div', ['style' => "padding:8px"], array_map(function ($sibling) use ($filtrInstance, $_) {
- return $_('div', [], [
- $_('label', ['style' => "margin:0 8px"], [
- $_('input', array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'YES'], ('YES' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : [])),
- " TAK "
- ]),
- $_('label', ['style' => "margin:0 8px"], [
- $_('input', array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'NO'], ('NO' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : [])),
- " NIE "
- ]),
- $_('label', ['style' => "margin:0 8px"], [
- $_('input', ['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'x']),
- " pomiń "
- ]),
- // $_('button', ['onClick'=>"this.form.f_instance['{$sibling}'].value = ''; return false"], "odznacz"),
- $_('button', ['onClick'=>"console.log(this.form.elements['f_instance[{$sibling}]']); this.form.elements['f_instance[{$sibling}]'].value = 'x'; return false"], "odznacz"),
- " - {$sibling}"
- ]);
- }, $siblings)),
- $_('div', [], [
- $_('input', ['type'=>"hidden", 'name'=>'_route', 'value'=>"ViewObject"]),
- $_('input', ['type'=>"hidden", 'name'=>'namespace', 'value'=>$namespace]),
- $_('input', ['type'=>"submit", 'value'=>"Filtruj - TEST"]),
- ]),
- ]);
- DBG::nicePrint($_POST, '$_POST');
- {
- $args = $_POST;
- $fIsInstance = [];
- $fIsNotInstance = [];
- if (!empty($args['f_instance'])) {
- foreach ($args['f_instance'] as $inst => $selected) {
- if ('YES' === $selected) {
- $fIsInstance[] = $inst;
- } else if ('NO' === $selected) {
- $fIsNotInstance[] = $inst;
- }
- }
- }
- }
- $queryFeatures = $acl->buildQuery([
- // TODO: 'propertyName' => "*,@instance",
- 'f_is_instance' => $fIsInstance,
- 'f_is_not_instance' => $fIsNotInstance,
- '@instances' => '1',
- 'limit' => 10
- ]);
- // $total = $queryFeatures->getTotal();
- $items = $queryFeatures->getItems();
- $rootNamespace = $acl->getRootNamespace();
- DBG::nicePrint($rootNamespace, '$rootNamespace');
- $jsRenderFunName = 'render_dropdown_instances_' . substr(md5(time()), 0, 6);
- DBG::nicePrint($jsRenderFunName, '$jsRenderFunName');
- UI::table([
- 'rows' => array_map(function($row) use ($namespace, $siblings, $rootNamespace, $jsRenderFunName) {
- return [
- 'ID' => $row['ID'],
- 'DESC' => $row['DESC'],
- 'TYPE' => $row['TYPE'],
- 'Typ' => UI::h('div', ['class'=>"p5UI__dropdown-wrap"], [
- UI::h('button', [
- // 'onClick' => "p5UI__dropdown(event, this, 'left bottom')",
- 'onClick' => "p5UI__dropdown(event, this, 'left bottom', {$jsRenderFunName}({$row['ID']}))",
- 'class' => "btn btn-xs btn-default p5UI__dropdown-btn"
- ], [
- UI::h('i', ['class' => "glyphicon glyphicon-tags", 'title' => "Ustaw typ danych (instancje)"]),
- ]),
- UI::h('div', ['class' => "p5UI__dropdown-content"]
- , array_merge(
- [
- UI::h('input', ['type' => "text", 'placeholder' => "Search..", 'class' => "p5UI__dropdown-input", 'onkeyup' => "p5_ViewObject_instances_filterInput(this)"], null),
- ]
- , array_map(function ($sibling) use ($row, $namespace, $rootNamespace) {
- return UI::h('div', ['label'=>$sibling, 'style'=>"padding:4px 0"], [
- UI::h('button', array_merge(['class' => "btn btn-xs btn-default",
- 'style' => "margin:0 4px 0 0",
- 'title' => "Ustaw instancje '{$sibling}'",
- 'onClick' => "return p5_ViewObject_instance_set(this, '{$row['ID']}', '{$sibling}', 'yes')"],
- (in_array($sibling, explode(',', $row['@instances']))) ? ['disabled' => "disabled"] : []
- ), "+"),
- UI::h('button', ['class' => "btn btn-xs btn-default",
- 'style' => "margin:0 4px 0 0",
- 'title' => "Usuń instancje '{$sibling}'",
- 'onClick' => "return p5_ViewObject_instance_set(this, '{$row['ID']}', '{$sibling}', 'no')"], "-"),
- UI::h('span', [], substr($sibling, strlen($rootNamespace) + 1)),
- ]);
- }, $siblings)
- )
- )
- ]),
- 'instancesList' => implode(', ', ACL::getFeatureNamespaces($namespace, $row['ID'])),
- ];
- }, $items)
- ]);
- echo UI::h('style', ['type' => "text/css"], "
- .p5UI__dropdown-content { min-width:400px; border:1px solid #ccc; background-color: #fff; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2) }
- .p5UI__dropdown-content .p5UI__dropdown-item { display:block; color:#000; padding:4px; text-decoration:none }
- .p5UI__dropdown-content .p5UI__dropdown-item:hover { background-color:#ebebeb }
- ");
- echo UI::h('script', ['src'=>"static/vendor.js?v=816e859d", 'type'=>"text/javascript"]);
- $jsArgs = [
- 'SET_INSTANCE_URL' => $this->getLink('setInstanceAjax'),
- 'NAMESPACE' => $namespace,
- 'DBG' => DBG::isActive() ? 'true' : 'false',
- ];
- UI::inlineJS(__FILE__ . '.instancesDropdown.js', [
- 'JS_GLOBAL_FUNCTION_NAME' => $jsRenderFunName,
- 'NAMESPACE' => $namespace,
- 'SET_INSTANCE_URL' => $this->getLink('setInstanceAjax'),
- 'DBG' => DBG::isActive() ? 1 : 0,
- 'INITIAL_DROPDOWN_DATA' => [
- // 'allowed_instances' => $siblings,
- 'allowed_instances' => array_map(function ($sibling) use ($rootNamespace) {
- return [
- 'namespace' => $sibling,
- 'label' => substr($sibling, strlen($rootNamespace) + 1)
- ];
- }, $siblings),
- 'items' => array_map(function($row) use ($namespace, $siblings, $rootNamespace, $jsRenderFunName) {
- return [
- 'pk' => $row['ID'], // TODO: $primaryKeyField
- 'instances' => explode(',', $row['@instances']),
- ];
- }, $items)
- ],
- ]);
- echo UI::h('script', [], "
- var SET_INSTANCE_URL = '{$jsArgs['SET_INSTANCE_URL']}'
- var NAMESPACE = '{$jsArgs['NAMESPACE']}'
- function p5_ViewObject_instance_set(n, pk, sibling, toConnect) {
- console.log('p5_ViewObject_instance_set pk('+pk+'), sibling('+sibling+'), toConnect('+toConnect+'), n', n);
- window.fetch(SET_INSTANCE_URL, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'same-origin',
- body: JSON.stringify({
- namespace: NAMESPACE,
- primaryKey: pk,
- instance: sibling,
- toConnect: toConnect,
- })
- }).then(function (response) {
- return response.json()
- }).then(function (response) {
- p5UI__notifyAjaxCallback(response)
- console.log(response) // TODO: render list
- })
- }
- ");
- echo UI::h('script', [], "
- function p5_ViewObject_instances_filterInput(n) {
- var input, filter, ul, li, a, i, div;
- input = n // .id-myInput
- filter = input.value.toUpperCase()
- div = n.parentNode // .id-myDropdown
- a = div.getElementsByTagName('div')
- for (i = 0; i < a.length; i++) {
- if (a[i].getAttribute('label') && a[i].getAttribute('label').toUpperCase().indexOf(filter) > -1) {
- a[i].style.display = 'block'
- } else {
- a[i].style.display = 'none'
- }
- }
- }
- ");
- echo '<hr style="margin-top:300px">';
- exit;
- }
- 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();
- }
- }
- public function setInstanceAjaxAction() {
- Response::sendTryCatchJson(array($this, 'setInstanceAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function setInstanceAjax($args) {
- // namespace => default_db/CRM_PROCES/PROCES_INIT
- // primaryKey => 6
- // instance => default_db/CRM_PROCES/PROCES_TREE
- // toConnect => yes
- if (empty($args['namespace'])) throw new Exception("Missing namespace");
- if (empty($args['primaryKey'])) throw new Exception("Missing primaryKey");
- if (empty($args['instance'])) throw new Exception("Missing instance");
- if (empty($args['toConnect'])) throw new Exception("Missing toConnect");
- if (!in_array($args['toConnect'], ['yes', 'no'])) throw new Exception("Wrong param toConnect");
- $idInstance = ACL::getInstanceId($args['instance']);
- throw new Exception("TODO: check instance config"); // if 'view' then set instance is not allowed
- // $instanceTable = ACL::getInstanceTable($args['namespace']);
- // switch ($args['toConnect']) {
- // case 'yes': {
- // // TODO: _HIST info - waiting
- // $ret = DB::getPDO()->execSql("
- // insert into `{$instanceTable}` (`pk`, `idInstance`)
- // values ( :pk , :idInstance )
- // ", [
- // 'pk' => $args['primaryKey'],
- // 'idInstance' => $idInstance,
- // ]);
- // // TODO: _HIST info - mark as done
- // } break;
- // case 'no': {
- // // TODO: _HIST info - waiting
- // $ret = DB::getPDO()->execSql("
- // delete from `{$instanceTable}`
- // where `pk` = :pk
- // and `idInstance` = :idInstance
- // ", [
- // 'pk' => $args['primaryKey'],
- // 'idInstance' => $idInstance,
- // ]);
- // // TODO: _HIST info - mark as done
- // } break;
- // }
- // return [
- // 'type' => 'success',
- // 'msg' => "Wprowadzono zmiany ({$ret})",
- // // TODO: 'data' => all instances for pk
- // ];
- }
- 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 getCsvTheGeomAjaxAction() {
- try {
- self::getCsvTheGeomAjax();
- } catch (Exception $e) {
- UI::gora();
- UI::menu();
- UI::alert('danger', $e->getMessage());
- echo UI::h('div', [ 'style' => "text-align:center" ], [
- UI::h('a', [ 'href' => $_SERVER['HTTP_REFERER'], 'class' => "btn btn-primary", 'style' => "width:80px" ], "Powrót"),
- ]);
- UI::dol();
- }
- }
- public function getCsvTheGeomAjax($minDistance = 10, $nearDistance = 1) {
- Lib::loadClass('EpsgConversion');
- Lib::loadClass('Geometry');
- $namespace = V::get('namespace', '', $_GET, 'word');
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $table = $acl->getRootTableName();
- $id = V::get('id', 0, $_GET, 'int');
- $query_points = "select st_astext(`the_geom`) as `the_geom` from `{$table}` where `ID` = {$id}";
- $result_points = DB::getPDO()->fetchValue($query_points);
- $points = Geometry::objectFromText($result_points, 'Wgs84ToPuwg2000')->points();
- $lines = Geometry::pointsToLines($points);
- // Dodanie początkowego punktu pierwszej linii do tabeli wszystkcih punktów
- $_points = [['point' => $points[0], 'type' => ['p']]];
- // Szukanie kolzji dla każdej linii prostej
- foreach ($lines as $line) {
- $polygon_asText = Geometry::lineToRectangle($line, $nearDistance)->asText('Puwg2000ToWgs84');
- $query_nears = "select st_astext(`the_geom`) as `the_geom` from `rurociagi_obce_wsg84` where st_intersects(st_geomfromtext('{$polygon_asText}'), `the_geom`)";
- $results_nears = DB::getPDO()->fetchAll($query_nears);
- $nears = [];
- foreach ($results_nears as $result_nears) {
- $nears = array_merge($nears, Geometry::pointsToLines(Geometry::objectFromText($result_nears['the_geom'], 'Wgs84ToPuwg2000')->points()));
- }
- $nears = array_filter($nears, function ($near) use ($line, $nearDistance) {
- return Geometry::distance($line, $near) <= $nearDistance;
- });
- // Szukanie odcinków kolizyjnych
- $crossPoints = [];
- $_nearsOnLine = [];
- foreach ($nears as $near) {
- if ($_crossPoints = Geometry::crossPoint($line, $near)) {
- switch (count($_crossPoints)) {
- case 1:
- // Znaleziono kolizję przecinającą linię
- $crossPoints[] = ['point' => $_crossPoints[0], 'type' => ['x']];
- break;
- case 2:
- // Znaleziono kolizję idealnie nałożoną na linię
- $_nearsOnLine[] = Geometry::line($_crossPoints[0], $_crossPoints[1]);
- break;
- default:
- throw new Exception(__CLASS__ . "::" . __FUNCTION__ . ' - unknown error');
- }
- }
- // Analiza pobliskich kolizji
- $a = Geometry::closedPointOnLine($near->a, $line);
- $b = Geometry::closedPointOnLine($near->b, $line);
- if (Geometry::distance($a, $line->a) < Geometry::distance($b, $line->a)) $nearOnLine = Geometry::line($a, $b);
- else $nearOnLine = Geometry::line($b, $a);
- // Weryfikacja czy pobliska kolizja nie jest jednocześnie kolizją przecinajacą i czy nie jest za krótka (<1m) - wtedy ją usuwamy
- $add = true;
- if ($nearOnLine->length() < 1) {
- foreach ($crossPoints as $crossPoint) {
- if (Geometry::distance($crossPoint['point'], $nearOnLine) == 0) {
- $add = false;
- break;
- }
- }
- }
- if ($add) $_nearsOnLine[] = $nearOnLine;
- }
- // Przesortowanie wszystkich kolizji linowych
- usort($_nearsOnLine, function ($A, $B) use ($line) {
- if (Geometry::samePoint($A->a, $B->a)) return 0;
- if (Geometry::distance($A, $line->a) < Geometry::distance($B, $line->a)) return -1;
- return 1;
- });
- // Scalenie wszystkich kolizji jeżeli odstęp między nimi jest krótszy niz 1m
- $lastNearOnLine = null;
- $nearsOnLine = [];
- foreach ($_nearsOnLine as $nearOnLine) {
- if ($lastNearOnLine) {
- if (Geometry::distance($nearOnLine, $lastNearOnLine) < 1) {
- $nearOnLine->a = $lastNearOnLine->a;
- if (Geometry::distance($nearOnLine->b, $line->a) < Geometry::distance($lastNearOnLine->b, $line->a)) $nearOnLine->b = $lastNearOnLine->b;
- } else $nearsOnLine[] = $lastNearOnLine;
- }
- $lastNearOnLine = $nearOnLine;
- }
- if ($lastNearOnLine) $nearsOnLine[] = $lastNearOnLine;
- // Nałożenie kolizji liniowych na punkty kolizyjne
- foreach ($nearsOnLine as $nearOnLine) {
- $crossPoints[] = ['point' => $nearOnLine->a, 'type' => ['iistart']];
- $crossPoints[] = ['point' => $nearOnLine->b, 'type' => ['iistop']];
- }
- // Podzielenie linii prostej na krótsze odcinki, jezeli jest zbyt długa (>$minDistance)
- if (($distance = $line->length()) > $minDistance) {
- $parts = ceil($distance / $minDistance);
- $deltaX = ($line->b->x - $line->a->x) / $parts;
- $deltaY = ($line->b->y - $line->a->y) / $parts;
- for ($j = 1; $j < $parts; $j++) {
- $_point = Geometry::point($line->a->x + $j * $deltaX, $line->a->y + $j * $deltaY);
- $collision = false;
- foreach ($nearsOnLine as $nearOnLine) {
- if (Geometry::distance($nearOnLine, $_point) == 0) {
- $collision = true;
- break;
- }
- }
- $type = ['m'];
- if ($collision) $type[] = 'ii';
- $crossPoints[] = ['point' => Geometry::point($line->a->x + $j * $deltaX, $line->a->y + $j * $deltaY), 'type' => $type];
- }
- }
- // Przesortowanie wszystkich punktów na linii
- usort($crossPoints, function ($a, $b) use ($line) {
- if (Geometry::samePoint($a['point'], $b['point'])) return 0;
- if (Geometry::distance($a['point'], $line->a) < Geometry::distance($b['point'], $line->a)) return -1;
- return 1;
- });
- // Dodanie wszystkich punktów kolizyjnych i pośrednich do tabeli wszystkich punktów
- foreach ($crossPoints as $crossPoint) $_points[] = ['point' => $crossPoint['point'], 'type' => $crossPoint['type']];
- // Dodanie końcowego punktu linii do tabeli wszystkich punktów
- $_points[] = ['point' => $line->b, 'type' => ['p']];
- }
- // Scalenie pobliskich kolizji występujących na różnych liniach
- $starts = array_keys(array_filter($_points, function($point) { return in_array('iistart', $point['type']); }));
- $stops = array_keys(array_filter($_points, function($point) { return in_array('iistop', $point['type']); }));
- $points = array_keys(array_filter($_points, function($point) { return in_array('p', $point['type']); }));
- foreach ($stops as $i) {
- if (in_array($i+1, $points) && in_array($i+2, $starts)) {
- if (Geometry::distance($_points[$i]['point'], $_points[$i+1]['point']) + Geometry::distance($_points[$i+1]['point'], $_points[$i+2]['point']) < 1) {
- unset($_points[$i]);
- unset($_points[$i + 2]);
- $_points[$i + 1]['type'][] = 'ii';
- }
- }
- }
- // Połączenie kilku takich samych punktów w jeden punkt (np. punkt początku linii oraz punkt początku kolizji - gdy wypadają w tym samym miejscu)
- $points = [];
- $lastPoint = null;
- $desc = [];
- foreach ($_points as $point) {
- if ($lastPoint) {
- if (Geometry::samePoint($point['point'], $lastPoint['point'])) $point['type'] = array_merge($lastPoint['type'], $point['type']);
- else $points[] = $lastPoint;
- }
- $lastPoint = $point;
- }
- if ($lastPoint) $points[] = $lastPoint;
- // Funkcja generująca czytelny opis rodzaju punktu
- $typeToDesc = function($type) {
- if (in_array('iistart', $type) && in_array('iistop', $type)) {
- $type = array_diff($type, ['iistart', 'iistop']);
- $type[] = 'ii';
- }
- usort($type, function($a, $b) {
- if ($a == 'p' || $a == 'm') return -1;
- if ($b == 'p' || $b == 'm') return 1;
- return 0;
- });
- return implode('|', array_map(function($_type) {
- $types = [
- 'p' => 'Punkt',
- 'm' => 'Posredni',
- 'x' => 'Kolizja (X)',
- 'ii' => 'Kolizja (II)',
- 'iistart' => 'Kolizja (II) start',
- 'iistop' => 'Kolizja (II) stop'
- ];
- if (isset($types[$_type])) return $types[$_type];
- throw new Exception("Nieznany typ punktu - {$_type} (" . __CLASS__ . '::' . __FUNCTION__ . ')');
- }, $type));
- };
- // Generowanie pliku CSV
- $csv = implode("\n", array_map(function ($point, $i) use ($typeToDesc) {
- try {
- $z = EpsgConversion::GetZByPuwg2000($point['point']->x, $point['point']->y);
- } catch (Exception $e) {
- $z = 0;
- }
- return $i . "," . round($point['point']->y, 3) . "," . round($point['point']->x, 3) . "," . round($z, 3) . "," . $typeToDesc($point['type']);
- }, $points, range(1, count($points))));
- // echo "<pre>{$csv}</pre>";
- Response::sendCsv($csv, "{$table}.{$id}");
- }
- 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 createFormAction() {// TODO: move to createFormJsonAction
- try {
- $args = $_REQUEST;
- $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->sendAjaxCreate();
- } catch (Exception $e) {
- DBG::log($e);
- throw $e;
- }
- }
- public function createFormJsonAction() {
- Response::sendTryCatchJson(array($this, 'createFormJson'), $args = $_REQUEST);
- }
- public function createFormJson($args) { // namespace, _hash, _primaryKey
- $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);
- if (!Core_AclHelper::hasCreatePerms($acl)) {
- return [
- 'type' => "success",
- 'msg' => "Dodaj nowy rekord",
- 'body' => [
- 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak uprawnień do utworzenia nowego rekordu." ]
- ],
- ];
- // throw new Exception("Brak uprawnień do utworzenia nowego 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();
- $forceFilterInit = array();
- $defaultAclGroup = User::getDefaultAclGroup();
- if ($defaultAclGroup) {
- $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
- $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
- }
- foreach ($_GET as $k => $v) { // TODO: read from $args ?
- if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
- $fldName = substr($k, 3);
- $forceFilterInit[$fldName] = $v;
- }
- }
- DBG::log($forceFilterInit, 'array', "\$forceFilterInit");
- foreach ($fieldsList as $kID => $field) {
- $defaultValue = '';
- if (!empty($forceFilterInit[$field['name']])) {
- $defaultValue = $forceFilterInit[$field['name']];
- }
- $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
- }
- DBG::log($cols, 'array', "\$cols - field values");
- $tsValues = array();
- $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" ],
- ];
- $jsFields = [];
- $tabindex = 0;
- foreach ($fieldsList as $kID => $vCol) {
- $fieldName = $vCol['name'];
- $fieldLabel = str_replace('<br>', ' ', $vCol['label']);
- DBG::log(['$fieldName'=>$fieldName, 'canCreate'=>$acl->canCreateField($fieldName)], 'array', "form field");
- if ($acl->canCreateField($fieldName)) {
- 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'] ], $fieldLabel ],
- [ '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, 'C', $kID, "f{$kID}", $cols[$kID], $fieldParams),
- ] ]
- ] ];
- // } 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" ] ], [
- "Dodaj nowy rekord",
- ] ],
- [ 'P5UI__FeatureCreateForm', [
- 'class' => "", 'action' => "", 'method' => "post",
- 'id' => "CREATE_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
- 'ajaxSaveUrl' => "{$syncUrl}&_task=createSaveAjax", // TODO:? &_hash={$this->_htmlID}
- 'ajaxSaveLegacyUrl' => "{$syncUrl}&_task=createSaveLegacy", // TODO: Legacy RM
- 'namespace' => $acl->getNamespace(),
- 'tableLabelHtml' => $tblLabel,
- '_htmlID' => $acl->getName(),
- ], [
- [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
- ] ] // form
- ] ] // .container
- ];
- return [
- 'type' => "success",
- 'msg' => "Dodaj nowy rekord",
- 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
- ];
- }
- public function createSaveAjaxAction() {
- Response::sendTryCatchJson(array($this, 'createSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function createSaveAjax($args) {
- throw new Exception("TODO: ...");
- }
- public function createSaveLegacyAction() { // TODO: Legacy RM
- $args = [
- 'namespace' => V::get('namespace', '', $_GET),
- 'body' => Request::getRequestJson(),
- ];
- DBG::log($args, 'array', 'createSaveLegacyAction');
- Response::sendTryCatchJson(array($this, 'createSaveLegacy'), $args);
- }
- public function createSaveLegacy($args) { // TODO: Legacy RM
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $body = V::get('body', null, $args);
- if (!$body) throw new HttpException("Bad Request - missing body", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $tbl = $this->getTableAjaxWidget($acl);
- DBG::log($args, 'array', "ajaxCreateSave");
- $createdId = null;
- try {
- $item = $acl->convertObjectFromUserInput($body, $type = 'array_by_id', $prefix = 'f');
- $createdId = $acl->addItem($item);
- if ($createdId) {
- return [
- 'type' => 'success',
- 'msg' => "Utworzono pomyślnie rekord nr {$createdId}",
- 'id' => $createdId,
- 'record' => $acl->buildQuery([])->getItem($createdId),
- ];
- }
- else {
- return [
- 'type' => 'error',
- 'msg' => "Nie udało się utworzyć nowego rekordu!",
- ];
- }
- }
- catch (Exception $e) {
- return [
- 'type' => 'error',
- 'msg' => $e->getMessage(),
- ];
- }
- }
- public function editFormAction() { // TODO: not used - moved to editFormJsonAction
- 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()) {
- return [
- 'type' => "success",
- 'msg' => "Edycja rekordu nr {$id}",
- 'body' => [
- 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak dostępu do rekordu" ]
- ],
- ];
- // 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[ $acl->getPrimaryKeyField() ],
- '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'];
- $fieldLabel = str_replace('<br>', ' ', $vCol['label']);
- DBG::log(['$fieldName'=>$fieldName, '$record'=>$record, 'canWrite'=>$acl->canWriteObjectField($fieldName, $record), 'canRead'=>$acl->canReadObjectField($fieldName, $record)], 'array', "form field");
- 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'] ], $fieldLabel ],
- [ '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'] ], $fieldLabel ],
- [ '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;
- }
- public function typespecialAction() { Response::sendTryCatchJson(array($this, 'typespecial'), $args = $_REQUEST); }
- public function typespecial($args) { // @required idField, @optional: q (query), selected (selected value), idRecord (fetch value for given record)
- $idField = V::get('idField', 0, $args, 'int');
- if (!$idField) throw new HttpException("Bad Request - missing idField", 400);
- $query = V::get('q', '', $_REQUEST);
- DBG::log("\$query({$query})");
- $cellInfo = DB::getPDO()->fetchFirst("
- select *
- from CRM_PROCES_idx_TABLES_INFO_VIEW
- where ID_CELL = :id
- ", [ ':id' => $idField ]);
- DBG::log($cellInfo, 'array', "cell info");
- if (!$cellInfo) throw new HttpException("Bad Request - wrong idField", 400);
- // 'ID_CELL' => '24310',
- // 'CELL_NAME' => 'L_APPOITMENT_USER',
- // 'CELL_LABEL' => 'Osoba odpowiedzialna',
- // 'CELL_DESCRIPTION' => '',
- // 'CELL_SORT_PRIO' => '3',
- // 'ID_TABLE' => '13051',
- // 'TABLE_NAME' => 'TEST_PERMS',
- // 'TABLE_LABEL' => 'Test permy',
- // 'TABLE_DESCRIPTION' => '',
- // 'ID_DATABASE' => '36',
- $namespace = (false !== strpos($cellInfo['TABLE_NAME'], '/')) ? $cellInfo['TABLE_NAME'] : "default_db/{$cellInfo['TABLE_NAME']}";
- if (!$namespace) throw new HttpException("Bad Request - wrong idField, cannot find namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $fieldName = $cellInfo['CELL_NAME'];
- $jsonData = array();
- $typeSpecial = Typespecial::getInstance($idField, $fieldName);
- if ($typeSpecial) {
- // if (idRecord or selected) { // TODO
- // $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
- // $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
- $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;
- }
- }
- return $jsonData;
- }
- function exportAction() {
- Router::getRoute('ExportTableAjax')->defaultAction();
- }
-
- public function loadDataAjaxAction() {
- $namespace = V::get('namespace', '', $_REQUEST, 'word');
- if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
- $acl = Core_AclHelper::getAclByNamespace($namespace);
- $backRefFilter = [
- 'namespace' => V::get('backRefNS', '', $_REQUEST),
- 'primaryKey' => V::get('backRefPK', '', $_REQUEST),
- 'fieldName' => V::get('backRefField', '', $_REQUEST),
- ];
- $childRefFilter = [
- 'namespace' => V::get('childRefNS', '', $_GET),
- 'primaryKey' => V::get('childRefPK', '', $_GET),
- ];
- $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
- 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(ini_get("upload_max_filesize"), 'array', "ini_get('upload_max_filesize')");
- DBG::log(ini_get("post_max_size"), 'array', "ini_get('post_max_size')");
- 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($destPath, $fileName) {
- if (!file_exists("{$destPath}/{$fileName}")) return $fileName;
- $infoPath = pathinfo($fileName);
- // pathinfo('/path/t1/t2/fileName.ext') = [
- // [dirname] => /path/t1/t2
- // [basename] => fileName.ext
- // [extension] => ext
- // [filename] => fileName
- // ]
- return $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
- };
- $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
- $safeName = $generateSafeFileName($destPath, $file['name']);
- return [
- $file['tmp_name'], // TODO: BUG when empty? file size limit!
- "{$destPath}/{$safeName}",
- $safeName,
- ];
- }, $_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}'",
- ];
- }
- public function removeFileAjaxAction() {
- Response::sendTryCatchJson([$this, 'removeFileAjax'], $args = $_REQUEST);
- }
- public function removeFileAjax($args) { // ajaxFileRemove
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new Exception("Missing namespace");
- $id = V::get('ID', 0, $args, 'int');
- if ($id <= 0) throw new Exception("Missing ID");
- $filename = V::get('filename', '', $args);
- if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
- $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
- $dbID = $acl->getDB();
- $db = DB::getPDO($dbID);
- if (!$db) throw new HttpException("No DB ({$dbID})", 406);
- $record = $acl->buildQuery([])->getItem($id);
- if (!$record) throw new HttpException("No item ID({$id})", 404);
- if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
- if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
- Lib::loadClass('FileUploader');
- Lib::loadClass('FoldersConfig');
- $tblName = $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);
- // $affected = DB::getPDO($acl->getDB())->update();
- $rootTableName = $acl->getRootTableName();
- $pkField = $acl->getSqlPrimaryKeyField();
- $primaryKey = $id;
- try {
- $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
- 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
- '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' => "Usunięto plik '{$filename}'",
- 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
- 'A_RECORD_UPDATE_DATE' => 'NOW()',
- ]);
- }
- } catch (Exception $e) {
- DBG::log($e);
- }
- return [
- 'type' => 'success',
- 'msg' => 'Plik został usunięty',
- ];
- }
- public function procesInitFiltrAjaxAction() {
- Response::sendTryCatchJson([$this, 'procesInitFiltrAjax'], $args = $_GET);
- }
- public function procesInitFiltrAjax($args) { // ajaxFileRemove
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new Exception("Missing namespace");
- $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
- $pInitList = User::getAcl()->getTableProcesInitList($acl->getID());
- DBG::log($pInitList, 'array', "\$pInitList");
- if (!empty($pInitList)) {
- $procesIds = array_keys($pInitList);
- $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
- DBG::log($mapTree, 'array', "\$mapTree");
- DBG::log($pInitList, 'array', "\$pInitList");
- $pInitListSelected = User::getAcl()->getPermsFiltrProcesId();
- return [
- 'type' => 'success',
- 'msg' => 'ok',
- 'pInitData' => [
- 'pInitList' => $pInitList,
- 'mapTree' => $mapTree,
- 'pInitListSelected' => $pInitListSelected,
- ],
- ];
- }
- return [
- 'type' => 'success'
- ];
- }
- public function tableToolsAjaxAction() {
- Response::sendTryCatchJson([$this, 'tableToolsAjax'], $args = $_GET);
- }
- public function tableToolsAjax($args) { // ajaxFileRemove
- $namespace = V::get('namespace', '', $args, 'word');
- if (!$namespace) throw new Exception("Missing namespace");
- $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
- $listUrlFunctions = Route_UrlAction::getObjectTools($acl->getID(), User::getLogin());
- DBG::log($listUrlFunctions, 'array', "\$listUrlFunctions");
- $listUrlFunctions = array_map(function ($urlFunction) use ($namespace) {
- if ('index.php?' === substr($urlFunction['baseLink'], 0, strlen('index.php?'))) $urlFunction['baseLink'] .= "&_fromNamespace={$namespace}";
- return $urlFunction;
- }, $listUrlFunctions);
- return [
- 'type' => "success",
- 'msg' => 'ok',
- 'body' => [
- 'tableTools' => array_values(array_map(function ($urlFunction) {
- return [
- 'url' => $urlFunction['baseLink'],
- 'label' => $urlFunction['label'],
- // TODO: $urlFunction['link_target'] // "_blank"
- // ? $urlFunction['name']
- ];
- }, array_filter($listUrlFunctions, function ($urlFunction) {
- return empty($urlFunction['cell_id_params']);
- }))),
- ],
- ];
- }
- function executeRowFunctionAction() { UI::layout([ $this, 'executeRowFunction' ]); }
- function executeRowFunction() {
- $namespace = V::get('namespace', '', $_GET);
- $name = V::get('name', '', $_GET);
- $pk = V::get('pk', '', $_GET);
- if (!$namespace) throw new Exception("Missing namespace");
- if (!$name) throw new Exception("Missing name");
- if (!$pk) throw new Exception("Missing pk");
- $acl = ACL::getAclByNamespace($namespace);
- if (!method_exists($acl, 'executeGuiRowFunction')) throw new Exception("Function executeGuiRowFunction not defined for '{$namespace}'");
- $acl->executeGuiRowFunction($name, $pk);
- }
- }
|