TableAjax.php 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635
  1. <?php
  2. Lib::loadClass('ViewAjax');
  3. Lib::loadClass('TableAjaxMap');
  4. Lib::loadClass('Typespecial');
  5. Lib::loadClass('UI');
  6. Lib::loadClass('FoldersConfig');
  7. Lib::loadClass('FileUploader');
  8. Lib::loadClass('UserProfile');
  9. Lib::loadClass('ProcesHelper');
  10. Lib::loadClass('Router');
  11. Lib::loadClass('Route_UrlAction');
  12. Lib::loadClass('Core_AclHelper');
  13. Lib::loadClass('AntAclBase');
  14. // TODO: change all links: MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={idZasob} to _route=ViewTableAjax&typeName=p5_default_db:{tableName}
  15. class TableAjax extends ViewAjax {
  16. public $_cnf = '';// Column
  17. public $_htmlID = '';
  18. public $_rowFunctions = array();
  19. public $_pageSize = 10;
  20. public $_pageSizes = array();
  21. public $_filterInit = null;
  22. public $_forceFilterInit = null;
  23. public $showProcesInitFiltr = null;
  24. public $showTableTools = null;
  25. public $useUserTableFilter = false;
  26. public $syncUrl = null;
  27. public function __construct($tblAcl) {
  28. $this->_tbl = $tblAcl->getName();
  29. $this->_acl = $tblAcl;
  30. $this->_zasobID = $tblAcl->getID();
  31. $this->_pageSize = 10;
  32. {
  33. UserProfile::load();
  34. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  35. $this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
  36. }
  37. $this->_pageSizes = array(10, 20, 50, 100);// default page sizes
  38. $this->_filterInit = new stdClass();
  39. $hash = V::get('_hash', '', $_GET);
  40. if ($hash) {
  41. $this->_htmlID = $hash;
  42. $this->_readState();
  43. } else {
  44. $this->_htmlID = $this->generateHtmlID();
  45. $this->_readState();
  46. }
  47. }
  48. public function setSyncUrl($syncUrl) { $this->syncUrl = $syncUrl; }
  49. public function setRootUrl($rootUrl) { $this->rootUrl = $rootUrl; }
  50. private function _hasStateFilterInit() {
  51. return (
  52. array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])
  53. && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID])
  54. && !empty((array)$_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'])
  55. );
  56. }
  57. // TODO: read state from cache by key $this->_htmlID
  58. // TODO: load filters and state: table, edit, add, etc.
  59. // TODO: save this data in Workspace 1, 2, 3, etc.
  60. // TODO: default filters in VIEWTABLE_AJAX
  61. // $tbl->setLabel($zasobObj->OPIS);
  62. // $tbl->setFilterInit($filterInit);
  63. // $tbl->addRowFunction('edit');
  64. // $tbl->addRowFunction('hist');
  65. // $tbl->addRowFunction('files');
  66. // $tbl->addRowFunction('cp');
  67. private function _readState() {
  68. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  69. $_SESSION['TableAjax_Cache'] = array();
  70. }
  71. //trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
  72. //trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
  73. if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  74. foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
  75. //trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
  76. switch ($k) {
  77. case '_label':
  78. $this->_label = $v;
  79. break;
  80. case '_filterInit':
  81. // DBG::log([ '$this->_filterInit' => $this->_filterInit ], 'array', "TODO:BUG?:filters");
  82. $this->_filterInit = $v;
  83. break;
  84. case '_rowFunctions':
  85. $this->_rowFunctions = $v;
  86. break;
  87. default:
  88. }
  89. }
  90. }
  91. }
  92. protected function _saveState($key = null) {
  93. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  94. $_SESSION['TableAjax_Cache'] = array();
  95. }
  96. if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  97. $_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
  98. }
  99. if (!$key) {
  100. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  101. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  102. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  103. } else if ($key == '_label') {
  104. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  105. } else if ($key == '_filterInit') {
  106. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  107. } else if ($key == '_rowFunctions') {
  108. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  109. }
  110. }
  111. public function setPageSizes($pageSizes) {
  112. $this->_pageSizes = $pageSizes;
  113. }
  114. public function setBackRefFilter($backRefFilter) {
  115. $this->_backRefFilter = $backRefFilter;
  116. }
  117. public function setChildRefFilter($childRefFilter) {
  118. $this->_childRefFilter = $childRefFilter;
  119. }
  120. public function setFilterInit($filterInit) {
  121. // DBG::log([ '$this->_filterInit' => $this->_filterInit, 'hasFiltersInit' => $this->_hasStateFilterInit() ], 'array', "TODO:BUG?:filters - setFilterInit");
  122. if ($this->_hasStateFilterInit()) {
  123. return;
  124. }
  125. $this->_filterInit = (object)$filterInit;
  126. $this->_saveState();
  127. }
  128. /**
  129. * @param array $forceFilterInit
  130. */
  131. public function setForceFilterInit($forceFilterInit) {
  132. $this->_forceFilterInit = (object)$forceFilterInit;
  133. }
  134. private function setFilters($filterInit) {
  135. $this->_filterInit = (object)$filterInit;
  136. // DBG::log([ '$this->_filterInit' => $this->_filterInit ], 'array', "TODO:BUG?:filters - setFilters");
  137. $this->_saveState();
  138. }
  139. function getFilters() {
  140. return (array)$this->_filterInit;
  141. }
  142. public function setRowFunctions($functions) {
  143. $this->_rowFunctions = [];
  144. $defaultRowFunction = array();
  145. $defaultRowFunction['edit'] = [ 'href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord', 'class' => "btn btn-xs btn-link" ];
  146. $defaultRowFunction['hist'] = [ 'href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia', 'class' => "btn btn-xs btn-link" ];
  147. $defaultRowFunction['files'] = [ 'href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki', 'class' => "btn btn-xs btn-link" ];
  148. $defaultRowFunction['cp'] = [ 'href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});', 'class' => "btn btn-xs btn-link" ];
  149. $defaultRowFunction['msgs'] = [ 'href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości', 'class' => "btn btn-xs btn-link" ];
  150. foreach ($functions as $funName => $params) {
  151. if (true === $params) {
  152. if (array_key_exists($funName, $defaultRowFunction)) {
  153. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  154. } else {
  155. throw new Exception("Row function not defined '{$funName}'");
  156. }
  157. }
  158. if (is_array($params)) {
  159. $this->_rowFunctions[$funName] = $params;
  160. }
  161. }
  162. $this->_saveState('_rowFunctions');
  163. }
  164. public function addRowFunction($funName, $funParams = array()) {
  165. $defaultRowFunction = array();
  166. //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="glyphicon glyphicon-pencil" title="Edytuj rekord"></a>';
  167. //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="glyphicon glyphicon-book" title="Historia"></a>';
  168. //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="glyphicon glyphicon-folder-open" title="Pliki"></a>';
  169. //$defaultRowFunction['cp'] = '<a href="#" class="glyphicon glyphicon-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
  170. $defaultRowFunction['edit'] = [ 'href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord', 'class' => "btn btn-xs btn-link" ];
  171. $defaultRowFunction['hist'] = [ 'href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia', 'class' => "btn btn-xs btn-link" ];
  172. $defaultRowFunction['files'] = [ 'href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki', 'class' => "btn btn-xs btn-link" ];
  173. $defaultRowFunction['cp'] = [ 'href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});', 'class' => "btn btn-xs btn-link" ];
  174. $defaultRowFunction['msgs'] = [ 'href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości', 'class' => "btn btn-xs btn-link" ];
  175. if (array_key_exists($funName, $defaultRowFunction)) {
  176. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  177. }
  178. else {
  179. $this->_rowFunctions[$funName] = $funParams;
  180. }
  181. $this->_saveState('_rowFunctions');
  182. }
  183. private function _parseRowFunctions($idRecord = null, $pomin = array(), $showLabel = false) {
  184. $rowFunctions = array();
  185. foreach ($this->_rowFunctions as $kFunName => $vParams) {
  186. if (in_array($kFunName, $pomin)) continue;
  187. //$rowFunctionsOut .= str_replace('{0}', $idRecord, $vUrl);
  188. $attrs = array();
  189. // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  190. $label = '';
  191. $ico = '';
  192. foreach ($vParams as $kParamName => $v) {
  193. if ($kParamName == 'ico') {
  194. $ico = '<span class="' . $v . '"></span>';
  195. continue;
  196. }
  197. $attr = $v;
  198. if ($idRecord > 0) {
  199. $attr = str_replace('{0}', $idRecord, $attr);
  200. }
  201. if ($showLabel && $kParamName == 'title') {
  202. $label = $attr;
  203. }
  204. $attr = $kParamName . '="' . $attr . '"';
  205. $attrs[] = $attr;
  206. }
  207. $rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico} {$label} " . '</a>';
  208. }
  209. return $rowFunctions;
  210. }
  211. private function _showRowFunctions($idRecord = null, $pomin = array(), $showLabel = false) {
  212. $rowFunctionsOut = $this->_parseRowFunctions($idRecord, $pomin, $showLabel);
  213. $rowFunctionsOut = implode('', $rowFunctionsOut);
  214. return $rowFunctionsOut;
  215. }
  216. private function _showRowFunctionsJson($idRecord = null, $pomin = array(), $showLabel = false) {
  217. $rowFunctions = $this->_parseRowFunctions($idRecord, $pomin, $showLabel);
  218. $rowFunctions = (object)$rowFunctions;
  219. return $rowFunctions;
  220. }
  221. public function allowTreeView() {
  222. if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
  223. if ($this->_tbl == 'CRM_PROCES') return true;
  224. return false;
  225. }
  226. public function renderStatic($tblAjaxMap = null) {
  227. static $_rendered = false;
  228. if ($_rendered) return;
  229. if ($tblAjaxMap) $tblAjaxMap->printCSS();
  230. if ($tblAjaxMap) $tblAjaxMap->printJS();
  231. echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
  232. echo UI::h('script', ['src'=>"static/jquery.doubleScroll.js"]);
  233. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css"]);
  234. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
  235. UI::inlineCSS( __FILE__ . '.style.css' );
  236. echo UI::h('script', [ 'src' => "static/vendor.js" ]); // window.p5VendorJs: {React, ReactDOM, createReactClass, Redux}
  237. echo UI::h('script', [ 'src' => "static/p5UI/buildDom.js" ]);
  238. $_rendered = true;
  239. }
  240. public function render() {
  241. $acl = $this->_acl;
  242. $hasGeomFlds = Core_AclHelper::hasGeomFields($acl);
  243. // $tblAjaxMap = ($hasGeomFlds) ? new TableAjaxMap($acl, 512, 400) : null;
  244. $tblAjaxMap = new TableAjaxMap($acl, 512, 400);
  245. $hasPermCreate = Core_AclHelper::hasCreatePerms($acl);
  246. $jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
  247. $jsToogleTableToolsFunctionName = 'tableAjaxToggleTableTools';
  248. ob_start();
  249. $this->renderStatic($tblAjaxMap);
  250. UI::startContainer();
  251. UI::showMessagesForTable($this->_tbl);
  252. UI::endContainer();
  253. $namespace = $acl->getNamespace();
  254. {
  255. $nsSiblings = ACL::getNamespaceSiblings($namespace);
  256. $siblingSelected = $namespace;
  257. $baseUrl = Router::getRoute('ViewTableAjax')->getLink();
  258. }
  259. echo UI::h('div', [ 'class' => "AjaxTableCont" ], [
  260. UI::h('div', [ 'class' => "AjaxTable--header" ], [ // breadcrumb
  261. UI::h('div', [ 'class' => "pull-left", 'style' => "margin-right:12px" ], [
  262. UI::h('a', [
  263. 'href' => "#",
  264. 'onclick' => "return tableAjaxBackToTable();",
  265. 'class' => "AjaxTable--title",
  266. ], $this->getLabelHtml(100) ),
  267. ]),
  268. ($hasPermCreate)
  269. ? UI::h('div', [ 'class' => "btn-group pull-left" ], [
  270. UI::h('a', [ 'title' => "Dodaj nowy rekord", 'class' => "btn btn-xs btn-default", 'href' => "#CREATE" ], [
  271. UI::h('span', [ 'class' => "glyphicon glyphicon-plus" ]),
  272. " Dodaj nowy rekord",
  273. ]),
  274. ])
  275. : '',
  276. ($this->showProcesInitFiltr)
  277. ? UI::h('div', [ 'class' => "btn-group pull-right" ], [
  278. UI::h('a', [ 'class' => "btn btn-xs btn-info dropdown-toggle",
  279. 'data-toggle' => "dropdown",
  280. 'href' => "#",
  281. 'title' => "Uruchom filtr procesu powiązanego z tabelą " . $this->getLabel(),
  282. 'onclick' => "return {$jsToogleFiltrProcesuFunctionName}(this);",
  283. ], "Filtr procesu <span class=\"caret\"></span>"),
  284. UI::h('ul', [ 'class' => "dropdown-menu pull-left", 'style' => "max-height:250px;overflow:auto;" ], [
  285. UI::h('li', [ 'class' => "disabled" ], [
  286. UI::h('a', [ 'href' => "#", 'onclick' => "return false;" ], " loading ... "),
  287. ]),
  288. ]),
  289. ])
  290. : '',
  291. ($this->showTableTools)
  292. ? UI::h('div', [ 'class' => "btn-group pull-right" ], [
  293. UI::h('a', [ 'class' => "btn btn-xs btn-default dropdown-toggle",
  294. 'style' => "margin-right:16px",
  295. 'data-toggle' => "dropdown",
  296. 'href' => "#",
  297. 'title' => "Narzędzia powiązane z tabelą " . $this->getLabel(),
  298. 'onclick' => "return {$jsToogleTableToolsFunctionName}(this);",
  299. ], "Narzędzia <span class=\"caret\"></span>"),
  300. UI::h('ul', [ 'class' => "dropdown-menu pull-left", 'style' => "max-height:250px;overflow:auto;" ], [
  301. UI::h('li', [ 'class' => "disabled" ], [
  302. UI::h('a', [ 'href' => "#", 'onclick' => "return false;" ], " loading ... "),
  303. ]),
  304. ]),
  305. ])
  306. : '',
  307. ($nsSiblings)
  308. ? UI::h('div', [ 'class' => "btn-group pull-right" ], [
  309. UI::h('a', [ 'class' => "btn btn-xs btn-default dropdown-toggle",
  310. 'style' => "margin-right:16px",
  311. 'data-toggle' => "dropdown",
  312. 'href' => "#",
  313. 'title' => "Powiązane obiekty z " . $this->getLabel(),
  314. ], "Obiekty <span class=\"caret\"></span>"),
  315. UI::h('ul', [ 'class' => "dropdown-menu pull-left", 'style' => "max-height:250px;overflow:auto;" ], array_map(function ($sibling) use ($baseUrl, $siblingSelected) {
  316. $siblingLabel = explode('/', $sibling); $siblingLabel = array_pop($siblingLabel);
  317. return UI::h('li', [ 'class' => "" ], [
  318. UI::h('a', [
  319. 'href' => "{$baseUrl}&namespace={$sibling}",
  320. 'class' => "btn btn-link " . ($siblingSelected === $sibling ? "active" : ""),
  321. 'style' => "text-align:left"
  322. ], $siblingLabel),
  323. ]);
  324. }, $nsSiblings)),
  325. ])
  326. : '',
  327. ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI')
  328. ? UI::h('a', [ 'class' => "pull-right", 'style' => "padding:0 20px 0 0", 'href' => "index.php?MENU_INIT=TREEJS&ZASOB_ID={$this->_zasobID}" ], "<i class=\"glyphicon glyphicon-eye-open\"></i> Drzewo")
  329. : '',
  330. ($this->_tbl !== 'IN7_MK_BAZA_DYSTRYBUCJI' && $this->allowTreeView())
  331. ? UI::h('a', [ 'class' => "pull-right", 'style' => "padding:0 20px 0 0", 'href' => "index.php?MENU_INIT=VIEWTREE_AJAX&ZASOB_ID={$this->_zasobID}" ], "<i class=\"glyphicon glyphicon-eye-open\"></i> Drzewo")
  332. : '',
  333. ($this->_tbl == 'WMS_MAP_GEOREFERENCES')
  334. ? UI::h('a', [ 'class' => "pull-right", 'style' => "padding:0 20px 0 0", 'href' => "index.php?_route=GeoreferencesManager" ], "<i class=\"glyphicon glyphicon glyphicon-wrench\"></i> Zarządzaj punktami")
  335. : '',
  336. UI::h('div', [ 'style' => "clear:both" ]),
  337. ]),
  338. ($this->_backRefFilter)
  339. ? UI::h('div', [ 'class' => "container" ], [
  340. UI::h('div', [ 'class' => "alert alert-info" ], [
  341. "Rekordy powiązane z rekordem {$this->_backRefFilter['primaryKey']} z ",
  342. UI::h('a', [
  343. 'href' => "index.php?_route=ViewTableAjax&namespace={$this->_backRefFilter['namespace']}",
  344. ], $this->_backRefFilter['namespace']),
  345. " - ",
  346. UI::h('a', [
  347. 'href' => $this->rootUrl,
  348. 'style' => "color:red",
  349. ], "usuń filtr"),
  350. ]),
  351. ])
  352. : '',
  353. ($this->_childRefFilter)
  354. ? UI::h('div', [ 'class' => "container" ], [
  355. UI::h('div', [ 'class' => "alert alert-info" ], [
  356. "Rekordy powiązane z rekordem {$this->_childRefFilter['primaryKey']} z ",
  357. UI::h('a', [
  358. 'href' => "index.php?_route=ViewTableAjax&namespace={$this->_childRefFilter['namespace']}",
  359. ], $this->_childRefFilter['namespace']),
  360. " - ",
  361. UI::h('a', [
  362. 'href' => $this->rootUrl,
  363. 'style' => "color:red",
  364. ], "usuń filtr"),
  365. ]),
  366. ])
  367. : '',
  368. UI::h('div', [ 'id' => $this->_htmlID ]),
  369. ]);
  370. UI::inlineJS(__FILE__ . '.generateFunctionNode.js');
  371. UI::inlineJS(__FILE__ . '.GeomField.js');
  372. if ($this->showProcesInitFiltr) {
  373. UI::inlineJS(__FILE__ . '.procesInitFiltr.js', [
  374. 'JS_FUNCTION_NAME' => $jsToogleFiltrProcesuFunctionName,
  375. 'URL_GET_PROCES_INIT_FILTR' => $this->showProcesInitFiltr,
  376. 'ID_ZASOB' => $this->_zasobID,
  377. ]);
  378. }
  379. if ($this->showTableTools) {
  380. UI::inlineJS(__FILE__ . '.tableTools.js', [
  381. 'JS_FUNCTION_NAME' => $jsToogleTableToolsFunctionName,
  382. 'URL_GET_TABLE_TOOLS' => $this->showTableTools,
  383. ]);
  384. }
  385. UI::inlineJS(APP_PATH_WWW . '/static/p5UI/FieldCheckboxSearch.js', []); // p5UI__FieldCheckboxSearch
  386. UI::inlineCSS(APP_PATH_WWW . '/static/p5UI/FieldCheckboxLoading.css');
  387. UI::inlineJS(APP_PATH_WWW . '/static/p5UI/FieldCheckboxLoading.js', []); // p5UI__FieldCheckboxLoading
  388. // echo UI::h('style', [ 'type' => "text/css" ], "
  389. // .stickyCol1 { display:none }
  390. // ");
  391. UI::inlineJS(__FILE__ . '.createTableFiltersStateObject.js', [
  392. 'DBG' => ('1' === V::get('DBG_JS', '', $_GET)),
  393. ]);
  394. UI::inlineJS(__FILE__ . '.createTableSelectedStateObject.js', [
  395. 'URI_WPS' => Request::getPathUri() . 'wps.php',
  396. 'DBG' => ('1' === V::get('DBG_JS', '', $_GET)),
  397. ]);
  398. UI::inlineJS(__FILE__ . '.createTableDataStateObject.js', [
  399. 'URI_WPS' => Request::getPathUri() . 'wps.php',
  400. 'DBG' => ('1' === V::get('DBG_JS', '', $_GET)),
  401. ]);
  402. UI::inlineJS(__FILE__ . '.p5UI__TableAjax.js', [
  403. 'DBG' => ('1' === V::get('DBG_JS', '', $_GET)),
  404. ]);
  405. UI::inlineJS(__FILE__ . '.p5UI__TableAjaxSortableLabel.js', [
  406. 'DBG' => ('1' === V::get('DBG_JS', '', $_GET)),
  407. ]);
  408. UI::inlineJS(__FILE__ . '.p5UI__selected.js', [
  409. 'DBG' => ('1' === V::get('DBG_JS', '', $_GET)),
  410. ]);
  411. UI::inlineJS(__FILE__ . '.TableAjax.js', [
  412. 'URI_BASE' => Request::getPathUri(),
  413. 'URI_WPS' => Request::getPathUri() . 'wps.php',
  414. 'RENDER_AS_REACT' => V::get('TEST_RENDER_AS_REACT', '', $_GET),
  415. 'SKIP_TOTAL' => true, // TEST: ('1' === V::get('SKIP_TOTAL', '', $_GET)),
  416. 'DBG' => ('1' === V::get('DBG_JS', '', $_GET)),
  417. ]);
  418. $filterInit = $this->_filterInit;
  419. $forceFilterInit = $this->_forceFilterInit;
  420. $pageSizes = $this->_pageSizes;
  421. $pageSize = $this->_pageSize;
  422. $rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
  423. $exportFields = Core_AclHelper::getExportFieldList($acl);
  424. UI::inlineJS(__FILE__ . '.hist.js', [
  425. 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
  426. 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
  427. 'URL_HIST_BASE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls=" . __CLASS__ . "&_hash={$this->_htmlID}&_task=HIST", // &ID=...
  428. 'FUNCTION_HIST_ROUTE' => "TableAjax__HIST_Route",
  429. ]);
  430. UI::inlineJS(__FILE__ . '.create.js', [
  431. 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
  432. 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
  433. 'NAMESPACE' => $acl->getNamespace(),
  434. 'FIRCE_FILTER_INIT' => $forceFilterInit,
  435. 'FUNCTION_CREATE_ROUTE' => "TableAjax__CREATE_Route",
  436. 'URL_CREATE_FORM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=createFormJson",
  437. ]);
  438. UI::inlineJS(__FILE__ . '.edit.js', [
  439. 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
  440. 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
  441. 'NAMESPACE' => $acl->getNamespace(),
  442. 'FUNCTION_EDIT_ROUTE' => "TableAjax__EDIT_Route",
  443. 'URL_EDIT_FORM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=editFormJson&_primaryKey=",
  444. ]);
  445. UI::inlineJS(__FILE__ . '.openRef.js', []); // p5UI__tableAjaxOpenRefCell
  446. $specialFilters = (method_exists($acl, 'getSpecialFilters')) ? $acl->getSpecialFilters() : null;
  447. $className = __CLASS__;
  448. UI::inlineJS(__FILE__ . '.init.js', [
  449. 'GUI_SHOW_CHECKBOXES' => 1, // ('1' === V::get('TEST_CHECKBOX', '', $_GET)),
  450. 'CHECKBOX_ID_CONTEXT' => V::get('TEST_CHECKBOX_CONTEXT', '', $_GET), // TODO: test generate @selected context
  451. 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
  452. 'NAMESPACE' => $acl->getNamespace(),
  453. 'FUNCTION_HIST_ROUTE' => 'TableAjax__HIST_Route',
  454. 'FUNCTION_EDIT_ROUTE' => 'TableAjax__EDIT_Route',
  455. 'URL_LOAD_AJAX_BASE' => $this->syncUrl . '&_hash=' . $this->_htmlID . '&_task=loadDataAjax',
  456. 'URL_USER_TABLE_FILTER' => ($this->useUserTableFilter) ? $this->useUserTableFilter : '',
  457. 'FILTER_INIT' => $filterInit,
  458. 'FIRCE_FILTER_INIT' => $forceFilterInit,
  459. 'PAGE_SIZE' => $pageSize,
  460. 'PAGE_SIZES' => $pageSizes,
  461. 'URL_GET_CSV_THE_GEOM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=getCsvTheGeomAjax",
  462. 'URL_REMOVE_THE_GEOM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=removeTheGeomAjax",
  463. 'URL_MORE_FUNCTIONS_CELL_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=moreFunctionsCellAjax",
  464. 'URL_EDIT_INLINE_SAVE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=EDIT_INLINE_SAVE",
  465. 'URL_THE_GEOM_SAVE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=THE_GEOM_SAVE",
  466. 'URL_PAGE_SIZE_SAVE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=PAGE_SIZE_SAVE",
  467. 'URL_HIDDEN_COLS_SAVE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=HIDDEN_COLS_SAVE",
  468. 'URL_EDIT_INLINE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=EDIT_INLINE",
  469. 'URL_RECORD_COPY' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=COPY",
  470. 'URL_RECORD_FILES' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES",
  471. 'HAS_ADDITIONAL_LAYERS' => $this->hasAdditionalLayers() ? 1 : 0,
  472. 'URL_ADD_USER_TABLE_FILTER_AJAX' => Request::getPathUri() . "index.php?_route=ViewTableAjax&_task=addUserTableFilterAjax",
  473. 'URL_RM_USER_TABLE_FILTER_AJAX' => Request::getPathUri() . "index.php?_route=ViewTableAjax&_task=rmUserTableFilterAjax",
  474. 'LABEL_HTML' => $this->getLabelHtml(100),
  475. 'SPECIAL_FILTER_FUNCTIONS' => (!empty($specialFilters)) ? $specialFilters : false,
  476. 'ROW_FUNCTIONS' => $rowFunctions,
  477. 'TABLE_FUNCTIONS' => array_merge(
  478. [ 'shortdesc' => [ 'icon' => "align-left", 'title' => "Long desc", 'method' => "longTextChanged" ] ],
  479. ($hasGeomFlds)
  480. ? [ 'mapeditor' => [ 'icon' => "map-marker", 'title' => "Mapa", 'method' => 'mapEditorChanged' ] ]
  481. : [],
  482. [ 'create' => [ 'href' => '#CREATE', 'icon' => 'plus', 'title' => "Dodaj nowy rekord" ] ],
  483. [ 'refresh' => [ 'icon' => 'refresh', 'title' => "Odśwież dane", 'method' => "refresh" ] ]
  484. ),
  485. 'EXPORT_FIELDS' => $exportFields,
  486. ]);
  487. UI::inlineJS(__FILE__ . '.upload.js', [
  488. 'URL_UPLOAD_FILES_AJAX' => "index.php?_route=ViewTableAjax&_task=uploadFilesAjax",
  489. ]);
  490. UI::setTitle($this->_acl->getRawLabel(100) . " - " . UI::getTitle());
  491. return ob_get_clean();
  492. }
  493. public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
  494. $vLabel = $pInitList[$vInitId];
  495. $kId = $vInitId;
  496. echo UI::h('a', [
  497. 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
  498. 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
  499. ], [
  500. UI::h('i', [
  501. 'class' => "glyphicon glyphicon-info-sign",
  502. 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
  503. 'style' => "color:#aaa",
  504. 'onmouseover' => "this.style.color='#337AB7'",
  505. 'onmouseout' => "this.style.color='#aaa'"]),
  506. "{{$kId}} {$vLabel}"
  507. ]);
  508. }
  509. public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
  510. $vLabel = $pInitList[$vGotoId];
  511. $kId = $vGotoId;
  512. // TODO:?: prevent to execute procedure
  513. echo UI::h('a', [
  514. 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
  515. 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
  516. ], [
  517. UI::h('span', [ 'style' => "padding:10px;"]),
  518. UI::h('i', [ 'class' => "glyphicon glyphicon-arrow-right", 'style' => "color:#aaa"]),
  519. UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign",
  520. 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
  521. 'style' => "color:#aaa",
  522. 'onmouseover' => "this.style.color='#337AB7'",
  523. 'onmouseout' => "this.style.color='#aaa'"]),
  524. "{{$kId}} {$vLabel}",
  525. ]);
  526. }
  527. public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
  528. $vLabel = $pInitList[$vGotoLvl2Id];
  529. $kId = $vGotoLvl2Id;
  530. // TODO:?: prevent to execute procedure
  531. echo UI::h('a', [
  532. 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
  533. 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
  534. ], [
  535. UI::h('span', [ 'style' => "padding:20px;" ]),
  536. UI::h('i', [ 'class' => "glyphicon glyphicon-arrow-right", 'style' => "color:#aaa" ]),
  537. UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign",
  538. 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
  539. 'style' => "color:#aaa",
  540. 'onmouseover' => "this.style.color='#337AB7'",
  541. 'onmouseout' => "this.style.color='#aaa'"]),
  542. "{{$kId}} {$vLabel}",
  543. ]);
  544. }
  545. public function hasAdditionalLayers() {
  546. $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
  547. return !empty($layers);
  548. }
  549. public function ajaxTask($task) {
  550. switch ($task) {
  551. case 'EDIT_INLINE': {
  552. $this->sendAjaxResponseJson('ajaxInlineEdit', $_REQUEST);
  553. break;
  554. }
  555. case 'EDIT_INLINE_SAVE': {
  556. $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
  557. break;
  558. }
  559. case 'COPY': {
  560. $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
  561. break;
  562. }
  563. case 'CREATE_SAVE': { // TODO: mv to _route = ViewTableAjax & _task = createSaveAjax
  564. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  565. break;
  566. }
  567. case 'HIST': {
  568. $this->sendAjaxResponseJson('ajaxHist', $_REQUEST);
  569. break;
  570. }
  571. case 'FILES': {
  572. try {
  573. $id = V::get('ID', 0, $_REQUEST, 'int');
  574. if ($id <= 0) throw new HttpException("404", 404);
  575. $this->sendAjaxFiles($id, $_REQUEST);
  576. } catch (HttpException $e) {
  577. Http::sendHeaderByCode($e->getCode());
  578. echo $e->getMessage();
  579. //UI::alert('danger', $e->getMessage());
  580. } catch (Exception $e) {
  581. echo '<div class="container">';
  582. UI::alert('danger', $e->getMessage());
  583. echo '</div>';
  584. }
  585. break;
  586. }
  587. case 'FILES_UPLOAD': {
  588. $this->sendAjaxResponseJson('ajaxFileUpload', $_REQUEST);
  589. break;
  590. }
  591. case 'FILES_LIST': {
  592. $this->sendAjaxResponseJson('ajaxFileList', $_REQUEST);
  593. break;
  594. }
  595. case 'filePermsRefresh': {
  596. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  597. break;
  598. }
  599. case 'FILES_CONN_TBL_LIST': {
  600. $id = V::get('ID', 0, $_REQUEST, 'int');
  601. if ($id > 0) {
  602. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  603. } else {
  604. echo '404';
  605. }
  606. break;
  607. }
  608. case 'TYPESPECIAL': {
  609. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  610. if ($fldID > 0) {
  611. $this->sendTypeSpecial($fldID, $_REQUEST);
  612. } else {
  613. echo '404';
  614. }
  615. break;
  616. }
  617. case 'HIDDEN_COLS_SAVE': {
  618. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  619. break;
  620. }
  621. case 'PAGE_SIZE_SAVE': {
  622. $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
  623. break;
  624. }
  625. case 'THE_GEOM_SAVE': {
  626. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  627. break;
  628. }
  629. default:
  630. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  631. }
  632. }
  633. /**
  634. * ajax url: &_task=EDIT_INLINE
  635. * @param $rowID - $_GET['ID']
  636. * @param $fieldName - $_GET['col']
  637. */
  638. private function ajaxInlineEdit() {
  639. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  640. $args = $_REQUEST;
  641. $idRecord = V::get('ID', 0, $_REQUEST, 'int');
  642. $fieldName = V::get('col', '', $_REQUEST);
  643. if ($idRecord <= 0 || empty($fieldName)) throw new HttpException("404", 404);
  644. $response = array();
  645. ob_start();
  646. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  647. if (!$fieldID) die("404: No field by name ({$fieldName})");
  648. $response['idZasob'] = $fieldID;
  649. $response['htmlFieldName'] = "f{$fieldID}";
  650. if ($DBG) echo "fieldID: {$fieldID}\n";
  651. $record = $this->_acl->buildQuery([])->getItem($idRecord);
  652. if (!$record) die("404: No item ID({$idRecord})");
  653. $fieldVal = '';
  654. if ($this->_acl->canReadObjectField($fieldName, $record)) {
  655. $fieldVal = V::get($fieldName, $fieldVal, $record);
  656. } else {
  657. $fieldVal = '*****';
  658. }
  659. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  660. $vCol = $this->_acl->getField($fieldID);
  661. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  662. $response['fieldLabel'] = $vCol['label'];
  663. $tsValues = array();
  664. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  665. if ($typeSpecial) {
  666. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  667. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $fieldName, V::get($fieldName, $fieldVal, $record));
  668. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  669. if (!empty($specialValues)) {
  670. $tsValues[ $record['ID'] ] = implode('<br>', $specialValues);
  671. }
  672. }
  673. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  674. if (!empty($tsValues[ $record['ID'] ])) $fieldParams['typespecialValue'] = $tsValues[ $record['ID'] ];
  675. if (!empty($tsValues[ $record['ID'] ])) $response['typespecialValue'] = $tsValues[ $record['ID'] ];
  676. $vDefault = $this->_acl->getFieldDefaultValue($fieldName);
  677. if (!empty($vDefault)) $fieldParams['default'] = $vDefault;
  678. if (!empty($vDefault)) $response['defaultValue'] = $vDefault;
  679. if (method_exists($this->_acl, 'getFormItem')) {
  680. try {
  681. $item = $this->_acl->getFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $record);
  682. $response['formItem'] = $item;
  683. if (!empty($item['rawColType']['simpleType'])) $response['simpleType'] = $item['rawColType']['simpleType'];
  684. if (!empty($item['rawColType']['restrictions'])) $response['restrictions'] = $item['rawColType']['restrictions'];
  685. DBG::log($item, 'array', "\$item (Acl->getFormItem)");
  686. } catch (Exception $e) {
  687. echo '<div style="display:none">';
  688. UI::alert('danger', $e->getMessage());
  689. echo '</div>';
  690. }
  691. }
  692. ?>
  693. <label for="<?= "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  694. <strong title="<?= "[{$fieldID}] {$fieldName}"; ?>"><?= "{$vCol['label']}"; ?></strong>
  695. <?php if (!empty($vCol['opis'])) : ?>
  696. <em><?= $vCol['opis']; ?></em>
  697. <?php endif; ?>
  698. </label>
  699. <?php
  700. if (!$this->_acl->canWriteObjectField($fieldName, $record)) {
  701. // TODO: hide Zapisz btn on frontend side
  702. if (!$this->_acl->canReadObjectField($fieldName, $record)) {
  703. UI::alert('warning', "Brak uprawnień do odczytu i zapisu");
  704. } else {
  705. echo '<p style="margin-top:16px">' . $fieldVal . '</p>';
  706. UI::alert('warning', "Brak uprawnień do zapisu");
  707. }
  708. } else {
  709. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $record);
  710. if ($typeSpecial
  711. || $this->_acl->isDateField($fieldName)
  712. || $this->_acl->isDateTimeField($fieldName)
  713. ) {
  714. echo '<p style="padding:120px 0;"></p>';
  715. }
  716. }
  717. $response['legacy_html'] = ob_get_clean();
  718. //$response['legacy_html'] = utf8_encode($response['legacy_html']);// pl chars bug
  719. return $response;
  720. }
  721. private function ajaxEditInlineSave($args) {
  722. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  723. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  724. $fieldName = V::get('col', '', $_REQUEST);
  725. if (empty($primaryKey)) throw new HttpException("Wrong param id!", 400);
  726. if (empty($fieldName)) throw new HttpException("Wrong param col!", 400);
  727. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  728. if (!$fieldID) throw new HttpException("Field not exists!", 404);
  729. $item = $this->_acl->buildQuery([])->getItem($primaryKey);
  730. if (!$item) throw new HttpException("Item not exists!", 404);
  731. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  732. if (!isset($itemFromUser[$fieldName])) throw new HttpException("Field not set!", 400);
  733. $itemPatch = array();
  734. $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
  735. $itemPatch[$primaryKeyField] = $primaryKey;
  736. $response = new stdClass();
  737. try {
  738. $affected = $this->_acl->updateItem($itemPatch);
  739. if ($affected > 0) {
  740. $response->type = 'success';
  741. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  742. } else if ($affected == 0) {
  743. $response->type = 'info';
  744. $response->msg = "Nie wprowadzono żadnych zmian";
  745. }
  746. $response->record = $this->_acl->buildQuery([])->getItem($primaryKey);
  747. }
  748. catch (Exception $e) {
  749. $response->type = 'error';
  750. $response->msg = $e->getMessage();
  751. }
  752. return $response;
  753. }
  754. public function sendAjaxEdit($id, $args) { // TODO: not used @see ViewTableAjax::editFormAction
  755. header("Content-type: text/plain");
  756. $acl = $this->_acl;
  757. $record = $acl->buildQuery([])->getItem($id);
  758. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  759. UI::alert('danger', "Brak dostępu do rekordu");
  760. return;
  761. }
  762. $fieldsList = array();
  763. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  764. if ($fieldName == 'ID') continue;
  765. $field['name'] = $fieldName;
  766. $field['opis'] = $acl->getFieldOpis($fieldName);
  767. $field['label'] = $acl->getFieldLabel($fieldName);
  768. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  769. $fieldsList[$kID] = $field;
  770. }
  771. $cols = array();
  772. foreach ($fieldsList as $kID => $field) {
  773. $cols[$kID] = '';
  774. if ($this->_acl->canReadObjectField($field['name'], $record)) {
  775. $cols[$kID] = V::get($field['name'], '', $record);
  776. } else {
  777. $cols[$kID] = '*****';
  778. }
  779. // if ($acl->canReadObjectField($field['name'])) {
  780. // $cols[$kID] = V::get($field['name'], '', $record);
  781. // } else {
  782. // $cols[$kID] = '*****';
  783. // }
  784. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  785. }
  786. $tsValues = array();
  787. if (!empty($fieldsList)) {
  788. foreach ($fieldsList as $vColID => $vCol) {
  789. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  790. if ($typeSpecial) {
  791. $colValue = V::get($vCol['name'], '', $record);
  792. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $vCol['name'], $colValue);
  793. if (!empty($specialValues)) {
  794. $tsValues[$vColID] = implode('<br>', $specialValues);
  795. }
  796. }
  797. }
  798. }
  799. $rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  800. ?>
  801. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  802. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?= $this->_htmlID; ?>">
  803. <fieldset>
  804. <legend>Edycja rekordu Nr <?= $record['ID']; ?><span class="pull-right valign-btns-bottom"><?= $rowFunctionsOut; ?></span></legend>
  805. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  806. <?php if ($acl->canWriteObjectField($vCol['name'], $record)) : ?>
  807. <div class="form-group">
  808. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?= "f{$kID}"; ?>"><?= $vCol['label']; ?>
  809. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?= htmlspecialchars($vCol['opis']); ?>" data-original-title="<?= "[{$kID}] {$vCol['name']}"; ?>"></i>
  810. </label>
  811. <div class="col-xs-12 col-sm-9 col-md-10">
  812. <?php
  813. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  814. if (!empty($tsValues[$kID])) {
  815. $fieldParams['typespecialValue'] = $tsValues[$kID];
  816. }
  817. echo $acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  818. ?>
  819. </div>
  820. </div>
  821. <?php elseif ($acl->canReadObjectField($vCol['name'], $record)) : ?>
  822. <div class="form-group">
  823. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?= "f{$kID}"; ?>"><?= $vCol['label']; ?>
  824. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?= htmlspecialchars($vCol['opis']); ?>" data-original-title="<?= "[{$kID}] {$vCol['name']}"; ?>"></i>
  825. </label>
  826. <div class="col-xs-12 col-sm-9 col-md-10">
  827. <p style="margin-top:5px;">
  828. <?php
  829. //echo $acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  830. if (!empty($tsValues[$kID])) {
  831. echo $tsValues[$kID];
  832. } else if (!empty($record[ $vCol['name'] ])) {
  833. echo $record[ $vCol['name'] ];
  834. }
  835. ?>
  836. </p>
  837. </div>
  838. </div>
  839. <?php endif; ?>
  840. <?php endforeach; ?>
  841. <div class="form-group">
  842. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  843. <button type="submit" class="btn btn-primary" tabindex="<?= (++$tabindex); ?>">Zapisz</button>
  844. </div>
  845. </div>
  846. </fieldset>
  847. </form>
  848. <p style="padding:100px 0;"></p>
  849. </div>
  850. <script>
  851. jQuery(document).ready(function(){
  852. jQuery('textarea').autosize();
  853. jQuery('.frm-help').popover({trigger:'hover'});
  854. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  855. var formData = {};
  856. jQuery(this).serializeArray().map(function(i) { formData[i.name] = i.value; });// TODO: edit Widget - send only updated fields
  857. // TODO: change Edit btn to return to edit record with fields -> show form
  858. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  859. //taskCont.empty();
  860. taskCont.children().fadeOut('slow');
  861. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  862. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  863. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
  864. function notifyAjaxCallback(data) {
  865. var notify = {}, outMsg = '';
  866. notify.type = (data && data.type)? data.type : '';
  867. notify.msg = (data && data.msg)? data.msg : '';
  868. switch (notify.type) {
  869. case 'success':
  870. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  871. break;
  872. case 'info':
  873. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  874. break;
  875. case 'error':
  876. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  877. break;
  878. case 'warning':
  879. notify.type = 'warn';
  880. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  881. break;
  882. default:
  883. notify.msg = 'Nieznany błąd';
  884. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  885. notify.type = '';
  886. }
  887. jQuery.notify(notify.msg, notify.type);
  888. var alertType = ('error' == data.type) ? 'danger' : data.type;
  889. outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
  890. return outMsg;
  891. }
  892. superagent
  893. .post('<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=editSaveAjax')
  894. .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
  895. .send({
  896. namespace: '<?= $acl->getNamespace(); ?>',
  897. primaryKey: '<?= $record['ID']; ?>',
  898. form: formData
  899. })
  900. .set('Accept', 'application/json')
  901. .end(function(err, res) {
  902. var payload;
  903. if (err || !res.ok || 'application/json' !== res.type) {
  904. payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
  905. } else {
  906. payload = {type: 'success', msg: res.body.msg || '', body: res.body};
  907. }
  908. var data = res.body;
  909. alertCntWrap.removeClass('AjaxTable-loading');
  910. alertCnt.empty();
  911. if (false === ['success', 'info'].indexOf(payload.type)) {
  912. jQuery(errorTxt).appendTo(alertCnt);
  913. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  914. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  915. var backToEditBtn = jQuery('<a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Popraw dane <?php echo $id; ?></a>').appendTo(errLinks);
  916. backToEditBtn.on('click', function(){
  917. alertCnt.remove();
  918. taskCont.children().fadeIn('slow');
  919. return false;
  920. });
  921. } else {
  922. var outMsg = notifyAjaxCallback(payload);
  923. var out = '';
  924. out += outMsg;
  925. out += '<div class="breadcrumb">' +
  926. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  927. ' <a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord <?php echo $id; ?></a>' +
  928. '</div>';
  929. jQuery(out).appendTo(alertCnt);
  930. // add rowFunctions from response
  931. if (data && data.rowFunctions && data.primaryKey) {
  932. var rowFunWrapNode = $('<div class="container"></div>').insertAfter(alertCnt);
  933. var rowFunListNode = $('<ul></ul>').appendTo(rowFunWrapNode);
  934. var keys = Object.keys(data.rowFunctions),
  935. total = keys.length,
  936. moreFuncBtnNode,
  937. moreFunctions = [],
  938. idx
  939. ;
  940. moreFunctions = keys.splice(3);
  941. keys.forEach(function(key) {
  942. var cellNode = $('<li></li>');
  943. var funObj = data.rowFunctions[key],
  944. funcNode = p5UI_TableAjax_generateFunctionNode(funObj, data.primaryKey, {ico: true, label: true})
  945. ;
  946. funcNode.appendTo(cellNode);
  947. cellNode.appendTo(rowFunListNode);
  948. });
  949. }
  950. }
  951. });
  952. return false;
  953. });
  954. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  955. var input, btn, btnIco;
  956. input = jQuery(e.target);
  957. btn = input.next('.button-appendBack');
  958. btnIco = btn.find('.glyphicon');
  959. if (btn.attr('title') != input.val()) {
  960. btnIco.show();
  961. } else {
  962. btnIco.hide();
  963. }
  964. });
  965. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
  966. var input, btn, btnIco;
  967. btn = jQuery(this);
  968. btnIco = btn.find('.glyphicon');
  969. input = btn.prev();
  970. if (input.is('input')) {
  971. if (btn.attr('title') != input.val()) {
  972. input.val(btn.attr('title'));
  973. btnIco.hide();
  974. }
  975. }
  976. });
  977. });
  978. </script>
  979. <?php
  980. exit;
  981. }
  982. public function sendAjaxCreate($args = []) {
  983. $acl = $this->_acl;
  984. header("Content-type: text/plain");
  985. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  986. if (!Core_AclHelper::hasCreatePerms($acl)) {
  987. UI::alert('danger', "Brak uprawnień do utworzenia nowego rekordu.");
  988. return;
  989. }
  990. $cols = array();
  991. $forceFilterInit = array();
  992. $defaultAclGroup = User::getDefaultAclGroup();
  993. if ($defaultAclGroup) {
  994. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  995. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  996. }
  997. foreach ($_GET as $k => $v) {
  998. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  999. $fldName = substr($k, 3);
  1000. $forceFilterInit[$fldName] = $v;
  1001. }
  1002. }
  1003. $pkField = $acl->getPrimaryKeyField();
  1004. $fieldsList = $acl->getFields();
  1005. $fieldsList = array_filter($fieldsList, function ($vCol) {
  1006. return ($vCol['name'] != $pkField);
  1007. });
  1008. foreach ($fieldsList as $kID => $vCol) {
  1009. $defaultValue = '';
  1010. if (!empty($forceFilterInit[$vCol['name']])) {
  1011. $defaultValue = $forceFilterInit[$vCol['name']];
  1012. }
  1013. // TODO: read from session cache
  1014. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  1015. $label = V::get('label', '', $vCol);
  1016. $fieldsList[$kID]['label'] = ($label) ? $label : $vCol['name'];
  1017. }
  1018. ?>
  1019. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  1020. <form action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  1021. <fieldset>
  1022. <legend>Dodaj nowy rekord</legend>
  1023. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  1024. <?php if ($acl->canCreateField($vCol['name'])) : ?>
  1025. <div class="form-group">
  1026. <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?= V::get('label', $vCol['name'], $vCol); ?>
  1027. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars(V::get('opis', '', $vCol)); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  1028. </label>
  1029. <div>
  1030. <?php
  1031. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  1032. echo $acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  1033. ?>
  1034. </div>
  1035. </div>
  1036. <?php endif; ?>
  1037. <?php endforeach; ?>
  1038. <div class="form-group">
  1039. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  1040. </div>
  1041. </fieldset>
  1042. </form>
  1043. </div>
  1044. <script>
  1045. jQuery(document).ready(function(){
  1046. jQuery('textarea').autosize();
  1047. jQuery('.frm-help').popover({trigger:'hover'});
  1048. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  1049. var data = jQuery(this).serialize();
  1050. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  1051. taskCont = taskContLast.parent();
  1052. taskContLast.fadeOut('slow');
  1053. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  1054. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> save ... </div></div>').appendTo(taskCnt);
  1055. function notifyAjaxCallback(data) {
  1056. var notify = {};
  1057. notify.type = (data && data.type)? data.type : '';
  1058. notify.msg = (data && data.msg)? data.msg : '';
  1059. switch (notify.type) {
  1060. case 'success':
  1061. if (!notify.msg) notify.msg = 'OK';
  1062. break;
  1063. case 'info':
  1064. if (!notify.msg) notify.msg = '';
  1065. break;
  1066. case 'error':
  1067. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1068. break;
  1069. case 'warning':
  1070. notify.type = 'warn';
  1071. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1072. break;
  1073. default:
  1074. notify.msg = 'Nieznany błąd';
  1075. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1076. notify.type = '';
  1077. }
  1078. jQuery.notify(notify.msg, notify.type);
  1079. }
  1080. $.ajax({
  1081. data: data,
  1082. dataType: 'json',
  1083. type: "POST",
  1084. async: true,
  1085. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  1086. })
  1087. .always(function(dataOrJqXHR){
  1088. var data;
  1089. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  1090. if ('responseJSON' in dataOrJqXHR) {
  1091. data = dataOrJqXHR.responseJSON;
  1092. } else {
  1093. data = {};
  1094. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  1095. if (dataOrJqXHR.status == 404) {
  1096. data.type = 'error';
  1097. } else {
  1098. data.type = 'warning';
  1099. }
  1100. }
  1101. }
  1102. else {
  1103. data = dataOrJqXHR;
  1104. }
  1105. notifyAjaxCallback(data);
  1106. taskCnt.removeClass('AjaxTable-loading');
  1107. taskCnt.empty();
  1108. if (data.type == 'error' || data.type == 'warning') {
  1109. var out = '<div class="container">' +
  1110. '<div class="alert alert-danger">' +
  1111. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  1112. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  1113. '</div>';
  1114. out += '<div class="breadcrumb">' +
  1115. ' <a class="create-fix" href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do formularza i popraw dane</a></li>' +
  1116. '</div>' +
  1117. '</div>';
  1118. jQuery(out).appendTo(taskCnt);
  1119. var taskContLastNode = taskContLast
  1120. , taskCntNode = taskCnt;
  1121. taskCnt.find('.create-fix').click(function(){
  1122. taskCntNode.remove();
  1123. taskContLastNode.fadeIn('slow');
  1124. return false;
  1125. });
  1126. }
  1127. else if (data.type == 'success') {
  1128. var msg = '';
  1129. if (data.id && data.id > 0) {
  1130. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  1131. } else if (data.msg) {
  1132. msg = data.msg;
  1133. } else {
  1134. msg = 'OK';
  1135. }
  1136. var out = '<div class="container">';
  1137. out += '<div class="alert alert-success">' + msg + '</div>';
  1138. out += '<div class="breadcrumb">' +
  1139. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  1140. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  1141. ' <a href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-plus"></i> Dodaj nowy rekord</a></li>' +
  1142. '</div>';
  1143. out += '</div>';
  1144. jQuery(out).appendTo(taskCnt);
  1145. }
  1146. });
  1147. return false;
  1148. });
  1149. });
  1150. </script>
  1151. <?php
  1152. exit;
  1153. }
  1154. private function ajaxCreateSave($args) {
  1155. DBG::log($args, 'array', "ajaxCreateSave");
  1156. $acl = $this->_acl;
  1157. $response = new stdClass();
  1158. $createdId = null;
  1159. try {
  1160. $item = $acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  1161. $createdId = $acl->addItem($item);
  1162. if ($createdId) {
  1163. $response->type = 'success';
  1164. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  1165. $response->id = $createdId;
  1166. $response->record = $acl->buildQuery([])->getItem($createdId);
  1167. }
  1168. else {
  1169. $response->type = 'error';
  1170. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  1171. }
  1172. }
  1173. catch (Exception $e) {
  1174. $response->type = 'error';
  1175. $response->msg = $e->getMessage();
  1176. }
  1177. return $response;
  1178. }
  1179. private function ajaxCopy($args) {
  1180. $acl = $this->_acl;
  1181. $id = V::get('ID', 0, $_REQUEST, 'int');
  1182. if ($id <= 0) {
  1183. throw new HttpException("Wrong param ID!", 404);
  1184. }
  1185. $item = $acl->buildQuery([])->getItem($id);
  1186. if (!$item) {
  1187. throw new HttpException("Item '{$id}' not exists!", 404);
  1188. }
  1189. $response = new stdClass();
  1190. $itemCopy = $acl->createItemCopy($item);
  1191. $createdId = null;
  1192. try {
  1193. $createdId = $acl->addItem($itemCopy);
  1194. if ($createdId) {
  1195. $response->type = 'success';
  1196. $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
  1197. $response->id = $createdId;
  1198. $response->record = $acl->buildQuery([])->getItem($createdId);
  1199. }
  1200. else {
  1201. $response->type = 'error';
  1202. $response->msg = "Nie udało się skopiować rekordu!";
  1203. }
  1204. }
  1205. catch (Exception $e) {
  1206. $response->type = 'error';
  1207. $response->msg = "Wystąpiły błędy!";
  1208. $response->msg = $e->getMessage();
  1209. }
  1210. return $response;
  1211. }
  1212. private function ajaxHist($args) {
  1213. $jsonResponse = array();
  1214. $id = V::get('ID', 0, $args, 'int');
  1215. $acl = $this->_acl;
  1216. $record = $acl->buildQuery([])->getItem($id);
  1217. if (!$record) throw new HttpException("404: No item ID({$id})", 404);
  1218. $visibleCols = $acl->getRealFieldList();
  1219. try {
  1220. $rowsHist = $acl->getHistItems($id);
  1221. } catch (Exception $e) {
  1222. DBG::log($e);
  1223. $rowsHist = [];
  1224. }
  1225. $jsonResponse['row_functions'] = $this->_parseRowFunctions($record['ID'], array('hist', 'cp'), $showLabel = true);
  1226. $visibleColsWithIds = array();
  1227. $visibleColsLabels = array();
  1228. foreach ($visibleCols as $vColName) {
  1229. $fldId = $acl->getFieldIdByName($vColName);
  1230. if ($fldId) {
  1231. $visibleColsWithIds[$fldId] = $vColName;
  1232. $label = $acl->getFieldLabel($vColName);
  1233. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  1234. $visibleColsLabels[$fldId] = $label;
  1235. }
  1236. }
  1237. $jsonResponse['label'] = "Historia rekordu Nr {$id}";
  1238. $jsonResponse['fields'] = array_values($visibleColsWithIds);
  1239. $jsonResponse['field_label'] = $visibleColsLabels;
  1240. if (empty($rowsHist)) return $jsonResponse;
  1241. $jsonResponse['rows'] = array();
  1242. foreach ($rowsHist as $histRow) {
  1243. $histItem = array();
  1244. $histItem['ID'] = V::get('ID', '', $histRow);
  1245. $histItem['_created'] = V::get('_created', '', $histRow);
  1246. $histItem['_author'] = V::get('_author', '', $histRow);
  1247. $histItem['changes'] = array();
  1248. foreach ($visibleColsWithIds as $fldId => $fieldName) {
  1249. if (!array_key_exists($fieldName, (array)$histRow)) continue;
  1250. $value = V::get($fieldName, '', $histRow);
  1251. if ('N/S;' == $value) continue;
  1252. $changeItem = array();
  1253. $changeItem['fieldName'] = $fieldName;
  1254. $changeItem['acl_read'] = $acl->canReadObjectField($fieldName, $record);
  1255. if ($changeItem['acl_read']) {
  1256. $changeItem['value'] = V::get($fieldName, '', $histRow);
  1257. }
  1258. if ('the_geom' == $fieldName && $acl->canWriteObjectField($fieldName, $record)) {
  1259. $sourceName = $acl->getSourceName();
  1260. if ('default_db' == $sourceName && !empty($value)) {
  1261. $typeName = $acl->getName();
  1262. $idHist = V::get('ID', '', $histRow);
  1263. $changeItem['revert_function_url'] = Request::getPathUri() . "index.php?_route=ViewTableAjax&typeName=p5_{$sourceName}:{$typeName}&_task=revertFromHistAjax&ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
  1264. $changeItem['revert_function_data'] = "ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
  1265. }
  1266. }
  1267. $histItem['changes'][$fieldName] = $changeItem;
  1268. }
  1269. $jsonResponse['rows'][] = $histItem;
  1270. }
  1271. return $jsonResponse;
  1272. }
  1273. public function ajaxFileUpload($args) {
  1274. $id = V::get('ID', 0, $args, 'int');
  1275. if ($id <= 0) throw new HttpException("404", 404);
  1276. $dbID = $this->_acl->getDB();
  1277. $db = DB::getDB($dbID);
  1278. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1279. $record = $this->_acl->buildQuery([])->getItem($id);
  1280. if (!$record) throw new HttpException("No item ID({$id})", 404);
  1281. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1282. if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1283. $tblName = $this->_acl->getName();
  1284. $confTblName = "{$tblName}_COLUMN";
  1285. $folderConfAll = FoldersConfig::getRawData();
  1286. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  1287. $folderConf = FoldersConfig::getAll($confTblName);
  1288. $uploader = new FileUploader($confTblName, (object)$record);
  1289. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1290. $uploader->findFolder();
  1291. $errorMsg = '';
  1292. if (!empty($args['SCANS_COLUMN_ADD'])) {
  1293. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  1294. }
  1295. else {
  1296. $uploaded = $uploader->tryUploadAjax($errorMsg);
  1297. }
  1298. $retJson = new stdClass();
  1299. if (!$uploaded) throw new Exception($errorMsg);
  1300. $uploadedFileName = '';
  1301. $uploadedFile = $uploader->getLastUploadedFile();
  1302. if ($uploadedFile) {
  1303. $uploadedFileName = explode('/', $uploadedFile);
  1304. $uploadedFileName = end($uploadedFileName);
  1305. }
  1306. //echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  1307. $retJson->type = 'SUCCESS';
  1308. $retJson->msg = "Plik został poprawnie wgrany do odpowiedniego katalogu {$uploadedFileName}";
  1309. if (!empty($uploadedFileName)) {
  1310. $sqlObj = new stdClass();
  1311. $sqlObj->ID = $record['ID'];
  1312. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  1313. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  1314. }
  1315. return $retJson;
  1316. }
  1317. public function ajaxFileList($args) {
  1318. $id = V::get('ID', 0, $args, 'int');
  1319. if ($id <= 0) throw new HttpException("404", 404);
  1320. $dbID = $this->_acl->getDB();
  1321. $db = DB::getDB($dbID);
  1322. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1323. $record = $this->_acl->buildQuery([])->getItem($id);
  1324. if (!$record) throw new HttpException("No item ID({$id})", 404);
  1325. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1326. $tblName = $this->_acl->getName();
  1327. $confTblName = "{$tblName}_COLUMN";
  1328. $folderConfAll = FoldersConfig::getRawData();
  1329. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  1330. $folderConf = FoldersConfig::getAll($confTblName);
  1331. $uploader = new FileUploader($confTblName, (object)$record);
  1332. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1333. $uploader->findFolder();
  1334. $mainFolder = $uploader->getDestFolder();
  1335. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  1336. $localPath = $uploader->getLocalPath();
  1337. $folderWeb = $uploader->getFolderWeb();
  1338. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  1339. return $jsonFiles;
  1340. }
  1341. private function ajaxFilePermsRefresh($args) {
  1342. $id = V::get('ID', 0, $args, 'int');
  1343. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  1344. $dbID = $this->_acl->getDB();
  1345. $db = DB::getDB($dbID);
  1346. if (!$db) throw new HttpException("No DB", 406);
  1347. $record = $this->_acl->buildQuery([])->getItem($id);
  1348. if (!$record) throw new Exception("No item ID({$id})", 404);
  1349. $tblName = $this->_acl->getName();
  1350. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  1351. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  1352. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  1353. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  1354. $mainDB = DB::getDB();
  1355. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  1356. $sql = "insert into `_SYNC_FILE_PERMS` (
  1357. `ID_PROJECT`,
  1358. `A_SYNCHRONIZED`
  1359. )
  1360. values (
  1361. '{$record['ID']}'
  1362. , 0
  1363. )
  1364. ON DUPLICATE KEY UPDATE
  1365. `A_SYNCHRONIZED`=0
  1366. ";
  1367. }
  1368. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  1369. $sql = "insert into `_SYNC_FILE_PERMS` (
  1370. `ID_PROJECT`,
  1371. `A_SYNCHRONIZED`
  1372. )
  1373. values (
  1374. '{$record['ID_PROJECT']}'
  1375. , 0
  1376. )
  1377. ON DUPLICATE KEY UPDATE
  1378. `A_SYNCHRONIZED`=0
  1379. ";
  1380. }
  1381. else {
  1382. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  1383. `TBL_NAME`,
  1384. `TBL_ID`,
  1385. `L_APPOITMENT_USER`,
  1386. `A_ADM_COMPANY`,
  1387. `A_CLASSIFIED`,
  1388. `A_SYNCHRONIZED`
  1389. )
  1390. values (
  1391. '{$tblName}'
  1392. , '{$id}'
  1393. , '{$sql_L_APPOITMENT_USER}'
  1394. , '{$sql_A_ADM_COMPANY}'
  1395. , '{$sql_A_CLASSIFIED}'
  1396. , 0
  1397. )
  1398. ON DUPLICATE KEY UPDATE
  1399. `A_SYNCHRONIZED`=0
  1400. ";
  1401. }
  1402. $res = $mainDB->query($sql);
  1403. if ($mainDB->has_errors()) {
  1404. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  1405. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainDB->get_errors());echo'</pre>';
  1406. throw new Exception("Nie udało się dodać zadania");
  1407. }
  1408. // TODO: this blocks browser ajax query
  1409. //$limit = 3;
  1410. //while ($limit--) {
  1411. // sleep(10);
  1412. // TODO: check if task is done
  1413. //}
  1414. $confTblName = "{$tblName}_COLUMN";
  1415. $folderConfAll = FoldersConfig::getRawData();
  1416. if (!FoldersConfig::hasConfig($confTblName)) {
  1417. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  1418. }
  1419. $folderConf = FoldersConfig::getAll($confTblName);
  1420. $uploader = new FileUploader($confTblName, (object)$record);
  1421. if (!$uploader->setConfig($folderConf)) {
  1422. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1423. }
  1424. $uploader->findFolder();
  1425. $mainFolder = $uploader->getDestFolder();
  1426. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  1427. $localPath = $uploader->getLocalPath();
  1428. $folderWeb = $uploader->getFolderWeb();
  1429. $jsonData = new stdClass();
  1430. $jsonData->msg = 'Zadanie dodane';
  1431. $jsonData->type = 'success';
  1432. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  1433. return $jsonData;
  1434. }
  1435. private function sendAjaxFilesConnTblList($id, $args) {
  1436. header("Content-type: application/json");
  1437. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  1438. $dbID = $this->_acl->getDB();
  1439. $db = DB::getDB($dbID);
  1440. if (!$db) {
  1441. header('HTTP/1.0 406 Not Acceptable');
  1442. echo 'No DB (' . $dbID . ')';
  1443. exit;
  1444. }
  1445. $record = $this->_acl->buildQuery([])->getItem($id);
  1446. if (!$record) {
  1447. header('HTTP/1.0 404 Not Found');
  1448. echo 'No item ID(' . $rowID . ')';
  1449. exit;
  1450. }
  1451. $connTblName = '';
  1452. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  1453. if ($connTblID <= 0) {
  1454. header('HTTP/1.0 406 Not Acceptable');
  1455. echo 'No conn Table ID';
  1456. exit;
  1457. }
  1458. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  1459. if (empty($connTblTypespecials)) {
  1460. header('HTTP/1.0 406 Not Acceptable');
  1461. echo "No conn Table (ID={$connTblID})";
  1462. exit;
  1463. }
  1464. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">connTblTypespecials (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($connTblTypespecials);echo'</pre>';}
  1465. if(1) {
  1466. header('HTTP/1.0 404 Not Found');
  1467. echo 'TODO: ...';
  1468. exit;
  1469. }
  1470. $tblName = $this->_acl->getName();
  1471. $confTblName = "{$tblName}_COLUMN";
  1472. $folderConfAll = FoldersConfig::getRawData();
  1473. if (!FoldersConfig::hasConfig($confTblName)) {
  1474. header('HTTP/1.0 404 Not Found');
  1475. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  1476. exit;
  1477. }
  1478. $folderConf = FoldersConfig::getAll($confTblName);
  1479. $uploader = new FileUploader($confTblName, (object)$record);
  1480. if (!$uploader->setConfig($folderConf)) {
  1481. header('HTTP/1.0 404 Not Found');
  1482. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  1483. exit;
  1484. }
  1485. $uploader->findFolder();
  1486. $mainFolder = $uploader->getDestFolder();
  1487. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  1488. $localPath = $uploader->getLocalPath();
  1489. $folderWeb = $uploader->getFolderWeb();
  1490. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  1491. echo json_encode($jsonFiles);
  1492. exit;
  1493. }
  1494. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  1495. $jsonFiles = array();
  1496. if (!is_array($files) || empty($files)) {
  1497. return $jsonFiles;
  1498. }
  1499. sort($files);
  1500. foreach ($files as $vFilePath) {
  1501. $file = new stdClass();
  1502. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  1503. //$file->name = explode('/', $vFilePath);
  1504. //$file->name = end($file->name);
  1505. $file->size = filesize($vFilePath);
  1506. $file->sizeStr = V::humanFileSize($file->size);
  1507. $file->type = '';
  1508. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  1509. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  1510. $jsonFiles[] = $file;
  1511. }
  1512. return $jsonFiles;
  1513. }
  1514. private function getConnectedTables() {
  1515. $connTbls = array();
  1516. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  1517. $fields = $this->_acl->getVirtualFieldListByIdZasob();
  1518. if (!empty($fields)) {
  1519. foreach ($fields as $vColID => $vCol) {
  1520. $typeSpecial = Typespecial::getInstance($vColID);
  1521. if ($typeSpecial) {
  1522. $tsConnTbls = $typeSpecial->getTblAliasList();
  1523. if (!empty($tsConnTbls)) {
  1524. foreach ($tsConnTbls as $kID => $vName) {
  1525. $connTbls[$kID] = $vName;
  1526. }
  1527. }
  1528. }
  1529. }
  1530. }
  1531. return $connTbls;
  1532. }
  1533. private function getConnectedTblTypespecials($connTblID) {
  1534. $connTblTypespecials = array();
  1535. $fields = $this->_acl->getVirtualFieldListByIdZasob();
  1536. if (!empty($fields)) {
  1537. foreach ($fields as $vColID => $vCol) {
  1538. $typeSpecial = Typespecial::getInstance($vColID);
  1539. if ($typeSpecial) {
  1540. $tsConnTbls = $typeSpecial->getTblAliasList();
  1541. if (array_key_exists($connTblID, $tsConnTbls)) {
  1542. $connTblTypespecials[] = $typeSpecial;
  1543. }
  1544. }
  1545. }
  1546. }
  1547. return $connTblTypespecials;
  1548. }
  1549. private function sendAjaxFiles($id, $args) {
  1550. header("Content-type: text/plain");
  1551. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  1552. $acl = $this->_acl;
  1553. $dbID = $acl->getDB();
  1554. $db = DB::getDB($dbID);
  1555. if (!$db) throw new HttpException("", 406);
  1556. $record = $acl->buildQuery([])->getItem($id);
  1557. if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
  1558. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1559. $tblName = $acl->getName();
  1560. $confTblName = "{$tblName}_COLUMN";
  1561. $folderConfAll = FoldersConfig::getRawData();
  1562. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych", 404);
  1563. $folderConf = FoldersConfig::getAll($confTblName);
  1564. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  1565. $uploader = new FileUploader($confTblName, (object)$record);
  1566. $errMsg = '';
  1567. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})" . '<br>' . "\n" . $errMsg, 404);
  1568. $uploader->findFolder();
  1569. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">uploader (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($uploader);echo'</pre>'; }
  1570. $mainFolder = $uploader->getDestFolder();
  1571. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">mainFolder (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainFolder);echo'</pre>'; }
  1572. if (!$mainFolder) {
  1573. $destFolderPath = $uploader->getDestLocalPath(true);
  1574. $folderCreated = $uploader->tryCreateDestFolder($destFolderPath);
  1575. if ($folderCreated) {
  1576. //UI::alert('info', "Utworzono katalog");
  1577. $uploader->findFolder();
  1578. $mainFolder = $uploader->getDestFolder();
  1579. } else {
  1580. UI::alert('warning', "Nie udało się utworzyć katalogu");
  1581. }
  1582. }
  1583. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  1584. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">files (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($files);echo'</pre>'; }
  1585. $sharePoint = V::get('share_point', null, $folderConf);
  1586. if ($sharePoint) {
  1587. if ('//' == substr($mainFolder, 0, 2)) {
  1588. $sharePoint = FoldersConfig::getNfsOsPath() . "{$mainFolder}";
  1589. } else {
  1590. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  1591. }
  1592. }
  1593. $localPath = $uploader->getLocalPath();
  1594. $folderWeb = $uploader->getFolderWeb();
  1595. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  1596. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">jsonFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonFiles);echo'</pre>'; }
  1597. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  1598. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  1599. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  1600. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  1601. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  1602. sort($skanyFiles);
  1603. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  1604. $rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('files', 'cp'), true);
  1605. $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
  1606. $fileIndex = V::get($fileIndexField, $record['ID'], $record);
  1607. $namespace = $acl->getNamespace();
  1608. echo UI::h('div', [ 'class' => "container" ], [
  1609. UI::h('h4', [ 'style' => "margin:20px 0 3px 0;" ], [
  1610. "Pliki w katalogu ",
  1611. ($sharePoint)
  1612. ? UI::h('a', [ 'href' => $sharePoint ], [
  1613. UI::h('span', [ 'class' => "glyphicon glyphicon-folder-open" ]),
  1614. UI::h('code', [ 'style' => "margin-left:6px" ], $mainFolder),
  1615. ])
  1616. : UI::h('code', [], $mainFolder),
  1617. UI::h('span', [ 'class' => "pull-right valign-btns-bottom" ], [
  1618. UI::h('span', [ 'id' => "FILES_LIST_ACTIONS_{$this->_htmlID}" ]),
  1619. " {$rowFunctionsOut}",
  1620. ]),
  1621. ]),
  1622. UI::h('div', [ 'style' => "clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;" ], [
  1623. UI::h('table', [ 'class' => "table table-bordered table-hover" ], [
  1624. UI::h('colgroup', [], [
  1625. UI::h('col', [ 'style' => "" ]),
  1626. UI::h('col', [ 'style' => "width:30px" ]),
  1627. ($sharePoint)
  1628. ? UI::h('col', [ 'style' => "width:30px" ])
  1629. : '',
  1630. UI::h('col', [ 'style' => "width:80px" ]),
  1631. UI::h('col', [ 'style' => "width:140px" ]),
  1632. ]),
  1633. UI::h('tbody', [ 'id' => "FILES_LIST_{$this->_htmlID}" ], [
  1634. (empty($mainFolder) || empty($files))
  1635. ? UI::h('tr', [], [
  1636. UI::h('td', [ 'colspan' => "5" ], [
  1637. (empty($mainFolder))
  1638. ? UI::h('div', [ 'class' => "alert alert-warning" ], [
  1639. UI::h('h4', [], "Brak folderu!"),
  1640. "Folder dla tego rekordu nie został utworzony."
  1641. ])
  1642. : UI::h('div', [ 'class' => "alert alert-info" ], [
  1643. UI::h('h4', [], "Brak plików!"),
  1644. ])
  1645. ]),
  1646. ])
  1647. : '',
  1648. ]),
  1649. ]),
  1650. ]),
  1651. UI::h('br'),
  1652. UI::h('br'),
  1653. (!$this->_acl->canWriteRecord($record))
  1654. ? UI::h('div', [ 'class' => "alert alert-warning" ], [
  1655. "Brak uprawnień do dodawania plików",
  1656. ])
  1657. : UI::h('div', [ 'id' => "FILES_CONN_TBLS_{$this->_htmlID}" ]),
  1658. (!$this->_acl->canWriteRecord($record))
  1659. ? ''
  1660. : UI::h('form', [ 'enctype' => "multipart/form-data", 'method' => "POST", 'action' => "", 'id' => "FILES_FRM_{$this->_htmlID}", 'class' => "form-inline" ], [
  1661. UI::h('input', [ 'type' => "hidden", 'name' => "M_DIST_UPLOAD_SOURCE", 'value' => "local" ]),
  1662. UI::h('ul', [ 'id' => "FILES_TAB_{$this->_htmlID}", 'class' => "nav nav-tabs", 'style' => "margin:0;"], [
  1663. UI::h('li', [ 'class' => "active" ], [ UI::h('a', [ 'href' => "#local", 'data-toggle' => "local" ], "Wybierz plik lokalny"), ]),
  1664. UI::h('li', [], [ UI::h('a', [ 'href' => "#scan", 'data-toggle' => "scan" ], "Wybierz plik ze skanów" ), ]),
  1665. UI::h('li', [], [ UI::h('a', [ 'href' => "#multiple", 'data-toggle' => "multiple" ], "Wgraj wiele plików" ), ]),
  1666. ]),
  1667. UI::h('div', [ 'id' => "myTabContent", 'class' => "tab-content" ], [
  1668. UI::h('div', [ 'class' => "tab-pane fade in active", 'id' => "local", 'style' => "text-align: center;" ], [
  1669. UI::h('input', [ 'name' => "M_DIST_FILES_NAME", 'type' => "file", 'size' => "60", 'class' => "field-upload btn",
  1670. 'style' => "width:86%;margin:10px auto;padding:10px 4%;background:#eee;text-align:center",
  1671. 'ondragover' => "this.style.backgroundColor='#D9EDF7'",
  1672. 'ondragleave' => "this.style.backgroundColor='#eee'",
  1673. 'ondragend' => "this.style.backgroundColor='#eee'",
  1674. ]),
  1675. ]),
  1676. UI::h('div', [ 'class' => "tab-pane fade", 'id' => "multiple" ], [
  1677. UI::h('div', [
  1678. 'id' => "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
  1679. 'style' => "width:86%; margin:10px auto; padding:40px 100px; background-color:#eee; border-radius:4px; text-align:center",
  1680. 'ondrop' => "p5TAFiles_onDropMultiple(event, this, '{$id}', '{$namespace}')",
  1681. 'ondragover' => "p5TAFiles_onDragOverMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#D9EDF7'",
  1682. 'ondragleave' => "p5TAFiles_onDragLeaveMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#eee'",
  1683. 'ondragend' => "p5TAFiles_onDragEndMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#eee'",
  1684. ], [
  1685. "Upuść pliki tutaj",
  1686. ]),
  1687. ]),
  1688. UI::h('div', [ 'class' => "tab-pane fade", 'id' => "scan" ], [
  1689. (empty($skanyFiles))
  1690. ? UI::h('div', [ 'class' => "alert alert-info" ], [
  1691. UI::h('h4', [], "Brak plików"),
  1692. (!empty($skanyFolderWeb))
  1693. ? "skonfiguruj urządzenie biurowe aby wysyłało skany na ftp://skaner:(h*a*s*l*o)@".$_SERVER['SERVER_NAME']." <br> lub <a href=".FoldersConfig::getNfsOsPath().$skanySharePoint.">".FoldersConfig::getNfsOsPath().$skanySharePoint."</a>"
  1694. : '',
  1695. ])
  1696. : UI::h('div', [ 'style' => "max-height:150px; overflow:auto; border-bottom:1px solid #ddd;" ], [
  1697. UI::h('table', [ 'class' => "table table-bordered table-hover" ], [
  1698. UI::h('colgroup', [], [
  1699. UI::h('col', [ 'style' => "width:30px;" ]),
  1700. UI::h('col', [ 'style' => "" ]),
  1701. UI::h('col', [ 'style' => "width:30px;" ]),
  1702. UI::h('col', [ 'style' => "width:80px;" ]),
  1703. UI::h('col', [ 'style' => "width:140px;" ]),
  1704. ]),
  1705. UI::h('tbody', [], array_map(function ($vFilePath) use ($skanyLocalPath, $skanyFolderWeb) {
  1706. $vFileName = explode('/', $vFilePath);
  1707. $vFileName = end($vFileName);
  1708. $vFileSize = filesize($vFilePath);
  1709. $vFileSizeOut = V::humanFileSize($vFileSize);
  1710. return UI::h('tr', [], [
  1711. UI::h('td', [], [ UI::h('input', [ 'style' => "margin:0", 'type' => "radio", 'name' => "SCANS_COLUMN_ADD", 'value' => $vFileName]) ]),
  1712. UI::h('td', [], [ UI::h('div', [ 'style' => "overflow:hidden; white-space:nowrap", 'title' => $vFileName ], $vFileName) ]),
  1713. UI::h('td', [ 'style' => "white-space:nowrap; text-align:center" ], [
  1714. UI::h('a', [ 'href' => str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath), 'target' => "_blank", 'class' => "glyphicon glyphicon-download-alt" ])
  1715. ]),
  1716. UI::h('td', [ 'style' => "white-space:nowrap; text-align:right" ], $vFileSizeOut),
  1717. UI::h('td', [ 'style' => "white-space:nowrap" ], date("Y-m-d H:i:s", filectime($vFilePath))),
  1718. ]);
  1719. }, $skanyFiles)),
  1720. ])
  1721. ]),
  1722. ])
  1723. ]),
  1724. UI::h('br'),
  1725. UI::h('h4', [], [
  1726. "Ustal nazwę pliku zgodną z obiegiem dokumentów",
  1727. //TODO: link do procesu o obiegu dokumentów <i class="glyphicon glyphicon-question-sign" style="cursor:help" title="działa w nowszych przeglądarkach jak Firefox, Chrome"></i>
  1728. ]),
  1729. UI::h('table', [ 'style' => "width:100%", 'class' => "table table-bordered" ], [
  1730. UI::h('tr', [], [
  1731. UI::h('th', [], "Nr"),
  1732. UI::h('th', [], "Typ"),
  1733. UI::h('th', [ 'style' => "width:40%" ], [
  1734. "Opis ",
  1735. UI::h('i', [ 'class' => "glyphicon glyphicon-question-sign", 'title' => "kogo dotyczy / czego / sprawa / nazwa_firmy itp" ]),
  1736. ]),
  1737. UI::h('th', [ 'style' => "width:16%" ], "Data wersji"),
  1738. UI::h('th', [ 'style' => "width:12%" ], "Numer wersji"),
  1739. ]),
  1740. UI::h('tr', [], [
  1741. UI::h('td', [], $fileIndex),
  1742. UI::h('td', [], [
  1743. UI::h('select', [ 'class' => "form-control", 'name' => "M_DIST_FILES_TYPE" ], array_map(function ($vLabel, $kType) {
  1744. return UI::h('option', array_merge([ 'value' => $kType],
  1745. ($kType == 'TODO')
  1746. ? [ 'selected' => "selected"]
  1747. : []
  1748. ), $vLabel);
  1749. }, $fileTypes, array_keys($fileTypes)) ),
  1750. UI::h('br'),
  1751. UI::h('label', [ 'class' => "checkbox" ], [
  1752. UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_TYPE_AUTO" ]),
  1753. " Wykrycie automatyczne typu z wysylanego pliku",
  1754. ]),
  1755. UI::h('label', [ 'class' => "checkbox" ], [
  1756. UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_TEMP" ]),
  1757. " Plik tymczasowy / roboczy / nieoficjalny (_TEMP)",
  1758. ]),
  1759. ]),
  1760. UI::h('td', [], [
  1761. UI::h('input', [ 'class' => "form-control", 'style' => "width:100%", 'type' => "text", 'name' => "M_DIST_FILES_DESCRIPTION", 'value' => "", 'maxlength' => "50" ]),
  1762. "<br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>",
  1763. ]),
  1764. UI::h('td', [], [
  1765. UI::h('div', [ 'class' => "input-group" ], [
  1766. UI::h('input', [ 'name' => "M_DIST_FILES_DATE", 'type' => "text", 'value' => date('Y-m-d'), 'class' => "se_type-date form-control", 'data-format' => "yyyy-MM-dd", 'maxlength' => "10" ]),
  1767. UI::h('span', [ 'class' => "input-group-addon" ], [
  1768. UI::h('span', [ 'class' => "glyphicon glyphicon-calendar" ]),
  1769. ]),
  1770. ]),
  1771. // UI::h('input', [ 'class' => "form-control", 'type' => "date", 'name' => "M_DIST_FILES_DATE", 'value' => date('Y-m-d'), 'maxlength' => "10" ]),
  1772. "<br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (" . date('Y-m-d') . ")</label>",
  1773. ]),
  1774. UI::h('td', [], [
  1775. UI::h('input', [ 'class' => "form-control", 'style' => "width:100%", 'type' => "number", 'name' => "M_DIST_FILES_VERSION" ]),
  1776. UI::h('br'),
  1777. UI::h('label', [ 'class' => "checkbox" ], [
  1778. UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_VERSION_AUTO" ]),
  1779. " Automatycznie dodaj wersje",
  1780. ]),
  1781. ]),
  1782. ]),
  1783. UI::h('tr', [], [
  1784. UI::h('td', [ 'colspan' => "5" ], [
  1785. UI::h('div', [ 'id' => "FRM_UPLOAD_RESULTS_{$this->_htmlID}" ]),
  1786. UI::h('p', [], [
  1787. UI::h('input', [ 'type' => "submit", 'value' => "Wyślij", 'class' => "btn btn-primary" ], "wybrany plik do folderu:"),
  1788. ]),
  1789. UI::h('p', [], [
  1790. UI::h('code', [], [
  1791. UI::h('b', [], $uploader->getDestPathShare(true)),
  1792. ]),
  1793. UI::h('br'),
  1794. UI::h('i', [ 'style' => "color:#777" ], "(Jeśli folder nie istnieje to zostanie utworzony automatycznie)"),
  1795. ]),
  1796. ]),
  1797. ]),
  1798. ]),
  1799. ]),
  1800. ]);
  1801. $className = __CLASS__;
  1802. $namespace = $acl->getNamespace();
  1803. UI::inlineJS(__FILE__ . '.files.js', [
  1804. 'UNIQ_HASH' => $this->_htmlID,
  1805. 'FUNCTION_FILE_LIST_UPDATE_AJAX' => "fileListUpdateAjax{$this->_htmlID}", // fileListUpdateAjax
  1806. 'FUNCTION_FILE_LIST_UPDATE' => "fileListUpdate{$this->_htmlID}", // fileListUpdate
  1807. 'FUNCTION_CONN_TBL_LIST_UPDATE_AJAX' => "connTblListUpdateAjax{$this->_htmlID}", // connTblListUpdateAjax
  1808. 'FUNCTION_CONN_TBL_LIST_UPDATE' => "connTblListUpdate{$this->_htmlID}", // connTblListUpdate
  1809. 'FUNCTION_FILE_LIST_ACTIONS' => "fileListActions{$this->_htmlID}", // fileListActions
  1810. 'CONN_TABLES' => $this->getConnectedTables(),
  1811. 'NODE_ID_FILES_FRM' => "FILES_FRM_{$this->_htmlID}",
  1812. 'NODE_ID_FRM_UPLOAD_RESULTS' => "FRM_UPLOAD_RESULTS_{$this->_htmlID}",
  1813. 'NODE_ID_FILES_TAB' => "FILES_TAB_{$this->_htmlID}",
  1814. 'NODE_ID_FILES_LIST' => "FILES_LIST_{$this->_htmlID}",
  1815. 'NODE_ID_FILES_CONN_TBLS' => "FILES_CONN_TBLS_{$this->_htmlID}",
  1816. 'NODE_ID_FILES_LIST_ACTIONS' => "FILES_LIST_ACTIONS_{$this->_htmlID}",
  1817. 'NODE_ID_FILES_MULTIPLE_UPLOAD' => "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
  1818. 'URL_FILE_LIST_UPDATE_AJAX' => "index-ajax.php?_zasobID={$this->_zasobID};&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_LIST&ID={$record['ID']}",
  1819. 'URL_FILE_REMOVE_AJAX' => "index.php?_route=ViewTableAjax&namespace={$namespace}&_task=removeFileAjax&ID={$record['ID']}",
  1820. 'URL_CONNECTED_TABLE_LIST' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_CONN_TBL_LIST&ID={$record['ID']}",
  1821. 'URL_FILE_PERMS_REFRESH' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=filePermsRefresh&ID={$record['ID']}",
  1822. 'URL_FILE_UPLOAD' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_UPLOAD&ID={$record['ID']}",
  1823. 'CAN_WRITE_RECORD' => (int)$this->_acl->canWriteRecord($record),
  1824. 'SHARE_POINT' => $sharePoint,
  1825. 'JSON_FILES' => $jsonFiles,
  1826. ]);
  1827. exit;
  1828. }
  1829. private function sendTypeSpecial($fldID, $args) { // TODO: mv to index.php?_route=ViewTableAjax&_task=typespecial&idField=" + idField, // &q=... or &selected=... or &idRecord=...
  1830. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  1831. header("Content-type: application/json");
  1832. $fldName = '';
  1833. $fld = $this->_acl->getField($fldID);
  1834. DBG::log($fld, 'array', "\$fld({$fldID})");
  1835. if (!$fld) {
  1836. // 404
  1837. } else {
  1838. $fldName = $fld['name'];
  1839. }
  1840. $jsonData = array();
  1841. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  1842. if ($typeSpecial) {
  1843. $query = V::get('q', '', $_REQUEST);
  1844. DBG::log("\$query({$query})");
  1845. $rawRows = null;
  1846. $rows = $typeSpecial->getValuesWithExports($query);
  1847. DBG::log($rows, 'array', "\$rows({$query})");
  1848. foreach ($rows as $kID => $vItem) {
  1849. $itemJson = new stdClass();
  1850. $itemJson->id = $vItem->id;
  1851. $itemJson->name = $vItem->param_out;
  1852. if (!empty($vItem->exports)) {
  1853. $itemJson->exports = $vItem->exports;
  1854. }
  1855. if (!empty($vItem->{'$order'})) {
  1856. $itemJson->{'$order'} = $vItem->{'$order'};
  1857. }
  1858. $jsonData[] = $itemJson;
  1859. }
  1860. }
  1861. /*
  1862. MENU_INIT:VIEWTABLE_AJAX
  1863. ZASOB_ID:1188
  1864. _task:TYPESPECIAL
  1865. fldID:3866
  1866. Form Dataview sourceview URL encoded
  1867. q:te
  1868. */
  1869. echo json_encode($jsonData);
  1870. exit;
  1871. }
  1872. public function ajaxData($args) {// executed from url: "{$this->syncUrl"&_hash={$this->_htmlID}&_task=loadDataAjax"
  1873. $acl = $this->_acl;
  1874. $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
  1875. $page = V::get('page', 0, $args, 'int');
  1876. $page = ($page > 0) ? $page - 1 : $page;
  1877. $currSortCol = V::get('currSortCol', '', $args);
  1878. $currSortFlip = V::get('currSortFlip', '', $args);
  1879. $params = array();
  1880. $params['limit'] = $pageSize;
  1881. $params['limitstart'] = $page * $params['limit'];
  1882. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  1883. $params['order_dir'] = $currSortFlip;
  1884. foreach ($args as $k => $v) {
  1885. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  1886. $params[$k] = $v;
  1887. }
  1888. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  1889. $params[$k] = $v;
  1890. }
  1891. }
  1892. if ($this->_backRefFilter) {
  1893. $params['__backRef'] = $this->_backRefFilter;
  1894. DBG::log($params, 'array', '$params __backRef');
  1895. }
  1896. if ($this->_childRefFilter) {
  1897. $params['__childRef'] = $this->_childRefFilter;
  1898. DBG::log($params, 'array', '$params __childRef');
  1899. }
  1900. $filters = new stdClass();
  1901. $filters->currSortCol = $currSortCol;
  1902. $filters->currSortFlip = $currSortFlip;
  1903. foreach ($args as $k => $v) {
  1904. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  1905. $filters->{$k} = $v;
  1906. }
  1907. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  1908. $filters->{$k} = $v;
  1909. }
  1910. }
  1911. $this->setFilters($filters);
  1912. session_write_close();
  1913. $vCols = $acl->getVirtualFieldListByIdZasob();
  1914. DBG::log($vCols, 'array', "\$vCols");
  1915. $visibleCols = $acl->getVisibleFieldListByIdZasob();
  1916. DBG::log($visibleCols, 'array', "\$visibleCols");
  1917. $jsonData = new stdClass();
  1918. $jsonData->page = $page + 1;
  1919. $jsonData->pageSize = $pageSize;
  1920. $jsonData->filters = $filters;
  1921. $jsonData->cols = new stdClass();
  1922. $jsonData->primaryKey = $acl->getPrimaryKeyField();
  1923. $ind = 0;
  1924. foreach ($visibleCols as $fieldID => $col) {
  1925. $ind++;
  1926. $columnConfig = (object)array('index'=>$ind);
  1927. if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  1928. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  1929. }
  1930. else if (in_array($col, array('Status'))) {
  1931. // Ahmes problems Status colors
  1932. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  1933. }
  1934. else if ($acl->isGeomField($col)) {
  1935. $columnConfig->type = 'geom';
  1936. }
  1937. if ('' !== ($label = $acl->getFieldLabel($col))) {
  1938. $columnConfig->friendly = $label;
  1939. }
  1940. $colType = $acl->getFieldType($col);
  1941. if ($colType) {// @see MarkTableAjaxFilterColType
  1942. if ($colType['type'] == 'date') {
  1943. // $columnConfig->type = 'date';// TODO: require datetimepicker
  1944. }
  1945. if (!empty($colType['simpleType'])) $columnConfig->type = $colType['simpleType'];
  1946. } else {// typespecial - no type
  1947. $columnConfig->type = 'special';
  1948. }
  1949. $columnConfig->xsdType = $acl->getXsdFieldType($col);
  1950. if ($columnConfig->xsdType) {
  1951. list($prefix, $typeName, $refTypeName) = explode(":", $columnConfig->xsdType);
  1952. DBG::log([$prefix, $typeName, $refTypeName], 'array', "col '{$col}' xsdType");
  1953. switch ($prefix) {
  1954. case 'ref':
  1955. case 'alias_ref':
  1956. if (!$refTypeName) throw new HttpException("Schema Error for field({$col}) xsdType({$columnConfig->xsdType})", 500);
  1957. $columnConfig->type = 'ref';
  1958. $columnConfig->xsdRefUri = Api_WfsNs::getNsUri($typeName);
  1959. $columnConfig->xsdRefType = $refTypeName;
  1960. $columnConfig->xsdRefNsPrefix = $typeName;
  1961. break;
  1962. case 'xsd':
  1963. switch ($typeName) {
  1964. case 'string': $columnConfig->type = 'string'; break;
  1965. case 'NMTOKEN': $columnConfig->type = 'string'; break; // xsd:NMTOKEN - non empty string without space - pattern: \c+
  1966. case 'NCName': $columnConfig->type = 'string'; break; // xsd:NCName - non empty without ':' and not started with '-' - pattern: [\i-[:]][\c-[:]]*
  1967. case 'integer': $columnConfig->type = 'number'; break;
  1968. case 'int': $columnConfig->type = 'number'; break;
  1969. case 'long': $columnConfig->type = 'number'; break;
  1970. case 'date': $columnConfig->type = 'string'; break;
  1971. case 'datetime': $columnConfig->type = 'string'; break;
  1972. case 'dateTime': $columnConfig->type = 'string'; break;
  1973. case 'double': $columnConfig->type = 'string'; break;
  1974. }
  1975. break;
  1976. case 'p5':
  1977. switch ($typeName) {
  1978. case 'enum': $columnConfig->type = 'string'; break;
  1979. case 'alias': {
  1980. if ($format = $acl->getXsdFieldParam($col, 'format')) $columnConfig->format = $format;
  1981. if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
  1982. } break;
  1983. case 'string': {
  1984. $columnConfig->type = 'p5:string';
  1985. $columnConfig->format = $acl->getXsdFieldParam($col, 'format');
  1986. $columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
  1987. $columnConfig->formatEmpty = $acl->getXsdFieldParam($col, 'formatEmpty');
  1988. if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
  1989. } break;
  1990. }
  1991. break;
  1992. case 'gml': $columnConfig->type = 'geom'; break;
  1993. case 'p5Type':
  1994. switch ($typeName) {
  1995. case 'enum': $columnConfig->type = 'string'; break;
  1996. case 'alias': {
  1997. $format = $acl->getXsdFieldParam($col, 'format');
  1998. if ($format) $columnConfig->format = $format;
  1999. } break;
  2000. case 'integer': $columnConfig->type = 'number'; break;
  2001. case 'string': {
  2002. $columnConfig->type = 'p5:string';
  2003. $columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
  2004. if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
  2005. } break;
  2006. case 'polygon':
  2007. case 'lineString':
  2008. case 'point': {
  2009. $columnConfig->type = 'geom';
  2010. } break;
  2011. }
  2012. break;
  2013. }
  2014. }
  2015. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  2016. if ($typeSpecial) {
  2017. DBG::log($typeSpecial, 'array', "\$typeSpecial id({$fieldID}) col({$col})");
  2018. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  2019. if ($columnConfig->_tsRetId == 0) {
  2020. $columnConfig->sortable = false;
  2021. $columnConfig->filterable = false;
  2022. $tsParamOut = V::get('param_out', null, $typeSpecial);
  2023. if ($tsParamOut) {
  2024. $tsFormat = V::get('format', null, $tsParamOut);
  2025. $tsValues = V::get('values', null, $tsParamOut);
  2026. $tsAliases = V::get('alias', null, $tsParamOut);
  2027. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  2028. $tsAliasMap = array();
  2029. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  2030. $bugTsColsNotVisible = array();
  2031. foreach ($tsValues as $kVarName => $vIdZasob) {
  2032. if (array_key_exists($vIdZasob, $tsAliases)) {
  2033. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  2034. } else {
  2035. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  2036. }
  2037. if (!array_key_exists($vIdZasob, $visibleCols)) {
  2038. $bugTsColsNotVisible[] = $vIdZasob;
  2039. }
  2040. }
  2041. if (empty($bugTsColsNotVisible)) {
  2042. $tsSimpleLink = new stdClass();
  2043. $tsSimpleLink->format = $tsFormat;
  2044. $tsSimpleLink->aliasMap = $tsAliasMap;
  2045. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  2046. $columnConfig->type = 'simpleLink';
  2047. } else {
  2048. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  2049. }
  2050. }
  2051. }
  2052. }
  2053. // TODO: hot fix for filterable TypespecialVariable fields, @see more in TypespecialVariable::getInstance
  2054. {
  2055. switch ($col) {
  2056. case 'A_ADM_COMPANY':
  2057. case 'A_CLASSIFIED':
  2058. case 'K_OD_KOGO':
  2059. case 'OD_KOGO_ADRES':
  2060. case 'M_DISTRIBUTOR':
  2061. case 'DEFAULT_ACL_GROUP':
  2062. {
  2063. $columnConfig->sortable = true;
  2064. $columnConfig->filterable = true;
  2065. } break;
  2066. }
  2067. }
  2068. }
  2069. if ($columnConfig->xsdType) {// fix fields type p5:typeSpecialSimpleLink (previously defined by Typespecial)
  2070. switch ($columnConfig->xsdType) {
  2071. case 'p5:typeSpecialSimpleLink': {
  2072. $columnConfig->type = 'simpleLink';
  2073. $columnConfig->_tsRetId = 0;
  2074. $columnConfig->_tsSimpleLink = new stdClass();
  2075. $columnConfig->_tsSimpleLink->format = $acl->getXsdFieldParam($col, 'format');
  2076. $columnConfig->_tsSimpleLink->aliasMap = $acl->getXsdFieldParam($col, 'aliasMap');
  2077. } break;
  2078. }
  2079. }
  2080. // @see ajaxHiddenColsSave
  2081. if (UserProfile::isHiddenColumn($acl->getID(), $fieldID)) {
  2082. $columnConfig->hidden = true;
  2083. }
  2084. $columnConfig->description = $acl->getFieldOpis($col);
  2085. $jsonData->cols->{$col} = $columnConfig;
  2086. }
  2087. DBG::log($jsonData->cols, 'array', "\$jsonData->cols");
  2088. $jsonData->rows = array();
  2089. if ($acl instanceof AntAclBase) {
  2090. $params['f_is_instance'] = $acl->getNamespace();
  2091. }
  2092. $queryFeatures = $acl->buildQuery($params);
  2093. $jsonData->total = ('1' === V::get('SKIP_TOTAL', '', $args)) ? -1 : $queryFeatures->getTotal();
  2094. if ('1' === V::get('ONLY_TOTAL', '', $args)) {
  2095. $jsonData->type = 'success';
  2096. $jsonData->msg = 'pobrano nowe dane';
  2097. return $jsonData;
  2098. }
  2099. $listItems = $queryFeatures->getItems();
  2100. $primaryKeyField = $acl->getPrimaryKeyField();
  2101. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  2102. // TODO: add virtual data by Typespecial
  2103. if (!empty($vCols) && !empty($items)) {
  2104. foreach ($vCols as $vColID => $vCol) {
  2105. $colType = $acl->getFieldTypeById($vColID);
  2106. if ($colType) continue;// pomin Typespecial dla realnych komorek w bazie danych
  2107. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  2108. if ($typeSpecial) {
  2109. $columnConfig = V::get($vCol, null, $jsonData->cols);
  2110. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  2111. // pomin simple link values - mved to js render
  2112. } else {
  2113. DBG::log($typeSpecial, 'array', "Typespecial({$vColID})");
  2114. $ids = array_keys($items);
  2115. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  2116. DBG::log($specialValues, 'array', "Typespecial({$vColID}) \$specialValues");
  2117. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  2118. $tsValue = implode('<br>', $vValues);
  2119. DBG::log($items[$kItemID], 'array', "Typespecial({$vColID}) Item[{$kItemID}].{$vCol}");
  2120. if (!empty($items[$kItemID][$vCol]) && !empty($tsValue)) {
  2121. $items[$kItemID][$vCol] .= ": {$tsValue}";
  2122. } else {
  2123. $items[$kItemID][$vCol] = $tsValue;
  2124. }
  2125. }
  2126. }
  2127. }
  2128. }
  2129. }
  2130. {
  2131. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__ = [];}
  2132. $p5Alias = [];
  2133. foreach ((array)$jsonData->cols as $fieldName => $conf) {
  2134. if ('p5:alias' == V::get('xsdType', '', $conf)) {
  2135. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__[$fieldName] = $conf;}
  2136. $aliasType = $acl->getXsdFieldParam($fieldName, 'type');// 'type' => 'sql_table_alias',
  2137. if ('sql_table_alias' == $aliasType) {
  2138. $p5Alias[$fieldName] = (array)$conf;
  2139. $p5Alias[$fieldName]['type'] = 'sql_table_alias';
  2140. $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');// 'local_join_key' => 'ID',
  2141. $p5Alias[$fieldName]['remote_table_name'] = $acl->getXsdFieldParam($fieldName, 'remote_table_name');// 'remote_table_name' => 'CRM_LISTA_ZASOBOW_ORDERS_summary_view',
  2142. $p5Alias[$fieldName]['remote_join_key'] = $acl->getXsdFieldParam($fieldName, 'remote_join_key');// 'remote_join_key' => 'ID',
  2143. $p5Alias[$fieldName]['remote_column_value'] = $acl->getXsdFieldParam($fieldName, 'remote_column_value');// 'remote_column_value' => 'SUM_POS',
  2144. } else if ('sql_query_alias' == $aliasType) {
  2145. $p5Alias[$fieldName] = (array)$conf;
  2146. $p5Alias[$fieldName]['type'] = 'sql_query_alias';
  2147. $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');
  2148. $p5Alias[$fieldName]['join_query_format'] = $acl->getXsdFieldParam($fieldName, 'join_query_format');
  2149. }
  2150. }
  2151. }
  2152. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$p5Alias'] = $p5Alias;}
  2153. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'] = [];}
  2154. if ($p5Alias) {
  2155. $sqlLocalTableName = $acl->getRootTableName();
  2156. $primaryKeyField = $acl->getPrimaryKeyField();
  2157. foreach ($p5Alias as $fieldName => $conf) {
  2158. $aliasValuesRaw = [];
  2159. if ('sql_table_alias' == $conf['type']) {
  2160. $localKeys = [];
  2161. $localKeyName = V::get('local_join_key', '', $conf);
  2162. if ($localKeyName) {
  2163. if (!array_key_exists($localKeyName, $localKeys)) {
  2164. $localKeys[$localKeyName] = [];
  2165. foreach ($items as $item) {
  2166. $keyLocal = V::get($localKeyName, 0, $item);
  2167. if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
  2168. }
  2169. }
  2170. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$localKeys'] = $localKeys;}
  2171. if (!empty($localKeys[$localKeyName])) {
  2172. $sqlRemoteTable = V::get('remote_table_name', '', $conf);
  2173. $sqlRemoteValueFieldName = V::get('remote_column_value', '', $conf);
  2174. $sqlRemoteKeyName = V::get('remote_join_key', '', $conf);
  2175. $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
  2176. try {
  2177. $aliasValuesRaw = DB::getPDO()->fetchAllByKey("
  2178. select r.{$sqlRemoteKeyName} as {$sqlLocalKeyName}, r.{$sqlRemoteValueFieldName} as remote_value
  2179. from {$sqlRemoteTable} r
  2180. where r.{$sqlRemoteKeyName} in(" . implode(",", $localKeys[$localKeyName]) . ")
  2181. ", $sqlLocalKeyName);
  2182. } catch (Exception $e) {
  2183. // TODO: error msg for GUI
  2184. DBG::log($e);
  2185. }
  2186. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'][$fieldName] = $aliasValuesRaw;}
  2187. }
  2188. }
  2189. } else if ('sql_query_alias' == $conf['type']) {
  2190. $localKeys = [];
  2191. $localKeyName = V::get('local_join_key', '', $conf);
  2192. $sqlFormat = V::get('join_query_format', '', $conf);
  2193. if ($localKeyName && $sqlFormat) {
  2194. if (!array_key_exists($localKeyName, $localKeys)) {
  2195. $localKeys[$localKeyName] = [];
  2196. foreach ($items as $item) {
  2197. $keyLocal = V::get($localKeyName, 0, $item);
  2198. if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
  2199. }
  2200. }
  2201. }
  2202. if (!empty($localKeys[$localKeyName])) {
  2203. $sql = str_replace('{sql_in_local_join_key}', implode(",", $localKeys[$localKeyName]), $sqlFormat);
  2204. $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
  2205. try {
  2206. $aliasValuesRaw = DB::getPDO()->fetchAllByKey($sql, $sqlLocalKeyName);
  2207. } catch (Exception $e) {
  2208. // TODO: error msg for GUI
  2209. DBG::log($e);
  2210. }
  2211. }
  2212. }
  2213. DBG::log($aliasValuesRaw, 'array', '$aliasValuesRaw');
  2214. if (!empty($aliasValuesRaw)) {
  2215. DBG::log($aliasValuesRaw, 'array', "DBG_P5: \$aliasValuesRaw");
  2216. array_walk($items, function (&$item) use ($fieldName, $sqlLocalKeyName, $aliasValuesRaw) {
  2217. $sqlValue = V::get($sqlLocalKeyName, null, $item);
  2218. DBG::log($sqlValue, 'array', "DBG_P5: \$sqlValue");
  2219. DBG::log($aliasValuesRaw[$sqlValue]['remote_value'], 'array', "DBG_P5: \$aliasValuesRaw[{$sqlValue}]['remote_value']");
  2220. DBG::log($item, 'array', "DBG_P5: \$item");
  2221. if ($sqlValue !== null && array_key_exists($sqlValue, $aliasValuesRaw)) {
  2222. DBG::log($aliasValuesRaw[$sqlValue]['remote_value'], 'array', "DBG_P5: TODO_update_value");
  2223. $item[$fieldName] = $aliasValuesRaw[$sqlValue]['remote_value'];
  2224. DBG::log($item[$fieldName], 'array', "DBG_P5: TODO_updated_value");
  2225. }
  2226. });
  2227. }
  2228. }
  2229. }
  2230. }
  2231. foreach ($items as $item) {
  2232. // TODO: hide items without 'R'
  2233. foreach ($visibleCols as $fieldName) {
  2234. // TODO: ID default 'R'
  2235. if (!$acl->canReadObjectField($fieldName, $item)) $item[$fieldName] = '*****';
  2236. // null => empty string
  2237. if (!isset($item[$fieldName]) || (!$item[$fieldName] && $item[$fieldName] !== '0')) {
  2238. // DBG::log($item[$fieldName], 'array', "isEmptyString[{$fieldName}]");
  2239. $item[$fieldName] = '';
  2240. }
  2241. }
  2242. $jsonData->rows[] = $item;
  2243. }
  2244. $jsonData->type = 'success';
  2245. $jsonData->msg = 'pobrano nowe dane';
  2246. // { // TODO: BUG - race condition in requests
  2247. // session_write_close();
  2248. // if (!empty($params['f_L_APPOITMENT_USER']) && strlen($params['f_L_APPOITMENT_USER']) === 3) sleep(2); // TODO: DBG
  2249. // if (!empty($params['f_L_APPOITMENT_USER']) && strlen($params['f_L_APPOITMENT_USER']) === 3) $jsonData->__DBG__sleep = 2; // TODO: DBG
  2250. // }
  2251. return $jsonData;
  2252. }
  2253. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  2254. $value = '';
  2255. $type = $this->_acl->getFieldTypeById($fieldID);
  2256. if ($type) {
  2257. if ($type['type'] == 'date') {
  2258. $value = $type['default'];
  2259. }
  2260. // fix bug when field is unique and is null allowed: change empty string to null
  2261. if ($type['null']) {
  2262. $value = 'NULL';
  2263. }
  2264. // fix bug when field is enum and is set to '0': for php '0' is empty
  2265. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  2266. if (false !== strpos($type['type'], "''")) {
  2267. // enum('', '1','2')
  2268. $value = '';
  2269. } else if (false !== strpos($type['type'], "'0'")) {
  2270. // enum('0', '1','2')
  2271. $value = '0';
  2272. } else {
  2273. $value = $type['default'];
  2274. }
  2275. }
  2276. }
  2277. return $value;
  2278. }
  2279. /**
  2280. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  2281. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  2282. */
  2283. private function ajaxHiddenColsSave($args) {
  2284. $response = new stdClass();
  2285. if (empty($args)) {
  2286. $response->type = 'info';
  2287. return $response;
  2288. }
  2289. UserProfile::load();
  2290. // clean up old, wrong values
  2291. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  2292. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  2293. }
  2294. $colVis = UserProfile::getHiddenCols($this->_zasobID);
  2295. $fields = $this->_acl->getFieldListByIdZasob();
  2296. foreach ($fields as $idField => $fieldName) {
  2297. if (isset($args[$fieldName])) {
  2298. if ($args[$fieldName] == 'SHOW') {
  2299. $colVis[$idField] = 1;
  2300. } else if ($args[$fieldName] == 'HIDE') {
  2301. $colVis[$idField] = 0;
  2302. }
  2303. }
  2304. }
  2305. UserProfile::setHiddenCols($this->_zasobID, $colVis);
  2306. UserProfile::save();
  2307. $response->type = 'success';
  2308. return $response;
  2309. }
  2310. private function ajaxPageSizeSave($args) {
  2311. $response = new stdClass();
  2312. if (empty($args)) {
  2313. $response->type = 'info';
  2314. return $response;
  2315. }
  2316. $pageSize = V::get('pageSize', 0, $args, 'int');
  2317. UserProfile::load();
  2318. // clean up old, wrong values
  2319. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  2320. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  2321. }
  2322. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  2323. $tableAjaxSettings['pageSize'] = $pageSize;
  2324. UserProfile::setTableAjaxSettings($tableAjaxSettings);
  2325. UserProfile::save();
  2326. $response->type = 'success';
  2327. return $response;
  2328. }
  2329. private function ajaxTheGeomSave($args) {
  2330. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  2331. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  2332. $polygon = V::get('polygon', 0, $args);
  2333. $geomFieldName = 'the_geom';
  2334. if ($primaryKey <= 0) {
  2335. throw new HttpException("Wrong param ID", 404);
  2336. }
  2337. // TODO: validate polygon - ex.: POLYGON((2072030.2315435 7234115.910678,2072029.4815435 7234093.660678,2072115.2315435 7234091.160678,2072115.4815435 7234113.660678,2072115.2315435 7234113.660678,2072094.2315435 7234113.910678,2072030.2315435 7234115.910678)))
  2338. $record = $this->_acl->buildQuery([])->getItem($primaryKey);
  2339. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  2340. throw new HttpException("Brak dostępu do rekordu", 403);
  2341. }
  2342. if (!$this->_acl->canWriteObjectField($geomFieldName, $record)) {
  2343. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  2344. }
  2345. $itemPatch = array();
  2346. $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
  2347. $itemPatch[$primaryKeyField] = $primaryKey;
  2348. $response = new stdClass();
  2349. try {
  2350. $affected = $this->_acl->updateItem($itemPatch);
  2351. if ($affected > 0) {
  2352. $response->type = 'success';
  2353. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  2354. } else if ($affected == 0) {
  2355. $response->type = 'info';
  2356. $response->msg = "Nie wprowadzono żadnych zmian";
  2357. }
  2358. $response->record = $this->_acl->buildQuery([])->getItem($primaryKey);
  2359. }
  2360. catch (Exception $e) {
  2361. $response->type = 'error';
  2362. $response->msg = $e->getMessage();
  2363. }
  2364. return $response;
  2365. }
  2366. public function sendAjaxResponseJson($method, $args) {
  2367. try {
  2368. $response = $this->{$method}($args);
  2369. }
  2370. catch (HttpException $e) {
  2371. $response = new stdClass();
  2372. $response->type = 'error';
  2373. $response->msg = $e->getMessage();
  2374. $response->errorCode = $e->getCode();
  2375. Http::sendHeaderByCode($e->getCode());
  2376. }
  2377. catch (Exception $e) {
  2378. $response = new stdClass();
  2379. $response->type = 'error';
  2380. $response->msg = $e->getMessage();
  2381. $response->errorCode = $e->getCode();
  2382. }
  2383. header('Content-type: application/json');
  2384. if (!$response) $response = new stdClass();
  2385. echo json_encode($response);
  2386. exit;
  2387. }
  2388. }