TableAjax.php 99 KB

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