TableAjax.php 98 KB

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