| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914 |
- <?php
- Lib::loadClass('ViewAjax');
- class TableAjax extends ViewAjax {
- private $_cnf = '';// Column
- private $_htmlID = '';
- private $_dataSource = null;
- private $_rowFunctions = array();
- private $_pageSizes = array();
- private $_filterInit = null;
- private $_forceFilterInit = null;
- private $_showProcesInit = true;
- public function __construct($tblAcl) {
- $this->_tbl = $tblAcl->getName();
- $this->_acl = $tblAcl;
- $this->_zasobID = $tblAcl->getID();
- $this->_dataSource = $tblAcl->getDataSource();
- $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();
- }
- $this->_geomFields = $this->_dataSource->getGeomFields();
- }
- public function showProcesInit($bool = true) {
- $this->_showProcesInit = $bool;
- }
- 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 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 addRowFunction($funName, $funParams = array()) {
- $defaultRowFunction = array();
- //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="ico-pencil" title="Edytuj rekord"></a>';
- //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="ico-book" title="Historia"></a>';
- //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="ico-folder-open" title="Pliki"></a>';
- //$defaultRowFunction['cp'] = '<a href="#" class="ico-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
- $defaultRowFunction['edit'] = array('href'=>'#EDIT/{0}', 'ico'=>'ico-pencil', 'title'=>'Edytuj rekord');
- $defaultRowFunction['hist'] = array('href'=>'#HIST/{0}', 'ico'=>'ico-book', 'title'=>'Historia');
- $defaultRowFunction['files'] = array('href'=>'#FILES/{0}', 'ico'=>'ico-folder-open', 'title'=>'Pliki');
- $defaultRowFunction['cp'] = array('href'=>'#', 'ico'=>'ico-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
- if (array_key_exists($funName, $defaultRowFunction)) {
- $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
- }
- else {
- $this->_rowFunctions[$funName] = $funParams;
- }
- $this->_saveState('_rowFunctions');
- }
- private function _parseRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
- $rowFunctions = array();
- foreach ($this->_rowFunctions as $kFunName => $vParams) {
- if (in_array($kFunName, $pomin)) continue;
- //$rowFunctionsOut .= str_replace('{0}', $recordID, $vUrl);
- $attrs = array();
- // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'ico-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
- $label = '';
- $ico = '';
- foreach ($vParams as $kParamName => $v) {
- if ($kParamName == 'ico') {
- if ($showLabel) {
- $ico = '<span class="' . $v . '"></span>';
- } else {
- $attrs[] = 'class="' . $v . '"';
- }
- continue;
- }
- $attr = $v;
- if ($recordID > 0) {
- $attr = str_replace('{0}', $recordID, $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($recordID = null, $pomin = array(), $showLabel = false) {
- $rowFunctionsOut = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
- $rowFunctionsOut = implode('', $rowFunctionsOut);
- return $rowFunctionsOut;
- }
- private function _showRowFunctionsJson($recordID = null, $pomin = array(), $showLabel = false) {
- $rowFunctions = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
- $rowFunctions = (object)$rowFunctions;
- return $rowFunctions;
- }
- private function getProcesInitSelected() {
- $userAcl = User::getAcl();
- return $userAcl->getPermsProcesId();
- }
- private function _fetchConnectedProcesInitList() {
- $pInitList = array();// [proces_init_id] => label (DESC)
- if (!$this->_showProcesInit) {
- return $pInitList;
- }
- $userAcl = User::getAcl();
- $pInitListRaw = $userAcl->getProcesInitList($this->_zasobID);
- if (empty($pInitListRaw)) {
- return $pInitList;
- }
- $db = DB::getDB();
- $sql = "select p.`ID`, p.`DESC`
- from `CRM_PROCES` as p
- where p.`ID` in(" . implode(",", array_values($pInitListRaw)) . ")
- and p.`TYPE`='PROCES_INIT'
- ";
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $pInitList[$r->ID] = $r->DESC;
- }
- return $pInitList;
- }
- public function allowTreeView() {
- if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
- if ($this->_tbl == 'CRM_PROCES') return true;
- return false;
- }
- public function hasGeomFields() {
- $hasGeomFields = false;
- $fieldsList = $this->_acl->getFields();
- foreach ($fieldsList as $kID => $vCol) {
- if ($this->_dataSource->isGeomField($vCol['name'])) {
- if ($this->_acl->hasFieldPerm($kID, 'R')) {
- $hasGeomFields = true;
- break;
- }
- }
- }
- return $hasGeomFields;
- }
- public function render() {
- $pInitList = $this->_fetchConnectedProcesInitList();
- $pInitListSelected = $this->getProcesInitSelected();
- $hasGeomFlds = $this->hasGeomFields();
- $tblAjaxMap = null;
- if ($hasGeomFlds) {
- Lib::loadClass('TableAjaxMap');
- $tblAjaxMap = new TableAjaxMap($this->_acl, 512, 300);
- }
- ob_start();
- ?>
- <?php if ($tblAjaxMap) $tblAjaxMap->printCSS(); ?>
- <?php if ($tblAjaxMap) $tblAjaxMap->printJS(); ?>
- <link rel="stylesheet" type="text/css" href="stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css">
- <style type="text/css">
- .AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
- .AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
- .AjaxTable *,
- .AjaxTableCont .foot * {font-size:12px !important;}
- .AjaxTable.table {white-space:nowrap; width:auto;}
- .AjaxTable p {margin:0;}
- .AjaxTable td, .AjaxTable th {line-height:18px;}
- .AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
- .AjaxTable span.filter {background-color:#999;}
- .AjaxTable .indeterminate {opacity: 0.4;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";filter:alpha(opacity=40);}
- .AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
- .AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
- .AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
- .AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
- .AjaxTable input[type=text].filter {margin:0;padding:0;box-shadow:none;width:100%;background:#eee;float:left;color:#000;}
- .AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
- .AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
- .AjaxTable .date-wrap {width:100%;min-width:115px;}
- .AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
- .AjaxTableCont .dropdown-menu {max-height:250px;padding:0 20px 0 0;overflow:auto;}
- .AjaxTable .actions a {padding:0;margin:0;}
- .AjaxTableCont .text-right {text-align:right}
- .AjaxTableCont .breadcrumb em {color:#bbb;}
- .AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
- .AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
- .AjaxTable-loading .loading-info,
- .AjaxTableCont .inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
- .AjaxTableCont .loading-info {display:none;}
- .AjaxTableCont .inlineEditBox .loading-info {display:block;}
- .AjaxTable .stickyCol2 input[type=text].filter {width:50px;}
- .AjaxTableCont .table {margin-bottom:0px;}
- .AjaxTableCont .foot {margin:10px;}
- .AjaxTableCont .stickyCol1 a:hover { }
- .AjaxTableTaskCnt {padding:0 10px 10px 10px;}
- .AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
- .AjaxTable .tbl-short-txt span{display:block; height:18px;}
- .AjaxTable .tooltip-inner{white-space:normal;}
- .AjaxTable thead .sort .ta-ordering {cursor:pointer;}
- .AjaxTable thead .sort .ta-ordering span {margin:0 14px 0 0; padding:0 14px 0 0; background-repeat:no-repeat; background-position:right top;}
- .AjaxTable thead .sort .ta-ordering-down span {background-image:url(stuff/twitter-bootstrap/img/ordering-down.png);}
- .AjaxTable thead .sort .ta-ordering-up span {background-image:url(stuff/twitter-bootstrap/img/ordering-up.png);}
- .AjaxTable thead .sort .ta-ordering {position:relative;}
- .AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
- .AjaxTable thead .sort th .hover-show{display:none;}
- .AjaxTable thead .sort th:hover .hover-show{display:inline;}
- .AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none;}
- .AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}
- .AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
- .AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
- .AjaxTableCont .pagination { margin:0; }
- .AjaxTableCont .pagination a { line-height:16px; }
- .AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
- .AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
- .AjaxTableCont .AjaxTableEdit .show-last-value .btn-appendBack,
- .AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .btn-appendBack {display:none;}
- .AjaxTableHist em {color:silver;}
- .TableAjax-SpecialFilter {margin:0;padding:4px 4px 4px 127px;}
- .TableAjax-SpecialFilter .btn-group {margin:0 4px;padding:0;}
- /* overwrite bootstrap table border */
- .AjaxTable, .AjaxTableEdit,
- .AjaxTable td, .AjaxTableEdit td,
- .AjaxTable th, .AjaxTableEdit th { border-color:#999; }
- /* */
- .AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
- .AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
- .AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
- .AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
- .AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
- .AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
- .AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }
- /* map */
- .AjaxTable .cell-mapfld { cursor:pointer; }
- .AjaxTable .cell-mapfld:hover { opacity:1; }
- .AjaxTable .cell-mapfld-remove { display:none; }
- .AjaxTable .cell-mapfld-hasValue .cell-mapfld-select { background-color:#f00; }
- .AjaxTable .cell-mapfld-hasValue .cell-mapfld-remove { display:inline-block; }
- .AjaxTableCont .mapEditor { position:absolute; bottom:0; right:6px; width:512px; height:318px; overflow:hidden; background:#eee; border:1px solid #999; }
- .AjaxTableCont .mapEditor-panel { height:16px; padding:0 6px; background:#999; border-bottom:1px solid #eee; }
- .AjaxTableCont .mapEditor-panel a { display:block; float:right; padding:0 6px; font-weight:bold; font-size:12px; line-height:16px; color:#fff; }
- .AjaxTableCont .mapEditor-panel a:hover { color:#006CD7; text-decoration:none; }
- .AjaxTableCont .mapEditor-panel a.mapEditor-panel-close:hover { color:#f00; }
- .AjaxTableCont .mapEditor-map { background:#fff; height:300px; }
- .AjaxTableCont .valign-btns-bottom a { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
- </style>
- <div class="AjaxTableCont">
- <ul class="breadcrumb">
- <li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>
- <?php if (!empty($pInitList)) : ?>
- <div class="btn-group pull-right">
- <a class="btn btn-mini btn-info dropdown-toggle" data-toggle="dropdown" href="#" title="Uruchom filtr procesu powiązanego z tabelą <?php echo $this->getLabel(); ?>">
- Filtr procesu
- <span class="caret"></span>
- </a>
- <ul class="dropdown-menu pull-left">
- <?php foreach ($pInitList as $kId => $vLabel) : ?>
- <?php if ($pInitListSelected && $pInitListSelected == $kId) : ?>
- <li class="disabled">
- <?php else : ?>
- <li>
- <?php endif; ?>
- <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>"><?php echo "{{$kId}} " . V::strShortUtf8($vLabel, 50); ?></a>
- </li>
- <?php endforeach; ?>
- </ul>
- </div>
- <?php endif; ?>
- <?php if ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') : ?>
- <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=TREEJS&ZASOB_ID={$this->_zasobID}"; ?>"><i class="icon-eye-open"></i> Drzewo</a>
- <?php elseif ($this->allowTreeView()) : ?>
- <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=VIEWTREE_AJAX&ZASOB_ID={$this->_zasobID}"; ?>"><i class="icon-eye-open"></i> Drzewo</a>
- <?php endif; ?>
- </ul>
- <div id="<?php echo $this->_htmlID; ?>"></div>
- </div>
- <script>
- (function($) {
- var TableAjaxGeomField = function() {
- var priv = {}; //private api
- var publ = {}; //public api
- priv.options = {};
- var defaults = {
- recordID: '',
- fieldValue: '',
- hasValueClassName: 'TableAjaxGeomField-hasValue',
- linkClassNamePrefix: 'TableAjaxGeomField',
- linkSelectClassName: 'select',
- linkSelectAddClassNames: '', // 'ico-map-marker'
- linkRemoveClassName: 'remove',
- linkRemoveAddClassNames: '', // 'ico-remove'
- removeUrl: '',
- onSelect: null,
- onRemove: null,
- debug: false
- };
- priv.init = function() {
- priv.render();
- };
- priv.render = function() {
- var state = priv.options;
- var cellMapSelect = jQuery('<i title="Pokaż/utwórz obiekt na mapie"></i>');
- cellMapSelect.addClass(state.linkClassNamePrefix + '-' + state.linkSelectClassName);
- if (state.linkSelectAddClassNames) {
- cellMapSelect.addClass(state.linkSelectAddClassNames);
- }
- cellMapSelect.on('click', {recordID: priv.options.recordID, fieldValue: priv.options.fieldValue}, function(e) {
- if (typeof state.onSelect == "function") {
- state.onSelect.call(this, e.data.recordID, e.data.fieldValue);
- }
- });
- var cellMapRemove = jQuery('<i title="Usuń obiekt z mapy"></i>');
- cellMapRemove.addClass(state.linkClassNamePrefix + '-' + state.linkRemoveClassName);
- if (state.linkRemoveAddClassNames) {
- cellMapRemove.addClass(state.linkRemoveAddClassNames);
- }
- cellMapRemove.on('click', {recordID: state.recordID, fieldValue: state.fieldValue}, function(e) {
- if (typeof state.onRemove == "function") {
- state.onRemove.call(this, publ, e.data.recordID, e.data.fieldValue);
- }
- });
- var node = $(state.id);
- node.empty();
- node.addClass(state.linkClassNamePrefix);
- node.removeClass(state.hasValueClassName);
- if (state.fieldValue) {
- node.addClass(state.hasValueClassName);
- }
- node.append(cellMapSelect);
- node.append(cellMapRemove);
- };
- publ.setValue = function(value) {
- console.log('TEST setValue: ', value, 'this', this);
- priv.options.fieldValue = value;
- priv.render();
- };
- publ.init = function(options) {
- if (priv.options.debug) console.log('TableAjaxGeomField initialization...', options);
- //merge supplied options with defaults
- $.extend(priv.options, defaults, options);
- priv.init();
- return publ;
- };
- return publ;
- };
- $.fn.TableAjaxGeomFieldSetValue = function(value) {
- return this.each(function() {
- var tblAjaxMapGeomFld = $(this).data('TableAjaxGeomField');
- if (tblAjaxMapGeomFld) {
- tblAjaxMapGeomFld.setValue(value);
- }
- });
- return this;
- };
- $.fn.TableAjaxGeomField = function(options) {
- options = options || {};
- return this.each(function() {
- options.id = this;
- if (!$(this).data('TableAjaxGeomField')) {
- $(this).data('TableAjaxGeomField', new TableAjaxGeomField().init(options));
- }
- });
- return this;
- };
- }(jQuery));
- (function($, undefined) {
- var TableAjax = function () {
- var priv = {}; //private api
- var publ = {}; //public api
- priv.options = {};
- var defaults = {
- url: '', //webservice url
- urlData: '', //webservice params
- urlPost: false, //use POST instead of GET
- debug: false, //prints debug info to console
- filter: false, //show filter row
- filterInit: false,// init filters data
- forceFilterInit: false,
- columnPicker: false, //show columnpicker
- checkboxes: false, //show body checkboxes
- actions: '', //holds action links
- pageSize: 10, //current pagesize
- pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
- hidePagerOnEmpty: false, //removes pager if no rows
- types: { //type specific options
- string: {},
- number: {},
- bool: {},
- date: {}
- },
- rowFunctions: false,
- tblFunctions: false,
- specialFilterFunctions: false,
- filtersClean: false,
- router: false,
- longDesc: false,
- mapEditor: false // mapEditor visible or not
- };
- var _cont; // container holding table
- var _table; // the table
- var _head; // table header
- var _headSort; // table header sorting row
- var _headFilter; // table header columns filter row
- var _headSpecialFilter; // table header special filter row
- var _body; // table body
- var _foot; // table footer
- var _inlineEditBox; // inline edit box with form
- var _popoverCell; // inline popover cell
- var _popoverCellCurrent; // inline popover cell
- var _popoverCellAjaxXhr;
- var _mapEditor; // map editor node
- var _mapEditorWrap; // map editor wrapper node
- var _mapEditorDialog; // map editor jquery ui dialog node
- var _data; //columns and rows
- var _currPage = 1; // current page
- var _pageSize; // current pagesize
- var _totalPages; // total pages
- var _currSortCol; // current sorting column
- var _currSortFlip = false; // current sorting direction
- var _currDpOp; // clicked datepicker operator
- var _filterCols = {}; // array with current filters
- var _filterFields = {}; // array with filter DOM elements
- var _specialFilters = {}; // array with current special filters
- var _filterTimeout; // timer for delayed filtering
- var _uniqueCol; // reference to column with the unique property
- var _uniqueCols = {}; // array with checked rows
- var _checkToggleChecked = false; // check-all toggle state
- var _tableWidth;
- /*
- initialize the plugin.
- */
- priv.init = function () {
- _cont = priv.options.id;
- priv.options.types.string = ((priv.options.types || {}).string || {});
- priv.options.types.number = ((priv.options.types || {}).number || {});
- priv.options.types.bool = ((priv.options.types || {}).bool || {});
- priv.options.types.date = ((priv.options.types || {}).date || {});
- if (priv.options.specialFilterFunctions && priv.options.filterInit) {
- $.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
- var fltrName = 'sf_' + groupName;
- if (fltrName in priv.options.filterInit) {
- _specialFilters[groupName] = priv.options.filterInit[fltrName];
- }
- });
- }
- //try call webservice for data
- priv.update(priv.options.router);
- if (typeof priv.options.router == "function") {
- $(window).bind('hashchange', function() {
- //console.log('hashchange: location.hash: ' + location.hash);
- priv.options.router.apply(this);
- });
- }
- };
- /*
- creates the table with all its parts and handlers.
- note that only the parts we need is created.
- (yeah, the function is huge)
- */
- priv.createTable = function () {
- //create table itself
- if (!_table) {
- _head = _body = _foot = undefined;
- _table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_cont);
- }
- //create the header which will later hold both sorting and filtering
- if (!_head) {
- _table.find('thead').remove();
- _headSort = _headFilter = _headSpecialFilter = undefined;
- _head = $('<thead></thead>').prependTo(_table);
- }
- // TODO: test colgroup
- //_table.find('colgroup').remove();
- //$('<colgroup><col span="1" style="background-color:red"><col span="10" style="width:200px;overlow-x:auto"></colgroup>').prependTo(_table);
- //sort the columns in index order
- var colsSorted = Object.keys(_data.cols).sort(function (a, b) {
- return _data.cols[a].index - _data.cols[b].index;
- });
- //create the header sorting row
- if (!_headSort) {
- _head.find('.sort i').tooltip('hide');
- _head.find('.sort').remove();
- _headSort = $('<tr class="sort"></tr>').prependTo(_head);
- //create the functions column
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- var headCell = $('<th class="text-right head-info stickyCol1"></th>').appendTo(_headSort);
- $.map(priv.options.tblFunctions, function(funObj, funName){
- var funHtml = $('<a></a>');
- funHtml.attr('href', funObj.href || '#');
- if (funObj.title) funHtml.attr('title', funObj.title);
- if (funObj.icon) funHtml.attr('class', 'ico-' + funObj.icon);
- if (funObj.method) funHtml.on('click', priv[funObj.method]);
- funHtml.appendTo(headCell);
- });
- }
- //create the checkall toggle
- if (_uniqueCol && priv.options.checkboxes) {
- var checked = _checkToggleChecked ? 'checked' : '';
- var headCell = $('<th></th>').appendTo(_headSort);
- var elem = $('<input {0} class="checkToggle" type="checkbox" />'.f(checked)).appendTo(headCell);
- elem.on('change', priv.checkToggleChanged);
- }
- //create the sortable headers
- for (var i = 0; i < colsSorted.length; i++) {
- var column = colsSorted[i];
- var props = _data.cols[column];
- if (!props.hidden) {
- var headCell = $('<th class="ta-ordering"></th>').appendTo(_headSort);
- if (i == 1) headCell.addClass('stickyCol2');
- if (false) {// TODO: old way
- var link = $('<a class="pull-left" href="#">{0}</a>'.f(props.friendly || column));
- link.on('click', {column: column}, priv.columnClicked).appendTo(headCell);
- if (props.tooltip) {
- $('<i class="icon-info-sign"></i>').tooltip({
- title: props.tooltip.trim(),
- html: true,
- container: 'body',
- placement: "top",
- delay: {
- show: 500,
- hide: 100
- }
- }).appendTo(link);
- }
- //Add sort arrow
- if (column == _currSortCol) {
- if (_currSortFlip) $('<i class="icon-chevron-down pull-right"></i>').appendTo(headCell);
- else $('<i class="icon-chevron-up pull-right"></i>').appendTo(headCell);
- }
- //Add hide btn
- if (column != 'ID') {
- var hideColBtn = $('<i class="icon-remove pull-right hover-show"></i>');
- hideColBtn.on('click', {column: column}, priv.columnHideClicked);
- hideColBtn.appendTo(headCell);
- }
- }
- if (props.type != 'special' && props.type != 'geom') {
- headCell.on('click', {column: column}, priv.columnClicked);
- }
- var colTitle = column;
- if (props._tsRetId) {
- colTitle = 'Kliknij na pole i przejdź do powiązanych rekordów (' + colTitle + ')';
- }
- if (props.friendly) {
- var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(props.friendly, colTitle));
- } else {
- var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(column, colTitle));
- }
- headCnt.appendTo(headCell);
- //Add sort arrow
- if (column == _currSortCol) {
- if (_currSortFlip) headCell.addClass('ta-ordering-down');
- else headCell.addClass('ta-ordering-up');
- }
- if (column != 'ID') {
- var hideColBtn = $('<i class="icon-remove remove-cell"></i>');
- hideColBtn.on('click', {column: column}, priv.columnHideClicked);
- hideColBtn.appendTo(headCell);
- }
- }
- }
- }
- //create the header filtering row
- if (!_headFilter && priv.options.filter) {
- _head.find(".filter").remove();
- _headFilter = $('<tr class="filter"></tr>').appendTo(_head);
- var headCell;
- var elem;
- var placeHolder = '';
- var tooltip = '';
- //create the functions column
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- var headCell = $('<th class="text-right stickyCol1"></th>').appendTo(_headFilter);
- if (priv.options.filtersClean) {
- var elem = $('<a href="#" title="Kasuj filtry" class="ico-remove"> </a>').appendTo(headCell);
- elem.on('click', priv.filtersClean);
- }
- }
- //create the filter checkbox
- if (_uniqueCol && priv.options.checkboxes) {
- tooltip = priv.options.types.bool.filterTooltip || 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked';
- headCell = $('<th></th>').appendTo(_headFilter);
- elem = $('<input class="filter indeterminate" checked type="checkbox" />').appendTo(headCell);
- $.map(_filterCols, function (colProps, col) {
- if (col == "unique") {
- if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
- else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
- else if (colProps.filter == '') elem.addClass('indeterminate');
- }
- });
- if (tooltip) {
- elem.tooltip({
- title: tooltip.trim(),
- html: true,
- container: 'body',
- trigger: 'hover',
- placement: 'top',
- delay: {
- show: 500,
- hide: 100
- }
- });
- }
- elem.on('click', {column: "unique"}, priv.filterChanged);
- }
- //create the column filters
- for (var i = 0; i < colsSorted.length; i++) {
- var column = colsSorted[i];
- var props = _data.cols[column];
- tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
- placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
- if (!props.hidden) {
- headCell = $('<th></th>').appendTo(_headFilter);
- if (i == 1) headCell.addClass('stickyCol2');
- // @mark MarkTableAjaxFilterColType
- switch (props.type || 'string') {
- case "number":
- if (placeHolder == undefined) placeHolder = priv.options.types.number.placeHolder;
- placeHolder = (placeHolder === true || placeHolder == undefined) ? '10..20 =50' : placeHolder === false ? '' : placeHolder;
- if (tooltip == undefined) tooltip = priv.options.types.number.filterTooltip;
- tooltip = (tooltip === true || tooltip == undefined) ? 'Values 10 to 20:<br/>10..20<br/>Values exactly 50:<br/>=50' : tooltip === false ? '' : tooltip;
- elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
- elem.on('keyup', {column: column}, priv.filterChanged);
- break;
- case "date":
- if (placeHolder == undefined) placeHolder = priv.options.types.date.placeHolder;
- placeHolder = (placeHolder === true || placeHolder == undefined) ? '-7..0' : placeHolder === false ? '' : placeHolder;
- if (tooltip == undefined) tooltip = priv.options.types.date.filterTooltip;
- tooltip = (tooltip === true || tooltip == undefined) ? 'Today:<br/>0..1<br/>A week today excluded:<br/>-7..0' : tooltip === false ? '' : tooltip;
- elem = $('<div><input placeholder="{0}" class="filter" type="text" /></div>'.f(placeHolder));
- if (priv.options.types.date.datePicker === true || priv.options.types.date.datePicker == undefined)
- {
- if ($().datepicker)
- {
- elem.addClass('date-wrap');
- var today = 0;//new priv.ext.XDate(false).setHours(0, 0, 0, 0).toString('yyyy-MM-dd');
- var dp = $('<div style="float:right" class="date" data-date="{0}" data-date-format="{1}" />'.f(today, 'yyyy-mm-dd')).appendTo(elem);
- $('<input style="display:none" type="text" />').appendTo(dp);
- $('<span class="add-on"><i class="icon-chevron-right"></i></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
- $('<span class="add-on"><i class="icon-chevron-left"></i></span>').on('click', {op: "r"}, priv.dpOpChanged).appendTo(dp);
- dp.datepicker({weekStart:1});
- dp.on('changeDate', {column: column, input: $('input.filter', elem)}, priv.dpClicked);
- }
- else
- if (priv.options.debug) console.log('datepicker plugin not found');
- }
- elem.on('keyup', 'input.filter', {column: column}, priv.filterChanged);
- break;
- case "bool":
- if (tooltip == undefined) tooltip = priv.options.types.bool.filterTooltip;
- tooltip = (tooltip === true || tooltip == undefined) ? 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked' : tooltip === false ? '' : tooltip;
- elem = $('<input class="filter indeterminate" checked type="checkbox" />');
- elem.on('click', {column: column}, priv.filterChanged);
- break;
- case "string":
- if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
- placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
- if (tooltip == undefined) tooltip = priv.options.types.string.filterTooltip;
- tooltip = (tooltip === true || tooltip == undefined) ? 'Find str: str<br/>Find all but str: !str<br/>Find str inside: %str%' : tooltip === false ? '' : tooltip;
- elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
- elem.on('keyup', {column: column}, priv.filterChanged);
- break;
- case "special":
- elem = $('<div> </div>');
- break;
- case "geom":
- if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
- placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
- elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
- elem.on('keyup', {column: column}, priv.filterChanged);
- break;
- case "none":
- elem = $('<div> </div>');
- break;
- }
- if (false) {// tooltip OFF - (tooltip)
- elem.tooltip({
- title: tooltip.trim(),
- html: true,
- container: 'body',
- trigger: 'focus',
- placement: 'top',
- delay: {
- show: 500,
- hide: 100
- }
- });
- }
- if (elem && props.filter) {
- $.map(_filterCols, function (colProps, col) {
- if (col == column) {
- if (colProps.col.type == 'bool') {
- if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
- else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
- else if (colProps.filter == '') elem.addClass('indeterminate');
- }
- else elem.val(colProps.filter);
- }
- });
- if (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]) {
- elem.prop('disabled', true);
- }
- elem.appendTo(headCell);
- _filterFields[column] = elem;
- }
- }
- }
- }
- //create the header special filters row
- if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
- //create the functions column
- if (priv.options.specialFilterFunctions) {
- jQuery(_cont).prev('.TableAjax-SpecialFilter').remove();
- var _headSpecialFilter = $('<div class="btn-toolbar TableAjax-SpecialFilter"></div>').insertBefore(_cont);
- $.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
- var btnHtml, btnSelected, groupHtml = $('<div class="btn-group"></div>');
- // _specialFilters[e.data.group] = e.data.value;
- if (groupName in _specialFilters) {
- btnSelected = _specialFilters[groupName];
- }
- if (groupObj.icon) {
- $('<button class="btn btn-mini" title="' + groupName + '"><i class="' + groupObj.icon + '"></i></button>').appendTo(groupHtml);
- }
- $.map(groupObj.btns, function(btnObj, btnName) {
- btnHtml = $('<button class="btn btn-mini' + ((btnSelected && btnSelected == btnObj.value)? ' active' : '') + '">' + btnName + '</button>').appendTo(groupHtml);
- btnHtml.on('click', {group: groupName, value: btnObj.value}, priv.specialFilterChanged);
- });
- btnHtml = $('<button class="btn btn-mini' + ((!btnSelected)? ' disabled' : '') + '" title="Kasuj filtr"><i class="icon-remove"></i></button>').appendTo(groupHtml);
- btnHtml.on('click', {group: groupName, value: ''}, priv.specialFilterChanged);
- groupHtml.appendTo(_headSpecialFilter);
- });
- }
- }
- //create the body
- if (!_body) {
- _table.find('tbody').remove();
- _body = $('<tbody></tbody>').insertAfter(_head);
- _body.on('change', '.unique', priv.rowChecked);
- //_body.on('click', 'td', priv.rowClicked);
- //_body.on('dbclick', 'td', priv.rowDBClicked);
- //find out what rows to show next...
- var rowsAdded = 0;
- _data.toRow = _data.fromRow + priv.options.pageSize;
- if (_data.toRow > _data.total)
- _data.toRow = _data.total;
- //slice out the chunk of data we need and create rows
- //$.each(_data.rows.slice(_data.fromRow, _data.toRow), function (index, props) {
- $.each(_data.rows, function (index, props) {
- var row = $('<tr></tr>').appendTo(_body);
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- var cell = $('<td class="text-right stickyCol1"></td>').appendTo(row);
- var cellID = _uniqueCol || 'ID';
- cellID = (cellID in props)? props[cellID] : null;
- $.map(priv.options.rowFunctions, function(funObj, funName){
- $(funObj.f(cellID)).appendTo(cell);
- });
- }
- //create checkbox
- if (_uniqueCol && priv.options.checkboxes) {
- var check = _uniqueCols[props[_uniqueCol]] != undefined ? 'checked' : '';
- var checkable = props['checkable'] === false ? 'disabled' : '';
- var cell = $('<td></td>').appendTo(row);
- $('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cell);
- }
- //create cells
- for (var i = 0; i < colsSorted.length; i++) {
- var key = colsSorted[i];
- var val = props[key];
- if (!_data.cols[key]) return;
- if (_data.cols[key].unique) row.data('unique', val);
- var cellID = _uniqueCol || 'ID';
- cellID = (cellID in props)? props[cellID] : null;
- if (!_data.cols[key].hidden) {
- var cell = $('<td></td>').appendTo(row);
- cell.on('dblclick', {id:cellID, col:key}, priv.rowDblClicked);
- var cellCnt = $('<span></span>').appendTo(cell);
- if (i == 1) cell.addClass('stickyCol2');
- cell.data('column', key);
- if (val === undefined) continue;
- var format = props[key + 'Format'] || _data.cols[key].format || '{0}';
- var showTooltip = true;
- switch (_data.cols[key].type) {
- case "string":
- cellCnt.html(format.f(val));
- break;
- case "number":
- val = Number(val);
- var forceDecimals = !isNaN(_data.cols[key].decimals);
- if (forceDecimals) cellCnt.html(format.f(val.toFixed(_data.cols[key].decimals)));
- else {
- (val || 0) % 1 === 0
- ? cellCnt.html(format.f(val))
- : cellCnt.html(format.f(val.toFixed(priv.options.types.number.decimals || 2)));
- }
- break;
- case "date":
- cellCnt.html(format.f(val));
- break;
- case "bool":
- $('<input type="checkbox" {0} disabled />'.f(val ? "checked" : "")).appendTo(cellCnt);
- break;
- case "special":
- cellCnt.html(format.f(val));
- break;
- case "geom":
- cellCnt.TableAjaxGeomField({
- recordID: cellID,
- fieldValue: val,
- hasValueClassName: 'cell-mapfld-hasValue',
- //removeUrl: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + cellID,
- linkClassNamePrefix: 'cell-mapfld',
- linkSelectClassName: 'select',
- linkSelectAddClassNames: 'ico-map-marker',
- linkRemoveClassName: 'remove',
- linkRemoveAddClassNames: 'ico-remove',
- onSelect: function(recordID, geomShape) {
- console.log('recordID:', recordID, 'geomShape:', geomShape);
- priv.mapEditorShow();
- _mapEditor.TableAjaxMapSelectRecord(recordID, geomShape);
- },
- onRemove: function(geomField, recordID, geomShape) {
- if (confirm('Czy usunąć obiekt z mapy dla rekordu ' + recordID + '?')) {
- if (!recordID) return;
- var selectedRecordId = recordID;
- 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 = 'Usunięto obiekt z mapy dla rekordu ' + selectedRecordId;
- break;
- case 'info':
- if (!notify.msg) notify.msg = 'Rekord nie był powiązany z żadnym obiektem na mapie';
- 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: {},
- dataType: 'json',
- type: "POST",
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + recordID
- })
- .done(function(data, textStatus, jqXHR){
- notifyAjaxCallback(data);
- console.log('TODO: data.record.the_geom:', data.record.the_geom);
- if (data && data.record && data.record.the_geom) {
- console.log('TODO: data.record.the_geom:2:', data.record.the_geom);
- geomField.setValue(data.record.the_geom);
- }
- else if (data && data.record) {
- console.log('TODO: data.record.the_geom:2:', data.record.the_geom);
- geomField.setValue(data.record.the_geom);
- }
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- });
- }
- }
- });
- break;
- }
- if (_data.cols[key]._tsRetId) {
- showTooltip = false;
- if (_data.cols[key]._tsRetId > 0) {
- cellCnt.on('click', {id:cellID, col:key, friendly:_data.cols[key].friendly, value:format.f(val)}, priv.popoverCell);
- }
- }
- if (i > 1 && priv.options.longDesc) {
- cell.addClass('tbl-short-txt');
- if (showTooltip) {
- cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
- }
- }
- }
- }
- rowsAdded++;
- //enough rows created?
- if (rowsAdded >= priv.options.pageSize) {
- _data.toRow = _data.fromRow + rowsAdded;
- return false;
- }
- });
- if (_currPage == 1) {
- _pageSize = rowsAdded;
- _totalPages = Math.round(Math.ceil(_data.total / _pageSize));
- }
- //pad with empty rows if we're at last page.
- if (_currPage == _totalPages) {
- while (rowsAdded < _pageSize) {
- var row = $('<tr></tr>').appendTo(_body);
- if (_uniqueCol && priv.options.checkboxes) {
- var cell = $('<td></td>').appendTo(row);
- $('<input disabled type="checkbox" />').appendTo(cell);
- }
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- $('<td class="text-right stickyCol1"> </td>').appendTo(row);
- }
- var i = 0;
- $.each(_data.cols, function (column, props) {
- i++;
- if (props.hidden) return;
- if (i == 1) {
- $('<td class="stickyCol2"> </td>').appendTo(row);
- } else {
- $('<td> </td>').appendTo(row);
- }
- });
- rowsAdded++;
- }
- }
- }
- //create the footer
- if (!_foot) {
- _table.find('tfoot').remove();
- _foot = $('<tfoot></tfoot>').insertAfter(_body);
- //var footRow = $('<tr></tr>').appendTo(_foot);
- //var footCell = $('<td colspan="999"></td>').appendTo(footRow);
- // TODO: test load footer after table
- $(_cont).next('.foot').remove();
- _foot = $('<div class="foot"></div>').insertAfter(_cont);
- //create summary
- if (_data.total > 0) {
- $('<div class="foot-info"><p>Wiersze od {0} do {1} z {2}</p></div>'.f(_data.fromRow + 1, Math.min(_data.toRow, _data.total), _data.total)).appendTo(_foot);
- } else {
- $('<div><p>Brak wierszy pasujących do kryteriów wyszukiwania</p></div>').appendTo(_foot);
- _totalPages = 0;
- }
- //create the pager.
- var lowerPage = _currPage - 2;
- var upperPage = _currPage + 2;
- if (upperPage > _totalPages) {
- var diff = upperPage - _totalPages;
- upperPage = _totalPages;
- lowerPage -= diff;
- }
- if (lowerPage < 1) lowerPage = 1;
- if (upperPage < 5) upperPage = 5;
- var footToolbar = $('<div class="btn-toolbar"></div>').appendTo(_foot);
- var footDiv = $('<div class="btn-group"></div>').appendTo(footToolbar);
- var footPagerDiv = $('<div class="pagination"></div>').appendTo(footDiv);
- var footPagerUl = $('<ul></ul>').appendTo(footPagerDiv);
- $('<li class="{0}"><a href="#"><<</a></li>'.f(_currPage == 1 ? 'disabled' : ''))
- .on('click', {pageIndex: 1}, priv.pageChanged).appendTo(footPagerUl);
- $('<li class="{0}"><a href="#"><</a></li>'.f(_currPage == 1 ? 'disabled' : ''))
- .on('click', {pageIndex: _currPage - 1}, priv.pageChanged).appendTo(footPagerUl);
- for (var i = lowerPage; i <= upperPage; i++) {
- var link;
- if (i != _currPage) link = $('<li class="{1}"><a href="#">{0}</a></li>'.f(i, i > _totalPages ? 'disabled' : ''));
- if (i == _currPage) link = $('<li class="active"><a href="#">{0}</a></li>'.f(i));
- if (link) {
- link.on('click', {pageIndex: i}, priv.pageChanged);
- link.appendTo(footPagerUl);
- }
- }
- $('<li class="{0}"><a href="#">></a></li>'.f(_currPage == _totalPages ? 'disabled' : ''))
- .on('click', {pageIndex: _currPage + 1}, priv.pageChanged).appendTo(footPagerUl);
- $('<li class="{0}"><a href="#">>></a></li>'.f(_currPage == _totalPages ? 'disabled' : ''))
- .on('click', {pageIndex: _totalPages}, priv.pageChanged).appendTo(footPagerUl);
- //create pagesize dropdown
- if (priv.options.pageSizes.length) {
- var div = $('<div class="btn-group dropup pagesize"></div>').appendTo(footToolbar);
- var btn = $('<button class="btn btn-small dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy </button>').appendTo(div);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu">').appendTo(div);
- $.each(priv.options.pageSizes, function (index, val) {
- var li = $('<li></li>').appendTo(ul);
- $('<a href="#">{0}</a>'.f(val)).appendTo(li);
- });
- div.on('click', 'a', priv.pageSizeChanged);
- }
- //create columnpicker dropdown
- if (priv.options.columnPicker) {
- var div = $('<div class="btn-group dropup columnpicker"></div>').appendTo(footToolbar);
- var btn = $('<button class="btn btn-small dropdown-toggle" data-toggle="dropdown" href="#">Kolumny </button>').appendTo(div);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu">').appendTo(div);
- $.each(_data.cols, function (col, props) {
- if (props.type != "unique" && col != 'ID') {
- var li = $('<li></li>').appendTo(ul);
- $('<input {0} type="checkbox" title="{1}" value="{1}" > {2}</input>'.f((props.hidden) ? '' : 'checked', col, props.friendly || col)).appendTo(li);
- }
- });
- div.on('click', 'input', priv.columnPickerClicked);
- }
- if (priv.options.rowFunctions) {
- $.map(priv.options.tblFunctions, function(funObj, funName){
- var div = $('<div class="btn-group"></div>').appendTo(footToolbar);
- var funHtml = $('<button class="btn btn-small"></button>');
- if (funObj.title) funHtml.attr('title', funObj.title);
- if (funObj.method) funHtml.on('click', priv[funObj.method]);
- else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
- var funIconHtml = $('<i></i>');
- if (funObj.icon) funIconHtml.attr('class', 'icon-' + funObj.icon);
- funIconHtml.prependTo(funHtml);
- funHtml.addClass('btn');
- funHtml.appendTo(div);
- });
- }
- //create actions dropdown
- if (priv.options.actions) {
- var div = $('<div class="btn-group dropup actions"></div>').appendTo(footToolbar);
- var btn = $('<button class="btn dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-list"></i> </button>').appendTo(div);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu">').appendTo(div);
- if (priv.options.actions.filter) {
- var li = $('<li></li>').appendTo(ul);
- $('<input {0} type="checkbox" > Filter</input>'.f(priv.options.filter ? 'checked' : '')).appendTo(li);
- li.on('click', 'input', function (e) {
- priv.options.filter = !priv.options.filter;
- _head = undefined;
- priv.createTable();
- });
- }
- if (priv.options.actions.columnPicker) {
- var li = $('<li></li>').appendTo(ul);
- $('<input {0} type="checkbox" > ColumnPicker</input>'.f(priv.options.columnPicker ? 'checked' : '')).appendTo(li);
- li.on('click', 'input', function (e) {
- priv.options.columnPicker = !priv.options.columnPicker;
- _foot = undefined;
- priv.createTable();
- });
- }
- if (priv.options.actions.custom) {
- $.each(priv.options.actions.custom, function (index, val) {
- var li = $('<li></li>').appendTo(ul);
- $(val).appendTo(li);
- });
- }
- }
- }
- var stickyCol1Width = 55;
- var stickyCol2Width = 50;
- if (undefined === _tableWidth) {
- _tableWidth = true;
- var contW = jQuery(_cont).width();
- //console.log('_cont.width: ' + jQuery(_cont).width());
- var th1 = _table.find('.stickyCol1:first');
- var th2 = th1.next();
- var th1W = th1.innerWidth();
- var th2W = 50 + 2 * 5;//th2.innerWidth();
- var colsW = stickyCol1Width + 2 * 5 + 1 + stickyCol2Width + 2 * 5 + 1;
- //console.log('thF.width: ' + th1W + '; ' + th2W + '; colsW: ' + colsW);
- //jQuery(_cont).width(contW - colsW);
- jQuery(_cont).css({width:'' + (contW - colsW) + 'px', marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
- //console.log('_cont.width new: ' + jQuery(_cont).width());
- }
- _table.find('.stickyCol1').css({position:'absolute',
- left:'0',
- top:'auto',
- width:'' + stickyCol1Width + 'px',
- });
- _table.find('.stickyCol2').css({position:'absolute',
- left:'' + (stickyCol1Width + 2 * 5 + 1) + 'px',
- top:'auto',
- width:'' + stickyCol2Width + 'px',
- borderRight: '1px solid silver'
- });
- if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
- $('.btn-toolbar', _foot).remove();
- }
- if (priv.options.debug) console.log('table created L.<?php echo __LINE__; ?>');
- if (typeof priv.options.tableCreated == 'function') {
- priv.options.tableCreated.call(_table.get(0), {table: _table.get(0)});
- }
- if (!_inlineEditBox) {
- $(_foot).next('.inlineEditBox').remove();
- _inlineEditBox = $('<div class="inlineEditBox modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>').insertAfter(_foot);
- var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(_inlineEditBox);
- var iebHead = $('<div class="modal-header">').appendTo(frmInlineEdit);
- $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="icon-remove"></i></button>').appendTo(iebHead);
- $('<h3 id="myModalLabel">Edytuj</h3>').appendTo(iebHead);
- var iebBody = $('<div class="modal-body"></div>').appendTo(frmInlineEdit);
- $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
- $('<input type="hidden" name="col" value="">').appendTo(iebBody);
- $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
- var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
- $('<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
- var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
- frmInlineEdit.on('submit', function() {
- var data = _inlineEditBox.find('form').serialize();
- _inlineEditBox.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE_SAVE',
- type: 'POST',
- dataType: 'text',
- data: data,
- async: true,
- success: function (data) {
- //console.log('_inlineEditBox submit ajax data:', data);
- _inlineEditBox.find('.inlineEditBox-cnt').html(data);
- _inlineEditBox.find('.btn-save').hide();
- publ.loadPage(_currPage);
- },
- error: function (jhr, textStatus, errorThrown) {
- console.log('_inlineEditBox submit ajax error');
- }
- });
- return false;
- });
- }
- if (!_popoverCell) {
- $(_foot).next('.popoverCell').remove();
- _popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
- }
- if (!_mapEditorWrap) {
- $(_foot).next('.mapEditor').remove();
- _mapEditorWrap = $('<div class="mapEditor" style="display:none"></div>').insertAfter(_foot);
- _mapEditor = $('<div class="mapEditor-map"></div>').appendTo(_mapEditorWrap);
- }
- };
- /*
- calls the webservice(if defined).
- used only inside priv.init
- */
- priv.update = function (callback, skipCols, resetChecked) {
- if (!priv.options.url) {
- if (priv.options.debug) console.log('no url found L.<?php echo __LINE__; ?>');
- return;
- }
- if (priv.options.debug) console.log('requesting data from url:{0} data:{1} L.<?php echo __LINE__; ?>'.f(priv.options.url, JSON.stringify(priv.options.urlData) || ''));
- var initUrlAdd = '',
- reqData = {},
- filtersInitSet = false;
- if (priv.options.filterInit) {
- $.map(priv.options.filterInit, function (fltrProps, fltr) {
- switch (fltr) {
- case 'currSortCol':
- _currSortCol = fltrProps;
- initUrlAdd += '&currSortCol=' + fltrProps;
- break;
- case 'currSortFlip':
- _currSortFlip = (fltrProps == 'desc')? true : false;
- initUrlAdd += '&currSortFlip=' + fltrProps;
- break;
- default:
- if (fltr.substr(0, 3) == 'sf_') {
- reqData[fltr] = fltrProps;
- filtersInitSet = true;
- }
- else if (fltr.substr(0, 2) == 'f_') {
- reqData[fltr] = fltrProps;
- filtersInitSet = true;
- }
- }
- });
- }
- if (priv.options.forceFilterInit) {
- $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
- reqData['f_' + fltr] = fltrProps;
- filtersInitSet = true;
- });
- }
- $.ajax({
- url: priv.options.url + initUrlAdd,
- type: priv.options.urlPost ? 'POST' : 'GET',
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: reqData,
- async: true,
- success: function (data) {
- if (priv.options.debug) console.log('request finished L.<?php echo __LINE__; ?>');
- //assign the new data
- if (data.d && data.d.cols)
- priv.setData(data.d, skipCols, resetChecked);
- else
- priv.setData(data, skipCols, resetChecked);
- // set initial filters
- if (filtersInitSet && _data && _data.cols) {
- $.map(reqData, function(fltrValue, fltr){
- var colName = null;
- if (fltr.substr(0, 3) == 'sf_') {
- colName = fltr.substr(3);
- }
- else if (fltr.substr(0, 2) == 'f_') {
- colName = fltr.substr(2);
- }
- if (colName && _data.cols[colName]) {
- //add the filter to the filter array
- _filterCols[colName] = {
- filter: fltrValue,
- col: _data.cols[colName]
- };
- }
- });
- }
- //assign the new data
- if (data.d && data.d.cols)
- priv.setData(data.d, skipCols, resetChecked);
- else
- priv.setData(data, skipCols, resetChecked);
- if (typeof callback == "function")
- callback.call(this);
- },
- error: function (err) {
- //console.log('request error: {0}'.f(JSON.stringify(err)));
- if (typeof callback == "function")
- callback.call(this);
- }
- });
- };
- /*
- assigns the new data.
- */
- priv.setData = function (pData, skipCols, resetChecked) {
- var data = $.extend(true, {}, pData);
- data.fromRow = _data && _data.fromRow || 0;
- data.toRow = _data && _data.toRow || 0;
- //use previous column definitions?
- skipCols = skipCols || false;
- if (skipCols) data.cols = _data.cols;
- //else _filterCols = {};
- _data = data;
- _data.rowsOrg = _data.rows;
- //we might have more/less data now. Recalculate stuff.
- if (_currPage > 1) {
- _data.toRow = Math.min(_data.total, _data.toRow);
- _data.fromRow = _data.toRow - _pageSize;
- _data.fromRow = Math.max(_data.fromRow, 0);
- _currPage = Math.ceil(_data.fromRow / _pageSize) + 1;
- _totalPages = Math.ceil(_data.total / _pageSize);
- } else {
- _data.fromRow = 0;
- if (priv.options.pageSize != -1)
- _data.toRow = _data.fromRow + priv.options.pageSize;
- _data.toRow = Math.max(_data.toRow, _data.total);
- }
- //wash the new data a bit
- _uniqueCol = "";
- $.each(_data.cols, function (col, props) {
- //set sorting
- if (!_currSortCol && props.sortOrder) {
- _currSortCol = col;
- _currSortFlip = props.sortOrder != "asc";
- }
- //default to string type if missing
- if (!props.type) _data.cols[col].type = "string";
- //if several unique columns is defined, use the first.
- if (props.unique) {
- if (!_uniqueCol) _uniqueCol = col;
- else props.unique = false;
- }
- //if index property is missing, create one
- if (!props.index) _data.cols[col].index = new Number(0);//priv.ext.XDate();
- props.column = col;
- //set any initial filter
- if (!skipCols) {
- if (props.filter == undefined) props.filter = true;
- if (props.filter && typeof props.type != "bool" && typeof props.filter != "boolean") {
- _filterCols[col] = _filterCols[col] || {
- filter: String(props.filter),
- col: props
- };
- }
- }
- });
- //keep any previously checked rows around?
- if (resetChecked === true || resetChecked === undefined)
- _uniqueCols = {};
- else {
- for (var key in _uniqueCols)
- _uniqueCols[key] = priv.getRow(key);
- }
- if (_uniqueCol) {
- //create a unique column definition
- _data.cols["unique"] = {
- column: "unique",
- type: "unique",
- index: -1,
- hidden: true
- };
- //add rows that needs to be pre-checked
- $.each(_data.rows, function (index, row) {
- if (row["checked"] === true)
- _uniqueCols[row[_uniqueCol]] = row;
- });
- }
- if (!skipCols) {
- _head = undefined;
- }
- _body = undefined;
- _foot = undefined;
- priv.createTable();
- };
- /**
- * Filters the data.
- */
- priv.filter = function () {
- if (!priv.options.filter) return;
- if (Object.keys(_filterCols).length == 0) return;
- publ.loadPage(0);
- };
- /*
- sorts the data on the current sorting column
- */
- priv.sort = function () {
- if (!_data.cols[_currSortCol]) _currSortCol = "";
- if (!_currSortCol) return;
- publ.loadPage(0);
- };
- /*
- helper that returns the underlying data by the unique value
- */
- priv.getRow = function (unique) {
- var row;
- $.each(_data.rowsOrg, function (i, r) {
- if (r[_uniqueCol] == unique) {
- row = r;
- return false;
- }
- });
- return row;
- };
- /*
- when: typing a filter
- what: triggers filtering on the value
- */
- priv.filterChanged = function (e) {
- //clear old timer if we're typing fast enough
- if (_filterTimeout) {
- clearTimeout(_filterTimeout);
- if (priv.options.debug) console.log('filtering cancelled');
- }
- var filter = this.value
- , fltr = $(this)
- , col = _data.cols[e.data.column]
- , timeout = 300;
- if (this.value) {
- if (!fltr.hasClass('filter-active')) {
- fltr.addClass('filter-active');
- }
- } else {
- if (fltr.hasClass('filter-active')) {
- fltr.removeClass('filter-active');
- }
- }
- //boolean filters needs some special care
- if (col.type == "bool" || col.type == "unique") {
- timeout = 0;
- var elem = $(this);
- var cssClass = 'indeterminate';
- if (elem.hasClass(cssClass)) {
- e.preventDefault();
- elem.removeClass(cssClass);
- filter = true;
- } else {
- if (!elem.is(':checked')) {
- filter = false;
- } else {
- elem.addClass(cssClass);
- filter = '';
- }
- }
- }
- //add the filter to the filter array
- _filterCols[col.column] = {
- filter: filter,
- col: col
- };
- //wait a few deciseconds before filtering
- _filterTimeout = setTimeout(function () {
- _filterTimeout = undefined;
- priv.filter();
- }, timeout);
- };
- priv.filtersClean = function (e) {
- if (_filterTimeout) {
- clearTimeout(_filterTimeout);
- if (priv.options.debug) console.log('filtering cancelled - filtersClean');
- }
- var filtersActive = false;
- $.map(_filterCols, function (colProps, col) {
- if (colProps.filter.length > 0) {
- filtersActive = true;
- colProps.filter = '';
- }
- });
- if (filtersActive) {
- // TODO: dont remove value from forceFilterInit fields - no field names in search fields?
- var elems = _head.find('tr.filter').find('input');
- _head.find('tr.filter').find('input').val('').prop('disabled', false);
- priv.filter();
- }
- return false;
- },
- /**
- * Filters the data by specialFilter.
- * when: click on special filter
- * what: triggers filtering on the value
- */
- priv.specialFilterChanged = function (e) {
- console.log('specialFilterChanged...');
- console.log(e.data);
- _specialFilters[e.data.group] = e.data.value;
- publ.loadPage(0);
- };
- priv.longTextChanged = function(e) {
- priv.options.longDesc = !priv.options.longDesc;
- _body.find('td').each(function(ind, el){
- var $el = jQuery(el);
- if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
- //console.log(el.attr('class') + ': ' + el.text());
- if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
- if (priv.options.longDesc) {
- $el.addClass('tbl-short-txt');
- var $elSpan = jQuery(el.firstChild);
- $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
- } else {
- $el.removeClass('tbl-short-txt');
- }
- }
- }
- });
- return false;
- },
- priv.mapEditorHide = function() {
- priv.options.mapEditor = false;
- //_mapEditorDialog.dialog("close");
- _mapEditorDialog.dialog("destroy");
- }
- priv.mapEditorShow = function() {
- priv.options.mapEditor = true;
- _mapEditorWrap.show();
- _mapEditor.TableAjaxMap({
- //debug: true,
- wpsUrl: 'http://biuro.biall-net.pl/wps',
- wfsUrl: 'http://biuro.biall-net.pl/wps',
- layerName: '<?php echo $this->getLabelHtml(); ?>',
- onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
- console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
- if (!selectedRecordId) {
- alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
- return;
- }
- 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 = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
- 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);
- }
- $.ajax({
- data: {polygon: selectedFeatureExtent},
- dataType: 'json',
- type: "POST",
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_SAVE&ID=' + selectedRecordId
- })
- .done(function(data, textStatus, jqXHR){
- notifyAjaxCallback(data);
- //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
- publ.loadPage(0);// TODO: reload table data
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- });
- },
- onSelectBox: function(bounds) {
- if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
- var column = 'the_geom';
- if (undefined !== _filterFields['the_geom']) {
- var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
- _filterFields[column].val(filter);
- _filterCols[column] = {
- filter: filter,
- col: _data.cols[column]
- };
- priv.filter();
- }
- }
- }
- });
- _mapEditorDialog = _mapEditorWrap.dialog({
- width: 540,
- minWidth: 400,
- minHeight: 300,
- resizeStop: function(){
- _mapEditor.TableAjaxMapUpdateSize(); //to prevent drag-zoom error
- },
- dragStop: function(){
- _mapEditor.TableAjaxMapUpdateSize(); //to prevent drag-zoom error
- }
- });
- _mapEditorWrap.bind('dialogclose', function(e) {
- priv.options.mapEditor = false;
- });
- }
- priv.mapEditorChanged = function(e) {
- console.log('mapEditorChanged option(',priv.options.mapEditor,') e:', e);
- priv.options.mapEditor = !priv.options.mapEditor;
- if (priv.options.mapEditor) {
- priv.mapEditorShow();
- }
- else {
- priv.mapEditorHide();
- }
- return false;
- },
- /*
- when: changing page in pager
- what: triggers table to be created with new page
- */
- priv.pageChanged = function (e) {
- e.preventDefault();
- if (e.data.pageIndex < 1 || e.data.pageIndex > _totalPages) return;
- //set the new page
- _currPage = e.data.pageIndex;
- if (priv.options.debug) console.log('paging to index:{0} L.<?php echo __LINE__; ?>'.f(_currPage));
- //find out what rows to create
- _data.fromRow = ((_currPage - 1) * _pageSize);
- _data.toRow = _data.fromRow + _pageSize;
- if (_data.toRow > _data.rows.length) _data.toRow = _data.rows.length;
- //trigger callback
- if (typeof priv.options.pageChanged == 'function') {
- priv.options.pageChanged.call(e.target, {
- event: e,
- page: _currPage
- });
- }
- _body = undefined;
- _foot = undefined;
- priv.createTable();
- };
- /*
- when: changing pagesize in pagesize dropdown
- what: triggers table to be created with new pagesize
- */
- priv.pageSizeChanged = function (e) {
- e.preventDefault();
- var val = $(this).text().toLowerCase();
- if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));
- //set the new pagesize
- if (val == "all") priv.options.pageSize = _data.rows.length;
- else priv.options.pageSize = parseInt(val);
- //revert to first page, as its gets messy otherwise.
- _currPage = 1;
- _data.fromRow = 0;
- _data.toRow = _data.fromRow + priv.options.pageSize;
- if (_data.toRow > _data.rows.length) _data.toRow = _data.rows.length;
- //trigger callback
- if (typeof priv.options.pageSizeChanged == 'function') {
- priv.options.pageSizeChanged.call(e.target, {
- event: e,
- pageSize: priv.options.pageSize
- });
- }
- _body = undefined;
- _foot = undefined;
- priv.createTable();
- };
- /*
- when: clicking a column
- what: triggers table to be sorted by the column
- */
- priv.columnClicked = function (e) {
- e.preventDefault();
- if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));
- //set the new sorting column
- if (_currSortCol == e.data.column) _currSortFlip = !_currSortFlip;
- _currSortCol = e.data.column;
- //trigger callback
- if (typeof priv.options.columnClicked == 'function') {
- priv.options.columnClicked.call(e.target, {
- event: e,
- column: _data.cols[_currSortCol],
- descending: _currSortFlip
- });
- }
- _headSort = undefined;
- _body = undefined;
- priv.sort();
- };
- priv.saveHiddenCols = function() {
- var reqData = {};
- $.each(_data.cols, function (col, props) {
- if (props.type != "unique" && col != 'unique' && col != 'ID') {
- reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
- }
- });
- $.ajax({
- data: reqData,
- type: "POST",
- dataType: 'json',
- // async: true,
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE'
- })
- .done(function(data, textStatus, jqXHR){
- if (data && data.type && data.type == 'info') {
- jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
- } else {
- jQuery.notify('Zapisano ustawienia', 'success');
- }
- })
- .fail(function(){
- jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
- });
- };
- /*
- when: clicking a column in columnpicker
- what: triggers table to show/hide the column
- */
- priv.columnPickerClicked = function (e) {
- e.stopPropagation();
- var column = $(this).val();
- //toggle column visibility
- _data.cols[column].hidden = !_data.cols[column].hidden;
- priv.saveHiddenCols();
- //_data.cols[column].index = new priv.ext.XDate();
- _head = undefined;
- _body = undefined;
- priv.createTable();
- };
- priv.columnHideClicked = function (e) {
- e.stopPropagation();
- var column;
- if (e.data && e.data.column) {
- column = e.data.column;
- } else {
- return;
- }
- //toggle column visibility
- _data.cols[column].hidden = !_data.cols[column].hidden;
- priv.saveHiddenCols();
- //_data.cols[column].index = new priv.ext.XDate();
- _head = undefined;
- _body = undefined;
- _foot = undefined;
- priv.createTable();
- };
- /*
- when: clicking a row checkbox
- what: toggles checked state on row, and add/removes it from checked array
- */
- priv.rowChecked = function (e) {
- var elem = $(this);
- //get the row's unique value
- var unique = elem.closest('tr').data('unique');
- if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));
- //store the row in checked array
- if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
- else delete _uniqueCols[unique];
- };
- /*
- when: clicking anywhere on a row
- what: row data and other info is returned to caller
- */
- priv.rowClicked = function (e) {
- if (!_uniqueCol) {
- if (priv.options.debug) console.log('no unique column specified');
- return;
- }
- //gather callback data
- var elem = $(this);
- var column = _data.cols[elem.data('column')];
- var unique = elem.closest('tr').data('unique');
- var row = priv.getRow(unique);
- var isChecked = elem.closest('tr').find('.unique').is(':checked');
- //trigger callback
- if (typeof priv.options.rowClicked == 'function') {
- priv.options.rowClicked.call(e.target, {
- event: e,
- row: row,
- column: column,
- checked: isChecked
- });
- }
- };
- /**
- * Inline edit.
- */
- priv.rowDblClicked = function (e) {
- // hide popover for typespecial fld on click
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('hide');
- }
- // e.clientX: 1002; e.clientY: 245
- if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
- _inlineEditBox.modal();
- //_inlineEditBox.css({'position':'absolute', 'top':'100px', 'left':'100px'});
- _inlineEditBox.show();
- _inlineEditBox.find('input[name=ID]').val(e.data.id);
- _inlineEditBox.find('input[name=col]').val(e.data.col);
- _inlineEditBox.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
- $.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE&ID=' + e.data.id + '&col=' + e.data.col,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function (data) {
- _inlineEditBox.find('.inlineEditBox-cnt').html(data);
- _inlineEditBox.find('.btn-save').show();
- _inlineEditBox.find('.se_type-date').datepicker({
- format: "yyyy-mm-dd"
- , language: 'pl'
- , todayBtn: "linked"
- });
- _inlineEditBox.find('.se_type-datetime').parent().datetimepicker({
- language: 'pl'
- , format: 'yyyy-MM-dd hh:mm'
- , weekStart: 1
- });
- _inlineEditBox.find('textarea').autosize();
- var fld = _inlineEditBox.find('input[id^="f"]');
- if (fld && !fld.hasClass('se_type-date')) {
- fld.focus();
- fld.keydown(function(event) {
- console.log('input keydown: ', event.which);
- if (event.which == 13) {
- event.preventDefault();
- _inlineEditBox.find('form').submit();
- }
- });
- }
- },
- error: function (err) {
- console.log('err');
- }
- });
- } else {
- console.log('NO data');
- return false;
- }
- };
- priv.ajaxLoadTypeSpeciallCell = function(id, col) {
- //console.log('ajaxLoadTypeSpeciallCell load id=' + id + ' col=' + col);
- if (_popoverCellAjaxXhr) {
- _popoverCellAjaxXhr.abort();
- }
- var _popoverCellAjaxXhr = $.ajax({
- type: 'GET',
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=TYPESPECIALL_CELL&ID=' + id + '&col=' + col,
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: '',
- success: function(req){
- //console.log('ajaxLoadTypeSpeciallCell Data: ', req);
- if (req.data && req.data.tbl_id > 0) {
- var addHtml = '';
- for(var i in req.data.items){
- var url = 'index.php?MENU_INIT=VIEWTABLE_AJAX';
- url += '&ZASOB_ID=' + req.data.tbl_id;
- url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
- url += '&_hash=' + Math.random().toString(36).substring(2);
- addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
- addHtml += '<br>';
- }
- _popoverCell.append(addHtml);
- jQuery('#popoverCellContent').append(addHtml);
- }
- }
- });
- };
- priv.popoverCell = function (e) {
- e.preventDefault();
- e.stopPropagation();
- if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
- var lastId = _popoverCell.data('rowid'),
- lastCol = _popoverCell.data('col');
- if (lastId == e.data.id && lastCol == e.data.col) {
- //_popoverCellCurrent.popover('toggle');
- }
- else {
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('destroy');
- }
- _popoverCell.data('rowid', e.data.id);
- _popoverCell.data('col', e.data.col);
- _popoverCell.html(e.data.value + '<div id="popoverCellContent"></div>');
- if (_data.cols[e.data.col]) {
- if (_data.cols[e.data.col]._tsRetId > 0) {
- priv.ajaxLoadTypeSpeciallCell(e.data.id, e.data.col);
- }
- }
- _popoverCellCurrent = jQuery(e.currentTarget);
- // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">×</button>'
- var opts = {
- placement: 'left'
- , trigger: 'click'
- // , title: e.data.col + '<a href="#" class="icon-remove pull-right" onclick="return hidePopover();"></a>'
- , title: '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (e.data.friendly || e.data.col) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">×</button>' + '</div>'
- , html: true
- , content: _popoverCell.html()
- }
- _popoverCellCurrent.popover(opts);
- _popoverCellCurrent.popover('show');
- }
- } else {
- console.log('NO data');
- return false;
- }
- return;
- };
- priv.routeChanged = function(e) {
- hash = e.data.hash || '';
- if (hash.length == 0) {
- return;
- }
- if (hash.substring(0, 1) != '#') {
- hash = '#' + hash;
- }
- location.hash = hash;
- },
- publ.init = function (options) {
- if (priv.options.debug) console.log('TableAjax initialization...');
- //merge supplied options with defaults
- $.extend(priv.options, defaults, options);
- priv.init();
- return publ;
- };
- publ.loadPage = function(page, pageSize) {
- var skipCols = true, // skipCols = true - prevent columns delete
- resetChecked = false;
- var reqData = {
- page: page,
- pageSize: (pageSize || priv.options.pageSize),
- currSortCol: (_currSortCol || ''),
- currSortFlip: _currSortFlip ? "desc" : "asc"
- };
- if (Object.keys(_filterCols).length > 0) {
- $.each(_filterCols, function (col, colProps) {
- if (colProps.filter && colProps.filter.length > 0) {
- reqData['f_' + col] = colProps.filter;
- }
- });
- skipCols = true;
- }
- // specialFilters
- $.each(_specialFilters, function(groupName, btnValue) {
- if (btnValue.length > 0) {
- reqData['sf_' + groupName] = btnValue;
- }
- });
- if (priv.options.forceFilterInit) {
- $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
- reqData['f_' + fltr] = fltrProps;
- filtersInitSet = true;
- });
- }
- _table.parent().parent().addClass('AjaxTable-loading');
- $.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
- type: 'GET',
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: reqData,
- async: true,
- success: function (data) {
- if (data.d && data.d.cols)
- priv.setData(data.d, skipCols, resetChecked);
- else
- priv.setData(data, skipCols, resetChecked);
- if (typeof callback == "function")
- callback.call(this);
- _table.parent().parent().removeClass('AjaxTable-loading');
- },
- error: function (err) {
- //console.log('request error: {0}'.f(JSON.stringify(err)));
- }
- });
- };
- publ.getCurrentPage = function() {
- return _currPage;
- };
- publ.popoverCellRemove = function () {
- _popoverCellCurrent.popover('destroy');
- _popoverCell.data('rowid', -1);
- _popoverCell.data('col', -1);
- _popoverCell.html('');
- };
- return publ;
- }
- $.fn.TableAjax = function (options) {
- options = options || {};
- return this.each(function () {
- options.id = this;
- $(this).data('TableAjax', new TableAjax().init(options));
- });
- };
- $.fn.TableAjaxLoadPage = function (page, pageSize) {
- //console.log('TableAjaxLoadPage: ' + page + ' size: ' + pageSize);
- return this.each(function () {
- var tblAjax = jQuery(this).data('TableAjax');
- var curPage = page || tblAjax.getCurrentPage();
- if (tblAjax) tblAjax.loadPage(curPage, pageSize);
- });
- };
- String.prototype.format = String.prototype.f = function () {
- var s = this;
- i = arguments.length;
- while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
- return s;
- };
- })(jQuery);
- </script>
- <?php
- $filterInit = $this->_filterInit;
- $forceFilterInit = $this->_forceFilterInit;
- $pageSizes = $this->_pageSizes;
- $rowFunctions = $this->_showRowFunctionsJson();
- ?>
- <script>
- jQuery(document).ready(function(){
- jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
- columnPicker: true,
- filter: true,
- filterInit: <?php echo json_encode($filterInit); ?>,
- forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
- debug: false, // TODO: DBG
- height: 400, // TODO: ?
- sorting: true, // TODO: ?
- paging: true, // TODO: ?
- pageSizes: <?php echo json_encode($pageSizes); ?>,
- pageChanged: function(args) {
- var con = jQuery('#<?php echo $this->_htmlID; ?>');
- con.TableAjaxLoadPage(args.page);
- },
- pageSizeChanged: function(args) {
- var con = jQuery('#<?php echo $this->_htmlID; ?>');
- con.TableAjaxLoadPage(0, args.pageSize);
- },
- tblFunctions: {
- shortdesc: {
- icon: 'align-left',
- title: 'Long desc',
- method: 'longTextChanged'
- },
- <?php if ($hasGeomFlds) : ?>
- mapeditor: {
- icon: 'map-marker',
- title: 'Mapa',
- method: 'mapEditorChanged'
- },
- <?php endif; ?>
- create: {
- href: '#CREATE',
- icon: 'plus',
- title: 'Dodaj nowy rekord'
- }
- },
- rowFunctions: <?php echo json_encode($rowFunctions); ?>,
- specialFilterFunctions: <?php
- $fltrs = $this->_dataSource->getSpecialFilters();
- if (!empty($fltrs)) {
- echo json_encode($fltrs);
- } else {
- echo 'false';
- }
- echo ',';
- ?>
- router: function () {
- var routes = {
- EDIT: function (args) {
- var recordID = args;
- if (typeof args == 'object') {
- recordID = args.shift();
- recordID = parseInt(recordID);
- }
- if (typeof recordID !== 'number' || recordID <= 0) {
- // TODO: msg
- return false;
- }
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.hide();
- // remove previous task content
- var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
- taskCnt.parent().remove();
- taskCnt.remove();
- var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
- jQuery('<ul class="breadcrumb">' +
- '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
- '<li class="active">Edytuj rekord</li>' +
- '</ul>').appendTo(taskCont);
- taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
- jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT&ID=' + recordID,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function (data) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>');
- jQuery(data).appendTo(taskCnt);
- taskCnt.find('.se_type-date').datepicker({
- format: "yyyy-mm-dd"
- , language: 'pl'
- , todayBtn: "linked"
- });
- taskCnt.find('.se_type-datetime').parent().datetimepicker({
- language: 'pl'
- , format: 'yyyy-MM-dd hh:mm'
- , weekStart: 1
- });
- },
- error: function (err) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request error: {0}'.f(err));
- }
- });
- //return false;
- },
- HIST: function (args) {
- var recordID = args;
- if (typeof args == 'object') {
- recordID = args.shift();
- recordID = parseInt(recordID);
- }
- if (typeof recordID !== 'number' || recordID <= 0) {
- // TODO: msg
- return false;
- }
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.hide();
- // remove previous task content
- var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
- taskCnt.parent().remove();
- taskCnt.remove();
- var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
- jQuery('<ul class="breadcrumb">' +
- '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
- '<li class="active">Historia rekordu</li>' +
- '</ul>').appendTo(taskCont);
- var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
- jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function (data) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>');
- jQuery(data).appendTo(taskCnt);
- },
- error: function (err) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request error: {0}'.f(err));
- }
- });
- //return false;
- },
- FILES: function tableAjaxFiles(args) {
- var recordID = args;
- if (typeof args == 'object') {
- recordID = args.shift();
- recordID = parseInt(recordID);
- }
- if (typeof recordID !== 'number' || recordID <= 0) {
- // TODO: msg
- return false;
- }
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.hide();
- // remove previous task content
- var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
- taskCnt.parent().remove();
- taskCnt.remove();
- var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
- jQuery('<ul class="breadcrumb">' +
- '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
- '<li class="active">Pliki</li>' +
- '</ul>').appendTo(taskCont);
- var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
- jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function (data) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>', data);
- jQuery(data).appendTo(taskCnt);
- },
- error: function (jqXHR, textStatus, errorThrown) {
- //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
- taskCnt.removeClass('AjaxTable-loading');
- var txt = jqXHR.responseText || 'Error';
- if (jqXHR.status == 404) {
- jQuery('<div class="container"><div class="alert alert-error">' + txt + '</div></div>').appendTo(taskCnt);
- } else {
- jQuery('<div class="container"><div class="alert alert-error">' + txt + '</div></div>').appendTo(taskCnt);
- }
- }
- });
- //return false;
- },
- CREATE: function tableAjaxCreate() {
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.hide();
- // remove previous task content
- var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
- taskCnt.parent().remove();
- taskCnt.remove();
- var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
- jQuery('<ul class="breadcrumb">' +
- '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
- '<li class="active">Dodaj nowy rekord</li>' +
- '</ul>').appendTo(taskCont);
- taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
- jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
- var reqData = {};
- var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
- if (forceFilterInit) {
- $.map(forceFilterInit, function (fltrProps, fltr) {
- reqData['ff_' + fltr] = fltrProps;
- });
- }
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',
- type: 'GET',
- dataType: 'text',
- data: reqData,
- async: true,
- success: function (data) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>');
- jQuery(data).appendTo(taskCnt);
- taskCnt.find('.se_type-date').datepicker({
- format: "yyyy-mm-dd"
- , language: 'pl'
- , todayBtn: "linked"
- });
- taskCnt.find('.se_type-datetime').parent().datetimepicker({
- language: 'pl'
- , format: 'yyyy-MM-dd hh:mm'
- , weekStart: 1
- });
- },
- error: function (err) {
- taskCnt.removeClass('AjaxTable-loading');
- //console.log('request error: {0}'.f(err));
- }
- });
- //return false;
- }
- };
- var routePath = location.hash;
- //console.log('location.hash: ' + routePath);
- if (location.hash == '' || location.hash == '#') {
- return false;
- }
- if (routePath.charAt(0) == '#') {
- routePath = routePath.substr(1);
- }
- //console.log('routePath: ' + routePath);
- var parts = routePath.split('/');
- var task = parts.shift();
- //console.log('task(' + task + ') parts:');
- //console.log(parts);
- if (task in routes && typeof routes[task] == 'function') {
- routes[task](parts);
- } else {
- return false;
- }
- },
- filtersClean: true,
- longDesc: true
- });
- });
- function tableAjaxBackToTable() {
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- cont.show();
- var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
- taskCont.remove();
- // reload first page
- var con = jQuery('#<?php echo $this->_htmlID; ?>');
- con.TableAjaxLoadPage(0);// TODO: load current page
- }
- function tableAjaxCopy(args) {
- var recordID = args;
- if (typeof args == 'object') {
- recordID = args.shift();
- recordID = parseInt(recordID);
- }
- if (typeof recordID !== 'number' || recordID <= 0) {
- // TODO: msg
- return false;
- }
- if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
- return false;
- }
- var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
- //cont.hide();
- //var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
- //taskCont.remove();
- cont.children('.alert').fadeOut('slow');
- var alert = jQuery('<div class="alert fade in"><strong>Kopiuj rekord</strong> ... </div>').prependTo(cont);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
- type: 'GET',
- dataType: 'text',
- data: '',
- async: true,
- success: function (data) {
- //console.log('data: ', data);
- alert.remove();
- alert = jQuery(data).prependTo(cont);
- alert.alert();
- var con = jQuery('#<?php echo $this->_htmlID; ?>');
- con.TableAjaxLoadPage(0);
- },
- error: function (err) {
- alert.remove();
- console.log(err);
- }
- });
- return false;
- }
- function hidePopover() {
- var con = jQuery('#<?php echo $this->_htmlID; ?>');
- if (con) {
- var tblAjax = con.data('TableAjax');
- if (tblAjax) {
- tblAjax.popoverCellRemove();
- }
- }
- return false;
- }
- </script>
- <?php
- $out = ob_get_contents();
- ob_end_clean();
- return $out;
- }
- public function ajaxTask($task) {
- switch ($task) {
- case 'EDIT': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxEdit($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'EDIT_SAVE': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxEditSave($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'EDIT_INLINE': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- $col = V::get('col', '', $_REQUEST);
- if ($id > 0 && !empty($col)) {
- $this->sendAjaxEditInline($id, $col, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'EDIT_INLINE_SAVE': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- $col = V::get('col', '', $_REQUEST);
- if ($id > 0 && !empty($col)) {
- $this->sendAjaxEditInlineSave($id, $col, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'COPY': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxCopy($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'CREATE': {
- $this->sendAjaxCreate($_REQUEST);
- break;
- }
- case 'CREATE_SAVE': {
- $this->sendAjaxCreateSave($_REQUEST);
- break;
- }
- case 'HIST': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxHistory($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'FILES': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFiles($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'FILES_UPLOAD': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFilesUpload($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'FILES_LIST': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFilesList($id, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'FILE_REMOVE': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- if ($id > 0) {
- $this->sendAjaxFileRemove($id, $_REQUEST);
- } else {
- echo '404';
- }
- 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 'TYPESPECIALL_CELL': {
- $id = V::get('ID', 0, $_REQUEST, 'int');
- $col = V::get('col', '', $_REQUEST);
- if ($id > 0 && !empty($col)) {
- $this->sendTypeSpecialCell($id, $col, $_REQUEST);
- } else {
- echo '404';
- }
- break;
- }
- case 'HIDDEN_COLS_SAVE': {
- $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
- break;
- }
- case 'THE_GEOM_SAVE': {
- $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
- break;
- }
- case 'THE_GEOM_REMOVE': {
- $this->sendAjaxResponseJson('ajaxTheGeomRemove', $_REQUEST);
- break;
- }
- default:
- $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
- }
- }
- /**
- * ajax url: &_task=EDIT_INLINE
- * @param $rowID - $_GET['ID']
- * @param $fieldName - $_GET['col']
- */
- private function sendAjaxEditInline($rowID, $fieldName, $args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- header("Content-type: text/plain");
- $fieldID = $this->_acl->getFieldIdByName($fieldName);
- if (!$fieldID) {
- echo "404: No field by name ({$fieldName})";
- exit;
- }
- if ($DBG) echo "fieldID: {$fieldID}\n";
- $row = $this->_dataSource->getItem($rowID);
- if (!$row) {
- echo "404: No item ID({$rowID})";
- exit;
- }
- if (!$this->_acl->isAllowed($fieldID, 'R', $row)) {
- if ($DBG) echo " R not allowed\n";
- } else {
- if ($DBG) echo " R allowed\n";
- }
- if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
- if ($DBG) echo " W not allowed\n";
- } else {
- if ($DBG) echo " W allowed\n";
- }
- $fieldVal = '';
- if ($this->_acl->isAllowed($fieldID, 'R', $row)) {
- $fieldVal = V::get($fieldName, $fieldVal, $row);
- } else {
- $fieldVal = '*****';
- }
- $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
- $vCol = $this->_acl->getField($fieldID);
- $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
- $tsValues = array();
- Lib::loadClass('Typespecial');
- $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, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
- 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[$row->ID] = implode('<br>', $specialValues);
- }
- }
- Lib::loadClass('SE_Layout');
- ?>
- <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
- <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
- <?php if (!empty($vCol['opis'])) : ?>
- <em><?php echo $vCol['opis']; ?></em>
- <?php $perms = $this->_acl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
- <?php endif; ?>
- </label>
- <?php
- $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
- if (!empty($tsValues[$row->ID])) {
- $fieldParams['typespecialValue'] = $tsValues[$row->ID];
- }
- $vDefault = $this->_dataSource->getColDefault($fieldName);
- if (!empty($vDefault)) {
- $fieldParams['default'] = $vDefault;
- }
- echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
- if ($typeSpecial) {
- echo '<p style="padding:100px 0;"></p>';
- }
- exit;
- }
- private function sendAjaxEditInlineSave($rowID, $fieldName, $args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- sleep(1);// TODO: RMME DBG loading
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: save ID(' . $id . ') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($args);echo'</pre>';}
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">acl (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_acl);echo'</pre>';}
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- exit;
- }
- $tblName = $this->_acl->getName();
- $fieldID = $this->_acl->getFieldIdByName($fieldName);
- if (!$fieldID) {
- header('HTTP/1.0 404 Not Found');
- echo "404: No field by name ({$fieldName})";
- exit;
- }
- $row = $this->_dataSource->getItem($rowID);
- if (!$row) {
- header('HTTP/1.0 404 Not Found');
- echo "404: No item ID({$rowID})";
- exit;
- }
- if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
- header('HTTP/1.0 403 Forbidden');
- echo "403: field not allowed to Write ({$fieldName})";
- exit;
- } else {
- if ($DBG) echo " Write allowed\n";
- }
- $sqlObj = new stdClass();
- if (array_key_exists("f{$fieldID}", $args)) {
- if (!$this->_acl->isAllowed($fieldID, 'R', $record) && '*****' == $args["f{$fieldID}"]) {
- // default value for perms 'W' without 'R' is '*****'
- }
- else {
- $sqlObj->{$fieldName} = $args["f{$fieldID}"];
- if (empty($args["f{$fieldID}"]) && strlen($args["f{$fieldID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
- $sqlObj->{$fieldName} = $this->_acl->fixEmptyValueFromUser($fieldID);
- }
- }
- }
- else {
- if ($DBG) echo " TODO: field value not set\n";
- }
- $sqlObj->ID = $rowID;
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">E('.$tblName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sqlObj);echo'</pre>';}
- $ret = $db->UPDATE_OBJ($tblName, $sqlObj);
- if ($ret > 0) {
- echo '<div class="alert alert-success">';
- echo "Rekord zapisany pomyślnie";//"Record saved successfully";
- echo '</div>';
- } else if ($ret == 0) {
- echo '<div class="alert alert-info">';
- echo "Nie wprowadzono żadnych zmian";
- if ($db->has_errors()) {
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">db errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
- }
- echo '</div>';
- } else {
- echo '<div class="alert alert-error">';
- echo '<h4>' . "Wystąpiły błędy!" . '</h4>';
- if ($db->has_errors()) {
- $errors = $db->get_errors();
- echo implode('<br>', $errors);
- }
- echo '</div>';
- }
- exit;
- }
- private function sendAjaxEdit($id, $args) {
- header("Content-type: text/plain");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $cols = array();
- $record = $this->_dataSource->getItem($id);
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- echo '<div class="alert alert-error">';
- echo "Brak dostępu do rekordu";// TODO: more info - reason
- echo '</div>';
- return;
- }
- $fieldsList = $this->_acl->getFields();
- foreach ($fieldsList as $kID => $vCol) {
- if ($vCol['name'] == 'ID') {
- unset($fieldsList[$kID]);
- continue;
- }
- $cols[$kID] = '';
- if ($this->_acl->isAllowed($kID, 'R', $record)) {
- $cols[$kID] = V::get($vCol['name'], '', $record);
- } else {
- $cols[$kID] = '*****';
- }
- $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
- $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
- }
- $tsValues = array();
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fieldsList (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fieldsList);echo'</pre>';}
- if (!empty($fieldsList)) {
- Lib::loadClass('Typespecial');
- foreach ($fieldsList as $vColID => $vCol) {
- $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
- if ($typeSpecial) {
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
- $colValue = V::get($vCol['name'], '', $record);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">V::get('.$vCol['name'].', "", $record) (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($colValue);echo'</pre>';}
- $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record->ID, $vCol['name'], $colValue);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
- if (!empty($specialValues)) {
- $tsValues[$vColID] = implode('<br>', $specialValues);
- }
- }
- }
- }
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">tsValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($tsValues);echo'</pre>';}
- $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('edit', 'cp'), true);
- Lib::loadClass('SE_Layout');
- ?>
- <div class="container AjaxFrmHorizontalEdit">
- <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
- <fieldset>
- <legend>Edycja rekordu Nr <?php echo $record->ID; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
- <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
- <?php if ($this->_acl->isAllowed($kID, 'W', $record)) : ?>
- <div class="control-group">
- <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
- <i class="icon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
- <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
- </label>
- <div class="controls">
- <?php
- $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
- if (!empty($tsValues[$kID])) {
- $fieldParams['typespecialValue'] = $tsValues[$kID];
- }
- echo $this->_acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
- ?>
- </div>
- </div>
- <?php elseif ($this->_acl->isAllowed($kID, 'R', $record)) : ?>
- <div class="control-group">
- <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
- <i class="icon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
- <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
- </label>
- <div class="controls">
- <p style="margin-top:5px;">
- <?php
- //echo $this->_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="control-group">
- <div class="controls">
- <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$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 data = jQuery(this).serialize();
- // 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-error"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_SAVE&ID=<?php echo $record->ID; ?>',
- type: 'POST',
- dataType: 'text',
- data: data,
- async: true,
- success: function (data) {
- alertCntWrap.removeClass('AjaxTable-loading');
- //console.log('request finished L.<?php echo __LINE__; ?>');
- alertCnt.empty();
- var out = '';
- out += data;
- out += '<div class="breadcrumb">' +
- ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-small"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
- '<span class="divider">/</span>' +
- ' <a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Edytuj rekord <?php echo $id; ?></a>' +
- '</div>';
- jQuery(out).appendTo(alertCnt);
- },
- error: function (jhr, textStatus, errorThrown) {
- var errorTxt = jhr.responseText || 'Error';
- alertCntWrap.removeClass('AjaxTable-loading');
- //console.log('Request Error: {0}: {1}'.f(textStatus, errorThrown));
- alertCnt.empty();
- 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;
- });
- }
- });
- return false;
- });
- jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
- var input, btn;
- input = jQuery(e.target);
- btn = input.next();
- if (btn.is('button')) {
- if (btn.attr('title') != input.val()) {
- btn.show();
- } else {
- btn.hide();
- }
- }
- });
- jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value button.btn-appendBack').on('click', function(e) {
- var input, btn;
- btn = jQuery(e.target);
- input = btn.prev();
- if (input.is('input')) {
- if (btn.attr('title') != input.val()) {
- input.val(btn.attr('title'));
- btn.hide();
- }
- }
- });
- });
- </script>
- <?php
- exit;
- }
- private function sendAjaxEditSave($id, $args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- sleep(1);// TODO: RMME DBG loading
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: save ID(' . $id . ') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($args);echo'</pre>';}
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">acl (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_acl);echo'</pre>';}
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- exit;
- }
- $tblName = $this->_acl->getName();
- $record = $db->get_by_id($tblName, $id);
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- echo '<div class="alert alert-error">';
- echo "Brak dostępu do rekordu";// TODO: more info - reason
- echo '</div>';
- }
- $sqlObj = new stdClass();
- $fields = $this->_acl->getFields();
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fields (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fields);echo'</pre>';}
- foreach ($fields as $kID => $vField) {
- if (!$this->_acl->isAllowed($kID, 'W', $record)) {
- continue;
- }
- if (array_key_exists("f{$kID}", $args)) {
- if (!$this->_acl->isAllowed($kID, 'R', $record) && '*****' == $args["f{$kID}"]) {
- // default value for perms 'W' without 'R' is '*****'
- }
- else {
- $sqlObj->{$vField['name']} = $args["f{$kID}"];
- if (empty($args["f{$kID}"]) && strlen($args["f{$kID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
- $sqlObj->{$vField['name']} = $this->_acl->fixEmptyValueFromUser($kID);
- }
- }
- }
- }
- $sqlObj->ID = $id;
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sqlObj);echo'</pre>';}
- $ret = $db->UPDATE_OBJ($tblName, $sqlObj);
- if ($ret > 0) {
- echo '<div class="alert alert-success">';
- echo "Rekord zapisany pomyślnie";//"Record saved successfully";
- echo '</div>';
- } else if ($ret == 0) {
- echo '<div class="alert alert-info">';
- echo "Nie wprowadzono żadnych zmian";
- echo '</div>';
- } else {
- header('HTTP/1.0 404 Not Found');
- echo '<div class="alert alert-error">';
- echo '<h4>' . "Wystąpiły błędy!" . '</h4>';
- if ($db->has_errors()) {
- $errors = $db->get_errors();
- echo implode('<br>', $errors);
- }
- echo '</div>';
- }
- exit;
- }
- private function sendAjaxCreate($args) {
- header("Content-type: text/plain");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $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;
- }
- }
- $fieldsList = $this->_acl->getFields();
- foreach ($fieldsList as $kID => $vCol) {
- $defaultValue = '';
- if ($vCol['name'] == 'ID') {
- unset($fieldsList[$kID]);
- continue;
- }
- if (!empty($forceFilterInit[$vCol['name']])) {
- $defaultValue = $forceFilterInit[$vCol['name']];
- }
- // TODO: read from session cache
- $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
- $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
- }
- Lib::loadClass('SE_Layout');
- ?>
- <div class="container AjaxFrmHorizontalEdit">
- <form class="form-horizontal" 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 ($this->_acl->isAllowed($kID, 'C')) : ?>
- <div class="control-group">
- <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
- <i class="icon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
- <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
- </label>
- <div class="controls">
- <?php
- $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
- echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
- ?>
- </div>
- </div>
- <?php endif; ?>
- <?php endforeach; ?>
- <div class="control-group">
- <div class="controls">
- <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
- </div>
- </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-error"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> save ... </div></div>').appendTo(taskCnt);
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE',
- type: 'POST',
- dataType: 'json',
- data: data,
- async: true,
- success: function(data) {
- //console.log('success L.<?php echo __LINE__; ?> data', data);
- },
- error: function(xhr) {
- //console.log('error L.<?php echo __LINE__; ?> xhr', xhr);
- },
- complete: function(xhr) {
- if (xhr.responseJSON) {
- var data = xhr.responseJSON;
- } else {
- // TODO: error
- }
- taskCnt.removeClass('AjaxTable-loading');
- taskCnt.empty();
- if (typeof data == 'object') {
- if (data.type == 'ERROR') {
- var out = '<div class="container">' +
- '<div class="alert alert-error">' +
- '<h4>Wystąpiły błędy!</h4>' + data.msg +
- '</div>';
- out += '<div class="breadcrumb">' +
- ' <a class="create-fix" href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-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-small"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
- '<span class="divider">/</span>' +
- ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
- '<span class="divider">/</span>' +
- ' <a href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-plus"></i> Dodaj nowy rekord</a></li>' +
- '</div>';
- out += '</div>';
- jQuery(out).appendTo(taskCnt);
- }
- }
- }
- });
- return false;
- });
- });
- </script>
- <?php
- exit;
- }
- private function sendAjaxCreateSave($args) {
- header("Content-type: application/json");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- sleep(1);// TODO: RMME DBG loading
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: save ID(' . $id . ') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($args);echo'</pre>';}
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">acl (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_acl);echo'</pre>';}
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- echo '{"type":"ERROR", "msg": "' . "Błąd połączenia z bazą danych!" . '"}';
- exit;
- }
- $tblName = $this->_acl->getName();
- $sqlObj = new stdClass();
- $fields = $this->_acl->getFields();
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fields (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fields);echo'</pre>';}
- foreach ($fields as $kID => $vField) {
- if (!$this->_acl->isAllowed($kID, 'C')) {
- continue;
- }
- if (array_key_exists("f{$kID}", $args)) {
- $sqlObj->{$vField['name']} = $args["f{$kID}"];
- if (empty($args["f{$kID}"]) && strlen($args["f{$kID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
- $sqlObj->{$vField['name']} = $this->_acl->fixEmptyValueFromUser($kID);
- }
- }
- }
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sqlObj);echo'</pre>';}
- $retID = $db->ADD_NEW_OBJ($tblName, $sqlObj);
- $retJson = new stdClass();
- $retJson->type = '';
- $retJson->msg = '';
- if ($retID > 0) {
- $retJson->type = 'SUCCESS';
- $retJson->msg = "Utworzono pomyślnie rekord: ID = {$retID}";
- $retJson->id = $retID;
- } else {
- header('HTTP/1.0 404 Not Found');
- $retJson->type = 'ERROR';
- $retJson->msg = "";
- if ($db->has_errors()) {
- $outArr = array();
- $errorsSql = $db->get_errors();
- foreach ($errorsSql as $vErr) {
- if (substr($vErr, 0, 18) == 'SQL QUERY FAILED: ') {
- $vErr = substr($vErr, 18);
- // Duplicate entry '123456-1' for key 'P_NIP'
- if (substr($vErr, 0, 16) == 'Duplicate entry ') {
- }
- }
- $outArr[] = $vErr;
- }
- $retJson->msg .= implode('<br>', $outArr);
- }
- }
- echo json_encode($retJson);
- exit;
- }
- private function sendAjaxCopy($id, $args) {
- header("Content-type: text/plain");
- sleep(1);// TODO: RMME DBG loading
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- exit;
- }
- $row = $this->_dataSource->getItem($id);
- if (!$row) {
- header('HTTP/1.0 404 Not Found');
- echo "404: No item ID({$rowID})";
- exit;
- }
- $tblName = $this->_acl->getName();
- $types = $this->_acl->getTypes();
- $uniqKeys = $this->_acl->getUniqueKeys();
- $sqlObj = new stdClass();
- foreach ($types as $kName => $vType) {
- if ($kName == 'ID') {
- continue;
- } else if (in_array($kName, array('A_RECORD_UPDATE_AUTHOR','A_RECORD_UPDATE_DATE'))) {
- continue;
- }
- $sqlObj->{$kName} = V::get($kName, '', $row);
- if (in_array($kName, $uniqKeys)) {
- $sqlObj->{$kName} .= '?';
- }
- }
- $ret = $db->ADD_NEW_OBJ($tblName, $sqlObj);
- if ($ret > 0) {
- echo '<div class="alert alert-success">';
- echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
- echo "Rekord skopiowany pomyślnie - utworzono rekord nr {$ret}";//"Record saved successfully";
- echo '</div>';
- } else if ($ret == 0) {
- echo '<div class="alert alert-error">';
- echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
- echo "Nie udało się skopiować rekordu";
- if ($db->has_errors()) {
- echo '<br>' . implode("<br>", $db->get_errors());
- }
- echo '</div>';
- } else {
- echo '<div class="alert alert-error">';
- echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
- echo "Błąd bazy danych";
- echo '</div>';
- }
- exit;
- }
- private function sendAjaxHistory($id, $args) {
- header("Content-type: text/plain");
- $record = $this->_dataSource->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo "404: No item ID({$rowID})";
- exit;
- }
- $visibleCols = $this->_acl->getRealFieldList();
- $rowsHist = $this->_dataSource->getHistItems($id);
- $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('hist', 'cp'), true);
- $visibleColsWithIds = array();
- $visibleColsLabels = array();
- foreach ($visibleCols as $vColName) {
- $fldId = $this->_acl->getFieldIdByName($vColName);
- if ($fldId) {
- $visibleColsWithIds[$fldId] = $vColName;
- $label = $this->_acl->getFieldLabel($fldId);
- $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
- $visibleColsLabels[$fldId] = $label;
- }
- }
- ?>
- <fieldset>
- <legend>Historia rekordu Nr <?php echo $id; ?>
- <span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
- </legend>
- </fieldset>
- <?php if (empty($rowsHist)) : ?>
- <div class="alert alert-info">
- <h4>Brak danych</h4>
- </div>
- <?php else: ?>
- <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
- <thead>
- <tr>
- <th>Data</th>
- <th>User</th>
- <th>Zmiany</th>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($rowsHist as $row) : ?>
- <tr>
- <td style="white-space:nowrap"><?php echo $row->_created; ?></td>
- <td><?php echo $row->_author; ?></td>
- <td>
- <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
- <?php if (in_array($colName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue; ?>
- <?php if ($row->$colName == 'N/S;') continue; ?>
- <p><em><?php echo $visibleColsLabels[$fldId]; ?></em>:
- <?php if ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
- <?php echo $row->$colName; ?>
- <?php else : ?>
- <span title="Brak uprawnień do odczytu tego pola">*****</span>
- <?php endif; ?>
- </p>
- <?php endforeach; ?>
- </td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- <div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">
- <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
- <thead>
- <tr>
- <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
- <th><?php echo str_replace('_', ' ', $visibleColsLabels[$fldId]); ?></th>
- <?php endforeach; ?>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($rowsHist as $row) : ?>
- <tr>
- <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
- <td>
- <?php if ($row->$colName == 'N/S;') : ?>
- <em>N/S;</em>
- <?php elseif ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
- <?php echo $row->$colName; ?>
- <?php else : ?>
- <span title="Brak uprawnień do odczytu tego pola">*****</span>
- <?php endif; ?>
- </td>
- <?php endforeach; ?>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- </div>
- <?php endif; ?>
- <?php
- exit;
- }
- /**
- * Returns text/plain with type at first line: ERROR, WARNING, INFO, SUCCESS
- */
- private function sendAjaxFilesUpload($id, $args) {
- // http://www.sitepoint.com/html5-ajax-file-upload/
- //$ajaxFileName = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
- //header("Content-type: text/plain");
- 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 '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
- exit;
- }
- $record = $this->_dataSource->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
- exit;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- Lib::loadClass('FoldersConfig');
- $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);
- Lib::loadClass('FileUploader');
- $uploader = new FileUploader($confTblName, $record);
- $errMsg = '';
- if (!$uploader->setConfig($folderConf, $errMsg)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych(' . $tblName . ') <br>' . $errMsg . '"}';
- exit;
- }
- $uploader->findFolder();
- $errorMsg = '';
- if (!empty($_POST['SCANS_COLUMN_ADD'])) {
- $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
- }
- else {
- $uploaded = $uploader->tryUploadAjax($errorMsg);
- }
- /*
- //$errorMsg = "wykonalem funkcje move dla parametrow ".$_FILES['M_DIST_FILES_NAME']['tmp_name']." oraz ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME'] ." <br>Informacje dodatkowe :".$IN7_FILERENAME['INFO']." <br> EOL <br> ";
- // TODO: IN7_POST_HISTORY($TABLE, array('M_DIST_FILES'), array(" Wgrano plik z przegladarki WWW ".$_SERVER['REMOTE_ADDR']." ".$_FILES['M_DIST_FILES_NAME']['name']." do ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME']." "), $thiss, $SESSION);
- // TODO: IN7_POST_HISTORY($TABLE, array('M_DIST_FILES'), array(" Wgrano plik z przegladarki WWW ".$_SERVER['REMOTE_ADDR']." ".$_FILES['M_DIST_FILES_NAME']['name']." do ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME']." "), $thiss, $SESSION);
- */
- if ($uploaded) {
- $uploadedFileName = '';
- $uploadedFile = $uploader->getLastUploadedFile();
- if ($uploadedFile) {
- $uploadedFileName = explode('/', $uploadedFile);
- $uploadedFileName = end($uploadedFileName);
- }
- echo '{"type":"SUCCESS", "string": "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);
- }
- } else {
- echo '{"type":"ERROR", "string": "' . $errorMsg . '"}';
- }
- exit;
- }
- private function sendAjaxFileRemove($id, $args) {
- header("Content-type: application/json");
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- if (empty($_POST['filename'])) {
- echo '{"type":"ERROR", "string": "Nie wybrano pliku do usunięcia"}';
- exit;
- }
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
- exit;
- }
- $record = $this->_dataSource->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
- exit;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- Lib::loadClass('FoldersConfig');
- $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);
- Lib::loadClass('FileUploader');
- $uploader = new FileUploader($confTblName, $record);
- if (!$uploader->setConfig($folderConf)) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
- exit;
- }
- $uploader->findFolder();
- $errorMsg = '';
- $removed = $uploader->tryRemoveFromAjax($_POST['filename'], $errorMsg);
- if (!$removed) {
- echo '{"type":"ERROR", "string": "{' . $errorMsg . '}"}';
- } else {
- echo '{"type":"SUCCESS","string":"Plik został poprawnie usunięty"}';
- }
- exit;
- }
- private function sendAjaxFilesList($id, $args) {
- header("Content-type: application/json");
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
- exit;
- }
- $record = $this->_dataSource->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
- exit;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- Lib::loadClass('FoldersConfig');
- $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);
- Lib::loadClass('FileUploader');
- $uploader = new FileUploader($confTblName, $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, $record->ID);
- echo json_encode($jsonFiles);
- exit;
- }
- 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->_dataSource->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";
- Lib::loadClass('FoldersConfig');
- $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);
- Lib::loadClass('FileUploader');
- $uploader = new FileUploader($confTblName, $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, $record->ID);
- echo json_encode($jsonFiles);
- exit;
- }
- public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder, $recordID) {
- sort($files);
- $jsonFiles = array();
- 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 = round($file->size, 2) . "B";
- if ($file->size > 1024 * 1024) {
- $file->sizeStr = round(($file->size / (1024 * 1024)), 2) . "M";
- } else if ($file->size > 1024) {
- $file->sizeStr = round(($file->size / 1024), 2) . "K";
- }
- $file->type = '';
- $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
- $file->web = "PLIKI/{$this->_zasobID}/{$recordID}/{$file->name}";
- $jsonFiles[] = $file;
- }
- return $jsonFiles;
- }
- private function getConnectedTables() {
- $connTbls = array();
- return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
- $fields = $this->_acl->getVisibleFieldList();
- if (!empty($fields)) {
- Lib::loadClass('Typespecial');
- 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->getVisibleFieldList();
- if (!empty($fields)) {
- Lib::loadClass('Typespecial');
- 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));
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- header('HTTP/1.0 406 Not Acceptable');
- exit;
- }
- $record = $this->_dataSource->getItem($id);
- if (!$record) {
- header('HTTP/1.0 404 Not Found');
- echo "404: No item ID({$rowID})";
- exit;
- }
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- echo '<div class="alert alert-error">';
- echo "Brak dostępu do rekordu";// TODO: more info - reason
- echo '</div>';
- return;
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- Lib::loadClass('FoldersConfig');
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- header('HTTP/1.0 404 Not Found');
- echo "Brak danych konfiguracyjnych";
- exit;
- }
- $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>';
- Lib::loadClass('FileUploader');
- $uploader = new FileUploader($confTblName, $record);
- $errMsg = '';
- if (!$uploader->setConfig($folderConf, $errMsg)) {
- header('HTTP/1.0 404 Not Found');
- echo "Błąd danych konfiguracyjnych ({$tblName})";
- echo '<br>' . "\n" . $errMsg;
- exit;
- }
- $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>'; }
- $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) {
- $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
- }
- $localPath = $uploader->getLocalPath();
- $folderWeb = $uploader->getFolderWeb();
- $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder, $record->ID);
- 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);
- ?>
- <script src="stuff/jquery.form.js"></script>
- <div class="container">
- <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
- <?php if ($sharePoint) : ?>
- <a href="<?php echo $sharePoint; ?>"><code><?php echo $mainFolder; ?></code></a>
- <?php else : ?>
- <code><?php echo $mainFolder; ?></code>
- <?php endif; ?>
- <span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
- </h4>
- <div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
- <table class="table table-bordered table-hover">
- <colgroup>
- <col style="">
- <col style="width:30px;">
- <?php if ($sharePoint) : ?>
- <col style="width:30px;">
- <?php endif; ?>
- <col style="width:80px;">
- <col style="width:140px;">
- </colgroup>
- <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
- <?php if (empty($mainFolder)) : ?>
- <tr>
- <td colspan="5">
- <div class="alert alert-warning">
- <h4>Brak folderu!</h4>
- Folder dla tego rekordu nie został utworzony.
- </div>
- </td>
- </tr>
- <?php elseif (empty($files)) : ?>
- <tr>
- <td colspan="5">
- <div class="alert alert-info">
- <h4>Brak plików</h4>
- </div>
- </td>
- </tr>
- <?php endif; ?>
- </tbody>
- </table>
- </div>
- <br>
- <br>
- <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
- <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
- <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
- <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
- <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
- <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
- </ul>
- <div id="myTabContent" class="tab-content">
- <div class="tab-pane fade in active" id="local" style="text-align: center;">
- <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'">
- </div>
- <div class="tab-pane fade" id="scan">
- <?php if (empty($skanyFiles)) : ?>
- <div class="alert alert-info">
- <h4>Brak plików</h4>
- <?php if(!empty($skanyFolderWeb)) echo "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>"; ?>
- </div>
- <?php else : ?>
- <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
- <table class="table table-bordered table-hover">
- <colgroup>
- <col style="width:30px;">
- <col style="">
- <col style="width:30px;">
- <col style="width:80px;">
- <col style="width:140px;">
- </colgroup>
- <tbody>
- <?php foreach ($skanyFiles as $vFilePath) : ?>
- <tr>
- <?php
- $vFileName = explode('/', $vFilePath);
- $vFileName = end($vFileName);
- $vFileSize = filesize($vFilePath);
- $vFileSizeOut = round($vFileSize, 2) . "B";
- if ($vFileSize > 1024 * 1024) {
- $vFileSizeOut = round(($vFileSize / (1024 * 1024)), 2) . "M";
- } else if ($vFileSize > 1024) {
- $vFileSizeOut = round(($vFileSize / 1024), 0) . "K";
- }
- ?>
- <td><input style="margin:0;" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
- <td><div style="overflow:hidden; white-space:nowrap;" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
- <td style="white-space:nowrap; text-align:center;"><a href="<?php echo str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath); ?>" target="_blank" class="ico-download-alt"></a></td>
- <td style="white-space:nowrap;"><?php echo $vFileSizeOut; ?></td>
- <td style="white-space:nowrap;"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- </div>
- <?php endif; ?>
- </div>
- </div>
- <script>
- $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function (e) {
- e.preventDefault();
- $(this).tab('show');
- })
- .on('shown', function (e) {
- var fileSource = $(e.target).data('toggle')
- , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
- if (frm['M_DIST_UPLOAD_SOURCE']) {
- frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
- }
- })
- </script>
- <br>
- <table style="width:100%" class="table table-noborder">
- <tr>
- <td colspan="5">
- <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
- <?php //TODO: link do procesu o obiegu dokumentów <i class="icon-question-sign" style="cursor:help" title="działa w nowszych przeglądarkach jak Firefox, Chrome"></i> ?>
- </h4>
- </td>
- </tr>
- <tr>
- <th style="border-right:1px solid #eee">ID</th>
- <th style="border-right:1px solid #eee">TYP</th>
- <th style="border-right:1px solid #eee">Opis <i class="icon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
- <th style="border-right:1px solid #eee">Data Wersji</th>
- <th>Numer Wersji</th>
- </tr>
- <tr>
- <td style="border-right:1px solid #eee;">
- <?php echo $record->ID; ?>
- </td>
- <td style="border-right:1px solid #eee;">
- <select name="M_DIST_FILES_TYPE">
- <?php foreach ($fileTypes as $kType => $vLabel) : ?>
- <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
- <?php endforeach; ?>
- </select>
- <br>
- <label class="checkbox">
- <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
- Wykrycie automatyczne TYPU z wysylanego pliku
- </label>
- <label class="checkbox">
- <input type="checkbox" name="M_DIST_FILES_TEMP">
- Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
- </label>
- </td>
- <td style="border-right:1px solid #eee;">
- <input type="text" name="M_DIST_FILES_DESCRIPTION" value="<?php echo $M_DIST_FILES_DESCRIPTION; ?>" maxlength="50">
- <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
- </td>
- <td style="border-right:1px solid #eee;">
- <input type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10" class="span2">
- <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
- </td>
- <td>
- <input type="number" name="M_DIST_FILES_VERSION" class="span2">
- <br>
- <label class="checkbox">
- <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
- Automatycznie dodaj wersje
- </label>
- </td>
- </tr>
- <tr>
- <td colspan="5">
- <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
- <p>
- <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
- </p>
- <p>
- <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
- <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
- </p>
- </td>
- </tr>
- </table>
- </form>
- </div>
- <script>
- function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
- var postData = {};
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_LIST&ID=<?php echo $record->ID; ?>',
- type: 'POST',
- //dataType: 'json',
- //contentType: "application/json; charset=utf-8",
- data: postData,
- async: true,
- success: function (data) {
- fileListUpdate<?php echo $this->_htmlID; ?>(data);
- },
- error: function (jhr, textStatus, errorThrown) {
- console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
- }
- });
- }
- function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
- var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
- fileListNode.empty();
- fileListJson.map(function(file){
- var node = $('<tr></tr>');
- var fFun = $('<i class="ico-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
- var fNameCell = $('<td style="overflow: hidden;"></td>');
- var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
- fName.append(fFun);
- fName.append(file.name);
- fName.appendTo(fNameCell);
- node.append(fNameCell);
- node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="ico-download-alt"></a>' + '</td>');
- <?php if ($sharePoint) : ?>
- node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="<?php echo $sharePoint; ?>/' + file.name + '" target="_blank" class="ico-folder-open"></a>' + '</td>');
- <?php endif; ?>
- node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
- node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
- node.appendTo(fileListNode);
- $(fFun).click(function(e){
- var n = $(e.target);
- var fname= n.data('filename');
- if (!fname) {
- return false;
- }
- if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
- var postData = {filename: fname};
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILE_REMOVE&ID=<?php echo $record->ID; ?>',
- type: 'POST',
- //dataType: 'json',
- //contentType: "application/json; charset=utf-8",
- data: postData,
- async: true,
- success: function (data) {
- if (data && data.type) {
- if (data.type == 'SUCCESS') {
- n.parents('tr').remove();
- //console.log('TODO: SUCCESS msg: ', data.string);
- }
- else if (data.type == 'ERROR') {
- //console.log('TODO: ERROR msg: ', data.string);
- }
- } else {
- console.log('TODO: ??? data: ', data);
- }
- },
- error: function (jhr, textStatus, errorThrown) {
- console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
- }
- });
- }
- });
- });
- }
- function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
- var postData = {};
- // clear current file list
- jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
- jQuery.ajax({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_CONN_TBL_LIST&ID=<?php echo $record->ID; ?>&connTblID=' + connTblID,
- type: 'POST',
- //dataType: 'json',
- //contentType: "application/json; charset=utf-8",
- data: postData,
- async: true,
- success: function (data) {
- connTblListUpdate<?php echo $this->_htmlID; ?>(data);
- },
- error: function (jqXHR, textStatus, errorThrown) {
- var txt = jqXHR.responseText || 'Error';
- jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').html('<tr><td colspan="6"><div class="alert alert-error">' + txt + '</div></td></tr>');
- console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
- }
- });
- }
- function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
- var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
- fileListNode.empty();
- fileListJson.map(function(file){
- var node = $('<tr></tr>');
- var fNameCell = $('<td style="overflow: hidden;"></td>');
- var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
- fName.append(file.name);
- fName.appendTo(fNameCell);
- node.append(fNameCell);
- node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="ico-download-alt"></a>' + '</td>');
- node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
- node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
- node.appendTo(fileListNode);
- });
- }
- jQuery(document).ready(function(){
- jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
- url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_UPLOAD&ID=<?php echo $record->ID; ?>',
- beforeSubmit: function(args, $form, options) {
- var argsMap = [];
- args.map(function(v, k) {
- argsMap[v.name] = v.value;
- });
- // validate
- if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
- if (!argsMap['M_DIST_FILES_NAME']) {
- console.log('TODO: nie wybrano lokalnego pliku!');
- return false;
- }
- }
- else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
- if (!argsMap['SCANS_COLUMN_ADD']) {
- console.log('TODO: nie wybrano pliku ze skanów!');
- return false;
- }
- }
- else {
- console.log('TODO: nie wybrano źródła pliku!');
- return false;
- }
- var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
- $out.html('Wysyłanie...');
- },
- success: function(data) {
- var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
- var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
- if (typeof data == 'object') {
- if (data.type == 'ERROR') {
- $out.html('<div class="alert alert-error">' + btnClose + data.string + '</div>');
- } else if (data.type == 'SUCCESS') {
- $out.html('<div class="alert alert-success">' + btnClose + data.string + '</div>');
- fileListUpdateAjax<?php echo $this->_htmlID; ?>();
- }
- } else {
- if (data.substr(0, 7) == 'WARNING') {
- data = data.substr(7);
- $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
- } else if (data.substr(0, 5) == 'ERROR') {
- data = data.substr(5);
- $out.html('<div class="alert alert-error">' + btnClose + data + '</div>');
- } else if (data.substr(0, 7) == 'SUCCESS') {
- data = data.substr(7);
- $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
- fileListUpdateAjax<?php echo $this->_htmlID; ?>();
- } else if (data.substr(0, 4) == 'INFO') {
- data = data.substr(4);
- $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
- }
- }
- }
- });
- var fileList = <?php echo json_encode($jsonFiles); ?>;
- fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
- var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
- if (connTbls) {
- var connTblsOut = '';
- for(var key in connTbls) {
- connTblsOut += '<button class="btn btn-small conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
- };
- if (connTblsOut) {
- connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
- connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
- '<table class="table table-bordered table-hover">' +
- '<colgroup>' +
- '<col style="">' +
- '<col style="width:30px;">' +
- <?php if ($sharePoint) : ?>
- '<col style="width:30px;">' +
- <?php endif; ?>
- '<col style="width:80px;">' +
- '<col style="width:140px;">' +
- '</colgroup>' +
- '<tbody class="files-list">' +
- '</tbody>' +
- '</table>' +
- '</div>';
- var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
- _connTblsWrap.css('marginBottom', '26px');
- _connTblsWrap.html(connTblsOut);
- _connTblsWrap.find('.conn-tbl-load').each(function(){
- jQuery(this).click(function(e){
- var tblID = jQuery(e.target).data('zasobid');
- console.log('clicked: ', tblID);
- if (tblID) {
- connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
- }// TODO: else show error
- });
- });
- }
- }
- });
- </script>
- <?php
- exit;
- }
- private function sendTypeSpecial($fldID, $args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- header("Content-type: application/json");
- $fldName = '';
- $fld = $this->_acl->getField($fldID);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fld);echo'</pre>';}
- if (!$fld) {
- // 404
- } else {
- $fldName = $fld['name'];
- }
- $jsonData = array();
- Lib::loadClass('Typespecial');
- $typeSpecial = Typespecial::getInstance($fldID, $fldName);
- if ($typeSpecial) {
- $query = V::get('q', '', $_REQUEST);
- $rawRows = null;
- $rows = $typeSpecial->getValuesWithExports($query);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
- 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;
- }
- $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;
- }
- private function sendTypeSpecialCell($id, $fldName, $args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- header("Content-type: application/json");
- $jsonData = new stdClass();
- $fldID = $this->_acl->getFieldIdByName($fldName);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fldID);echo'</pre>';}
- $item = $this->_dataSource->getItem($id);
- if (!$this->_acl->isAllowed($fldID, 'R', $item)) {
- $jsonData->msg = 'Brak dostępu';
- echo json_encode($jsonData);
- exit;
- }
- if (!$fldID) {
- $jsonData->msg = 'Wrong field';
- echo json_encode($jsonData);
- exit;
- }
- Lib::loadClass('Typespecial');
- $typeSpecial = Typespecial::getInstance($fldID, $fldName);
- if ($typeSpecial) {
- $jsonData->data = $typeSpecial->getReturnData($this->_zasobID, $id, $fldName, '');
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">specialValuesByIds('.$id.'/'.$fldName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValuesByIds);echo'</pre>';}
- }
- echo json_encode($jsonData);
- exit;
- }
- private function ajaxData($args) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $pageSize = V::get('pageSize', 10, $args, 'int');
- $page = V::get('page', 0, $args, 'int');
- $currSortCol = V::get('currSortCol', '', $args);
- $currSortFlip = V::get('currSortFlip', '', $args);
- if ($page > 0) {
- $page -= 1;
- }
- else {
-
- }
- $params = array();
- $params['limit'] = $pageSize;
- $params['limitstart'] = $page * $params['limit'];
- $params['order_by'] = ($currSortCol)? $currSortCol : '';
- $params['order_dir'] = $currSortFlip;
- $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
- $params[$k] = $v;
- $filters->{$k} = $v;
- }
- else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
- $params[$k] = $v;
- $filters->{$k} = $v;
- }
- }
- $this->setFilters($filters);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">_dataSource (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_dataSource);echo'</pre>';}
- $vCols = $this->_acl->getVirtualFieldList();
- if (!empty($vCols)) {
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">vCols (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCols);echo'</pre>';}
- }
- Lib::loadClass('Typespecial');
- $total = $this->_dataSource->getTotal($params);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">get_total (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($total);echo'</pre>';}
- $items = $this->_dataSource->getItems($params);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">items (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items);echo'</pre>';}
- // TODO: add virtual data by Typespecial
- if (!empty($vCols) && !empty($items)) {
- foreach ($vCols as $vColID => $vCol) {
- $colType = $this->_acl->getFieldTypeById($vColID);
- if ($colType) {
- continue;// pomin Typespecial dla realnych komorek w bazie danych
- }
- $typeSpecial = Typespecial::getInstance($vColID, $vCol);
- if ($typeSpecial) {
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
- $ids = array_keys($items);
- $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vCol.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
- if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
- $tsValue = implode('<br>', $vValues);
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Item['.$kItemID.'].'.$vCol.' specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items[$kItemID]);echo'</pre>';}
- if (!empty($items[$kItemID]->{$vCol}) && !empty($tsValue)) {
- $items[$kItemID]->{$vCol} .= ": {$tsValue}";
- } else {
- $items[$kItemID]->{$vCol} = $tsValue;
- }
- }
- }
- }
- }
- $visibleCols = $this->_acl->getVisibleFieldList();
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">visibleCols (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($visibleCols);echo'</pre>';}
- $jsonData = new stdClass();
- $jsonData->total = $total;
- $jsonData->cols = new stdClass();
- $ind = 0;
- foreach ($visibleCols as $fieldID => $col) {
- $ind++;
- $columnConfig = (object)array('index'=>$ind);
- if ($col == 'ID') {
- // /SE/se-dev/index.php?MENU_INIT=USERS2_MARKETING_EDIT&ARG1=EDIT&ARG1_VAL=31105
- $columnConfig->format = '<a href="#EDIT/{0}">{0}</a>';
- $columnConfig->unique = true;
- }
- else 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 ($this->_dataSource->isGeomField($col)) {
- $columnConfig->type = 'geom';
- }
- if ('' !== ($label = $this->_acl->getFieldLabel($fieldID))) {
- $columnConfig->friendly = $label;
- }
- $colType = $this->_acl->getFieldType($col);
- if ($colType) {// @see MarkTableAjaxFilterColType
- if ($colType['type'] == 'date') {
- //$columnConfig->type = 'date';// TODO: require datepicker
- }
- } else {// typespecial - no type
- $columnConfig->type = 'special';
- }
- $typeSpecial = Typespecial::getInstance($fieldID, $col);
- if ($typeSpecial) {
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">typeSpecial (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
- $columnConfig->_tsRetId = $typeSpecial->getReturnId();
- }
- // @see ajaxHiddenColsSave
- // $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
- if (isset($_SESSION['USER_PROFILE'][$this->_zasobID])) {
- if (isset($_SESSION['USER_PROFILE'][$this->_zasobID][$fieldID])) {
- if ($_SESSION['USER_PROFILE'][$this->_zasobID][$fieldID] != 1) {
- $columnConfig->hidden = true;
- }
- }
- }
- $jsonData->cols->{$col} = $columnConfig;
- }
- $jsonData->rows = array();
- foreach ($items as $vItem) {
- // TODO: hide items without 'R'
- foreach ($visibleCols as $kID => $vCol) {
- // TODO: ID default 'R'
- if (!$this->_acl->isAllowed($kID, 'R', $vItem)) {
- $vItem->{$vCol} = '*****';
- }
- // null => empty string
- if (!isset($vItem->{$vCol}) || (!$vItem->{$vCol} && $vItem->{$vCol} !== '0')) {
- if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">isEmptyString['.$vCol.'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vItem->{$vCol});echo'</pre>';}
- $vItem->{$vCol} = '';
- }
- }
- $jsonData->rows[] = $vItem;
- }
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">this->_dataSource (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_dataSource);echo'</pre>';
- //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">jsonData (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonData);echo'</pre>';
- 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;
- }
- Lib::loadClass('UserProfile');
- 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 = array();
- if (array_key_exists($this->_zasobID, $_SESSION['USER_PROFILE'])) {
- $colVis = $_SESSION['USER_PROFILE'][$this->_zasobID];
- }
- $fields = $this->_acl->getFields();
- foreach ($fields as $kFldId => $vFld) {
- $vFldName = $vFld['name'];
- if (isset($args[$vFldName])) {
- if ($args[$vFldName] == 'SHOW') {
- $colVis[$kFldId] = 1;
- } else if ($args[$vFldName] == 'HIDE') {
- $colVis[$kFldId] = 0;
- }
- }
- }
- $_SESSION['USER_PROFILE'][$this->_zasobID] = $colVis;
- UserProfile::save();
- $response->type = 'success';
- return $response;
- }
- private function ajaxTheGeomSave($args) {
- $id = V::get('ID', 0, $args, 'int');
- $polygon = V::get('polygon', 0, $args);
- $geomFieldName = 'the_geom';
- if ($id <= 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->_dataSource->getItem($id);
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- throw new HttpException("Brak dostępu do rekordu", 403);
- }
- $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
- if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
- throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
- }
- $itemPath = new stdClass();
- $itemPath->{$geomFieldName} = "GeomFromText('{$polygon}')";
- $itemPath->ID = $id;
- $affected = $this->_dataSource->updateItem($itemPath);
- $response = new stdClass();
- 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";
- } else {
- $response->type = 'error';
- $response->msg = "Wystąpiły błędy!";
- $response->errors = $this->_dataSource->getDbErrors();
- }
- $response->record = $this->_dataSource->getItem($id);
- return $response;
- }
- private 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;
- }
- private function ajaxTheGeomRemove($args) {// ajax task 'THE_GEOM_REMOVE'
- $id = V::get('ID', 0, $args, 'int');
- $geomFieldName = 'the_geom';
- $response = new stdClass();
- if ($id <= 0) {
- throw new HttpException("Wrong param ID", 404);
- }
- $tblName = $this->_acl->getName();
- $record = $this->_dataSource->getItem($id);
- if (!$record) {
- throw new HttpException("Nie odnaleziono rekordu nr {$id}", 404);
- }
- if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
- throw new HttpException("Brak dostępu do rekordu nr {$id}", 403);
- }
- $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
- if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
- throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
- }
- if (empty($record->{$geomFieldName})) {
- $response->type = 'info';
- $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
- $response->record = $record;
- return $response;
- }
- $itemPath = new stdClass();
- $itemPath->{$geomFieldName} = "NULL";
- $itemPath->ID = $id;
- $affected = $this->_dataSource->updateItem($itemPath);
- $response = new stdClass();
- 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";
- } else {
- $response->type = 'error';
- $response->msg = "Wystąpiły błędy!";
- $response->errors = $this->_dataSource->getDbErrors();
- }
- $response->record = $this->_dataSource->getItem($id);
- return $response;
- }
- public function sendFileContent($id, $fileName) {
- $DBG = ('1' == V::get('DBG', '', $_REQUEST));
- $dbID = $this->_acl->getDB();
- $db = DB::getDB($dbID);
- if (!$db) {
- throw new HttpException('No DB', 406);
- }
- $record = $this->_dataSource->getItem($id);
- if (!$record) {
- throw new HttpException("No item ID({$rowID})", 404);
- }
- if (!$this->_acl->canReadRecord($record)) {// TODO: Write, Super Write?
- throw new HttpException("Brak dostępu do rekordu", 406);
- }
- $tblName = $this->_acl->getName();
- $confTblName = "{$tblName}_COLUMN";
- Lib::loadClass('FoldersConfig');
- $folderConfAll = FoldersConfig::getRawData();
- if (!FoldersConfig::hasConfig($confTblName)) {
- throw new HttpException("Brak danych konfiguracyjnych", 404);
- }
- $folderConf = FoldersConfig::getAll($confTblName);
- if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>'; }
- Lib::loadClass('FileUploader');
- $uploader = new FileUploader($confTblName, $record);
- $errMsg = '';
- if (!$uploader->setConfig($folderConf, $errMsg)) {
- throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})\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>'; }
- $localPath = $uploader->getLocalPath();
- $filePath = "{$localPath}/{$mainFolder}/{$fileName}";
- if (!file_exists($filePath)) {
- throw new HttpException("Plik nie istnieje", 404);
- }
- if (function_exists('http_send_file')) {
- http_send_file($filePath);
- } else {
- header('Content-Description: File Transfer');
- header('Content-Type: application/octet-stream');
- header('Content-Disposition: attachment; filename='.basename($filePath));
- header('Content-Transfer-Encoding: binary');
- header('Expires: 0');
- header('Cache-Control: must-revalidate');
- header('Pragma: public');
- header('Content-Length: ' . filesize($filePath));
- set_time_limit(0);
- $filePointer = @fopen($filePath, "rb");
- if (!$filePointer) {
- throw new HttpException('Problem z odczytem pliku', 500);
- }
- while (!feof($filePointer)) {
- print(@fread($filePointer, 1024*8));
- ob_flush();
- flush();
- }
- fclose($filePointer);
- }
- }
- }
|