ViewTableAjax.php 63 KB

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