TableAjax.php 98 KB

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