TableAjax.php 100 KB

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