TableAjax.php 99 KB

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