ViewTableAjax.php 67 KB

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