TableAjax.php 99 KB

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