TableAjax.php 106 KB

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