TableAjax.php 100 KB

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