TableAjax.php 99 KB

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