TableAjax.php 106 KB

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