| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550 |
- <?php
- Lib::loadClass('ViewAjax');
- Lib::loadClass('TableAjaxMap');
- Lib::loadClass('Typespecial');
- Lib::loadClass('UI');
- Lib::loadClass('FoldersConfig');
- Lib::loadClass('FileUploader');
- Lib::loadClass('UserProfile');
- Lib::loadClass('ProcesHelper');
- Lib::loadClass('Router');
- Lib::loadClass('Route_UrlAction');
- Lib::loadClass('Core_AclHelper');
- Lib::loadClass('AntAclBase');
- // TODO: change all links: MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={idZasob} to _route=ViewTableAjax&typeName=p5_default_db:{tableName}
- class TableAjax extends ViewAjax {
- public $_cnf = '';// Column
- public $_htmlID = '';
- public $_rowFunctions = array();
- public $_pageSize = 10;
- public $_pageSizes = array();
- public $_filterInit = null;
- public $_forceFilterInit = null;
- public $showProcesInitFiltr = null;
- public $showTableTools = null;
- public $useUserTableFilter = false;
- public $syncUrl = null;
- public function __construct($tblAcl) {
- $this->_tbl = $tblAcl->getName();
- $this->_acl = $tblAcl;
- $this->_zasobID = $tblAcl->getID();
- $this->_pageSize = 10;
- {
- UserProfile::load();
- $tableAjaxSettings = UserProfile::getTableAjaxSettings();
- $this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
- }
- $this->_pageSizes = array(10, 20, 50, 100);// default page sizes
- $this->_filterInit = new stdClass();
- $hash = V::get('_hash', '', $_GET);
- if ($hash) {
- $this->_htmlID = $hash;
- $this->_readState();
- } else {
- $this->_htmlID = $this->generateHtmlID();
- $this->_readState();
- }
- }
- public function setSyncUrl($syncUrl) { $this->syncUrl = $syncUrl; }
- public function setRootUrl($rootUrl) { $this->rootUrl = $rootUrl; }
- private function _hasStateFilterInit() {
- return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
- }
- // TODO: read state from cache by key $this->_htmlID
- // TODO: load filters and state: table, edit, add, etc.
- // TODO: save this data in Workspace 1, 2, 3, etc.
- // TODO: default filters in VIEWTABLE_AJAX
- // $tbl->setLabel($zasobObj->OPIS);
- // $tbl->setFilterInit($filterInit);
- // $tbl->addRowFunction('edit');
- // $tbl->addRowFunction('hist');
- // $tbl->addRowFunction('files');
- // $tbl->addRowFunction('cp');
- private function _readState() {
- if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
- $_SESSION['TableAjax_Cache'] = array();
- }
- //trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
- //trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
- if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
- foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
- //trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
- switch ($k) {
- case '_label':
- $this->_label = $v;
- break;
- case '_filterInit':
- $this->_filterInit = $v;
- break;
- case '_rowFunctions':
- $this->_rowFunctions = $v;
- break;
- default:
- }
- }
- }
- }
- protected function _saveState($key = null) {
- if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
- $_SESSION['TableAjax_Cache'] = array();
- }
- if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
- $_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
- }
- if (!$key) {
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
- } else if ($key == '_label') {
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
- } else if ($key == '_filterInit') {
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
- } else if ($key == '_rowFunctions') {
- $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
- }
- }
- public function setPageSizes($pageSizes) {
- $this->_pageSizes = $pageSizes;
- }
- public function setBackRefFilter($backRefFilter) {
- $this->_backRefFilter = $backRefFilter;
- }
- public function setChildRefFilter($childRefFilter) {
- $this->_childRefFilter = $childRefFilter;
- }
- public function setFilterInit($filterInit) {
- if ($this->_hasStateFilterInit()) {
- return;
- }
- $this->_filterInit = (object)$filterInit;
- $this->_saveState();
- }
- /**
- * @param array $forceFilterInit
- */
- public function setForceFilterInit($forceFilterInit) {
- $this->_forceFilterInit = (object)$forceFilterInit;
- }
- private function setFilters($filterInit) {
- $this->_filterInit = (object)$filterInit;
- $this->_saveState();
- }
- public function setRowFunctions($functions) {
- $this->_rowFunctions = [];
- $defaultRowFunction = array();
- $defaultRowFunction['edit'] = [ 'href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord', 'class' => "btn btn-xs btn-link" ];
- $defaultRowFunction['hist'] = [ 'href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia', 'class' => "btn btn-xs btn-link" ];
- $defaultRowFunction['files'] = [ 'href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki', 'class' => "btn btn-xs btn-link" ];
- $defaultRowFunction['cp'] = [ 'href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});', 'class' => "btn btn-xs btn-link" ];
- $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" ];
- foreach ($functions as $funName => $params) {
- if (true === $params) {
- if (array_key_exists($funName, $defaultRowFunction)) {
- $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
- } else {
- throw new Exception("Row function not defined '{$funName}'");
- }
- }
- if (is_array($params)) {
- $this->_rowFunctions[$funName] = $params;
- }
- }
- $this->_saveState('_rowFunctions');
- }
- public function addRowFunction($funName, $funParams = array()) {
- $defaultRowFunction = array();
- //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="glyphicon glyphicon-pencil" title="Edytuj rekord"></a>';
- //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="glyphicon glyphicon-book" title="Historia"></a>';
- //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="glyphicon glyphicon-folder-open" title="Pliki"></a>';
- //$defaultRowFunction['cp'] = '<a href="#" class="glyphicon glyphicon-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
- $defaultRowFunction['edit'] = [ 'href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord', 'class' => "btn btn-xs btn-link" ];
- $defaultRowFunction['hist'] = [ 'href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia', 'class' => "btn btn-xs btn-link" ];
- $defaultRowFunction['files'] = [ 'href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki', 'class' => "btn btn-xs btn-link" ];
- $defaultRowFunction['cp'] = [ 'href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});', 'class' => "btn btn-xs btn-link" ];
- $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" ];
- if (array_key_exists($funName, $defaultRowFunction)) {
- $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
- }
- else {
- $this->_rowFunctions[$funName] = $funParams;
- }
- $this->_saveState('_rowFunctions');
- }
- private function _parseRowFunctions($idRecord = null, $pomin = array(), $showLabel = false) {
- $rowFunctions = array();
- foreach ($this->_rowFunctions as $kFunName => $vParams) {
- if (in_array($kFunName, $pomin)) continue;
- //$rowFunctionsOut .= str_replace('{0}', $idRecord, $vUrl);
- $attrs = array();
- // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
- $label = '';
- $ico = '';
- foreach ($vParams as $kParamName => $v) {
- if ($kParamName == 'ico') {
- $ico = '<span class="' . $v . '"></span>';
- continue;
- }
- $attr = $v;
- if ($idRecord > 0) {
- $attr = str_replace('{0}', $idRecord, $attr);
- }
- if ($showLabel && $kParamName == 'title') {
- $label = $attr;
- }
- $attr = $kParamName . '="' . $attr . '"';
- $attrs[] = $attr;
- }
- $rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico} {$label} " . '</a>';
- }
- return $rowFunctions;
- }
- private function _showRowFunctions($idRecord = null, $pomin = array(), $showLabel = false) {
- $rowFunctionsOut = $this->_parseRowFunctions($idRecord, $pomin, $showLabel);
- $rowFunctionsOut = implode('', $rowFunctionsOut);
- return $rowFunctionsOut;
- }
- private function _showRowFunctionsJson($idRecord = null, $pomin = array(), $showLabel = false) {
- $rowFunctions = $this->_parseRowFunctions($idRecord, $pomin, $showLabel);
- $rowFunctions = (object)$rowFunctions;
- return $rowFunctions;
- }
- public function allowTreeView() {
- if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
- if ($this->_tbl == 'CRM_PROCES') return true;
- return false;
- }
- public function renderStatic($tblAjaxMap = null) {
- static $_rendered = false;
- if ($_rendered) return;
- if ($tblAjaxMap) $tblAjaxMap->printCSS();
- if ($tblAjaxMap) $tblAjaxMap->printJS();
- echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
- echo UI::h('script', ['src'=>"static/jquery.doubleScroll.js"]);
- echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css"]);
- echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
- UI::inlineCSS( __FILE__ . '.style.css' );
- echo UI::h('script', [ 'src' => "static/vendor.js" ]); // window.p5VendorJs: {React, ReactDOM, createReactClass, Redux}
- echo UI::h('script', [ 'src' => "static/p5UI/buildDom.js" ]);
- $_rendered = true;
- }
- public function render() {
- $acl = $this->_acl;
- $hasGeomFlds = Core_AclHelper::hasGeomFields($acl);
- $tblAjaxMap = ($hasGeomFlds) ? new TableAjaxMap($acl, 512, 400) : null;
- $hasPermCreate = Core_AclHelper::hasCreatePerms($acl);
- $jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
- $jsToogleTableToolsFunctionName = 'tableAjaxToggleTableTools';
- ob_start();
- $this->renderStatic($tblAjaxMap);
- UI::startContainer();
- UI::showMessagesForTable($this->_tbl);
- UI::endContainer();
- $namespace = $acl->getNamespace();
- {
- $nsSiblings = ACL::getNamespaceSiblings($namespace);
- $siblingSelected = $namespace;
- $baseUrl = Router::getRoute('ViewTableAjax')->getLink();
- }
- echo UI::h('div', [ 'class' => "AjaxTableCont" ], [
- UI::h('ul', [ 'class' => "breadcrumb" ], [
- UI::h('li', [], [
- UI::h('a', [ 'href' => "#", 'onclick' => "return tableAjaxBackToTable();" ], $this->getLabelHtml() ),
- ]),
- ($hasPermCreate)
- ? UI::h('li', [], [
- UI::h('a', [ 'title' => "Dodaj nowy rekord", 'class' => "", 'href' => "#CREATE" ], [
- UI::h('span', [ 'class' => "glyphicon glyphicon-plus" ]),
- " Dodaj nowy rekord",
- ]),
- ])
- : '',
- ($this->showProcesInitFiltr)
- ? UI::h('div', [ 'class' => "btn-group pull-right" ], [
- UI::h('a', [ 'class' => "btn btn-xs btn-info dropdown-toggle",
- 'data-toggle' => "dropdown",
- 'href' => "#",
- 'title' => "Uruchom filtr procesu powiązanego z tabelą " . $this->getLabel(),
- 'onclick' => "return {$jsToogleFiltrProcesuFunctionName}(this);",
- ], "Filtr procesu <span class=\"caret\"></span>"),
- UI::h('ul', [ 'class' => "dropdown-menu pull-left", 'style' => "max-height:250px;overflow:auto;" ], [
- UI::h('li', [ 'class' => "disabled" ], [
- UI::h('a', [ 'href' => "#", 'onclick' => "return false;" ], " loading ... "),
- ]),
- ]),
- ])
- : '',
- ($this->showTableTools)
- ? UI::h('div', [ 'class' => "btn-group pull-right" ], [
- UI::h('a', [ 'class' => "btn btn-xs btn-default dropdown-toggle",
- 'style' => "margin-right:16px",
- 'data-toggle' => "dropdown",
- 'href' => "#",
- 'title' => "Narzędzia powiązane z tabelą " . $this->getLabel(),
- 'onclick' => "return {$jsToogleTableToolsFunctionName}(this);",
- ], "Narzędzia <span class=\"caret\"></span>"),
- UI::h('ul', [ 'class' => "dropdown-menu pull-left", 'style' => "max-height:250px;overflow:auto;" ], [
- UI::h('li', [ 'class' => "disabled" ], [
- UI::h('a', [ 'href' => "#", 'onclick' => "return false;" ], " loading ... "),
- ]),
- ]),
- ])
- : '',
- ($nsSiblings)
- ? UI::h('div', [ 'class' => "btn-group pull-right" ], [
- UI::h('a', [ 'class' => "btn btn-xs btn-default dropdown-toggle",
- 'style' => "margin-right:16px",
- 'data-toggle' => "dropdown",
- 'href' => "#",
- 'title' => "Powiązane obiekty z " . $this->getLabel(),
- ], "Obiekty <span class=\"caret\"></span>"),
- UI::h('ul', [ 'class' => "dropdown-menu pull-left", 'style' => "max-height:250px;overflow:auto;" ], array_map(function ($sibling) use ($baseUrl, $siblingSelected) {
- $siblingLabel = explode('/', $sibling); $siblingLabel = array_pop($siblingLabel);
- return UI::h('li', [ 'class' => "" ], [
- UI::h('a', [
- 'href' => "{$baseUrl}&namespace={$sibling}",
- 'class' => "btn btn-link " . ($siblingSelected === $sibling ? "active" : ""),
- 'style' => "text-align:left"
- ], $siblingLabel),
- ]);
- }, $nsSiblings)),
- ])
- : '',
- ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI')
- ? 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")
- : '',
- ($this->_tbl !== 'IN7_MK_BAZA_DYSTRYBUCJI' && $this->allowTreeView())
- ? 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")
- : '',
- ($this->_tbl == 'WMS_MAP_GEOREFERENCES')
- ? 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")
- : '',
- ]),
- ($this->_backRefFilter)
- ? UI::h('div', [ 'class' => "container" ], [
- UI::h('div', [ 'class' => "alert alert-info" ], [
- "Rekordy powiązane z rekordem {$this->_backRefFilter['primaryKey']} z ",
- UI::h('a', [
- 'href' => "index.php?_route=ViewTableAjax&namespace={$this->_backRefFilter['namespace']}",
- ], $this->_backRefFilter['namespace']),
- " - ",
- UI::h('a', [
- 'href' => $this->rootUrl,
- 'style' => "color:red",
- ], "usuń filtr"),
- ]),
- ])
- : '',
- ($this->_childRefFilter)
- ? UI::h('div', [ 'class' => "container" ], [
- UI::h('div', [ 'class' => "alert alert-info" ], [
- "Rekordy powiązane z rekordem {$this->_childRefFilter['primaryKey']} z ",
- UI::h('a', [
- 'href' => "index.php?_route=ViewTableAjax&namespace={$this->_childRefFilter['namespace']}",
- ], $this->_childRefFilter['namespace']),
- " - ",
- UI::h('a', [
- 'href' => $this->rootUrl,
- 'style' => "color:red",
- ], "usuń filtr"),
- ]),
- ])
- : '',
- UI::h('div', [ 'id' => $this->_htmlID ]),
- ]);
- UI::inlineJS(__FILE__ . '.generateFunctionNode.js');
- UI::inlineJS(__FILE__ . '.GeomField.js');
- if ($this->showProcesInitFiltr) {
- UI::inlineJS(__FILE__ . '.procesInitFiltr.js', [
- 'JS_FUNCTION_NAME' => $jsToogleFiltrProcesuFunctionName,
- 'URL_GET_PROCES_INIT_FILTR' => $this->showProcesInitFiltr,
- 'ID_ZASOB' => $this->_zasobID,
- ]);
- }
- if ($this->showTableTools) {
- UI::inlineJS(__FILE__ . '.tableTools.js', [
- 'JS_FUNCTION_NAME' => $jsToogleTableToolsFunctionName,
- 'URL_GET_TABLE_TOOLS' => $this->showTableTools,
- ]);
- }
- UI::inlineJS(__FILE__ . '.TableAjax.js', [
- 'URI_BASE' => Request::getPathUri(),
- ]);
- $filterInit = $this->_filterInit;
- $forceFilterInit = $this->_forceFilterInit;
- $pageSizes = $this->_pageSizes;
- $pageSize = $this->_pageSize;
- $rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
- $exportFields = Core_AclHelper::getExportFieldList($acl);
- UI::inlineJS(__FILE__ . '.hist.js', [
- 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
- 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
- 'URL_HIST_BASE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls=" . __CLASS__ . "&_hash={$this->_htmlID}&_task=HIST", // &ID=...
- 'FUNCTION_HIST_ROUTE' => "TableAjax__HIST_Route",
- ]);
- UI::inlineJS(__FILE__ . '.create.js', [
- 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
- 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
- 'NAMESPACE' => $acl->getNamespace(),
- 'FIRCE_FILTER_INIT' => $forceFilterInit,
- 'FUNCTION_CREATE_ROUTE' => "TableAjax__CREATE_Route",
- 'URL_CREATE_FORM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=createFormJson",
- ]);
- UI::inlineJS(__FILE__ . '.edit.js', [
- 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
- 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
- 'NAMESPACE' => $acl->getNamespace(),
- 'FUNCTION_EDIT_ROUTE' => "TableAjax__EDIT_Route",
- 'URL_EDIT_FORM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=editFormJson&_primaryKey=",
- ]);
- UI::inlineJS(__FILE__ . '.openRef.js', []); // p5UI__tableAjaxOpenRefCell
- $specialFilters = (method_exists($acl, 'getSpecialFilters')) ? $acl->getSpecialFilters() : null;
- $className = __CLASS__;
- UI::inlineJS(__FILE__ . '.init.js', [
- 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
- 'NAMESPACE' => $acl->getNamespace(),
- 'FUNCTION_HIST_ROUTE' => 'TableAjax__HIST_Route',
- 'FUNCTION_EDIT_ROUTE' => 'TableAjax__EDIT_Route',
- 'URL_LOAD_AJAX_BASE' => $this->syncUrl . '&_hash=' . $this->_htmlID . '&_task=loadDataAjax',
- 'URL_USER_TABLE_FILTER' => ($this->useUserTableFilter) ? $this->useUserTableFilter : '',
- 'FILTER_INIT' => $filterInit,
- 'FIRCE_FILTER_INIT' => $forceFilterInit,
- 'PAGE_SIZE' => $pageSize,
- 'PAGE_SIZES' => $pageSizes,
- 'URL_GET_CSV_THE_GEOM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=getCsvTheGeomAjax",
- 'URL_REMOVE_THE_GEOM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=removeTheGeomAjax",
- 'URL_MORE_FUNCTIONS_CELL_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=moreFunctionsCellAjax",
- 'URL_EDIT_INLINE_SAVE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=EDIT_INLINE_SAVE",
- 'URL_THE_GEOM_SAVE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=THE_GEOM_SAVE",
- 'URL_PAGE_SIZE_SAVE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=PAGE_SIZE_SAVE",
- 'URL_HIDDEN_COLS_SAVE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=HIDDEN_COLS_SAVE",
- 'URL_EDIT_INLINE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=EDIT_INLINE",
- 'URL_RECORD_COPY' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=COPY",
- 'URL_RECORD_FILES' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES",
- 'HAS_ADDITIONAL_LAYERS' => $this->hasAdditionalLayers() ? 1 : 0,
- 'URL_ADD_USER_TABLE_FILTER_AJAX' => Request::getPathUri() . "index.php?_route=ViewTableAjax&_task=addUserTableFilterAjax",
- 'URL_RM_USER_TABLE_FILTER_AJAX' => Request::getPathUri() . "index.php?_route=ViewTableAjax&_task=rmUserTableFilterAjax",
- 'LABEL_HTML' => $this->getLabelHtml(),
- 'SPECIAL_FILTER_FUNCTIONS' => (!empty($specialFilters)) ? $specialFilters : false,
- 'ROW_FUNCTIONS' => $rowFunctions,
- 'TABLE_FUNCTIONS' => array_merge(
- [ 'shortdesc' => [ 'icon' => "align-left", 'title' => "Long desc", 'method' => "longTextChanged" ] ],
- ($hasGeomFlds)
- ? [ 'mapeditor' => [ 'icon' => "map-marker", 'title' => "Mapa", 'method' => 'mapEditorChanged' ] ]
- : [],
- [ 'create' => [ 'href' => '#CREATE', 'icon' => 'plus', 'title' => "Dodaj nowy rekord" ] ],
- [ 'refresh' => [ 'icon' => 'refresh', 'title' => "Odśwież dane", 'method' => "refresh" ] ]
- ),
- 'EXPORT_FIELDS' => $exportFields,
- ]);
- UI::inlineJS(__FILE__ . '.upload.js', [
- 'URL_UPLOAD_FILES_AJAX' => "index.php?_route=ViewTableAjax&_task=uploadFilesAjax",
- ]);
- UI::setTitle($this->_acl->getRawLabel(100) . " - " . UI::getTitle());
- return ob_get_clean();
- }
- public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
- $vLabel = $pInitList[$vInitId];
- $kId = $vInitId;
- echo UI::h('a', [
- 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
- 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
- ], [
- UI::h('i', [
- 'class' => "glyphicon glyphicon-info-sign",
- 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
- 'style' => "color:#aaa",
- 'onmouseover' => "this.style.color='#337AB7'",
- 'onmouseout' => "this.style.color='#aaa'"]),
- "{{$kId}} {$vLabel}"
- ]);
- }
- public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
- $vLabel = $pInitList[$vGotoId];
- $kId = $vGotoId;
- // TODO:?: prevent to execute procedure
- echo UI::h('a', [
- 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
- 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
- ], [
- UI::h('span', [ 'style' => "padding:10px;"]),
- UI::h('i', [ 'class' => "glyphicon glyphicon-arrow-right", 'style' => "color:#aaa"]),
- UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign",
- 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
- 'style' => "color:#aaa",
- 'onmouseover' => "this.style.color='#337AB7'",
- 'onmouseout' => "this.style.color='#aaa'"]),
- "{{$kId}} {$vLabel}",
- ]);
- }
- public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
- $vLabel = $pInitList[$vGotoLvl2Id];
- $kId = $vGotoLvl2Id;
- // TODO:?: prevent to execute procedure
- echo UI::h('a', [
- 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
- 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
- ], [
- UI::h('span', [ 'style' => "padding:20px;" ]),
- UI::h('i', [ 'class' => "glyphicon glyphicon-arrow-right", 'style' => "color:#aaa" ]),
- UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign",
- 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
- 'style' => "color:#aaa",
- 'onmouseover' => "this.style.color='#337AB7'",
- 'onmouseout' => "this.style.color='#aaa'"]),
- "{{$kId}} {$vLabel}",
- ]);
- }
- public function hasAdditionalLayers() {
- $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
- return !empty($layers);
- }
- public function ajaxTask($task) {
- switch ($task) {
- case 'EDIT_INLINE': {
- $this->sendAjaxResponseJson('ajaxInlineEdit', $_REQUEST);
- break;
- }
- case 'EDIT_INLINE_SAVE': {
- $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
- break;
- }
- case 'COPY': {
- $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
- break;
- }
- case 'CREATE_SAVE': { // TODO: mv to _route = ViewTableAjax & _task = createSaveAjax
- $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
- break;
- }
- case 'HIST': {
- $this->sendAjaxResponseJson('ajaxHist', $_REQUEST);
- break;
- }
- case 'FILES': {
- try {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id <= 0) throw new HttpException("404", 404);
- $this->sendAjaxFiles($id, $_REQUEST);
- } catch (HttpException $e) {
- Http::sendHeaderByCode($e->getCode());
- echo $e->getMessage();
- //UI::alert('danger', $e->getMessage());
- } catch (Exception $e) {
- echo '<div class="container">';
- UI::alert('danger', $e->getMessage());
- echo '</div>';
- }
- break;
- }
- case 'FILES_UPLOAD': {
- $this->sendAjaxResponseJson('ajaxFileUpload', $_REQUEST);
- break;
- }
- case 'FILES_LIST': {
- $this->sendAjaxResponseJson('ajaxFileList', $_REQUEST);
- break;
- }
- case 'filePermsRefresh': {
- $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
- break;
- }
- case 'FILES_CONN_TBL_LIST': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFilesConnTblList($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'TYPESPECIAL': {
- $fldID = V::get('fldID', 0, $_REQUEST, 'int');
- if ($fldID > 0) {
- $this->sendTypeSpecial($fldID, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'HIDDEN_COLS_SAVE': {
- $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
- break;
- }
- case 'PAGE_SIZE_SAVE': {
- $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
- break;
- }
- case 'THE_GEOM_SAVE': {
- $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
- break;
- }
- default:
- $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
- }
- }
- /**
- * ajax url: &_task=EDIT_INLINE
- * @param $rowID - $_GET['ID']
- * @param $fieldName - $_GET['col']
- */
- private function ajaxInlineEdit() {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $args = $_REQUEST;
- $idRecord = V::get('ID', 0, $_REQUEST, 'int');
- $fieldName = V::get('col', '', $_REQUEST);
- if ($idRecord <= 0 || empty($fieldName)) throw new HttpException("404", 404);
- $response = array();
- ob_start();
- $fieldID = $this->_acl->getFieldIdByName($fieldName);
- if (!$fieldID) die("404: No field by name ({$fieldName})");
- $response['idZasob'] = $fieldID;
- $response['htmlFieldName'] = "f{$fieldID}";
- if ($DBG) echo "fieldID: {$fieldID}\n";
- $record = $this->_acl->buildQuery([])->getItem($idRecord);
- if (!$record) die("404: No item ID({$idRecord})");
- $fieldVal = '';
- if ($this->_acl->canReadObjectField($fieldName, $record)) {
- $fieldVal = V::get($fieldName, $fieldVal, $record);
- } else {
- $fieldVal = '*****';
- }
- $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
- $vCol = $this->_acl->getField($fieldID);
- $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
- $response['fieldLabel'] = $vCol['label'];
- $tsValues = array();
- $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
- if ($typeSpecial) {
- 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>';}
- $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $fieldName, V::get($fieldName, $fieldVal, $record));
- 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>';}
- if (!empty($specialValues)) {
- $tsValues[ $record['ID'] ] = implode('<br>', $specialValues);
- }
- }
- $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
- if (!empty($tsValues[ $record['ID'] ])) $fieldParams['typespecialValue'] = $tsValues[ $record['ID'] ];
- if (!empty($tsValues[ $record['ID'] ])) $response['typespecialValue'] = $tsValues[ $record['ID'] ];
- $vDefault = $this->_acl->getFieldDefaultValue($fieldName);
- if (!empty($vDefault)) $fieldParams['default'] = $vDefault;
- if (!empty($vDefault)) $response['defaultValue'] = $vDefault;
- if (method_exists($this->_acl, 'getFormItem')) {
- try {
- $item = $this->_acl->getFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $record);
- $response['formItem'] = $item;
- if (!empty($item['rawColType']['simpleType'])) $response['simpleType'] = $item['rawColType']['simpleType'];
- if (!empty($item['rawColType']['restrictions'])) $response['restrictions'] = $item['rawColType']['restrictions'];
- DBG::log($item, 'array', "\$item (Acl->getFormItem)");
- } catch (Exception $e) {
- echo '<div style="display:none">';
- UI::alert('danger', $e->getMessage());
- echo '</div>';
- }
- }
- ?>
- <label for="<?= "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
- <strong title="<?= "[{$fieldID}] {$fieldName}"; ?>"><?= "{$vCol['label']}"; ?></strong>
- <?php if (!empty($vCol['opis'])) : ?>
- <em><?= $vCol['opis']; ?></em>
- <?php endif; ?>
- </label>
- <?php
- if (!$this->_acl->canWriteObjectField($fieldName, $record)) {
- // TODO: hide Zapisz btn on frontend side
- if (!$this->_acl->canReadObjectField($fieldName, $record)) {
- UI::alert('warning', "Brak uprawnień do odczytu i zapisu");
- } else {
- echo '<p style="margin-top:16px">' . $fieldVal . '</p>';
- UI::alert('warning', "Brak uprawnień do zapisu");
- }
- } else {
- echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $record);
- if ($typeSpecial
- || $this->_acl->isDateField($fieldName)
- || $this->_acl->isDateTimeField($fieldName)
- ) {
- echo '<p style="padding:120px 0;"></p>';
- }
- }
- $response['legacy_html'] = ob_get_clean();
- //$response['legacy_html'] = utf8_encode($response['legacy_html']);// pl chars bug
- return $response;
- }
- private function ajaxEditInlineSave($args) {
- $primaryKeyField = $this->_acl->getPrimaryKeyField();
- $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
- $fieldName = V::get('col', '', $_REQUEST);
- if (empty($primaryKey)) throw new HttpException("Wrong param id!", 400);
- if (empty($fieldName)) throw new HttpException("Wrong param col!", 400);
- $fieldID = $this->_acl->getFieldIdByName($fieldName);
- if (!$fieldID) throw new HttpException("Field not exists!", 404);
- $item = $this->_acl->buildQuery([])->getItem($primaryKey);
- if (!$item) throw new HttpException("Item not exists!", 404);
- $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
- if (!isset($itemFromUser[$fieldName])) throw new HttpException("Field not set!", 400);
- $itemPatch = array();
- $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
- $itemPatch[$primaryKeyField] = $primaryKey;
- $response = new stdClass();
- try {
- $affected = $this->_acl->updateItem($itemPatch);
- if ($affected > 0) {
- $response->type = 'success';
- $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
- } else if ($affected == 0) {
- $response->type = 'info';
- $response->msg = "Nie wprowadzono żadnych zmian";
- }
- $response->record = $this->_acl->buildQuery([])->getItem($primaryKey);
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- public function sendAjaxEdit($id, $args) { // TODO: not used @see ViewTableAjax::editFormAction
- header("Content-type: text/plain");
- $acl = $this->_acl;
- $record = $acl->buildQuery([])->getItem($id);
- if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
- UI::alert('danger', "Brak dostępu do rekordu");
- return;
- }
- $fieldsList = array();
- foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
- if ($fieldName == 'ID') continue;
- $field['name'] = $fieldName;
- $field['opis'] = $acl->getFieldOpis($fieldName);
- $field['label'] = $acl->getFieldLabel($fieldName);
- if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
- $fieldsList[$kID] = $field;
- }
- $cols = array();
- foreach ($fieldsList as $kID => $field) {
- $cols[$kID] = '';
- if ($this->_acl->canReadObjectField($field['name'], $record)) {
- $cols[$kID] = V::get($field['name'], '', $record);
- } else {
- $cols[$kID] = '*****';
- }
- // if ($acl->canReadObjectField($field['name'])) {
- // $cols[$kID] = V::get($field['name'], '', $record);
- // } else {
- // $cols[$kID] = '*****';
- // }
- $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
- }
- $tsValues = array();
- if (!empty($fieldsList)) {
- foreach ($fieldsList as $vColID => $vCol) {
- $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
- if ($typeSpecial) {
- $colValue = V::get($vCol['name'], '', $record);
- $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $vCol['name'], $colValue);
- if (!empty($specialValues)) {
- $tsValues[$vColID] = implode('<br>', $specialValues);
- }
- }
- }
- }
- $rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
- ?>
- <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
- <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?= $this->_htmlID; ?>">
- <fieldset>
- <legend>Edycja rekordu Nr <?= $record['ID']; ?><span class="pull-right valign-btns-bottom"><?= $rowFunctionsOut; ?></span></legend>
- <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
- <?php if ($acl->canWriteObjectField($vCol['name'], $record)) : ?>
- <div class="form-group">
- <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?= "f{$kID}"; ?>"><?= $vCol['label']; ?>
- <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>
- </label>
- <div class="col-xs-12 col-sm-9 col-md-10">
- <?php
- $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
- if (!empty($tsValues[$kID])) {
- $fieldParams['typespecialValue'] = $tsValues[$kID];
- }
- echo $acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
- ?>
- </div>
- </div>
- <?php elseif ($acl->canReadObjectField($vCol['name'], $record)) : ?>
- <div class="form-group">
- <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?= "f{$kID}"; ?>"><?= $vCol['label']; ?>
- <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>
- </label>
- <div class="col-xs-12 col-sm-9 col-md-10">
- <p style="margin-top:5px;">
- <?php
- //echo $acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
- if (!empty($tsValues[$kID])) {
- echo $tsValues[$kID];
- } else if (!empty($record[ $vCol['name'] ])) {
- echo $record[ $vCol['name'] ];
- }
- ?>
- </p>
- </div>
- </div>
- <?php endif; ?>
- <?php endforeach; ?>
- <div class="form-group">
- <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
- <button type="submit" class="btn btn-primary" tabindex="<?= (++$tabindex); ?>">Zapisz</button>
- </div>
- </div>
- </fieldset>
- </form>
- <p style="padding:100px 0;"></p>
- </div>
- <script>
- jQuery(document).ready(function(){
- jQuery('textarea').autosize();
- jQuery('.frm-help').popover({trigger:'hover'});
- jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
- var formData = {};
- jQuery(this).serializeArray().map(function(i) { formData[i.name] = i.value; });// TODO: edit Widget - send only updated fields
- // TODO: change Edit btn to return to edit record with fields -> show form
- var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
- //taskCont.empty();
- taskCont.children().fadeOut('slow');
- var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
- , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
- 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);
- function notifyAjaxCallback(data) {
- var notify = {}, outMsg = '';
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
- break;
- case 'info':
- if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- var alertType = ('error' == data.type) ? 'danger' : data.type;
- outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
- return outMsg;
- }
- superagent
- .post('<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=editSaveAjax')
- .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
- .send({
- namespace: '<?= $acl->getNamespace(); ?>',
- primaryKey: '<?= $record['ID']; ?>',
- form: formData
- })
- .set('Accept', 'application/json')
- .end(function(err, res) {
- var payload;
- if (err || !res.ok || 'application/json' !== res.type) {
- payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
- } else {
- payload = {type: 'success', msg: res.body.msg || '', body: res.body};
- }
- var data = res.body;
- alertCntWrap.removeClass('AjaxTable-loading');
- alertCnt.empty();
- if (false === ['success', 'info'].indexOf(payload.type)) {
- jQuery(errorTxt).appendTo(alertCnt);
- var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
- jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
- 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);
- backToEditBtn.on('click', function(){
- alertCnt.remove();
- taskCont.children().fadeIn('slow');
- return false;
- });
- } else {
- var outMsg = notifyAjaxCallback(payload);
- var out = '';
- out += outMsg;
- out += '<div class="breadcrumb">' +
- ' <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>' +
- ' <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>' +
- '</div>';
- jQuery(out).appendTo(alertCnt);
- // add rowFunctions from response
- if (data && data.rowFunctions && data.primaryKey) {
- var rowFunWrapNode = $('<div class="container"></div>').insertAfter(alertCnt);
- var rowFunListNode = $('<ul></ul>').appendTo(rowFunWrapNode);
- var keys = Object.keys(data.rowFunctions),
- total = keys.length,
- moreFuncBtnNode,
- moreFunctions = [],
- idx
- ;
- moreFunctions = keys.splice(3);
- keys.forEach(function(key) {
- var cellNode = $('<li></li>');
- var funObj = data.rowFunctions[key],
- funcNode = p5UI_TableAjax_generateFunctionNode(funObj, data.primaryKey, {ico: true, label: true})
- ;
- funcNode.appendTo(cellNode);
- cellNode.appendTo(rowFunListNode);
- });
- }
- }
- });
- return false;
- });
- jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
- var input, btn, btnIco;
- input = jQuery(e.target);
- btn = input.next('.button-appendBack');
- btnIco = btn.find('.glyphicon');
- if (btn.attr('title') != input.val()) {
- btnIco.show();
- } else {
- btnIco.hide();
- }
- });
- jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
- var input, btn, btnIco;
- btn = jQuery(this);
- btnIco = btn.find('.glyphicon');
- input = btn.prev();
- if (input.is('input')) {
- if (btn.attr('title') != input.val()) {
- input.val(btn.attr('title'));
- btnIco.hide();
- }
- }
- });
- });
- </script>
- <?php
- exit;
- }
- public function sendAjaxCreate($args = []) {
- $acl = $this->_acl;
- header("Content-type: text/plain");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- if (!Core_AclHelper::hasCreatePerms($acl)) {
- UI::alert('danger', "Brak uprawnień do utworzenia nowego rekordu.");
- return;
- }
- $cols = array();
- $forceFilterInit = array();
- $defaultAclGroup = User::getDefaultAclGroup();
- if ($defaultAclGroup) {
- $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
- $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
- }
- foreach ($_GET as $k => $v) {
- if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
- $fldName = substr($k, 3);
- $forceFilterInit[$fldName] = $v;
- }
- }
- $pkField = $acl->getPrimaryKeyField();
- $fieldsList = $acl->getFields();
- $fieldsList = array_filter($fieldsList, function ($vCol) {
- return ($vCol['name'] != $pkField);
- });
- foreach ($fieldsList as $kID => $vCol) {
- $defaultValue = '';
- if (!empty($forceFilterInit[$vCol['name']])) {
- $defaultValue = $forceFilterInit[$vCol['name']];
- }
- // TODO: read from session cache
- $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
- $label = V::get('label', '', $vCol);
- $fieldsList[$kID]['label'] = ($label) ? $label : $vCol['name'];
- }
- ?>
- <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
- <form action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
- <fieldset>
- <legend>Dodaj nowy rekord</legend>
- <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
- <?php if ($acl->canCreateField($vCol['name'])) : ?>
- <div class="form-group">
- <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?= V::get('label', $vCol['name'], $vCol); ?>
- <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>
- </label>
- <div>
- <?php
- $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
- echo $acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
- ?>
- </div>
- </div>
- <?php endif; ?>
- <?php endforeach; ?>
- <div class="form-group">
- <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
- </div>
- </fieldset>
- </form>
- </div>
- <script>
- jQuery(document).ready(function(){
- jQuery('textarea').autosize();
- jQuery('.frm-help').popover({trigger:'hover'});
- jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
- var data = jQuery(this).serialize();
- var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
- taskCont = taskContLast.parent();
- taskContLast.fadeOut('slow');
- var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
- 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);
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'OK';
- break;
- case 'info':
- if (!notify.msg) notify.msg = '';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- $.ajax({
- data: data,
- dataType: 'json',
- type: "POST",
- async: true,
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
- })
- .always(function(dataOrJqXHR){
- var data;
- if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
- if ('responseJSON' in dataOrJqXHR) {
- data = dataOrJqXHR.responseJSON;
- } else {
- data = {};
- data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
- if (dataOrJqXHR.status == 404) {
- data.type = 'error';
- } else {
- data.type = 'warning';
- }
- }
- }
- else {
- data = dataOrJqXHR;
- }
- notifyAjaxCallback(data);
- taskCnt.removeClass('AjaxTable-loading');
- taskCnt.empty();
- if (data.type == 'error' || data.type == 'warning') {
- var out = '<div class="container">' +
- '<div class="alert alert-danger">' +
- '<h4>Wystąpiły błędy!</h4>' + data.msg +
- (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
- '</div>';
- out += '<div class="breadcrumb">' +
- ' <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>' +
- '</div>' +
- '</div>';
- jQuery(out).appendTo(taskCnt);
- var taskContLastNode = taskContLast
- , taskCntNode = taskCnt;
- taskCnt.find('.create-fix').click(function(){
- taskCntNode.remove();
- taskContLastNode.fadeIn('slow');
- return false;
- });
- }
- else if (data.type == 'success') {
- var msg = '';
- if (data.id && data.id > 0) {
- msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
- } else if (data.msg) {
- msg = data.msg;
- } else {
- msg = 'OK';
- }
- var out = '<div class="container">';
- out += '<div class="alert alert-success">' + msg + '</div>';
- out += '<div class="breadcrumb">' +
- ' <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>' +
- ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
- ' <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>' +
- '</div>';
- out += '</div>';
- jQuery(out).appendTo(taskCnt);
- }
- });
- return false;
- });
- });
- </script>
- <?php
- exit;
- }
- private function ajaxCreateSave($args) {
- DBG::log($args, 'array', "ajaxCreateSave");
- $acl = $this->_acl;
- $response = new stdClass();
- $createdId = null;
- try {
- $item = $acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
- $createdId = $acl->addItem($item);
- if ($createdId) {
- $response->type = 'success';
- $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
- $response->id = $createdId;
- $response->record = $acl->buildQuery([])->getItem($createdId);
- }
- else {
- $response->type = 'error';
- $response->msg = "Nie udało się utworzyć nowego rekordu!";
- }
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- private function ajaxCopy($args) {
- $acl = $this->_acl;
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id <= 0) {
- throw new HttpException("Wrong param ID!", 404);
- }
- $item = $acl->buildQuery([])->getItem($id);
- if (!$item) {
- throw new HttpException("Item '{$id}' not exists!", 404);
- }
- $response = new stdClass();
- $itemCopy = $acl->createItemCopy($item);
- $createdId = null;
- try {
- $createdId = $acl->addItem($itemCopy);
- if ($createdId) {
- $response->type = 'success';
- $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
- $response->id = $createdId;
- $response->record = $acl->buildQuery([])->getItem($createdId);
- }
- else {
- $response->type = 'error';
- $response->msg = "Nie udało się skopiować rekordu!";
- }
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = "Wystąpiły błędy!";
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- private function ajaxHist($args) {
- $jsonResponse = array();
- $id = V::get('ID', 0, $args, 'int');
- $acl = $this->_acl;
- $record = $acl->buildQuery([])->getItem($id);
- if (!$record) throw new HttpException("404: No item ID({$id})", 404);
- $visibleCols = $acl->getRealFieldList();
- try {
- $rowsHist = $acl->getHistItems($id);
- } catch (Exception $e) {
- DBG::log($e);
- $rowsHist = [];
- }
- $jsonResponse['row_functions'] = $this->_parseRowFunctions($record['ID'], array('hist', 'cp'), $showLabel = true);
- $visibleColsWithIds = array();
- $visibleColsLabels = array();
- foreach ($visibleCols as $vColName) {
- $fldId = $acl->getFieldIdByName($vColName);
- if ($fldId) {
- $visibleColsWithIds[$fldId] = $vColName;
- $label = $acl->getFieldLabel($vColName);
- $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
- $visibleColsLabels[$fldId] = $label;
- }
- }
- $jsonResponse['label'] = "Historia rekordu Nr {$id}";
- $jsonResponse['fields'] = array_values($visibleColsWithIds);
- $jsonResponse['field_label'] = $visibleColsLabels;
- if (empty($rowsHist)) return $jsonResponse;
- $jsonResponse['rows'] = array();
- foreach ($rowsHist as $histRow) {
- $histItem = array();
- $histItem['ID'] = V::get('ID', '', $histRow);
- $histItem['_created'] = V::get('_created', '', $histRow);
- $histItem['_author'] = V::get('_author', '', $histRow);
- $histItem['changes'] = array();
- foreach ($visibleColsWithIds as $fldId => $fieldName) {
- if (!array_key_exists($fieldName, (array)$histRow)) continue;
- $value = V::get($fieldName, '', $histRow);
- if ('N/S;' == $value) continue;
- $changeItem = array();
- $changeItem['fieldName'] = $fieldName;
- $changeItem['acl_read'] = $acl->canReadObjectField($fieldName, $record);
- if ($changeItem['acl_read']) {
- $changeItem['value'] = V::get($fieldName, '', $histRow);
- }
- if ('the_geom' == $fieldName && $acl->canWriteObjectField($fieldName, $record)) {
- $sourceName = $acl->getSourceName();
- if ('default_db' == $sourceName && !empty($value)) {
- $typeName = $acl->getName();
- $idHist = V::get('ID', '', $histRow);
- $changeItem['revert_function_url'] = Request::getPathUri() . "index.php?_route=ViewTableAjax&typeName=p5_{$sourceName}:{$typeName}&_task=revertFromHistAjax&ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
- $changeItem['revert_function_data'] = "ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
- }
- }
- $histItem['changes'][$fieldName] = $changeItem;
- }
- $jsonResponse['rows'][] = $histItem;
- }
- return $jsonResponse;
- }
- public function ajaxFileUpload($args) {
- $id = V::get('ID', 0, $args, 'int');
- if ($id <= 0) throw new HttpException("404", 404);
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) throw new HttpException("No DB ({$dbID})", 406);
- $record = $this->_acl->buildQuery([])->getItem($id);
- if (!$record) throw new HttpException("No item ID({$id})", 404);
- if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
- if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, (object)$record);
- if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
- $uploader->findFolder();
- $errorMsg = '';
- if (!empty($args['SCANS_COLUMN_ADD'])) {
- $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
- }
- else {
- $uploaded = $uploader->tryUploadAjax($errorMsg);
- }
- $retJson = new stdClass();
- if (!$uploaded) throw new Exception($errorMsg);
- $uploadedFileName = '';
- $uploadedFile = $uploader->getLastUploadedFile();
- if ($uploadedFile) {
- $uploadedFileName = explode('/', $uploadedFile);
- $uploadedFileName = end($uploadedFileName);
- }
- //echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
- $retJson->type = 'SUCCESS';
- $retJson->msg = "Plik został poprawnie wgrany do odpowiedniego katalogu {$uploadedFileName}";
- if (!empty($uploadedFileName)) {
- $sqlObj = new stdClass();
- $sqlObj->ID = $record['ID'];
- $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
- $db->UPDATE_OBJ($this->_tbl, $sqlObj);
- }
- return $retJson;
- }
- public function ajaxFileList($args) {
- $id = V::get('ID', 0, $args, 'int');
- if ($id <= 0) throw new HttpException("404", 404);
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) throw new HttpException("No DB ({$dbID})", 406);
- $record = $this->_acl->buildQuery([])->getItem($id);
- if (!$record) throw new HttpException("No item ID({$id})", 404);
- if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, (object)$record);
- if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- $files = $uploader->getFilesFromFolder($mainFolder, false, true);
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
- return $jsonFiles;
- }
- private function ajaxFilePermsRefresh($args) {
- $id = V::get('ID', 0, $args, 'int');
- if ($id <= 0) throw new HttpException("Wrong param ID", 404);
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) throw new HttpException("No DB", 406);
- $record = $this->_acl->buildQuery([])->getItem($id);
- if (!$record) throw new Exception("No item ID({$id})", 404);
- $tblName = $this->_acl->getName();
- // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
- $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
- $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
- $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
- $mainDB = DB::getDB();
- if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
- $sql = "insert into `_SYNC_FILE_PERMS` (
- `ID_PROJECT`,
- `A_SYNCHRONIZED`
- )
- values (
- '{$record['ID']}'
- , 0
- )
- ON DUPLICATE KEY UPDATE
- `A_SYNCHRONIZED`=0
- ";
- }
- else if ('IN7_DZIENNIK_KORESP' == $tblName) {
- $sql = "insert into `_SYNC_FILE_PERMS` (
- `ID_PROJECT`,
- `A_SYNCHRONIZED`
- )
- values (
- '{$record['ID_PROJECT']}'
- , 0
- )
- ON DUPLICATE KEY UPDATE
- `A_SYNCHRONIZED`=0
- ";
- }
- else {
- $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
- `TBL_NAME`,
- `TBL_ID`,
- `L_APPOITMENT_USER`,
- `A_ADM_COMPANY`,
- `A_CLASSIFIED`,
- `A_SYNCHRONIZED`
- )
- values (
- '{$tblName}'
- , '{$id}'
- , '{$sql_L_APPOITMENT_USER}'
- , '{$sql_A_ADM_COMPANY}'
- , '{$sql_A_CLASSIFIED}'
- , 0
- )
- ON DUPLICATE KEY UPDATE
- `A_SYNCHRONIZED`=0
- ";
- }
- $res = $mainDB->query($sql);
- if ($mainDB->has_errors()) {
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
- //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>';
- throw new Exception("Nie udało się dodać zadania");
- }
- // TODO: this blocks browser ajax query
- //$limit = 3;
- //while ($limit--) {
- // sleep(10);
- // TODO: check if task is done
- //}
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, (object)$record);
- if (!$uploader->setConfig($folderConf)) {
- throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
- }
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- $files = $uploader->getFilesFromFolder($mainFolder, false, true);
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonData = new stdClass();
- $jsonData->msg = 'Zadanie dodane';
- $jsonData->type = 'success';
- $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
- return $jsonData;
- }
- private function sendAjaxFilesConnTblList($id, $args) {
- header("Content-type: application/json");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- echo 'No DB (' . $dbID . ')';
- exit;
- }
- $record = $this->_acl->buildQuery([])->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo 'No item ID(' . $rowID . ')';
- exit;
- }
- $connTblName = '';
- $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
- if ($connTblID <= 0) {
- header('HTTP/1.0 406 Not Acceptable');
- echo 'No conn Table ID';
- exit;
- }
- $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
- if (empty($connTblTypespecials)) {
- header('HTTP/1.0 406 Not Acceptable');
- echo "No conn Table (ID={$connTblID})";
- exit;
- }
- 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>';}
- if(1) {
- header('HTTP/1.0 404 Not Found');
- echo 'TODO: ...';
- exit;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- $uploader = new FileUploader($confTblName, (object)$record);
- if (!$uploader->setConfig($folderConf)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- $files = $uploader->getFilesFromFolder($mainFolder, false, true);
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
- echo json_encode($jsonFiles);
- exit;
- }
- public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
- $jsonFiles = array();
- if (!is_array($files) || empty($files)) {
- return $jsonFiles;
- }
- sort($files);
- foreach ($files as $vFilePath) {
- $file = new stdClass();
- $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
- //$file->name = explode('/', $vFilePath);
- //$file->name = end($file->name);
- $file->size = filesize($vFilePath);
- $file->sizeStr = V::humanFileSize($file->size);
- $file->type = '';
- $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
- $file->web = str_replace($localPath, $folderWeb, $vFilePath);
- $jsonFiles[] = $file;
- }
- return $jsonFiles;
- }
- private function getConnectedTables() {
- $connTbls = array();
- return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
- $fields = $this->_acl->getVirtualFieldListByIdZasob();
- if (!empty($fields)) {
- foreach ($fields as $vColID => $vCol) {
- $typeSpecial = Typespecial::getInstance($vColID);
- if ($typeSpecial) {
- $tsConnTbls = $typeSpecial->getTblAliasList();
- if (!empty($tsConnTbls)) {
- foreach ($tsConnTbls as $kID => $vName) {
- $connTbls[$kID] = $vName;
- }
- }
- }
- }
- }
- return $connTbls;
- }
- private function getConnectedTblTypespecials($connTblID) {
- $connTblTypespecials = array();
- $fields = $this->_acl->getVirtualFieldListByIdZasob();
- if (!empty($fields)) {
- foreach ($fields as $vColID => $vCol) {
- $typeSpecial = Typespecial::getInstance($vColID);
- if ($typeSpecial) {
- $tsConnTbls = $typeSpecial->getTblAliasList();
- if (array_key_exists($connTblID, $tsConnTbls)) {
- $connTblTypespecials[] = $typeSpecial;
- }
- }
- }
- }
- return $connTblTypespecials;
- }
- private function sendAjaxFiles($id, $args) {
- header("Content-type: text/plain");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $acl = $this->_acl;
- $dbID = $acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) throw new HttpException("", 406);
- $record = $acl->buildQuery([])->getItem($id);
- if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
- if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
- $tblName = $acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych", 404);
- $folderConf = FoldersConfig::getAll($confTblName);
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
- $uploader = new FileUploader($confTblName, (object)$record);
- $errMsg = '';
- if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})" . '<br>' . "\n" . $errMsg, 404);
- $uploader->findFolder();
- 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>'; }
- $mainFolder = $uploader->getDestFolder();
- 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>'; }
- if (!$mainFolder) {
- $destFolderPath = $uploader->getDestLocalPath(true);
- $folderCreated = $uploader->tryCreateDestFolder($destFolderPath);
- if ($folderCreated) {
- //UI::alert('info', "Utworzono katalog");
- $uploader->findFolder();
- $mainFolder = $uploader->getDestFolder();
- } else {
- UI::alert('warning', "Nie udało się utworzyć katalogu");
- }
- }
- $files = $uploader->getFilesFromFolder($mainFolder, false, true);
- 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>'; }
- $sharePoint = V::get('share_point', null, $folderConf);
- if ($sharePoint) {
- if ('//' == substr($mainFolder, 0, 2)) {
- $sharePoint = FoldersConfig::getNfsOsPath() . "{$mainFolder}";
- } else {
- $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
- }
- }
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
- 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>'; }
- $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
- $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
- $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
- $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
- $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
- sort($skanyFiles);
- $fileTypes = FoldersConfig::getAll('m_dist_files_types');
- $rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('files', 'cp'), true);
- $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
- $fileIndex = V::get($fileIndexField, $record['ID'], $record);
- $namespace = $acl->getNamespace();
- echo UI::h('div', [ 'class' => "container" ], [
- UI::h('h4', [ 'style' => "margin:20px 0 3px 0;" ], [
- "Pliki w katalogu ",
- ($sharePoint)
- ? UI::h('a', [ 'href' => $sharePoint ], [
- UI::h('span', [ 'class' => "glyphicon glyphicon-folder-open" ]),
- UI::h('code', [ 'style' => "margin-left:6px" ], $mainFolder),
- ])
- : UI::h('code', [], $mainFolder),
- UI::h('span', [ 'class' => "pull-right valign-btns-bottom" ], [
- UI::h('span', [ 'id' => "FILES_LIST_ACTIONS_{$this->_htmlID}" ]),
- " {$rowFunctionsOut}",
- ]),
- ]),
- UI::h('div', [ 'style' => "clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;" ], [
- UI::h('table', [ 'class' => "table table-bordered table-hover" ], [
- UI::h('colgroup', [], [
- UI::h('col', [ 'style' => "" ]),
- UI::h('col', [ 'style' => "width:30px" ]),
- ($sharePoint)
- ? UI::h('col', [ 'style' => "width:30px" ])
- : '',
- UI::h('col', [ 'style' => "width:80px" ]),
- UI::h('col', [ 'style' => "width:140px" ]),
- ]),
- UI::h('tbody', [ 'id' => "FILES_LIST_{$this->_htmlID}" ], [
- (empty($mainFolder) || empty($files))
- ? UI::h('tr', [], [
- UI::h('td', [ 'colspan' => "5" ], [
- (empty($mainFolder))
- ? UI::h('div', [ 'class' => "alert alert-warning" ], [
- UI::h('h4', [], "Brak folderu!"),
- "Folder dla tego rekordu nie został utworzony."
- ])
- : UI::h('div', [ 'class' => "alert alert-info" ], [
- UI::h('h4', [], "Brak plików!"),
- ])
- ]),
- ])
- : '',
- ]),
- ]),
- ]),
- UI::h('br'),
- UI::h('br'),
- (!$this->_acl->canWriteRecord($record))
- ? UI::h('div', [ 'class' => "alert alert-warning" ], [
- "Brak uprawnień do dodawania plików",
- ])
- : UI::h('div', [ 'id' => "FILES_CONN_TBLS_{$this->_htmlID}" ]),
- (!$this->_acl->canWriteRecord($record))
- ? ''
- : UI::h('form', [ 'enctype' => "multipart/form-data", 'method' => "POST", 'action' => "", 'id' => "FILES_FRM_{$this->_htmlID}", 'class' => "form-inline" ], [
- UI::h('input', [ 'type' => "hidden", 'name' => "M_DIST_UPLOAD_SOURCE", 'value' => "local" ]),
- UI::h('ul', [ 'id' => "FILES_TAB_{$this->_htmlID}", 'class' => "nav nav-tabs", 'style' => "margin:0;"], [
- UI::h('li', [ 'class' => "active" ], [ UI::h('a', [ 'href' => "#local", 'data-toggle' => "local" ], "Wybierz plik lokalny"), ]),
- UI::h('li', [], [ UI::h('a', [ 'href' => "#scan", 'data-toggle' => "scan" ], "Wybierz plik ze skanów" ), ]),
- UI::h('li', [], [ UI::h('a', [ 'href' => "#multiple", 'data-toggle' => "multiple" ], "Wgraj wiele plików" ), ]),
- ]),
- UI::h('div', [ 'id' => "myTabContent", 'class' => "tab-content" ], [
- UI::h('div', [ 'class' => "tab-pane fade in active", 'id' => "local", 'style' => "text-align: center;" ], [
- UI::h('input', [ 'name' => "M_DIST_FILES_NAME", 'type' => "file", 'size' => "60", 'class' => "field-upload btn",
- 'style' => "width:86%;margin:10px auto;padding:10px 4%;background:#eee;text-align:center",
- 'ondragover' => "this.style.backgroundColor='#D9EDF7'",
- 'ondragleave' => "this.style.backgroundColor='#eee'",
- 'ondragend' => "this.style.backgroundColor='#eee'",
- ]),
- ]),
- UI::h('div', [ 'class' => "tab-pane fade", 'id' => "multiple" ], [
- UI::h('div', [
- 'id' => "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
- 'style' => "width:86%; margin:10px auto; padding:40px 100px; background-color:#eee; border-radius:4px; text-align:center",
- 'ondrop' => "p5TAFiles_onDropMultiple(event, this, '{$id}', '{$namespace}')",
- 'ondragover' => "p5TAFiles_onDragOverMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#D9EDF7'",
- 'ondragleave' => "p5TAFiles_onDragLeaveMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#eee'",
- 'ondragend' => "p5TAFiles_onDragEndMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#eee'",
- ], [
- "Upuść pliki tutaj",
- ]),
- ]),
- UI::h('div', [ 'class' => "tab-pane fade", 'id' => "scan" ], [
- (empty($skanyFiles))
- ? UI::h('div', [ 'class' => "alert alert-info" ], [
- UI::h('h4', [], "Brak plików"),
- (!empty($skanyFolderWeb))
- ? "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>"
- : '',
- ])
- : UI::h('div', [ 'style' => "max-height:150px; overflow:auto; border-bottom:1px solid #ddd;" ], [
- UI::h('table', [ 'class' => "table table-bordered table-hover" ], [
- UI::h('colgroup', [], [
- UI::h('col', [ 'style' => "width:30px;" ]),
- UI::h('col', [ 'style' => "" ]),
- UI::h('col', [ 'style' => "width:30px;" ]),
- UI::h('col', [ 'style' => "width:80px;" ]),
- UI::h('col', [ 'style' => "width:140px;" ]),
- ]),
- UI::h('tbody', [], array_map(function ($vFilePath) use ($skanyLocalPath, $skanyFolderWeb) {
- $vFileName = explode('/', $vFilePath);
- $vFileName = end($vFileName);
- $vFileSize = filesize($vFilePath);
- $vFileSizeOut = V::humanFileSize($vFileSize);
- return UI::h('tr', [], [
- UI::h('td', [], [ UI::h('input', [ 'style' => "margin:0", 'type' => "radio", 'name' => "SCANS_COLUMN_ADD", 'value' => $vFileName]) ]),
- UI::h('td', [], [ UI::h('div', [ 'style' => "overflow:hidden; white-space:nowrap", 'title' => $vFileName ], $vFileName) ]),
- UI::h('td', [ 'style' => "white-space:nowrap; text-align:center" ], [
- UI::h('a', [ 'href' => str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath), 'target' => "_blank", 'class' => "glyphicon glyphicon-download-alt" ])
- ]),
- UI::h('td', [ 'style' => "white-space:nowrap; text-align:right" ], $vFileSizeOut),
- UI::h('td', [ 'style' => "white-space:nowrap" ], date("Y-m-d H:i:s", filectime($vFilePath))),
- ]);
- }, $skanyFiles)),
- ])
- ]),
- ])
- ]),
- UI::h('br'),
- UI::h('h4', [], [
- "Ustal nazwę pliku zgodną z obiegiem dokumentów",
- //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>
- ]),
- UI::h('table', [ 'style' => "width:100%", 'class' => "table table-bordered" ], [
- UI::h('tr', [], [
- UI::h('th', [], "Nr"),
- UI::h('th', [], "Typ"),
- UI::h('th', [ 'style' => "width:40%" ], [
- "Opis ",
- UI::h('i', [ 'class' => "glyphicon glyphicon-question-sign", 'title' => "kogo dotyczy / czego / sprawa / nazwa_firmy itp" ]),
- ]),
- UI::h('th', [ 'style' => "width:16%" ], "Data wersji"),
- UI::h('th', [ 'style' => "width:12%" ], "Numer wersji"),
- ]),
- UI::h('tr', [], [
- UI::h('td', [], $fileIndex),
- UI::h('td', [], [
- UI::h('select', [ 'class' => "form-control", 'name' => "M_DIST_FILES_TYPE" ], array_map(function ($vLabel, $kType) {
- return UI::h('option', array_merge([ 'value' => $kType],
- ($kType == 'TODO')
- ? [ 'selected' => "selected"]
- : []
- ), $vLabel);
- }, $fileTypes, array_keys($fileTypes)) ),
- UI::h('br'),
- UI::h('label', [ 'class' => "checkbox" ], [
- UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_TYPE_AUTO" ]),
- " Wykrycie automatyczne typu z wysylanego pliku",
- ]),
- UI::h('label', [ 'class' => "checkbox" ], [
- UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_TEMP" ]),
- " Plik tymczasowy / roboczy / nieoficjalny (_TEMP)",
- ]),
- ]),
- UI::h('td', [], [
- UI::h('input', [ 'class' => "form-control", 'style' => "width:100%", 'type' => "text", 'name' => "M_DIST_FILES_DESCRIPTION", 'value' => "", 'maxlength' => "50" ]),
- "<br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>",
- ]),
- UI::h('td', [], [
- UI::h('div', [ 'class' => "input-group" ], [
- 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" ]),
- UI::h('span', [ 'class' => "input-group-addon" ], [
- UI::h('span', [ 'class' => "glyphicon glyphicon-calendar" ]),
- ]),
- ]),
- // UI::h('input', [ 'class' => "form-control", 'type' => "date", 'name' => "M_DIST_FILES_DATE", 'value' => date('Y-m-d'), 'maxlength' => "10" ]),
- "<br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (" . date('Y-m-d') . ")</label>",
- ]),
- UI::h('td', [], [
- UI::h('input', [ 'class' => "form-control", 'style' => "width:100%", 'type' => "number", 'name' => "M_DIST_FILES_VERSION" ]),
- UI::h('br'),
- UI::h('label', [ 'class' => "checkbox" ], [
- UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_VERSION_AUTO" ]),
- " Automatycznie dodaj wersje",
- ]),
- ]),
- ]),
- UI::h('tr', [], [
- UI::h('td', [ 'colspan' => "5" ], [
- UI::h('div', [ 'id' => "FRM_UPLOAD_RESULTS_{$this->_htmlID}" ]),
- UI::h('p', [], [
- UI::h('input', [ 'type' => "submit", 'value' => "Wyślij", 'class' => "btn btn-primary" ], "wybrany plik do folderu:"),
- ]),
- UI::h('p', [], [
- UI::h('code', [], [
- UI::h('b', [], $uploader->getDestPathShare(true)),
- ]),
- UI::h('br'),
- UI::h('i', [ 'style' => "color:#777" ], "(Jeśli folder nie istnieje to zostanie utworzony automatycznie)"),
- ]),
- ]),
- ]),
- ]),
- ]),
- ]);
- $className = __CLASS__;
- $namespace = $acl->getNamespace();
- UI::inlineJS(__FILE__ . '.files.js', [
- 'UNIQ_HASH' => $this->_htmlID,
- 'FUNCTION_FILE_LIST_UPDATE_AJAX' => "fileListUpdateAjax{$this->_htmlID}", // fileListUpdateAjax
- 'FUNCTION_FILE_LIST_UPDATE' => "fileListUpdate{$this->_htmlID}", // fileListUpdate
- 'FUNCTION_CONN_TBL_LIST_UPDATE_AJAX' => "connTblListUpdateAjax{$this->_htmlID}", // connTblListUpdateAjax
- 'FUNCTION_CONN_TBL_LIST_UPDATE' => "connTblListUpdate{$this->_htmlID}", // connTblListUpdate
- 'FUNCTION_FILE_LIST_ACTIONS' => "fileListActions{$this->_htmlID}", // fileListActions
- 'CONN_TABLES' => $this->getConnectedTables(),
- 'NODE_ID_FILES_FRM' => "FILES_FRM_{$this->_htmlID}",
- 'NODE_ID_FRM_UPLOAD_RESULTS' => "FRM_UPLOAD_RESULTS_{$this->_htmlID}",
- 'NODE_ID_FILES_TAB' => "FILES_TAB_{$this->_htmlID}",
- 'NODE_ID_FILES_LIST' => "FILES_LIST_{$this->_htmlID}",
- 'NODE_ID_FILES_CONN_TBLS' => "FILES_CONN_TBLS_{$this->_htmlID}",
- 'NODE_ID_FILES_LIST_ACTIONS' => "FILES_LIST_ACTIONS_{$this->_htmlID}",
- 'NODE_ID_FILES_MULTIPLE_UPLOAD' => "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
- 'URL_FILE_LIST_UPDATE_AJAX' => "index-ajax.php?_zasobID={$this->_zasobID};&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_LIST&ID={$record['ID']}",
- 'URL_FILE_REMOVE_AJAX' => "index.php?_route=ViewTableAjax&namespace={$namespace}&_task=removeFileAjax&ID={$record['ID']}",
- 'URL_CONNECTED_TABLE_LIST' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_CONN_TBL_LIST&ID={$record['ID']}",
- 'URL_FILE_PERMS_REFRESH' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=filePermsRefresh&ID={$record['ID']}",
- 'URL_FILE_UPLOAD' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_UPLOAD&ID={$record['ID']}",
- 'CAN_WRITE_RECORD' => (int)$this->_acl->canWriteRecord($record),
- 'SHARE_POINT' => $sharePoint,
- 'JSON_FILES' => $jsonFiles,
- ]);
- exit;
- }
- private function sendTypeSpecial($fldID, $args) { // TODO: mv to index.php?_route=ViewTableAjax&_task=typespecial&idField=" + idField, // &q=... or &selected=... or &idRecord=...
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- header("Content-type: application/json");
- $fldName = '';
- $fld = $this->_acl->getField($fldID);
- DBG::log($fld, 'array', "\$fld({$fldID})");
- if (!$fld) {
- // 404
- } else {
- $fldName = $fld['name'];
- }
- $jsonData = array();
- $typeSpecial = Typespecial::getInstance($fldID, $fldName);
- if ($typeSpecial) {
- $query = V::get('q', '', $_REQUEST);
- DBG::log("\$query({$query})");
- $rawRows = null;
- $rows = $typeSpecial->getValuesWithExports($query);
- DBG::log($rows, 'array', "\$rows({$query})");
- foreach ($rows as $kID => $vItem) {
- $itemJson = new stdClass();
- $itemJson->id = $vItem->id;
- $itemJson->name = $vItem->param_out;
- if (!empty($vItem->exports)) {
- $itemJson->exports = $vItem->exports;
- }
- if (!empty($vItem->{'$order'})) {
- $itemJson->{'$order'} = $vItem->{'$order'};
- }
- $jsonData[] = $itemJson;
- }
- }
- /*
- MENU_INIT:VIEWTABLE_AJAX
- ZASOB_ID:1188
- _task:TYPESPECIAL
- fldID:3866
- Form Dataview sourceview URL encoded
- q:te
- */
- echo json_encode($jsonData);
- exit;
- }
- public function ajaxData($args) {// executed from url: "{$this->syncUrl"&_hash={$this->_htmlID}&_task=loadDataAjax"
- $acl = $this->_acl;
- $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
- $page = V::get('page', 0, $args, 'int');
- $page = ($page > 0) ? $page - 1 : $page;
- $currSortCol = V::get('currSortCol', '', $args);
- $currSortFlip = V::get('currSortFlip', '', $args);
- $params = array();
- $params['limit'] = $pageSize;
- $params['limitstart'] = $page * $params['limit'];
- $params['order_by'] = ($currSortCol)? $currSortCol : '';
- $params['order_dir'] = $currSortFlip;
- foreach ($args as $k => $v) {
- if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
- $params[$k] = $v;
- }
- else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
- $params[$k] = $v;
- }
- }
- if ($this->_backRefFilter) {
- $params['__backRef'] = $this->_backRefFilter;
- DBG::log($params, 'array', '$params __backRef');
- }
- if ($this->_childRefFilter) {
- $params['__childRef'] = $this->_childRefFilter;
- DBG::log($params, 'array', '$params __childRef');
- }
- $filters = new stdClass();
- $filters->currSortCol = $currSortCol;
- $filters->currSortFlip = $currSortFlip;
- foreach ($args as $k => $v) {
- if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
- $filters->{$k} = $v;
- }
- else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
- $filters->{$k} = $v;
- }
- }
- $this->setFilters($filters);
- $vCols = $acl->getVirtualFieldListByIdZasob();
- DBG::log($vCols, 'array', "\$vCols");
- $visibleCols = $acl->getVisibleFieldListByIdZasob();
- DBG::log($visibleCols, 'array', "\$visibleCols");
- $jsonData = new stdClass();
- $jsonData->page = $page + 1;
- $jsonData->pageSize = $pageSize;
- $jsonData->filters = $filters;
- $jsonData->cols = new stdClass();
- $jsonData->primaryKey = $acl->getPrimaryKeyField();
- $ind = 0;
- foreach ($visibleCols as $fieldID => $col) {
- $ind++;
- $columnConfig = (object)array('index'=>$ind);
- if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
- $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
- }
- else if (in_array($col, array('Status'))) {
- // Ahmes problems Status colors
- $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
- }
- else if ($acl->isGeomField($col)) {
- $columnConfig->type = 'geom';
- }
- if ('' !== ($label = $acl->getFieldLabel($col))) {
- $columnConfig->friendly = $label;
- }
- $colType = $acl->getFieldType($col);
- if ($colType) {// @see MarkTableAjaxFilterColType
- if ($colType['type'] == 'date') {
- // $columnConfig->type = 'date';// TODO: require datetimepicker
- }
- if (!empty($colType['simpleType'])) $columnConfig->type = $colType['simpleType'];
- } else {// typespecial - no type
- $columnConfig->type = 'special';
- }
- $columnConfig->xsdType = $acl->getXsdFieldType($col);
- if ($columnConfig->xsdType) {
- list($prefix, $typeName, $refTypeName) = explode(":", $columnConfig->xsdType);
- DBG::log([$prefix, $typeName, $refTypeName], 'array', "col '{$col}' xsdType");
- switch ($prefix) {
- case 'ref':
- case 'alias_ref':
- if (!$refTypeName) throw new HttpException("Schema Error for field({$col}) xsdType({$columnConfig->xsdType})", 500);
- $columnConfig->type = 'ref';
- $columnConfig->xsdRefUri = Api_WfsNs::getNsUri($typeName);
- $columnConfig->xsdRefType = $refTypeName;
- $columnConfig->xsdRefNsPrefix = $typeName;
- break;
- case 'xsd':
- switch ($typeName) {
- case 'string': $columnConfig->type = 'string'; break;
- case 'NMTOKEN': $columnConfig->type = 'string'; break; // xsd:NMTOKEN - non empty string without space - pattern: \c+
- case 'NCName': $columnConfig->type = 'string'; break; // xsd:NCName - non empty without ':' and not started with '-' - pattern: [\i-[:]][\c-[:]]*
- case 'integer': $columnConfig->type = 'number'; break;
- case 'int': $columnConfig->type = 'number'; break;
- case 'long': $columnConfig->type = 'number'; break;
- }
- break;
- case 'p5':
- switch ($typeName) {
- case 'enum': $columnConfig->type = 'string'; break;
- case 'alias': {
- if ($format = $acl->getXsdFieldParam($col, 'format')) $columnConfig->format = $format;
- if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
- } break;
- case 'string': {
- $columnConfig->type = 'p5:string';
- $columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
- if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
- } break;
- }
- break;
- case 'p5Type':
- switch ($typeName) {
- case 'enum': $columnConfig->type = 'string'; break;
- case 'alias': {
- $format = $acl->getXsdFieldParam($col, 'format');
- if ($format) $columnConfig->format = $format;
- } break;
- case 'integer': $columnConfig->type = 'number'; break;
- case 'string': {
- $columnConfig->type = 'p5:string';
- $columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
- if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
- } break;
- }
- break;
- }
- }
- $typeSpecial = Typespecial::getInstance($fieldID, $col);
- if ($typeSpecial) {
- DBG::log($typeSpecial, 'array', "\$typeSpecial id({$fieldID}) col({$col})");
- $columnConfig->_tsRetId = $typeSpecial->getReturnId();
- if ($columnConfig->_tsRetId == 0) {
- $tsParamOut = V::get('param_out', null, $typeSpecial);
- if ($tsParamOut) {
- $tsFormat = V::get('format', null, $tsParamOut);
- $tsValues = V::get('values', null, $tsParamOut);
- $tsAliases = V::get('alias', null, $tsParamOut);
- if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
- $tsAliasMap = array();
- /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
- $bugTsColsNotVisible = array();
- foreach ($tsValues as $kVarName => $vIdZasob) {
- if (array_key_exists($vIdZasob, $tsAliases)) {
- $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
- } else {
- $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
- }
- if (!array_key_exists($vIdZasob, $visibleCols)) {
- $bugTsColsNotVisible[] = $vIdZasob;
- }
- }
- if (empty($bugTsColsNotVisible)) {
- $tsSimpleLink = new stdClass();
- $tsSimpleLink->format = $tsFormat;
- $tsSimpleLink->aliasMap = $tsAliasMap;
- $columnConfig->_tsSimpleLink = $tsSimpleLink;
- $columnConfig->type = 'simpleLink';
- } else {
- $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
- }
- }
- }
- }
- }
- if ($columnConfig->xsdType) {// fix fields type p5:typeSpecialSimpleLink (previously defined by Typespecial)
- switch ($columnConfig->xsdType) {
- case 'p5:typeSpecialSimpleLink': {
- $columnConfig->type = 'simpleLink';
- $columnConfig->_tsRetId = 0;
- $columnConfig->_tsSimpleLink = new stdClass();
- $columnConfig->_tsSimpleLink->format = $acl->getXsdFieldParam($col, 'format');
- $columnConfig->_tsSimpleLink->aliasMap = $acl->getXsdFieldParam($col, 'aliasMap');
- } break;
- }
- }
- // @see ajaxHiddenColsSave
- if (UserProfile::isHiddenColumn($acl->getID(), $fieldID)) {
- $columnConfig->hidden = true;
- }
- $columnConfig->description = $acl->getFieldOpis($col);
- $jsonData->cols->{$col} = $columnConfig;
- }
- DBG::log($jsonData->cols, 'array', "\$jsonData->cols");
- $jsonData->rows = array();
- if ($acl instanceof AntAclBase) {
- $params['f_is_instance'] = $acl->getNamespace();
- }
- $queryFeatures = $acl->buildQuery($params);
- $jsonData->total = $queryFeatures->getTotal();
- $listItems = $queryFeatures->getItems();
- $primaryKeyField = $acl->getPrimaryKeyField();
- $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
- // TODO: add virtual data by Typespecial
- if (!empty($vCols) && !empty($items)) {
- foreach ($vCols as $vColID => $vCol) {
- $colType = $acl->getFieldTypeById($vColID);
- if ($colType) continue;// pomin Typespecial dla realnych komorek w bazie danych
- $typeSpecial = Typespecial::getInstance($vColID, $vCol);
- if ($typeSpecial) {
- $columnConfig = V::get($vCol, null, $jsonData->cols);
- if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
- // pomin simple link values - mved to js render
- } else {
- DBG::log($typeSpecial, 'array', "Typespecial({$vColID})");
- $ids = array_keys($items);
- $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
- DBG::log($specialValues, 'array', "Typespecial({$vColID}) \$specialValues");
- if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
- $tsValue = implode('<br>', $vValues);
- DBG::log($items[$kItemID], 'array', "Typespecial({$vColID}) Item[{$kItemID}].{$vCol}");
- if (!empty($items[$kItemID][$vCol]) && !empty($tsValue)) {
- $items[$kItemID][$vCol] .= ": {$tsValue}";
- } else {
- $items[$kItemID][$vCol] = $tsValue;
- }
- }
- }
- }
- }
- }
- {
- if(V::get('DBG', '', $_GET)){$jsonData->__DBG__ = [];}
- $p5Alias = [];
- foreach ((array)$jsonData->cols as $fieldName => $conf) {
- if ('p5:alias' == V::get('xsdType', '', $conf)) {
- if(V::get('DBG', '', $_GET)){$jsonData->__DBG__[$fieldName] = $conf;}
- $aliasType = $acl->getXsdFieldParam($fieldName, 'type');// 'type' => 'sql_table_alias',
- if ('sql_table_alias' == $aliasType) {
- $p5Alias[$fieldName] = (array)$conf;
- $p5Alias[$fieldName]['type'] = 'sql_table_alias';
- $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');// 'local_join_key' => 'ID',
- $p5Alias[$fieldName]['remote_table_name'] = $acl->getXsdFieldParam($fieldName, 'remote_table_name');// 'remote_table_name' => 'CRM_LISTA_ZASOBOW_ORDERS_summary_view',
- $p5Alias[$fieldName]['remote_join_key'] = $acl->getXsdFieldParam($fieldName, 'remote_join_key');// 'remote_join_key' => 'ID',
- $p5Alias[$fieldName]['remote_column_value'] = $acl->getXsdFieldParam($fieldName, 'remote_column_value');// 'remote_column_value' => 'SUM_POS',
- } else if ('sql_query_alias' == $aliasType) {
- $p5Alias[$fieldName] = (array)$conf;
- $p5Alias[$fieldName]['type'] = 'sql_query_alias';
- $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');
- $p5Alias[$fieldName]['join_query_format'] = $acl->getXsdFieldParam($fieldName, 'join_query_format');
- }
- }
- }
- if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$p5Alias'] = $p5Alias;}
- if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'] = [];}
- if ($p5Alias) {
- $sqlLocalTableName = $acl->getRootTableName();
- $primaryKeyField = $acl->getPrimaryKeyField();
- foreach ($p5Alias as $fieldName => $conf) {
- $aliasValuesRaw = [];
- if ('sql_table_alias' == $conf['type']) {
- $localKeys = [];
- $localKeyName = V::get('local_join_key', '', $conf);
- if ($localKeyName) {
- if (!array_key_exists($localKeyName, $localKeys)) {
- $localKeys[$localKeyName] = [];
- foreach ($items as $item) {
- $keyLocal = V::get($localKeyName, 0, $item);
- if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
- }
- }
- if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$localKeys'] = $localKeys;}
- if (!empty($localKeys[$localKeyName])) {
- $sqlRemoteTable = V::get('remote_table_name', '', $conf);
- $sqlRemoteValueFieldName = V::get('remote_column_value', '', $conf);
- $sqlRemoteKeyName = V::get('remote_join_key', '', $conf);
- $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
- try {
- $aliasValuesRaw = DB::getPDO()->fetchAllByKey("
- select r.{$sqlRemoteKeyName} as {$sqlLocalKeyName}, r.{$sqlRemoteValueFieldName} as remote_value
- from {$sqlRemoteTable} r
- where r.{$sqlRemoteKeyName} in(" . implode(",", $localKeys[$localKeyName]) . ")
- ", $sqlLocalKeyName);
- } catch (Exception $e) {
- // TODO: error msg for GUI
- DBG::log($e);
- }
- if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'][$fieldName] = $aliasValuesRaw;}
- }
- }
- } else if ('sql_query_alias' == $conf['type']) {
- $localKeys = [];
- $localKeyName = V::get('local_join_key', '', $conf);
- $sqlFormat = V::get('join_query_format', '', $conf);
- if ($localKeyName && $sqlFormat) {
- if (!array_key_exists($localKeyName, $localKeys)) {
- $localKeys[$localKeyName] = [];
- foreach ($items as $item) {
- $keyLocal = V::get($localKeyName, 0, $item);
- if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
- }
- }
- }
- if (!empty($localKeys[$localKeyName])) {
- $sql = str_replace('{sql_in_local_join_key}', implode(",", $localKeys[$localKeyName]), $sqlFormat);
- $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
- try {
- $aliasValuesRaw = DB::getPDO()->fetchAllByKey($sql, $sqlLocalKeyName);
- } catch (Exception $e) {
- // TODO: error msg for GUI
- DBG::log($e);
- }
- }
- }
- DBG::log($aliasValuesRaw, 'array', '$aliasValuesRaw');
- if (!empty($aliasValuesRaw)) {
- DBG::log($aliasValuesRaw, 'array', "DBG_P5: \$aliasValuesRaw");
- array_walk($items, function (&$item) use ($fieldName, $sqlLocalKeyName, $aliasValuesRaw) {
- $sqlValue = V::get($sqlLocalKeyName, null, $item);
- DBG::log($sqlValue, 'array', "DBG_P5: \$sqlValue");
- DBG::log($aliasValuesRaw[$sqlValue]['remote_value'], 'array', "DBG_P5: \$aliasValuesRaw[{$sqlValue}]['remote_value']");
- DBG::log($item, 'array', "DBG_P5: \$item");
- if ($sqlValue !== null && array_key_exists($sqlValue, $aliasValuesRaw)) {
- DBG::log($aliasValuesRaw[$sqlValue]['remote_value'], 'array', "DBG_P5: TODO_update_value");
- $item[$fieldName] = $aliasValuesRaw[$sqlValue]['remote_value'];
- DBG::log($item[$fieldName], 'array', "DBG_P5: TODO_updated_value");
- }
- });
- }
- }
- }
- }
- foreach ($items as $item) {
- // TODO: hide items without 'R'
- foreach ($visibleCols as $fieldName) {
- // TODO: ID default 'R'
- if (!$acl->canReadObjectField($fieldName, $item)) $item[$fieldName] = '*****';
- // null => empty string
- if (!isset($item[$fieldName]) || (!$item[$fieldName] && $item[$fieldName] !== '0')) {
- // DBG::log($item[$fieldName], 'array', "isEmptyString[{$fieldName}]");
- $item[$fieldName] = '';
- }
- }
- $jsonData->rows[] = $item;
- }
- $jsonData->type = 'success';
- $jsonData->msg = 'pobrano nowe dane';
- // { // TODO: BUG - race condition in requests
- // session_write_close();
- // if (!empty($params['f_L_APPOITMENT_USER']) && strlen($params['f_L_APPOITMENT_USER']) === 3) sleep(2); // TODO: DBG
- // if (!empty($params['f_L_APPOITMENT_USER']) && strlen($params['f_L_APPOITMENT_USER']) === 3) $jsonData->__DBG__sleep = 2; // TODO: DBG
- // }
- return $jsonData;
- }
- private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
- $value = '';
- $type = $this->_acl->getFieldTypeById($fieldID);
- if ($type) {
- if ($type['type'] == 'date') {
- $value = $type['default'];
- }
- // fix bug when field is unique and is null allowed: change empty string to null
- if ($type['null']) {
- $value = 'NULL';
- }
- // fix bug when field is enum and is set to '0': for php '0' is empty
- if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
- if (false !== strpos($type['type'], "''")) {
- // enum('', '1','2')
- $value = '';
- } else if (false !== strpos($type['type'], "'0'")) {
- // enum('0', '1','2')
- $value = '0';
- } else {
- $value = $type['default'];
- }
- }
- }
- return $value;
- }
- /**
- * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
- * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
- */
- private function ajaxHiddenColsSave($args) {
- $response = new stdClass();
- if (empty($args)) {
- $response->type = 'info';
- return $response;
- }
- UserProfile::load();
- // clean up old, wrong values
- if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
- unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
- }
- $colVis = UserProfile::getHiddenCols($this->_zasobID);
- $fields = $this->_acl->getFieldListByIdZasob();
- foreach ($fields as $idField => $fieldName) {
- if (isset($args[$fieldName])) {
- if ($args[$fieldName] == 'SHOW') {
- $colVis[$idField] = 1;
- } else if ($args[$fieldName] == 'HIDE') {
- $colVis[$idField] = 0;
- }
- }
- }
- UserProfile::setHiddenCols($this->_zasobID, $colVis);
- UserProfile::save();
- $response->type = 'success';
- return $response;
- }
- private function ajaxPageSizeSave($args) {
- $response = new stdClass();
- if (empty($args)) {
- $response->type = 'info';
- return $response;
- }
- $pageSize = V::get('pageSize', 0, $args, 'int');
- UserProfile::load();
- // clean up old, wrong values
- if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
- unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
- }
- $tableAjaxSettings = UserProfile::getTableAjaxSettings();
- $tableAjaxSettings['pageSize'] = $pageSize;
- UserProfile::setTableAjaxSettings($tableAjaxSettings);
- UserProfile::save();
- $response->type = 'success';
- return $response;
- }
- private function ajaxTheGeomSave($args) {
- $primaryKeyField = $this->_acl->getPrimaryKeyField();
- $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
- $polygon = V::get('polygon', 0, $args);
- $geomFieldName = 'the_geom';
- if ($primaryKey <= 0) {
- throw new HttpException("Wrong param ID", 404);
- }
- // 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)))
- $record = $this->_acl->buildQuery([])->getItem($primaryKey);
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- throw new HttpException("Brak dostępu do rekordu", 403);
- }
- if (!$this->_acl->canWriteObjectField($geomFieldName, $record)) {
- throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
- }
- $itemPatch = array();
- $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
- $itemPatch[$primaryKeyField] = $primaryKey;
- $response = new stdClass();
- try {
- $affected = $this->_acl->updateItem($itemPatch);
- if ($affected > 0) {
- $response->type = 'success';
- $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
- } else if ($affected == 0) {
- $response->type = 'info';
- $response->msg = "Nie wprowadzono żadnych zmian";
- }
- $response->record = $this->_acl->buildQuery([])->getItem($primaryKey);
- }
- catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- }
- return $response;
- }
- public function sendAjaxResponseJson($method, $args) {
- try {
- $response = $this->{$method}($args);
- }
- catch (HttpException $e) {
- $response = new stdClass();
- $response->type = 'error';
- $response->msg = $e->getMessage();
- $response->errorCode = $e->getCode();
- Http::sendHeaderByCode($e->getCode());
- }
- catch (Exception $e) {
- $response = new stdClass();
- $response->type = 'error';
- $response->msg = $e->getMessage();
- $response->errorCode = $e->getCode();
- }
- header('Content-type: application/json');
- if (!$response) $response = new stdClass();
- echo json_encode($response);
- exit;
- }
- }
|