ViewTableAjax.php 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('ProcesHelper');
  4. Lib::loadClass('TableAjax');
  5. // Lib::loadClass('Request');
  6. Lib::loadClass('Response');
  7. Lib::loadClass('UI');
  8. Lib::loadClass('Api_WfsNs');
  9. Lib::loadClass('Core_AclHelper');
  10. Lib::loadClass('Route_UrlAction');
  11. Lib::loadClass('Router');
  12. Lib::loadClass('Typespecial');
  13. Lib::loadClass('UserProfile');
  14. class Route_ViewTableAjax extends RouteBase {
  15. function getTableAjaxWidget($acl, $backRefFilter = [], $childRefFilter = []) {
  16. $syncUrl = $this->getLink('', [ 'namespace' => $acl->getNamespace() ]);
  17. $tbl = new TableAjax($acl);
  18. $tbl->setRootUrl($syncUrl);
  19. if (!empty($backRefFilter['namespace']) && !empty($backRefFilter['primaryKey'])) {
  20. $tbl->setBackRefFilter($backRefFilter);
  21. $syncUrl = $this->getLink('', [
  22. 'namespace' => $acl->getNamespace(),
  23. 'backRefNS' => $backRefFilter['namespace'],
  24. 'backRefPK' => $backRefFilter['primaryKey'],
  25. 'backRefField' => $backRefFilter['fieldName'],
  26. ]);
  27. }
  28. if (!empty($childRefFilter['namespace']) && !empty($childRefFilter['primaryKey'])) {
  29. $tbl->setChildRefFilter($childRefFilter);
  30. $syncUrl = $this->getLink('', [
  31. 'namespace' => $acl->getNamespace(),
  32. 'childRefNS' => $childRefFilter['namespace'],
  33. 'childRefPK' => $childRefFilter['primaryKey'],
  34. ]);
  35. }
  36. $tblLabel = $acl->getNamespace();
  37. if ('default_db' == $acl->getSourceName()) {
  38. $tblLabel = array();
  39. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  40. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  41. if (!empty($zasobObj->DESC_PL)) $tblLabel[] = $zasobObj->DESC_PL;
  42. if (!empty($zasobObj->OPIS)) $tblLabel[] = $zasobObj->OPIS;
  43. $tblLabel = implode(" - ", $tblLabel);
  44. }
  45. $tbl->setSyncUrl($syncUrl);
  46. $tbl->showProcesInitFiltr = (Config::get('VIEW_TABLE_HIDE_PROCESS_LIST')) ? null : $this->getLink("procesInitFiltrAjax", [ 'namespace' => $acl->getNamespace() ]);
  47. $tbl->showTableTools = $this->getLink("tableToolsAjax", [ 'namespace' => $acl->getNamespace() ]);
  48. $tbl->useUserTableFilter = $this->getLink("getUserTableFilterAjax");
  49. $tbl->setLabel($tblLabel);
  50. if (Config::get('VIEW_TABLE_HIDE_BASE_ROW_FUNCTIONS')) {
  51. // dont show row functions column
  52. } else if (method_exists($acl, 'getGuiRowFunctions')) {
  53. foreach ($acl->getGuiRowFunctions() as $funKey => $funParams) {
  54. $tbl->addRowFunction($funKey, $funParams);
  55. }
  56. } else {
  57. $tbl->addRowFunction('edit');
  58. $tbl->addRowFunction('hist');
  59. $tbl->addRowFunction('files');
  60. $tbl->addRowFunction('cp');
  61. $tbl->addRowFunction('msgs');
  62. }
  63. return $tbl;
  64. }
  65. function defaultAction() {
  66. UI::gora();
  67. UI::menu();
  68. try {
  69. $this->defaultView();
  70. } catch (Exception $e) {
  71. UI::startContainer();
  72. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  73. UI::endContainer();
  74. DBG::log($e);
  75. }
  76. UI::dol();
  77. }
  78. function defaultView() {
  79. $namespace = V::get('namespace', '', $_GET, 'word');
  80. if (!$namespace) {
  81. $typeName = V::get('typeName', '', $_GET, 'word');
  82. if (!$typeName) throw new Exception("Wrong param typeName");
  83. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  84. }
  85. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  86. $forceFilterInit = array();
  87. $requestDataFilters = array();
  88. $filterInit = new stdClass();
  89. $filterInit->currSortCol = $acl->getPrimaryKeyField();
  90. $filterInit->currSortFlip = 'desc';
  91. foreach ($_REQUEST as $k => $v) {
  92. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
  93. $requestDataFilters[$k] = $v;
  94. $filterInit->$k = $v;
  95. }
  96. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
  97. $requestDataFilters[$k] = $v;
  98. $filterInit->$k = $v;
  99. }
  100. else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  101. $fldName = substr($k, 3);
  102. $forceFilterInit[$fldName] = $v;
  103. }
  104. }
  105. $backRefFilter = [
  106. 'namespace' => V::get('backRefNS', '', $_GET),
  107. 'primaryKey' => V::get('backRefPK', '', $_GET),
  108. 'fieldName' => V::get('backRefField', '', $_GET),
  109. ];
  110. $childRefFilter = [
  111. 'namespace' => V::get('childRefNS', '', $_GET),
  112. 'primaryKey' => V::get('childRefPK', '', $_GET),
  113. ];
  114. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
  115. $lastDataFilters = $tbl->getFilters();
  116. DBG::log([
  117. '$requestDataFilters' => $requestDataFilters,
  118. '$lastDataFilters' => $lastDataFilters,
  119. ], 'array', "TODO:BUG?:filters");
  120. if (empty($lastDataFilters) && empty($requestDataFilters)) {
  121. DBG::log(['TODO: run setFilterInit', [
  122. 'currSortCol' => $acl->getPrimaryKeyField(),
  123. 'currSortFlip' => 'desc',
  124. ]], 'array', "TODO:BUG?:filters");
  125. $tbl->setFilterInit([
  126. 'currSortCol' => $acl->getPrimaryKeyField(),
  127. 'currSortFlip' => 'desc',
  128. ]);
  129. } else if (!empty($requestDataFilters)) {
  130. $tbl->setFilterInit($filterInit);
  131. }
  132. if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
  133. if (V::get('DBG_INST', '', $_GET)) { // TODO: TEST namespace
  134. $siblings = ACL::getNamespaceSiblings($namespace);
  135. DBG::nicePrint($siblings, '$siblings');
  136. $filtrInstance = V::get('f_instance', [], $_POST, 'array');
  137. DBG::nicePrint($filtrInstance, '$filtrInstance');
  138. $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");
  139. $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");
  140. $_ = array(UI, 'h');
  141. echo $_('form', ['method' => "POST", 'style' => "width:600px; border:1px solid #ddd; border-radius:2px"], [
  142. $_('div', ['style' => "background-color:#ddd"], "Test Filtr instancji"),
  143. $_('div', ['style' => "padding:8px"], array_map(function ($sibling) use ($filtrInstance, $_) {
  144. return $_('div', [], [
  145. $_('label', ['style' => "margin:0 8px"], [
  146. $_('input', array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'YES'], ('YES' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : [])),
  147. " TAK "
  148. ]),
  149. $_('label', ['style' => "margin:0 8px"], [
  150. $_('input', array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'NO'], ('NO' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : [])),
  151. " NIE "
  152. ]),
  153. $_('label', ['style' => "margin:0 8px"], [
  154. $_('input', ['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'x']),
  155. " pomiń "
  156. ]),
  157. // $_('button', ['onClick'=>"this.form.f_instance['{$sibling}'].value = ''; return false"], "odznacz"),
  158. $_('button', ['onClick'=>"console.log(this.form.elements['f_instance[{$sibling}]']); this.form.elements['f_instance[{$sibling}]'].value = 'x'; return false"], "odznacz"),
  159. " - {$sibling}"
  160. ]);
  161. }, $siblings)),
  162. $_('div', [], [
  163. $_('input', ['type'=>"hidden", 'name'=>'_route', 'value'=>"ViewObject"]),
  164. $_('input', ['type'=>"hidden", 'name'=>'namespace', 'value'=>$namespace]),
  165. $_('input', ['type'=>"submit", 'value'=>"Filtruj - TEST"]),
  166. ]),
  167. ]);
  168. DBG::nicePrint($_POST, '$_POST');
  169. {
  170. $args = $_POST;
  171. $fIsInstance = [];
  172. $fIsNotInstance = [];
  173. if (!empty($args['f_instance'])) {
  174. foreach ($args['f_instance'] as $inst => $selected) {
  175. if ('YES' === $selected) {
  176. $fIsInstance[] = $inst;
  177. } else if ('NO' === $selected) {
  178. $fIsNotInstance[] = $inst;
  179. }
  180. }
  181. }
  182. }
  183. $queryFeatures = $acl->buildQuery([
  184. // TODO: 'propertyName' => "*,@instance",
  185. 'f_is_instance' => $fIsInstance,
  186. 'f_is_not_instance' => $fIsNotInstance,
  187. '@instances' => '1',
  188. 'limit' => 10
  189. ]);
  190. // $total = $queryFeatures->getTotal();
  191. $items = $queryFeatures->getItems();
  192. $rootNamespace = $acl->getRootNamespace();
  193. DBG::nicePrint($rootNamespace, '$rootNamespace');
  194. $jsRenderFunName = 'render_dropdown_instances_' . substr(md5(time()), 0, 6);
  195. DBG::nicePrint($jsRenderFunName, '$jsRenderFunName');
  196. UI::table([
  197. 'rows' => array_map(function($row) use ($namespace, $siblings, $rootNamespace, $jsRenderFunName) {
  198. return [
  199. 'ID' => $row['ID'],
  200. 'DESC' => $row['DESC'],
  201. 'TYPE' => $row['TYPE'],
  202. 'Typ' => UI::h('div', ['class'=>"p5UI__dropdown-wrap"], [
  203. UI::h('button', [
  204. // 'onClick' => "p5UI__dropdown(event, this, 'left bottom')",
  205. 'onClick' => "p5UI__dropdown(event, this, 'left bottom', {$jsRenderFunName}({$row['ID']}))",
  206. 'class' => "btn btn-xs btn-default p5UI__dropdown-btn"
  207. ], [
  208. UI::h('i', ['class' => "glyphicon glyphicon-tags", 'title' => "Ustaw typ danych (instancje)"]),
  209. ]),
  210. UI::h('div', ['class' => "p5UI__dropdown-content"]
  211. , array_merge(
  212. [
  213. UI::h('input', ['type' => "text", 'placeholder' => "Search..", 'class' => "p5UI__dropdown-input", 'onkeyup' => "p5_ViewObject_instances_filterInput(this)"], null),
  214. ]
  215. , array_map(function ($sibling) use ($row, $namespace, $rootNamespace) {
  216. return UI::h('div', ['label'=>$sibling, 'style'=>"padding:4px 0"], [
  217. UI::h('button', array_merge(['class' => "btn btn-xs btn-default",
  218. 'style' => "margin:0 4px 0 0",
  219. 'title' => "Ustaw instancje '{$sibling}'",
  220. 'onClick' => "return p5_ViewObject_instance_set(this, '{$row['ID']}', '{$sibling}', 'yes')"],
  221. (in_array($sibling, explode(',', $row['@instances']))) ? ['disabled' => "disabled"] : []
  222. ), "+"),
  223. UI::h('button', ['class' => "btn btn-xs btn-default",
  224. 'style' => "margin:0 4px 0 0",
  225. 'title' => "Usuń instancje '{$sibling}'",
  226. 'onClick' => "return p5_ViewObject_instance_set(this, '{$row['ID']}', '{$sibling}', 'no')"], "-"),
  227. UI::h('span', [], substr($sibling, strlen($rootNamespace) + 1)),
  228. ]);
  229. }, $siblings)
  230. )
  231. )
  232. ]),
  233. 'instancesList' => implode(', ', ACL::getFeatureNamespaces($namespace, $row['ID'])),
  234. ];
  235. }, $items)
  236. ]);
  237. echo UI::h('style', ['type' => "text/css"], "
  238. .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) }
  239. .p5UI__dropdown-content .p5UI__dropdown-item { display:block; color:#000; padding:4px; text-decoration:none }
  240. .p5UI__dropdown-content .p5UI__dropdown-item:hover { background-color:#ebebeb }
  241. ");
  242. echo UI::h('script', ['src'=>"static/vendor.js?v=816e859d", 'type'=>"text/javascript"]);
  243. $jsArgs = [
  244. 'SET_INSTANCE_URL' => $this->getLink('setInstanceAjax'),
  245. 'NAMESPACE' => $namespace,
  246. 'DBG' => DBG::isActive() ? 'true' : 'false',
  247. ];
  248. UI::inlineJS(__FILE__ . '.instancesDropdown.js', [
  249. 'JS_GLOBAL_FUNCTION_NAME' => $jsRenderFunName,
  250. 'NAMESPACE' => $namespace,
  251. 'SET_INSTANCE_URL' => $this->getLink('setInstanceAjax'),
  252. 'DBG' => DBG::isActive() ? 1 : 0,
  253. 'INITIAL_DROPDOWN_DATA' => [
  254. // 'allowed_instances' => $siblings,
  255. 'allowed_instances' => array_map(function ($sibling) use ($rootNamespace) {
  256. return [
  257. 'namespace' => $sibling,
  258. 'label' => substr($sibling, strlen($rootNamespace) + 1)
  259. ];
  260. }, $siblings),
  261. 'items' => array_map(function($row) use ($namespace, $siblings, $rootNamespace, $jsRenderFunName) {
  262. return [
  263. 'pk' => $row['ID'], // TODO: $primaryKeyField
  264. 'instances' => explode(',', $row['@instances']),
  265. ];
  266. }, $items)
  267. ],
  268. ]);
  269. echo UI::h('script', [], "
  270. var SET_INSTANCE_URL = '{$jsArgs['SET_INSTANCE_URL']}'
  271. var NAMESPACE = '{$jsArgs['NAMESPACE']}'
  272. function p5_ViewObject_instance_set(n, pk, sibling, toConnect) {
  273. console.log('p5_ViewObject_instance_set pk('+pk+'), sibling('+sibling+'), toConnect('+toConnect+'), n', n);
  274. window.fetch(SET_INSTANCE_URL, {
  275. method: 'POST',
  276. headers: { 'Content-Type': 'application/json' },
  277. credentials: 'same-origin',
  278. body: JSON.stringify({
  279. namespace: NAMESPACE,
  280. primaryKey: pk,
  281. instance: sibling,
  282. toConnect: toConnect,
  283. })
  284. }).then(function (response) {
  285. return response.json()
  286. }).then(function (response) {
  287. p5UI__notifyAjaxCallback(response)
  288. console.log(response) // TODO: render list
  289. })
  290. }
  291. ");
  292. echo UI::h('script', [], "
  293. function p5_ViewObject_instances_filterInput(n) {
  294. var input, filter, ul, li, a, i, div;
  295. input = n // .id-myInput
  296. filter = input.value.toUpperCase()
  297. div = n.parentNode // .id-myDropdown
  298. a = div.getElementsByTagName('div')
  299. for (i = 0; i < a.length; i++) {
  300. if (a[i].getAttribute('label') && a[i].getAttribute('label').toUpperCase().indexOf(filter) > -1) {
  301. a[i].style.display = 'block'
  302. } else {
  303. a[i].style.display = 'none'
  304. }
  305. }
  306. }
  307. ");
  308. echo '<hr style="margin-top:300px">';
  309. exit;
  310. }
  311. echo $tbl->render();
  312. if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
  313. Lib::loadClass('DebugExecutionTime');
  314. $dbgExecTime = new DebugExecutionTime();
  315. $dbgExecTime->activate();
  316. $dbgExecTime->log('start');
  317. UI::startContainer(['style'=>'border:1px solid red']);
  318. UI::tag('p', null, "TEST - load perms from db");
  319. $idTable = $acl->getID();
  320. UI::tag('p', null, "DBG idTable({$idTable})");
  321. if ($idTable > 0) {
  322. $dbgExecTime->log('before sql');
  323. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  324. $dbgExecTime->log('after sql', ['sql']);
  325. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  326. $csvIdProces = array();
  327. foreach ($aclTableRows as $row) {
  328. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  329. }
  330. }
  331. $tableName = $acl->getName();
  332. $databaseName = DB::getPDO()->getDatabaseName();
  333. UI::table([
  334. 'caption' => "Cell to process",
  335. 'rows' => array_map(
  336. function ($row) use ($aclTableRows, $idTable) {
  337. $row['proces'] = array();
  338. $row['id_zasob'] = 0;
  339. $row['PERM_R'] = 0;
  340. $row['PERM_W'] = 0;
  341. $row['PERM_X'] = 0;
  342. $row['PERM_C'] = 0;
  343. $row['PERM_S'] = 0;
  344. $row['PERM_O'] = 0;
  345. $row['PERM_V'] = 0;
  346. $row['PERM_E'] = 0;
  347. foreach ($aclTableRows as $aclInfo) {
  348. if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
  349. $row['proces'][] = $aclInfo['ID_PROCES'];
  350. $row['id_zasob'] = $aclInfo['ID_CELL'];
  351. $row['PERM_R'] += $aclInfo['PERM_R'];
  352. $row['PERM_W'] += $aclInfo['PERM_W'];
  353. $row['PERM_X'] += $aclInfo['PERM_X'];
  354. $row['PERM_C'] += $aclInfo['PERM_C'];
  355. $row['PERM_S'] += $aclInfo['PERM_S'];
  356. $row['PERM_O'] += $aclInfo['PERM_O'];
  357. $row['PERM_V'] += $aclInfo['PERM_V'];
  358. $row['PERM_E'] += $aclInfo['PERM_E'];
  359. }
  360. }
  361. $row['proces'] = (empty($row['proces']))
  362. ? "<i style=\"color:red\">Brak</i>"
  363. : implode(", ", $row['proces']);
  364. 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");
  365. return $row;
  366. }, DB::getPDO()->fetchAll("
  367. select t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
  368. from `information_schema`.`COLUMNS` t
  369. where t.TABLE_SCHEMA = '{$databaseName}'
  370. and t.TABLE_NAME like '{$tableName}'
  371. ")
  372. )
  373. ]);
  374. if (!empty($csvIdProces)) {
  375. $csvIdProces = implode(",", $csvIdProces);
  376. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  377. $userLogin = User::getLogin();
  378. $dbgExecTime->log('before sql');
  379. $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");
  380. $dbgExecTime->log('after sql', ['sql']);
  381. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  382. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  383. $userTablePerms = array();
  384. foreach ($aclTableRows as $row) {
  385. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  386. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  387. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  388. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  389. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  390. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  391. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  392. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  393. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  394. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  395. } else {
  396. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  397. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  398. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  399. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  400. }
  401. }
  402. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  403. } else UI::alert('warning', "brak \$csvIdProces");
  404. $dbgExecTime->printDebug();
  405. UI::endContainer();
  406. }
  407. }
  408. public function setInstanceAjaxAction() {
  409. Response::sendTryCatchJson(array($this, 'setInstanceAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  410. }
  411. public function setInstanceAjax($args) {
  412. // namespace => default_db/CRM_PROCES/PROCES_INIT
  413. // primaryKey => 6
  414. // instance => default_db/CRM_PROCES/PROCES_TREE
  415. // toConnect => yes
  416. if (empty($args['namespace'])) throw new Exception("Missing namespace");
  417. if (empty($args['primaryKey'])) throw new Exception("Missing primaryKey");
  418. if (empty($args['instance'])) throw new Exception("Missing instance");
  419. if (empty($args['toConnect'])) throw new Exception("Missing toConnect");
  420. if (!in_array($args['toConnect'], ['yes', 'no'])) throw new Exception("Wrong param toConnect");
  421. $idInstance = ACL::getInstanceId($args['instance']);
  422. throw new Exception("TODO: check instance config"); // if 'view' then set instance is not allowed
  423. // $instanceTable = ACL::getInstanceTable($args['namespace']);
  424. // switch ($args['toConnect']) {
  425. // case 'yes': {
  426. // // TODO: _HIST info - waiting
  427. // $ret = DB::getPDO()->execSql("
  428. // insert into `{$instanceTable}` (`pk`, `idInstance`)
  429. // values ( :pk , :idInstance )
  430. // ", [
  431. // 'pk' => $args['primaryKey'],
  432. // 'idInstance' => $idInstance,
  433. // ]);
  434. // // TODO: _HIST info - mark as done
  435. // } break;
  436. // case 'no': {
  437. // // TODO: _HIST info - waiting
  438. // $ret = DB::getPDO()->execSql("
  439. // delete from `{$instanceTable}`
  440. // where `pk` = :pk
  441. // and `idInstance` = :idInstance
  442. // ", [
  443. // 'pk' => $args['primaryKey'],
  444. // 'idInstance' => $idInstance,
  445. // ]);
  446. // // TODO: _HIST info - mark as done
  447. // } break;
  448. // }
  449. // return [
  450. // 'type' => 'success',
  451. // 'msg' => "Wprowadzono zmiany ({$ret})",
  452. // // TODO: 'data' => all instances for pk
  453. // ];
  454. }
  455. public function rmUserTableFilterAjaxAction() {
  456. Response::sendTryCatchJson(array($this, 'rmUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  457. }
  458. public function rmUserTableFilterAjax($args) {
  459. $namespace = V::get('namespace', '', $args);
  460. $filtrName = V::get('filtrName', '', $args);
  461. if (!$namespace) throw new Exception("Missing namespace");
  462. if (!$filtrName) throw new Exception("Missing filtrName");
  463. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  464. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  465. if (!$currentFilters) return [
  466. 'type' => 'warning',
  467. 'msg' => "Brak filtrów w bazie",
  468. ];
  469. $currentFilters = json_decode($currentFilters, 'assoc');
  470. unset($currentFilters[$namespace][$filtrName]);
  471. $affeced = DB::getPDO()->update('CRM_CONFIG', 'CONF_KEY', $userFltrConfKey, [
  472. 'CONF_VAL' => json_encode($currentFilters)
  473. ]);
  474. return [
  475. 'type' => 'success',
  476. 'msg' => 'Zapisano nowy filtr',
  477. 'data' => $currentFilters[$namespace]
  478. ];
  479. }
  480. public function addUserTableFilterAjaxAction() {
  481. Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  482. }
  483. public function addUserTableFilterAjax($args) {
  484. $namespace = V::get('namespace', '', $args);
  485. $filtrName = V::get('filtrName', '', $args);
  486. $visibleCols = V::get('visibleCols', '', $args);
  487. if (!$namespace) throw new Exception("Missing namespace");
  488. if (!$filtrName) throw new Exception("Missing filtrName");
  489. if (!$visibleCols) throw new Exception("Missing visibleCols");
  490. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  491. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  492. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  493. $currentFilters[$namespace][$filtrName] = $visibleCols;
  494. $sqlFltr = json_encode($currentFilters);
  495. DB::getPDO()->execSql("
  496. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  497. values ('$userFltrConfKey', '{$sqlFltr}')
  498. on duplicate key update CONF_VAL = '{$sqlFltr}'
  499. ");
  500. return [
  501. 'type' => 'success',
  502. 'msg' => 'Zapisano nowy filtr',
  503. 'data' => $currentFilters[$namespace]
  504. ];
  505. }
  506. public function getUserTableFilterAjaxAction() {
  507. Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  508. }
  509. public function getUserTableFilterAjax($args) {
  510. $namespace = V::get('namespace', '', $args);
  511. if (!$namespace) throw new Exception("Missing namespace");
  512. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  513. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  514. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  515. return [
  516. 'type' => 'success',
  517. 'msg' => 'Odczytano filtry użytkownika',
  518. 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
  519. ];
  520. }
  521. public function revertFromHistAjaxAction() {
  522. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  523. }
  524. public function revertFromHistAjax() {
  525. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  526. if (!$typeName) throw new Exception("Wrong param typeName");
  527. // TODO: use namespace from url
  528. // $namespace = V::get('namespace', '', $_GET, 'word');
  529. // if (!$namespace) {
  530. // $typeName = V::get('typeName', '', $_GET, 'word');
  531. // if (!$typeName) throw new Exception("Wrong param typeName");
  532. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  533. // }
  534. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  535. $id = V::get('ID', '', $_REQUEST, 'word');
  536. if (!$id) throw new Exception("Wrong param ID");
  537. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  538. if (!$idHist) throw new Exception("Wrong param idHist");
  539. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  540. if (!$fieldName) throw new Exception("Wrong param fieldName");
  541. $acl = Core_AclHelper::getAclByTypeName($typeName);
  542. $item = $acl->getItem($id);
  543. if (!$item) throw new HttpException("Item not found", 404);
  544. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  545. $histItem = $acl->getHistItem($id, $idHist);
  546. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  547. $histValue = V::get($fieldName, 'N/S;', $histItem);
  548. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  549. if ($acl->isGeomField($fieldName)) {
  550. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  551. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  552. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  553. $coords = trim(substr($histValue, strlen($wktType)), '()');
  554. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  555. if (!$wktValue) throw new Exception("BUG in hist record");
  556. $sqlObj = array();
  557. $sqlObj['ID'] = $id;
  558. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  559. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  560. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  561. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  562. $jsonResponse = array();
  563. $jsonResponse['type'] = 'success';
  564. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  565. $jsonResponse['actions'] = array();
  566. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  567. return $jsonResponse;
  568. } else {
  569. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  570. }
  571. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  572. }
  573. public function removeTheGeomAjaxAction() {
  574. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  575. }
  576. public function removeTheGeomAjax($args) {
  577. $namespace = V::get('namespace', '', $args, 'word');
  578. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  579. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  580. $primaryKeyField = $acl->getPrimaryKeyField();
  581. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  582. $geomFieldName = 'the_geom';
  583. $response = new stdClass();
  584. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  585. $record = $acl->getItem($primaryKey);
  586. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  587. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  588. if (empty($record->{$geomFieldName})) {
  589. $response->type = 'info';
  590. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  591. $response->record = $record;
  592. return $response;
  593. }
  594. $itemPatch = array();
  595. $itemPatch[$geomFieldName] = "NULL";
  596. $itemPatch[$primaryKeyField] = $primaryKey;
  597. $response = new stdClass();
  598. try {
  599. $affected = $acl->updateItem($itemPatch);
  600. if ($affected > 0) {
  601. $response->type = 'success';
  602. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  603. } else if ($affected == 0) {
  604. $response->type = 'info';
  605. $response->msg = "Nie wprowadzono żadnych zmian";
  606. }
  607. $response->record = $acl->getItem($primaryKey);
  608. }
  609. catch (Exception $e) {
  610. $response->type = 'error';
  611. $response->msg = $e->getMessage();
  612. }
  613. return $response;
  614. }
  615. public function getCsvTheGeomAjaxAction() {
  616. try {
  617. self::getCsvTheGeomAjax();
  618. } catch (Exception $e) {
  619. UI::gora();
  620. UI::menu();
  621. UI::alert('danger', $e->getMessage());
  622. echo UI::h('div', [ 'style' => "text-align:center" ], [
  623. UI::h('a', [ 'href' => $_SERVER['HTTP_REFERER'], 'class' => "btn btn-primary", 'style' => "width:80px" ], "Powrót"),
  624. ]);
  625. UI::dol();
  626. }
  627. }
  628. public function getCsvTheGeomAjax($minDistance = 10, $nearDistance = 1) {
  629. Lib::loadClass('EpsgConversion');
  630. Lib::loadClass('Geometry');
  631. $namespace = V::get('namespace', '', $_GET, 'word');
  632. $acl = Core_AclHelper::getAclByNamespace($namespace);
  633. $table = $acl->getRootTableName();
  634. $id = V::get('id', 0, $_GET, 'int');
  635. $query_points = "select st_astext(`the_geom`) as `the_geom` from `{$table}` where `ID` = {$id}";
  636. $result_points = DB::getPDO()->fetchValue($query_points);
  637. $points = Geometry::objectFromText($result_points, 'Wgs84ToPuwg2000')->points();
  638. $lines = Geometry::pointsToLines($points);
  639. // Dodanie początkowego punktu pierwszej linii do tabeli wszystkcih punktów
  640. $_points = [['point' => $points[0], 'type' => ['p']]];
  641. // Szukanie kolzji dla każdej linii prostej
  642. foreach ($lines as $line) {
  643. $polygon_asText = Geometry::lineToRectangle($line, $nearDistance)->asText('Puwg2000ToWgs84');
  644. $query_nears = "select st_astext(`the_geom`) as `the_geom` from `rurociagi_obce_wsg84` where st_intersects(st_geomfromtext('{$polygon_asText}'), `the_geom`)";
  645. $results_nears = DB::getPDO()->fetchAll($query_nears);
  646. $nears = [];
  647. foreach ($results_nears as $result_nears) {
  648. $nears = array_merge($nears, Geometry::pointsToLines(Geometry::objectFromText($result_nears['the_geom'], 'Wgs84ToPuwg2000')->points()));
  649. }
  650. $nears = array_filter($nears, function ($near) use ($line, $nearDistance) {
  651. return Geometry::distance($line, $near) <= $nearDistance;
  652. });
  653. // Szukanie odcinków kolizyjnych
  654. $crossPoints = [];
  655. $_nearsOnLine = [];
  656. foreach ($nears as $near) {
  657. if ($_crossPoints = Geometry::crossPoint($line, $near)) {
  658. switch (count($_crossPoints)) {
  659. case 1:
  660. // Znaleziono kolizję przecinającą linię
  661. $crossPoints[] = ['point' => $_crossPoints[0], 'type' => ['x']];
  662. break;
  663. case 2:
  664. // Znaleziono kolizję idealnie nałożoną na linię
  665. $_nearsOnLine[] = Geometry::line($_crossPoints[0], $_crossPoints[1]);
  666. break;
  667. default:
  668. throw new Exception(__CLASS__ . "::" . __FUNCTION__ . ' - unknown error');
  669. }
  670. }
  671. // Analiza pobliskich kolizji
  672. $a = Geometry::closedPointOnLine($near->a, $line);
  673. $b = Geometry::closedPointOnLine($near->b, $line);
  674. if (Geometry::distance($a, $line->a) < Geometry::distance($b, $line->a)) $nearOnLine = Geometry::line($a, $b);
  675. else $nearOnLine = Geometry::line($b, $a);
  676. // Weryfikacja czy pobliska kolizja nie jest jednocześnie kolizją przecinajacą i czy nie jest za krótka (<1m) - wtedy ją usuwamy
  677. $add = true;
  678. if ($nearOnLine->length() < 1) {
  679. foreach ($crossPoints as $crossPoint) {
  680. if (Geometry::distance($crossPoint['point'], $nearOnLine) == 0) {
  681. $add = false;
  682. break;
  683. }
  684. }
  685. }
  686. if ($add) $_nearsOnLine[] = $nearOnLine;
  687. }
  688. // Przesortowanie wszystkich kolizji linowych
  689. usort($_nearsOnLine, function ($A, $B) use ($line) {
  690. if (Geometry::samePoint($A->a, $B->a)) return 0;
  691. if (Geometry::distance($A, $line->a) < Geometry::distance($B, $line->a)) return -1;
  692. return 1;
  693. });
  694. // Scalenie wszystkich kolizji jeżeli odstęp między nimi jest krótszy niz 1m
  695. $lastNearOnLine = null;
  696. $nearsOnLine = [];
  697. foreach ($_nearsOnLine as $nearOnLine) {
  698. if ($lastNearOnLine) {
  699. if (Geometry::distance($nearOnLine, $lastNearOnLine) < 1) {
  700. $nearOnLine->a = $lastNearOnLine->a;
  701. if (Geometry::distance($nearOnLine->b, $line->a) < Geometry::distance($lastNearOnLine->b, $line->a)) $nearOnLine->b = $lastNearOnLine->b;
  702. } else $nearsOnLine[] = $lastNearOnLine;
  703. }
  704. $lastNearOnLine = $nearOnLine;
  705. }
  706. if ($lastNearOnLine) $nearsOnLine[] = $lastNearOnLine;
  707. // Nałożenie kolizji liniowych na punkty kolizyjne
  708. foreach ($nearsOnLine as $nearOnLine) {
  709. $crossPoints[] = ['point' => $nearOnLine->a, 'type' => ['iistart']];
  710. $crossPoints[] = ['point' => $nearOnLine->b, 'type' => ['iistop']];
  711. }
  712. // Podzielenie linii prostej na krótsze odcinki, jezeli jest zbyt długa (>$minDistance)
  713. if (($distance = $line->length()) > $minDistance) {
  714. $parts = ceil($distance / $minDistance);
  715. $deltaX = ($line->b->x - $line->a->x) / $parts;
  716. $deltaY = ($line->b->y - $line->a->y) / $parts;
  717. for ($j = 1; $j < $parts; $j++) {
  718. $_point = Geometry::point($line->a->x + $j * $deltaX, $line->a->y + $j * $deltaY);
  719. $collision = false;
  720. foreach ($nearsOnLine as $nearOnLine) {
  721. if (Geometry::distance($nearOnLine, $_point) == 0) {
  722. $collision = true;
  723. break;
  724. }
  725. }
  726. $type = ['m'];
  727. if ($collision) $type[] = 'ii';
  728. $crossPoints[] = ['point' => Geometry::point($line->a->x + $j * $deltaX, $line->a->y + $j * $deltaY), 'type' => $type];
  729. }
  730. }
  731. // Przesortowanie wszystkich punktów na linii
  732. usort($crossPoints, function ($a, $b) use ($line) {
  733. if (Geometry::samePoint($a['point'], $b['point'])) return 0;
  734. if (Geometry::distance($a['point'], $line->a) < Geometry::distance($b['point'], $line->a)) return -1;
  735. return 1;
  736. });
  737. // Dodanie wszystkich punktów kolizyjnych i pośrednich do tabeli wszystkich punktów
  738. foreach ($crossPoints as $crossPoint) $_points[] = ['point' => $crossPoint['point'], 'type' => $crossPoint['type']];
  739. // Dodanie końcowego punktu linii do tabeli wszystkich punktów
  740. $_points[] = ['point' => $line->b, 'type' => ['p']];
  741. }
  742. // Scalenie pobliskich kolizji występujących na różnych liniach
  743. $starts = array_keys(array_filter($_points, function($point) { return in_array('iistart', $point['type']); }));
  744. $stops = array_keys(array_filter($_points, function($point) { return in_array('iistop', $point['type']); }));
  745. $points = array_keys(array_filter($_points, function($point) { return in_array('p', $point['type']); }));
  746. foreach ($stops as $i) {
  747. if (in_array($i+1, $points) && in_array($i+2, $starts)) {
  748. if (Geometry::distance($_points[$i]['point'], $_points[$i+1]['point']) + Geometry::distance($_points[$i+1]['point'], $_points[$i+2]['point']) < 1) {
  749. unset($_points[$i]);
  750. unset($_points[$i + 2]);
  751. $_points[$i + 1]['type'][] = 'ii';
  752. }
  753. }
  754. }
  755. // 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)
  756. $points = [];
  757. $lastPoint = null;
  758. $desc = [];
  759. foreach ($_points as $point) {
  760. if ($lastPoint) {
  761. if (Geometry::samePoint($point['point'], $lastPoint['point'])) $point['type'] = array_merge($lastPoint['type'], $point['type']);
  762. else $points[] = $lastPoint;
  763. }
  764. $lastPoint = $point;
  765. }
  766. if ($lastPoint) $points[] = $lastPoint;
  767. // Funkcja generująca czytelny opis rodzaju punktu
  768. $typeToDesc = function($type) {
  769. if (in_array('iistart', $type) && in_array('iistop', $type)) {
  770. $type = array_diff($type, ['iistart', 'iistop']);
  771. $type[] = 'ii';
  772. }
  773. usort($type, function($a, $b) {
  774. if ($a == 'p' || $a == 'm') return -1;
  775. if ($b == 'p' || $b == 'm') return 1;
  776. return 0;
  777. });
  778. return implode('|', array_map(function($_type) {
  779. $types = [
  780. 'p' => 'Punkt',
  781. 'm' => 'Posredni',
  782. 'x' => 'Kolizja (X)',
  783. 'ii' => 'Kolizja (II)',
  784. 'iistart' => 'Kolizja (II) start',
  785. 'iistop' => 'Kolizja (II) stop'
  786. ];
  787. if (isset($types[$_type])) return $types[$_type];
  788. throw new Exception("Nieznany typ punktu - {$_type} (" . __CLASS__ . '::' . __FUNCTION__ . ')');
  789. }, $type));
  790. };
  791. // Generowanie pliku CSV
  792. $csv = implode("\n", array_map(function ($point, $i) use ($typeToDesc) {
  793. try {
  794. $z = EpsgConversion::GetZByPuwg2000($point['point']->x, $point['point']->y);
  795. } catch (Exception $e) {
  796. $z = 0;
  797. }
  798. return $i . "," . round($point['point']->y, 3) . "," . round($point['point']->x, 3) . "," . round($z, 3) . "," . $typeToDesc($point['type']);
  799. }, $points, range(1, count($points))));
  800. // echo "<pre>{$csv}</pre>";
  801. Response::sendCsv($csv, "{$table}.{$id}");
  802. }
  803. public function moreFunctionsCellAjaxAction() {
  804. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  805. }
  806. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  807. $id = V::get('ID', 0, $args, 'int');
  808. if ($id <= 0) throw new HttpException("404", 404);
  809. $namespace = V::get('namespace', '', $args, 'word');
  810. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  811. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  812. $response = new stdClass();
  813. $response->type = 'success';
  814. $response->msg = 'Funkcje';
  815. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  816. return $response;
  817. }
  818. public function createFormAction() {// TODO: move to createFormJsonAction
  819. try {
  820. $args = $_REQUEST;
  821. $namespace = V::get('namespace', '', $args, 'word');
  822. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  823. $acl = Core_AclHelper::getAclByNamespace($namespace);
  824. $tbl = $this->getTableAjaxWidget($acl);
  825. $tbl->sendAjaxCreate();
  826. } catch (Exception $e) {
  827. DBG::log($e);
  828. throw $e;
  829. }
  830. }
  831. public function createFormJsonAction() {
  832. Response::sendTryCatchJson(array($this, 'createFormJson'), $args = $_REQUEST);
  833. }
  834. public function createFormJson($args) { // namespace, _hash, _primaryKey
  835. $namespace = V::get('namespace', '', $args, 'word');
  836. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  837. $acl = Core_AclHelper::getAclByNamespace($namespace);
  838. $tbl = $this->getTableAjaxWidget($acl);
  839. if (!Core_AclHelper::hasCreatePerms($acl)) {
  840. return [
  841. 'type' => "success",
  842. 'msg' => "Dodaj nowy rekord",
  843. 'body' => [
  844. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak uprawnień do utworzenia nowego rekordu." ]
  845. ],
  846. ];
  847. // throw new Exception("Brak uprawnień do utworzenia nowego rekordu.");
  848. }
  849. $fieldsList = array();
  850. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  851. if ($fieldName == 'ID') continue;
  852. $field['name'] = $fieldName;
  853. $field['opis'] = $acl->getFieldOpis($fieldName);
  854. $field['label'] = $acl->getFieldLabel($fieldName);
  855. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  856. $fieldsList[$kID] = $field;
  857. }
  858. $cols = array();
  859. $forceFilterInit = array();
  860. $defaultAclGroup = User::getDefaultAclGroup();
  861. if ($defaultAclGroup) {
  862. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  863. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  864. }
  865. foreach ($_GET as $k => $v) { // TODO: read from $args ?
  866. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  867. $fldName = substr($k, 3);
  868. $forceFilterInit[$fldName] = $v;
  869. }
  870. }
  871. DBG::log($forceFilterInit, 'array', "\$forceFilterInit");
  872. foreach ($fieldsList as $kID => $field) {
  873. $defaultValue = '';
  874. if (!empty($forceFilterInit[$field['name']])) {
  875. $defaultValue = $forceFilterInit[$field['name']];
  876. }
  877. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  878. }
  879. DBG::log($cols, 'array', "\$cols - field values");
  880. $tsValues = array();
  881. $featureFunctions = [
  882. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  883. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  884. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  885. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  886. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  887. ];
  888. $jsFields = [];
  889. $tabindex = 0;
  890. foreach ($fieldsList as $kID => $vCol) {
  891. $fieldName = $vCol['name'];
  892. $fieldLabel = str_replace('<br>', ' ', $vCol['label']);
  893. DBG::log(['$fieldName'=>$fieldName, 'canCreate'=>$acl->canCreateField($fieldName)], 'array', "form field");
  894. if ($acl->canCreateField($fieldName)) {
  895. DBG::log("editFormJson::field({$fieldName})");
  896. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  897. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  898. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  899. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  900. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $fieldLabel ],
  901. [ '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}" ] ],
  902. ] ],
  903. [ 'div', [ 'class' => "" ], [
  904. UI::hGetFormItem($acl, $fieldName, 'C', $kID, "f{$kID}", $cols[$kID], $fieldParams),
  905. ] ]
  906. ] ];
  907. // } else {
  908. // $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  909. // "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  910. // ]];
  911. }
  912. }
  913. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  914. [ 'div', [ 'class' => "" ], [
  915. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  916. ] ]
  917. ] ];
  918. $tblLabel = $acl->getNamespace();
  919. if ('default_db' == $acl->getSourceName()) {
  920. $tblLabel = array();
  921. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  922. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  923. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  924. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  925. $tblLabel = implode(" - ", $tblLabel);
  926. }
  927. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  928. $jsGui = [
  929. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  930. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  931. "Dodaj nowy rekord",
  932. ] ],
  933. [ 'P5UI__FeatureCreateForm', [
  934. 'class' => "", 'action' => "", 'method' => "post",
  935. 'id' => "CREATE_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  936. 'ajaxSaveUrl' => "{$syncUrl}&_task=createSaveAjax", // TODO:? &_hash={$this->_htmlID}
  937. 'ajaxSaveLegacyUrl' => "{$syncUrl}&_task=createSaveLegacy", // TODO: Legacy RM
  938. 'namespace' => $acl->getNamespace(),
  939. 'tableLabelHtml' => $tblLabel,
  940. '_htmlID' => $acl->getName(),
  941. ], [
  942. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  943. ] ] // form
  944. ] ] // .container
  945. ];
  946. return [
  947. 'type' => "success",
  948. 'msg' => "Dodaj nowy rekord",
  949. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  950. ];
  951. }
  952. public function createSaveAjaxAction() {
  953. Response::sendTryCatchJson(array($this, 'createSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  954. }
  955. public function createSaveAjax($args) {
  956. throw new Exception("TODO: ...");
  957. }
  958. public function createSaveLegacyAction() { // TODO: Legacy RM
  959. $args = [
  960. 'namespace' => V::get('namespace', '', $_GET),
  961. 'body' => Request::getRequestJson(),
  962. ];
  963. DBG::log($args, 'array', 'createSaveLegacyAction');
  964. Response::sendTryCatchJson(array($this, 'createSaveLegacy'), $args);
  965. }
  966. public function createSaveLegacy($args) { // TODO: Legacy RM
  967. $namespace = V::get('namespace', '', $args, 'word');
  968. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  969. $body = V::get('body', null, $args);
  970. if (!$body) throw new HttpException("Bad Request - missing body", 400);
  971. $acl = Core_AclHelper::getAclByNamespace($namespace);
  972. $tbl = $this->getTableAjaxWidget($acl);
  973. DBG::log($args, 'array', "ajaxCreateSave");
  974. $createdId = null;
  975. try {
  976. $item = $acl->convertObjectFromUserInput($body, $type = 'array_by_id', $prefix = 'f');
  977. $createdId = $acl->addItem($item);
  978. if ($createdId) {
  979. return [
  980. 'type' => 'success',
  981. 'msg' => "Utworzono pomyślnie rekord nr {$createdId}",
  982. 'id' => $createdId,
  983. 'record' => $acl->buildQuery([])->getItem($createdId),
  984. ];
  985. }
  986. else {
  987. return [
  988. 'type' => 'error',
  989. 'msg' => "Nie udało się utworzyć nowego rekordu!",
  990. ];
  991. }
  992. }
  993. catch (Exception $e) {
  994. return [
  995. 'type' => 'error',
  996. 'msg' => $e->getMessage(),
  997. ];
  998. }
  999. }
  1000. public function editFormAction() { // TODO: not used - moved to editFormJsonAction
  1001. try {
  1002. $args = $_REQUEST;
  1003. $id = V::get('_primaryKey', 0, $args, 'int');
  1004. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  1005. $namespace = V::get('namespace', '', $args, 'word');
  1006. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1007. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1008. $tbl = $this->getTableAjaxWidget($acl);
  1009. $tbl->sendAjaxEdit($id, $args);
  1010. } catch (Exception $e) {
  1011. DBG::log($e);
  1012. throw $e;
  1013. }
  1014. }
  1015. public function editFormJsonAction() {
  1016. Response::sendTryCatchJson(array($this, 'editFormJson'), $args = $_REQUEST);
  1017. }
  1018. public function editFormJson($args) { // namespace, _hash, _primaryKey
  1019. $id = V::get('_primaryKey', 0, $args, 'int');
  1020. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  1021. $namespace = V::get('namespace', '', $args, 'word');
  1022. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1023. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1024. $tbl = $this->getTableAjaxWidget($acl);
  1025. $record = $acl->buildQuery([])->getItem($id);
  1026. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  1027. return [
  1028. 'type' => "success",
  1029. 'msg' => "Edycja rekordu nr {$id}",
  1030. 'body' => [
  1031. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak dostępu do rekordu" ]
  1032. ],
  1033. ];
  1034. // throw new Exception("Brak dostępu do rekordu");
  1035. }
  1036. $fieldsList = array();
  1037. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  1038. if ($fieldName == 'ID') continue;
  1039. $field['name'] = $fieldName;
  1040. $field['opis'] = $acl->getFieldOpis($fieldName);
  1041. $field['label'] = $acl->getFieldLabel($fieldName);
  1042. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  1043. $fieldsList[$kID] = $field;
  1044. }
  1045. $cols = array();
  1046. foreach ($fieldsList as $kID => $field) {
  1047. $cols[$kID] = '';
  1048. if ($acl->canReadObjectField($field['name'], $record)) {
  1049. $cols[$kID] = V::get($field['name'], '', $record);
  1050. } else {
  1051. $cols[$kID] = '*****';
  1052. }
  1053. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  1054. }
  1055. $tsValues = array();
  1056. if (!empty($fieldsList)) {
  1057. foreach ($fieldsList as $vColID => $vCol) {
  1058. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  1059. if ($typeSpecial) {
  1060. $colValue = V::get($vCol['name'], '', $record);
  1061. $specialValues = $typeSpecial->getEditSelectedValuesByIds($acl->getID(), $record['ID'], $vCol['name'], $colValue);
  1062. if (!empty($specialValues)) {
  1063. $tsValues[$vColID] = implode('<br>', $specialValues);
  1064. }
  1065. }
  1066. }
  1067. }
  1068. DBG::log($tsValues, 'array', "editFormJson::tsValues");
  1069. foreach ($tsValues as $idx => $value) {
  1070. if ('<' === substr($value, 0, 1)) {
  1071. // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
  1072. $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
  1073. }
  1074. }
  1075. DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
  1076. $featureFunctions = [
  1077. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  1078. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  1079. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  1080. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  1081. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  1082. ];
  1083. $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
  1084. 'id' => $record[ $acl->getPrimaryKeyField() ],
  1085. 'functions' => $featureFunctions,
  1086. 'showLabels' => true,
  1087. 'viewMoreDropdown' => [
  1088. 'primaryKey' => $record['ID'],
  1089. 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
  1090. ],
  1091. ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  1092. $jsFields = [];
  1093. $tabindex = 0;
  1094. foreach ($fieldsList as $kID => $vCol) {
  1095. $fieldName = $vCol['name'];
  1096. $fieldLabel = str_replace('<br>', ' ', $vCol['label']);
  1097. DBG::log(['$fieldName'=>$fieldName, '$record'=>$record, 'canWrite'=>$acl->canWriteObjectField($fieldName, $record), 'canRead'=>$acl->canReadObjectField($fieldName, $record)], 'array', "form field");
  1098. if ($acl->canWriteObjectField($fieldName, $record)) {
  1099. DBG::log("editFormJson::field({$fieldName})");
  1100. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  1101. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  1102. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1103. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  1104. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $fieldLabel ],
  1105. [ '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}" ] ],
  1106. ] ],
  1107. [ 'div', [ 'class' => "" ], [
  1108. UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
  1109. ] ]
  1110. ] ];
  1111. } else if ($acl->canReadObjectField($fieldName, $record)) {
  1112. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1113. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  1114. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $fieldLabel ],
  1115. [ '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}" ] ],
  1116. ] ],
  1117. [ 'div', [ 'class' => "" ], [
  1118. ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
  1119. (!empty($tsValues[$kID]))
  1120. ? $tsValues[$kID]
  1121. : V::get($fieldName, '', $record)
  1122. ] ],
  1123. ] ]
  1124. ] ];
  1125. // } else {
  1126. // $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1127. // "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  1128. // ]];
  1129. }
  1130. }
  1131. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1132. [ 'div', [ 'class' => "" ], [
  1133. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  1134. ] ]
  1135. ] ];
  1136. $tblLabel = $acl->getNamespace();
  1137. if ('default_db' == $acl->getSourceName()) {
  1138. $tblLabel = array();
  1139. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  1140. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  1141. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  1142. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  1143. $tblLabel = implode(" - ", $tblLabel);
  1144. }
  1145. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  1146. $jsGui = [
  1147. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  1148. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  1149. "Edycja rekordu Nr {$record['ID']}",
  1150. [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
  1151. ] ],
  1152. [ 'P5UI__FeatureEditForm', [
  1153. 'class' => "", 'action' => "", 'method' => "post",
  1154. 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  1155. 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
  1156. 'namespace' => $acl->getNamespace(),
  1157. 'idRecord' => $record['ID'],
  1158. 'tableLabelHtml' => $tblLabel,
  1159. ], [
  1160. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  1161. ] ] // form
  1162. ] ] // .container
  1163. ];
  1164. return [
  1165. 'type' => "success",
  1166. 'msg' => "Edycja rekordu nr {$id}",
  1167. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  1168. ];
  1169. }
  1170. public function editSaveAjaxAction() {
  1171. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  1172. }
  1173. public function editSaveAjax($args) {
  1174. $namespace = V::get('namespace', '', $args, 'word');
  1175. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1176. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1177. $primaryKeyField = $acl->getPrimaryKeyField();
  1178. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  1179. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  1180. $item = $acl->getItem($primaryKey);
  1181. if (!$item) throw new HttpException("Item not exists!", 404);
  1182. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  1183. $response = new stdClass();
  1184. $response->primaryKey = $primaryKey;
  1185. try {
  1186. $itemFromUser[$primaryKeyField] = $primaryKey;
  1187. $affected = $acl->updateItem($itemFromUser);
  1188. if ($affected > 0) {
  1189. $response->type = 'success';
  1190. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  1191. } else if ($affected == 0) {
  1192. $response->type = 'info';
  1193. $response->msg = "Nie wprowadzono żadnych zmian";
  1194. }
  1195. $response->record = $acl->getItem($primaryKey);
  1196. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  1197. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  1198. }
  1199. catch (Exception $e) {
  1200. $response->type = 'error';
  1201. $response->msg = "Wystąpiły błędy!";
  1202. $response->msg .= $e->getMessage();
  1203. }
  1204. return $response;
  1205. }
  1206. public function typeSpecialCellAction() {
  1207. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  1208. }
  1209. public function typeSpecialCell($args) {
  1210. $namespace = V::get('namespace', '', $args, 'word');
  1211. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1212. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1213. $id = V::get('ID', 0, $args, 'int');
  1214. $fieldName = V::get('col', '', $args);
  1215. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  1216. $col = $fieldName;// TODO: RM $col
  1217. $jsonData = new stdClass();
  1218. $idField = $acl->getFieldIdByName($fieldName);
  1219. if (!$idField) throw new Exception("Wrong field");
  1220. $item = $acl->getItem($id);
  1221. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  1222. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  1223. if ($typeSpecial) {
  1224. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  1225. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  1226. }
  1227. return $jsonData;
  1228. }
  1229. public function typespecialAction() { Response::sendTryCatchJson(array($this, 'typespecial'), $args = $_REQUEST); }
  1230. public function typespecial($args) { // @required idField, @optional: q (query), selected (selected value), idRecord (fetch value for given record)
  1231. $idField = V::get('idField', 0, $args, 'int');
  1232. if (!$idField) throw new HttpException("Bad Request - missing idField", 400);
  1233. $query = V::get('q', '', $_REQUEST);
  1234. DBG::log("\$query({$query})");
  1235. $cellInfo = DB::getPDO()->fetchFirst("
  1236. select *
  1237. from CRM_PROCES_idx_TABLES_INFO_VIEW
  1238. where ID_CELL = :id
  1239. ", [ ':id' => $idField ]);
  1240. DBG::log($cellInfo, 'array', "cell info");
  1241. if (!$cellInfo) throw new HttpException("Bad Request - wrong idField", 400);
  1242. // 'ID_CELL' => '24310',
  1243. // 'CELL_NAME' => 'L_APPOITMENT_USER',
  1244. // 'CELL_LABEL' => 'Osoba odpowiedzialna',
  1245. // 'CELL_DESCRIPTION' => '',
  1246. // 'CELL_SORT_PRIO' => '3',
  1247. // 'ID_TABLE' => '13051',
  1248. // 'TABLE_NAME' => 'TEST_PERMS',
  1249. // 'TABLE_LABEL' => 'Test permy',
  1250. // 'TABLE_DESCRIPTION' => '',
  1251. // 'ID_DATABASE' => '36',
  1252. $namespace = (false !== strpos($cellInfo['TABLE_NAME'], '/')) ? $cellInfo['TABLE_NAME'] : "default_db/{$cellInfo['TABLE_NAME']}";
  1253. if (!$namespace) throw new HttpException("Bad Request - wrong idField, cannot find namespace", 400);
  1254. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1255. $fieldName = $cellInfo['CELL_NAME'];
  1256. $jsonData = array();
  1257. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  1258. if ($typeSpecial) {
  1259. // if (idRecord or selected) { // TODO
  1260. // $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  1261. // $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  1262. $rawRows = null;
  1263. $rows = $typeSpecial->getValuesWithExports($query);
  1264. DBG::log($rows, 'array', "\$rows({$query})");
  1265. foreach ($rows as $kID => $vItem) {
  1266. $itemJson = new stdClass();
  1267. $itemJson->id = $vItem->id;
  1268. $itemJson->name = $vItem->param_out;
  1269. if (!empty($vItem->exports)) {
  1270. $itemJson->exports = $vItem->exports;
  1271. }
  1272. if (!empty($vItem->{'$order'})) {
  1273. $itemJson->{'$order'} = $vItem->{'$order'};
  1274. }
  1275. $jsonData[] = $itemJson;
  1276. }
  1277. }
  1278. return $jsonData;
  1279. }
  1280. function exportAction() {
  1281. Router::getRoute('ExportTableAjax')->defaultAction();
  1282. }
  1283. public function loadDataAjaxAction() {
  1284. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  1285. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1286. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1287. $backRefFilter = [
  1288. 'namespace' => V::get('backRefNS', '', $_REQUEST),
  1289. 'primaryKey' => V::get('backRefPK', '', $_REQUEST),
  1290. 'fieldName' => V::get('backRefField', '', $_REQUEST),
  1291. ];
  1292. $childRefFilter = [
  1293. 'namespace' => V::get('childRefNS', '', $_GET),
  1294. 'primaryKey' => V::get('childRefPK', '', $_GET),
  1295. ];
  1296. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
  1297. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  1298. }
  1299. public function uploadFilesAjaxAction() {
  1300. Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
  1301. }
  1302. public function uploadFilesAjax($args) {
  1303. DBG::log($_FILES, 'array', "\$_FILES");
  1304. DBG::log(ini_get("upload_max_filesize"), 'array', "ini_get('upload_max_filesize')");
  1305. DBG::log(ini_get("post_max_size"), 'array', "ini_get('post_max_size')");
  1306. DBG::log($args, 'array', "\$args");
  1307. $namespace = V::get('namespace', '', $args, 'word');
  1308. if (!$namespace) throw new Exception("Missing namespace");
  1309. $primaryKey = V::get('primaryKey', '', $args, 'int');
  1310. if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
  1311. if (empty($_FILES)) throw new Exception("Missing files");
  1312. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1313. Lib::loadClass('FileUploader');
  1314. Lib::loadClass('FoldersConfig');
  1315. // $dbID = $acl->getDB();
  1316. // $db = DB::getDB($dbID);
  1317. // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1318. $record = $acl->buildQuery([])->getItem($primaryKey);
  1319. DBG::log($record, 'array', "\$record");
  1320. if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
  1321. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1322. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1323. $rootTableName = $acl->getRootTableName();
  1324. $confTblName = "{$rootTableName}_COLUMN";
  1325. $folderConfAll = FoldersConfig::getRawData();
  1326. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
  1327. $folderConf = FoldersConfig::getAll($confTblName);
  1328. DBG::log($folderConf, 'array', "\$folderConf");
  1329. $uploader = new FileUploader($confTblName, (object)$record);
  1330. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
  1331. $uploader->findFolder();
  1332. DBG::log($uploader, 'array', "\$uploader");
  1333. // $errorMsg = '';
  1334. // if (!empty($args['SCANS_COLUMN_ADD'])) {
  1335. // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  1336. // }
  1337. // else {
  1338. // $uploaded = $uploader->tryUploadAjax($errorMsg);
  1339. // }
  1340. $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
  1341. DBG::log($destPath, 'array', "\$destPath");
  1342. if (!file_exists($destPath)) {
  1343. if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
  1344. }
  1345. $generateSafeFileName = function($destPath, $fileName) {
  1346. if (!file_exists("{$destPath}/{$fileName}")) return $fileName;
  1347. $infoPath = pathinfo($fileName);
  1348. // pathinfo('/path/t1/t2/fileName.ext') = [
  1349. // [dirname] => /path/t1/t2
  1350. // [basename] => fileName.ext
  1351. // [extension] => ext
  1352. // [filename] => fileName
  1353. // ]
  1354. return $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
  1355. };
  1356. $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
  1357. $safeName = $generateSafeFileName($destPath, $file['name']);
  1358. return [
  1359. $file['tmp_name'], // TODO: BUG when empty? file size limit!
  1360. "{$destPath}/{$safeName}",
  1361. $safeName,
  1362. ];
  1363. }, $_FILES);
  1364. DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
  1365. $errorMsgs = [];
  1366. $pkField = $acl->getSqlPrimaryKeyField();
  1367. foreach ($moveActions as $fileMoveAction) {
  1368. if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
  1369. $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
  1370. } else {
  1371. try {
  1372. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  1373. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  1374. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1375. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1376. ]);
  1377. if ($affected) {
  1378. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  1379. 'ID_USERS2' => $primaryKey,
  1380. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  1381. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1382. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1383. ]);
  1384. }
  1385. } catch (Exception $e) {
  1386. DBG::log($e);
  1387. $errorMsgs[] = $e->getMessage();
  1388. }
  1389. }
  1390. }
  1391. if (!empty($errorMsgs)) {
  1392. return [
  1393. 'type' => "error",
  1394. 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
  1395. 'errors' => $errorMsgs,
  1396. ];
  1397. }
  1398. return [
  1399. 'type' => "success",
  1400. 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
  1401. ];
  1402. }
  1403. public function removeFileAjaxAction() {
  1404. Response::sendTryCatchJson([$this, 'removeFileAjax'], $args = $_REQUEST);
  1405. }
  1406. public function removeFileAjax($args) { // ajaxFileRemove
  1407. $namespace = V::get('namespace', '', $args, 'word');
  1408. if (!$namespace) throw new Exception("Missing namespace");
  1409. $id = V::get('ID', 0, $args, 'int');
  1410. if ($id <= 0) throw new Exception("Missing ID");
  1411. $filename = V::get('filename', '', $args);
  1412. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  1413. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1414. $dbID = $acl->getDB();
  1415. $db = DB::getPDO($dbID);
  1416. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1417. $record = $acl->buildQuery([])->getItem($id);
  1418. if (!$record) throw new HttpException("No item ID({$id})", 404);
  1419. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1420. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1421. Lib::loadClass('FileUploader');
  1422. Lib::loadClass('FoldersConfig');
  1423. $tblName = $acl->getName();
  1424. $confTblName = "{$tblName}_COLUMN";
  1425. $folderConfAll = FoldersConfig::getRawData();
  1426. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  1427. $folderConf = FoldersConfig::getAll($confTblName);
  1428. $uploader = new FileUploader($confTblName, (object)$record);
  1429. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1430. $uploader->findFolder();
  1431. $errorMsg = '';
  1432. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  1433. if (!$removed) throw new Exception($errorMsg);
  1434. // $affected = DB::getPDO($acl->getDB())->update();
  1435. $rootTableName = $acl->getRootTableName();
  1436. $pkField = $acl->getSqlPrimaryKeyField();
  1437. $primaryKey = $id;
  1438. try {
  1439. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  1440. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  1441. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1442. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1443. ]);
  1444. if ($affected) {
  1445. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  1446. 'ID_USERS2' => $primaryKey,
  1447. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  1448. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1449. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1450. ]);
  1451. }
  1452. } catch (Exception $e) {
  1453. DBG::log($e);
  1454. }
  1455. return [
  1456. 'type' => 'success',
  1457. 'msg' => 'Plik został usunięty',
  1458. ];
  1459. }
  1460. public function procesInitFiltrAjaxAction() {
  1461. Response::sendTryCatchJson([$this, 'procesInitFiltrAjax'], $args = $_GET);
  1462. }
  1463. public function procesInitFiltrAjax($args) { // ajaxFileRemove
  1464. $namespace = V::get('namespace', '', $args, 'word');
  1465. if (!$namespace) throw new Exception("Missing namespace");
  1466. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1467. $pInitList = User::getAcl()->getTableProcesInitList($acl->getID());
  1468. DBG::log($pInitList, 'array', "\$pInitList");
  1469. if (!empty($pInitList)) {
  1470. $procesIds = array_keys($pInitList);
  1471. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  1472. DBG::log($mapTree, 'array', "\$mapTree");
  1473. DBG::log($pInitList, 'array', "\$pInitList");
  1474. $pInitListSelected = User::getAcl()->getPermsFiltrProcesId();
  1475. return [
  1476. 'type' => 'success',
  1477. 'msg' => 'ok',
  1478. 'pInitData' => [
  1479. 'pInitList' => $pInitList,
  1480. 'mapTree' => $mapTree,
  1481. 'pInitListSelected' => $pInitListSelected,
  1482. ],
  1483. ];
  1484. }
  1485. return [
  1486. 'type' => 'success'
  1487. ];
  1488. }
  1489. public function tableToolsAjaxAction() {
  1490. Response::sendTryCatchJson([$this, 'tableToolsAjax'], $args = $_GET);
  1491. }
  1492. public function tableToolsAjax($args) { // ajaxFileRemove
  1493. $namespace = V::get('namespace', '', $args, 'word');
  1494. if (!$namespace) throw new Exception("Missing namespace");
  1495. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1496. $listUrlFunctions = Route_UrlAction::getTableFunctions($acl->getID(), $idRecord = 0, $acl->getName(), User::getLogin());
  1497. DBG::log($listUrlFunctions, 'array', "\$listUrlFunctions");
  1498. $listUrlFunctions = array_map(function ($urlFunction) use ($namespace) {
  1499. if ('index.php?' === substr($urlFunction['baseLink'], 0, strlen('index.php?'))) $urlFunction['baseLink'] .= "&_fromNamespace={$namespace}";
  1500. return $urlFunction;
  1501. }, $listUrlFunctions);
  1502. return [
  1503. 'type' => "success",
  1504. 'msg' => 'ok',
  1505. 'body' => [
  1506. 'tableTools' => array_values(array_map(function ($urlFunction) {
  1507. return [
  1508. 'url' => $urlFunction['baseLink'],
  1509. 'label' => $urlFunction['label'],
  1510. // TODO: $urlFunction['link_target'] // "_blank"
  1511. // ? $urlFunction['name']
  1512. ];
  1513. }, array_filter($listUrlFunctions, function ($urlFunction) {
  1514. return empty($urlFunction['cell_id_params']);
  1515. }))),
  1516. ],
  1517. ];
  1518. }
  1519. function executeRowFunctionAction() { UI::layout([ $this, 'executeRowFunction' ]); }
  1520. function executeRowFunction() {
  1521. $namespace = V::get('namespace', '', $_GET);
  1522. $name = V::get('name', '', $_GET);
  1523. $pk = V::get('pk', '', $_GET);
  1524. if (!$namespace) throw new Exception("Missing namespace");
  1525. if (!$name) throw new Exception("Missing name");
  1526. if (!$pk) throw new Exception("Missing pk");
  1527. $acl = ACL::getAclByNamespace($namespace);
  1528. if (!method_exists($acl, 'executeGuiRowFunction')) throw new Exception("Function executeGuiRowFunction not defined for '{$namespace}'");
  1529. $acl->executeGuiRowFunction($name, $pk);
  1530. }
  1531. }